language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
566
3.15625
3
[]
no_license
//Normal Space Class: Defines a ladder space //Alex Wells, William Rathbun | Project 1 public class ladderSpace extends Space { public ladderSpace(){ } public int onLanding(int position){ switch (position) { //returns how many spaces ahead a player should climb case 1: return 37; case 4: return 10; case 9: return 22; case 21: return 41; case 28: return 56; case 36: return 8; case 51: return 16; case 71: return 20; case 80: return 20; default: return 0; //never reached } } }
C#
UTF-8
1,312
2.546875
3
[]
no_license
using System; using System.Net.Sockets; using System.Windows.Forms; using Client.Forms; using GameData.ClientInteraction; namespace Client { public static class Program { /// <summary> /// Главная точка входа для приложения. /// </summary> [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //TODO: установка сохранённых имени, цвета, настроек управления RunOnline(); //RunSolo(); } private static void RunOnline() { Application.Run(new MainMenuForm( true, "Player1", new ControlSettings(Keys.ControlKey, Keys.ShiftKey, Keys.Right, Keys.Left, Keys.Up, Keys.Down))); } private static void RunSolo() { var gameSession = new GameSession( 11, 10, 10, new ControlSettings(Keys.ControlKey, Keys.ShiftKey, Keys.Right, Keys.Left, Keys.Up, Keys.Down)); gameSession.StartSolo(); Application.Run(gameSession.GameForm); } } }
Java
UTF-8
3,609
2.515625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2012-2022 Erwin Müller <erwin.mueller@anrisoftware.com> * * 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.anrisoftware.propertiesutils; import java.util.Map; import java.util.Properties; import org.joda.time.Duration; import org.joda.time.Period; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * Extends the utility to return typed properties for Joda-Time typed. * * @author Erwin Müller, erwin.mueller@deventm.de * @since 4.5.1 */ @SuppressWarnings("serial") public class JodaDateProperties extends TypedProperties { public JodaDateProperties(Map<String, Object> properties, String listSepChars) { super(properties, listSepChars); } public JodaDateProperties(Map<String, Object> properties) { super(properties); } public JodaDateProperties(Properties properties, String listSepChars) { super(properties, listSepChars); } public JodaDateProperties(Properties properties) { super(properties); } /** * Returns a time period property using the format defined in * {@link ISOPeriodFormat#standard()}. * * @param key the property key. * * @return the {@link Period}. */ public Period getPeriodProperty(String key) { String property = getProperty(key); if (property == null) { return null; } else { return new Period(property); } } /** * Returns a time period property using the format defined in * {@link ISOPeriodFormat#standard()}. * * @param key the property key. * * @param formatter the {@link PeriodFormatter} that parses the period property. * * @return the {@link Period}. */ public Period getPeriodProperty(String key, PeriodFormatter formatter) { String property = getProperty(key); if (property == null) { return null; } else { return formatter.parsePeriod(property); } } /** * Returns a time duration property using the format defined in * {@link ISOPeriodFormat#standard()}. * * @param key the property key. * * @return the {@link Duration}. */ public Duration getDurationProperty(String key) { String property = getProperty(key); if (property == null) { return null; } else { return new Period(property).toStandardDuration(); } } /** * Returns a time duration property using the format defined in * {@link ISOPeriodFormat#standard()}. * * @param key the property key. * * @param formatter the {@link PeriodFormatter} that parses the duration * property. * * @return the {@link Duration}. */ public Duration getDurationProperty(String key, PeriodFormatter formatter) { String property = getProperty(key); if (property == null) { return null; } else { return formatter.parsePeriod(property).toStandardDuration(); } } }
Markdown
UTF-8
13,907
2.53125
3
[ "MIT" ]
permissive
# Development Tools A collection of awesome development libraries, resources and tools. > For those resource with ⭐️ it's just my personal preference. * [Analytics Platform](development-tools.md#analytics-platform) * [Console](development-tools.md#console) * [Code Editor](development-tools.md#code-editor) * [Online Code Playground](development-tools.md#online-code-playground) * [IDE](development-tools.md#ide) * [Container Platform](development-tools.md#container-platform) * [Database](development-tools.md#database) * [Diff Tools](development-tools.md#diff-tools) * [Source Control](development-tools.md#source-control) * [Emulator](development-tools.md#emulator) * [API Development Tools](development-tools.md#api-development-tools) * [Cloud Storage Clients](development-tools.md#cloud-storage-clients) * [SSH](development-tools.md#ssh) * [Server Tools](development-tools.md#server-tools) * [Packet Analyzer](development-tools.md#packet-analyzer) * [Windows Scripting](development-tools.md#windows-scripting) * [Utilities](development-tools.md#utilities) * [Monitoring](development-tools.md#monitoring) ## Analytics Platform * [Qlik Sense](https://www.qlik.com/us/products/qlik-sense) - Custom & Embedded Analytics Qlik Sense is a complete analytics platform that helps you tackle even the most complex analytics challenges. The complete set of open APIs enables you to fully customize analytics solutions. * [Tableau](https://www.tableau.com/) - Tableau Software is an American interactive data visualization software company founded in January 2003 by Christian Chabot, Pat Hanrahan and Chris Stolte, in Mountain View, California. The company is currently headquartered in Seattle, Washington, United States focused on business intelligence. ## Console * [Cmder](http://cmder.net/) - ⭐️ A software package created out of pure frustration over the absence of nice console emulators on Windows. It is based on amazing software, and spiced up with the Monokai color scheme and a custom prompt layout, looking sexy from the start. * [Hyper](https://hyper.is/) - An Electron-Based Terminal build on HTML/CSS/JS ## Code Editor * [Sublime Text](https://www.sublimetext.com/) - A sophisticated text editor for code, markup and prose. You'll love the slick user interface, extraordinary features and amazing performance * [Visual Studio Code](https://code.visualstudio.com/) - ⭐️ Code editor redefined and optimized for building and debugging modern web and cloud applications. * [Atom](https://atom.io/) - A free and open-source text and source code editor for macOS, Linux, and Microsoft Windows with support for plug-ins written in Node.js, and embedded Git Control, developed by GitHub. Atom is a desktop application built using web technologies. * [Notepad++](https://notepad-plus-plus.org/) - ⭐️ A free source code editor and Notepad replacement that supports several languages for Windows, its use is governed by [GPL](http://www.gnu.org/copyleft/gpl.html) License. ## Online Code Playground * [CodeSandbox](https://codesandbox.io/) - An online code editor with a focus on creating and sharing web application projects. * [CodePen](https://codepen.io/) - An online community for testing and showcasing user-created HTML, CSS and JavaScript code snippets. It functions as an online code editor * [JSFiddle](http://jsfiddle.net/) - An online playground to code and share code, this time with many flavors of JavaScript. * [ExtendsClass](https://extendsclass.com) - Online playgrounds for testing Regex, XPath, JSONPath and SQL. ## IDE * [Android Studio](https://developer.android.com/studio/) - Android Studio provides the fastest tools for building apps on every type of Android device. * [Eclipse](https://www.eclipse.org/) - A widely used Java IDE in computer programming. It contains a base workspace and an extensible plug-in system for customizing the environment. * [Visual Studio IDE](https://visualstudio.microsoft.com/vs/) - ⭐️ A fully-featured integrated development environment \(IDE\) for Android, iOS, Windows, web, and cloud. * [Pycharm](https://www.jetbrains.com/pycharm/) - PyCharm IDE is specifically for the Python language. It is developed by the Czech company [JetBrains](https://www.jetbrains.com/). * [WebStorm](https://www.jetbrains.com/webstorm/) - A powerful IDE for modern JavaScript development, perfectly equipped for building applications with React, Angular, Vue.js and Node.js. ## Container Platform * [Docker](https://www.docker.com/) - A computer program that performs operating-system-level virtualization, also known as "containerization". It was first released in 2013 and is developed by Docker, Inc. Docker is used to run software packages called "containers" * [Kubernetes](https://kubernetes.io/) - An open-source system for automating deployment, scaling, and management of containerized applications. ## Database * [PostgreSQL](https://www.postgresql.org/) - An object-relational database management system with an emphasis on extensibility and standards compliance * [pgAdmin](https://www.pgadmin.org/) - The most popular and feature rich Open Source administration and development platform for [PostgreSQL](https://www.postgresql.org/), the most advanced Open Source database in the world. * [MSSQL](https://www.microsoft.com/en-us/sql-server/sql-server-2016) - Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications. * [MongoDB](https://www.mongodb.com/) - A free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemata. ## Diff Tools * [Beyond Compare](https://www.scootersoftware.com/) - ⭐️ A data comparison utility. Aside from comparing files, the program is capable of doing side-by-side comparison of directories, FTP and SFTP directories, Dropbox directories, Amazon S3 directories, and archives. It is available for Windows, Mac OS, and Linux operating systems * [WinMerge](http://winmerge.org/) - A free software tool for data comparison and merging of text-like files. It is useful for determining what has changed between versions, and then merging changes between versions. * [OpenDBDiff](https://github.com/OpenDBDiff/OpenDBDiff) - A database comparison tool for Microsoft SQL Server 2005+ that reports schema differences and creates a synchronization script. * [Code Compare](https://marketplace.visualstudio.com/items?itemName=DevartSoftware.CodeCompare) - File diff tool that reads structure of C#, C++,VB code for better results. Includes: folder comparison tool, standalone app for comparing and merging files and folders, code review support. ## Source Control * [Git Bash](https://gitforwindows.org/) - Git Bash is a command-line git client for windows. * [GitKraken](https://www.gitkraken.com/) - An intuitive and elegant Git GUI client for Windows, Mac and Linux. With this Git client, you can visualize manage branches, forks, and merges in your Git repositories. * [SourceTree](https://www.sourcetreeapp.com/) - Free Git client for Windows and Mac. Sourcetree simplifies how you interact with your Git repositories so you can focus on coding. Visualize and manage your repositories through Sourcetree's simple Git GUI. * [SVN](https://subversion.apache.org/) - Software versioning and revision control system distributed as open source under the Apache License. Software developers use Subversion to maintain current and historical versions of files such as source code, web pages, and documentation. ## Emulator * [Android Studeo AVD Manager](https://developer.android.com/studio/) - An Android Emulator included with Android Studio IDE. * [GenyMotion](https://www.genymotion.com/) - Cross-platform Android emulator for developers & QA engineers. Develop & automate your tests to deliver best quality apps. * [BlueStacks](https://www.bluestacks.com/) - BlueStacks runs Android OS and apps on Windows PCs with instant switch between Android and Windows * [Nox App Player](https://www.bignox.com/) - ⭐️ Nox APP Player aims to provide the best experience for users to play Android games and apps on PC. ## API Development Tools * [Postman](https://www.getpostman.com/) - ⭐️ The worldwide used by API development environment. * [Paw](https://paw.cloud/) - The most advanced API tool for Mac. * [SoapUI](https://www.soapui.org/) - SoapUI is an open-source web service testing application for service-oriented architectures and representational state transfers. Its functionality covers web service inspection, invoking, development, simulation and mocking, functional testing, load and compliance testing. ## Cloud Storage Clients * [CloudBerry Explorer](https://www.cloudberrylab.com/explorer/amazon-s3.aspx) - Explorer for [Amazon S3](https://aws.amazon.com/s3/) provides a user interface to Amazon S3 accounts allowing to access, move and manage files across your local storage and S3 buckets. * [Cyberduck](https://cyberduck.io/) - A libre server and cloud storage browser for Mac and Windows with support for FTP, SFTP, WebDAV, Amazon S3, OpenStack Swift, Backblaze B2, Microsoft Azure & OneDrive, Google Drive and Dropbox. * [FileZilla](https://filezilla-project.org/) - A free software, cross-platform FTP application, consisting of FileZilla Client and FileZilla Server. Client binaries are available for Windows, Linux, and macOS, server binaries are available for Windows only ## SSH * [PuTTY](https://www.putty.org/) - An SSH and telnet client, developed originally by Simon Tatham for the Windows platform. PuTTY is open source software that is available with source code and is developed and supported by a group of volunteers. ## Server Tools * [Apache JMeter](https://jmeter.apache.org/) - Apache JMeter is an Apache project that can be used as a load testing tool for analyzing and measuring the performance of a variety of services, with a focus on web applications * [LoadRunner](https://www.microfocus.com/en-us/products/loadrunner-professional/download) - LoadRunner is a software testing tool from Micro Focus. It is used to test applications, measuring system behaviour and performance under load. LoadRunner can simulate thousands of users concurrently using application software, recording and later analyzing the performance of key components of the application. * [CollectD](http://collectd.org/) - A popular open source daemon, which collects basic system performance statistics over time and stores the data it collects in multiple formats, such as the RRD files that Cacti can use to graph the data. * [Barracuda Load Balancer ADC](https://www.barracuda.com/products/loadbalancer) - The Barracuda Load Balancer ADC is ideal for organizations looking for a high-performance, yet cost-effective application delivery and security solution. ## Packet Analyzer * [Wireshark](https://www.wireshark.org/download.html) - Wireshark is a free and open-source packet analyzer. It is used for network troubleshooting, analysis, software and communications protocol development, and education. Originally named Ethereal, the project was renamed Wireshark in May 2006 due to trademark issues ## Windows Scripting * [AutoHotkey](https://autohotkey.com/) - ⭐️ **AHK** is a free, open-source macro-creation and automation software for Windows that allows users to automate repetitive tasks * [RabbitMQ](https://www.rabbitmq.com/download.html) - ⭐️ **RabbitMQ** is an open-source message-broker software that originally implemented the Advanced Message Queuing Protocol and has since been extended with a plug-in architecture to support Streaming Text Oriented Messaging Protocol, Message Queuing Telemetry Transport, and other protocols. * [Apache Kafka](https://kafka.apache.org/) - Apache Kafka is an open-source stream-processing software platform developed by LinkedIn and donated to the Apache Software Foundation, written in Scala and Java. The project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds. * [Automic](https://docs.automic.com/documentation) - ⭐️ Use workload automation for business application and IT infrastructure processing and complex service orchestration. (💰 Enterprise Software) ## Utilities * [FileLocator](https://www.mythicsoft.com/filelocatorlite/download/) - ⭐️ FileLocator is a powerful search utility for Windows * [ScreenToGif](https://www.screentogif.com/) - This tool allows you to record a selected area of your screen, edit and save it as a gif or video * [LightShot](https://app.prntscr.com/en/index.html) - LightShot allows you to take a customizable screenshot and it support for both Mac and Windows * [CPU-Z](https://www.cpuid.com/softwares/cpu-z.html) - A freeware that gathers information on some of the main devices of your system. * [Pandoc](https://pandoc.org/index.html) - A universal document converter (Markdown, Docx. Pdf, etc) ## Monitoring * [Uptime Robot](https://uptimerobot.com/) - ⭐️ Uptime Robot is all about helping you to keep your websites up. It monitors your websites every 5 minutes and alerts you if your sites are down. It is Free and easy to use compare to Pingdom. * [Pingdom](https://www.pingdom.com/) - ⭐️ Pingdom is an uptime monitoring service. When problems happen with a site that Pingdom monitors, it immediately alerts the owner so the problem can be taken care of. Pingdom is recommended if you need more features. * [Status Cake](https://www.statuscake.com/) - Monitoring tools that are quick-and-easy to set up. Instant alerts that you can trust, the moment your site goes down. Gain invaluable insights into how your website's performance is impacting your customers’ experiences – helping your business to stay ahead of the competition.
Python
UTF-8
760
2.546875
3
[ "MIT" ]
permissive
import traces import pytest @pytest.mark.mpl_image_compare( savefig_kwargs={'bbox_inches': 'tight', 'dpi': 300}, remove_text=True, style='ggplot', tolerance=20, ) def test_plot(): ts = traces.TimeSeries() ts[0] = 0 ts[1] = 2 ts[3] = 1 ts[5] = 0 figure, axes = ts.plot() return figure def test_optional_import(): # TODO: something like this https://stackoverflow.com/a/51048604/1431778 pass def test_invalid_call(): ts = traces.TimeSeries() ts[0] = 0 ts[1] = 1 ts.plot(interpolate='previous') ts.plot(interpolate='linear') with pytest.raises(ValueError): ts.plot(interpolate='yomama') def test_empty(): ts = traces.TimeSeries() ts.plot()
Markdown
UTF-8
5,316
2.875
3
[ "MIT" ]
permissive
--- title: 课堂话语分析:转录的两个偏见(上) author: S layout: post permalink: /2011/04/classroom-discourse-analysis-two-biases-in-transcription-1/ views: - 630 categories: - 发改委 tags: - 应用语言学 - 视频转录 - 话语偏见 - 话语转录 - 语言人类学 - 课堂话语分析 --- 在话语分析领域,转录(transcription)就是把录音或视频中的话语转换为书面的文字。我在念硕士的时候,做过几个简单的视频转录工作。当时只觉得耗时耗力,一节四十分钟的课,大概需要六七个小时的时间进行转录,而且还没有记录非言语行为(nonverbal behavior)。业界比较常见的说法是,正规的转录是一比十的时间投入,即一个小时的原始材料,需要十个小时的转录时间。 但是,我当时只把转录当作一项体力活,是在真正的研究开始之前的一项“铺垫”或“预备”工作。这次上课堂话语分析课,读了一些文献,才知道原来转录本身也有这么大的学问。这篇日志主要基于加州大学语言人类学家Elinor Ochs(1979)的一篇文章,谈谈转录工作中的两个偏见。这两个偏见关乎我们转录文本的格式,极易被忽略,但对后续的分析却有着极大影响。 第一个偏见是从上至下的转录格式。 我们在转录的时候,一般是按照常规的习惯,依说话双方(或多方)的言语发生顺序(turn-by-turn utterances),从上往下交错地录入对话文本的,例如: #1 老师:小明,你觉得这段话是什么意思呢? #2 小明:小梅花鹿口渴了! #3 老师:噢?口渴了?具体是怎么一回事呢? #4 小明:口渴了然后就去找小溪流! 这种格式的好处显然是符合人的正常阅读习惯,但其坏处往往被忽略了:儿童并不一定遵循成人对话的逻辑;相对成人,儿童的思维是跳跃的,并且更容易受到情境中的其他因素的干扰,从而导致说话的不连贯性。然而,在这种从上至下交错录入的格式里,我们(阅读者)却很容易自然而然地依照成人的逻辑去理解对话。这就形成了从上至下转录的偏见(Top to Bottom Biases)。 例如,在上文的对话里,老师首先提出一个阐释性的问题,希望小明表达自己对某段话(姑且定其为一段课文)的“理解”(#1)。然而,小明的回答却是一个“事实性的陈述”(#2)。老师似乎没有弄懂小明的回答,因此继续追问,希望小明“澄清”自己的回答(#3)。但小明却没有理会老师的追问,而是继续推进自己的“事实陈述”(#4)。 这是怎么一回事呢?我们能不能从这段对话中得出结论——小明显然没有“理解”这段“课文”? 如果我们做出了这样的结论,便是从上至下的转录偏见在作怪。因为我们在阅读这段对话的时候,往往按照成人的逻辑,认为老师和小明的对话是有衔接关系的。换言之,我们假定小明说的两句话都确实是在“回答”老师的问题,这是我们推论的前提所在。然而,小明或许从一开始(#2)就根本没在回答老师的问题——或许他之前与同桌在讨论这段课文的情节;当老师提问之后,他仍然在表述之前与同桌的对话(#2,“小梅花鹿口渴了”),仅此而已。然后,当老师继续追问时,他的注意力仍然在之前与同桌的对话中,所以,他既没有“更改”自己之前的回答(#2),也没有“澄清”自己之前的回答(#2),而是将情节(事实)的陈述继续向前推进了一环(#4,“然后就去找小溪流”)。这两个回答与小明对课文的理解无关,与老师的提问也无关,而是与小明之前与同桌的对话、小明自身的注意力以及现场的情境(比如老师提问的音调能否足唤唤起小明的注意力)有关。 为了避免这一从上至下转录的偏见,Ochs提出了一种新的录入格式,也就是水平的格式,如下: [table id=1 /] 这一水平格式的好处在于,当阅读者从左向右阅读一个回合的对话(横行),然后将视线移向下一行的左侧,开始新一个回合的对话时,常规的从上至下的逻辑会得到一定程度的干扰,从而在一定程度上消除从上至下的理解偏见(注意:任何格式都无法完全更改阅读的常规理解习惯)。更重要的是,在这种格式中,阅读者可以清晰方便地看见某一个对话参与者的所有话语(纵列),从而审视其话语的内在逻辑。例如,在上面的表格中,我们可以明显看出小明的两句话之间的内在逻辑,而老师的提问并没有干扰(interrupt)小明的“自言自语”(或者是朝向同桌——而非老师——的话语)。 注:本文的内容大多采自Elinor Ochs的经典之作《转录作为一种理论》(除了这个小梅花鹿的囧例),对话语转录有兴趣的童鞋可以直接阅读原文,将会更有助益。 参考文献: <div> <div> Ochs, E. (1979). Transcription as theory. <em>Developmental pragmatics</em>, 43–72. </div> </div>
Python
UTF-8
1,582
3.609375
4
[]
no_license
import os def loadCharacterSelect(): print(os.path.isfile("characters/characterList.csv")) if os.path.isfile("characters/characterList.csv"): file = open("characters/characterList.csv", "r") else: file = open("characters/characterList.csv", "w+") charArray = file.readlines() characters = [] for char in charArray: if char.rstrip("\n") != "": characters.append(char.rstrip("\n")) return characters def characterSelectMenu(characterArray): if characterArray != []: characterNumber = 0 print("+++++++++++++++++++++++++++++++") print("-------CHARACTER SELECT--------") print("+++++++++++++++++++++++++++++++") for c in characterArray: characterNumber += 1 print(str(characterNumber) + ": " + c) exitNumber = characterNumber+1 print(str(characterNumber+1) + ": GO BACK") print("+++++++++++++++++++++++++++++++") goodSelect = False selection = "" while goodSelect == False: numberSelection = input("CHOOSE A CHARACTER: ") try: sn = int(numberSelection) if sn == exitNumber: goodselect = True return None else: selection = characterArray[sn-1] goodSelect = True except Exception as e: print("USE NUMERIC VALUE THAT IS SHOWN") return selection else: print("CURRENTLY NO CHARACTERS. \nYOU CAN CREATE CHARACTERS FROM THE MAIN MENU") return None
C#
UTF-8
1,758
3.296875
3
[]
no_license
public abstract class SocialNetwork { /// <summary> /// Email address of the user /// </summary> public virtual string EmailAddress { get; set; } /// <summary> /// When posting a public message, the number of characters allowed. /// </summary> public virtual int AllowedNumberOfCharacters { get { return 140; } } /// <summary> /// Login to the SocialNetwork /// </summary> /// <param name="emailAddress">Email Address used for login</param> /// <returns>Successful Login</returns> public abstract bool Login(string emailAddress); /// <summary> /// Post a public message /// </summary> /// <param name="message">Message to post</param> public abstract void Post(string message); /// <summary> /// Post a Photo and a message to go along with it. /// </summary> /// <param name="photo">Bytes of a photo</param> /// <param name="message">Message to Post</param> public abstract void Post(byte[] photo, string message); /// <summary> /// Ask the Social network to return my details /// </summary> /// <returns>Return the details of the user</returns> public virtual string WhoAmI() { return EmailAddress; } } public class Twitter : SocialNetwork { public override void Post(string message) { } public override void Post(byte[] photo, string message) { } public override bool Login(string emailAddress) { this.EmailAddress = emailAddress; return true; } } public abstract class SocialNetworkFactory { public static SocialNetwork CreateSocialNetwork(string name) { name = name.ToUpperInvariant(); switch(name) { case "TWITTER": return new Twitter(); default: return new Twitter(); } } }
Java
UTF-8
320
1.609375
2
[]
no_license
package com.hbwang.viewbindlib.inject.provider; import android.app.Activity; import com.hbwang.viewbindlib.inject.sender.bindclick.IBindClick; /** * ----------Dragon be here!----------/ * Created by HBWang on 2019/3/25-13:46 */ public interface IBindClickFactory { IBindClick getProduct(Activity activity); }
Shell
UTF-8
342
3.1875
3
[]
no_license
#!/bin/sh tree -T "Libarchive downloads" -H "." -L 1 -r -I "index.html" -i --noreport downloads | sed -E -e 's,^.*<a href=".">.</a>.*,,' > downloads/index.html cd downloads && ( FILES=`ls -1 *.zip *.tar* *.asc | sort -r` rm -f .sha256sums for FILE in ${FILES} do openssl sha256 ${FILE} >> .sha256sums done mv .sha256sums sha256sums )
C++
UTF-8
404
3.140625
3
[]
no_license
#include <iostream> #include "Stack.h" using namespace std; using namespace MYStack; int main() { Stack<int> A(10); A.push(7); A.push(11); cout << A.top() << endl; A.pop(); A.push(9); cout << A.top() << endl; cout << A[0] << endl; //cout << A[3] << endl; A.pop(); Stack<string> B(10); B.push("Bob"); B.push("Alice"); cout << B.top() << endl; B.pop(); B.push("Eve"); return 0; }
JavaScript
UTF-8
629
2.75
3
[]
no_license
//npm - global command, comes with node //npm -- version //local dependency - use it only in this particular project //npm i <packagename> //global dependency - use it in any project //npm install -g <packageName> //sudo npm install -g <packageName> (mac) //package.json - manifest file( stores important info about project/package) //manual approach ( create package.json inthe root, create properties etc) //npm init ( step by step, press enter to skip) //npm init -y (evktkykkterything default) const _ = require("lodash"); const items = [1, [2, [3, [4]]]]; const newItems = _.flattenDeep(items); console.log(newItems);
TypeScript
UTF-8
530
2.984375
3
[]
no_license
export class User { constructor(private name: string, private active: number, private unactive: number, private status: boolean) { } getName(): string { return this.name; } getActive(): number { return this.active; } getUnactive(): number { return this.unactive; } addActive() { this.active += 1; } addUnactive() { this.unactive += 1; } setStatus(stat: boolean) { this.status = stat; } getStatus() { return this.status; } }
Java
UTF-8
1,789
3.734375
4
[]
no_license
package Shu; import mode.TreeNode; import java.util.ArrayList; /** * 找二叉树的第k个节点 * 二叉查找树,二叉搜索树,的特点,左边节点都比跟节点小,右节点都比左节点大 * <p> * 利用中序遍历的有序性来做这个事 * <p> * 第k个或者第k大个节点,直接用中序求 * <p> * https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/ */ public class BinaryTreeKNode { public static void main(String[] args) { } private static int cnt = 0; private static TreeNode result; private static TreeNode KthNode(TreeNode root, int k) { findK(root, k); return result; } private static void findK(TreeNode node, int kth) { if (node == null || cnt >= kth) return; findK(node.left, kth); cnt++; if (cnt == kth) result = node; findK(node.right, kth); } //如果是第k小,可以拿个arrayList存下来 public ArrayList<Integer> inorder(TreeNode root, ArrayList<Integer> arr) { if (root == null) return arr; inorder(root.left, arr); arr.add(root.val); inorder(root.right, arr); return arr; } public int kthSmallest(TreeNode root, int k) { ArrayList<Integer> nums = inorder(root, new ArrayList<Integer>()); return nums.get(k - 1); } //我认为可以逆中序遍历,cnt-- private static TreeNode finkSmall(TreeNode root, int k) { cnt = k; findKSmallest(root); return result; } private static void findKSmallest(TreeNode node) { if (node == null || cnt == 0) return; findKSmallest(node.right); cnt--; if (cnt == 0) result = node; findKSmallest(node.left); } }
Shell
UTF-8
1,988
3.625
4
[ "MIT" ]
permissive
#!/usr/bin/env sh BASEDIR=$(git rev-parse --show-toplevel) COMMAND=${@} TOPIC=${TOPIC:-test} KAFKA_HOST=${KAFKA_HOST:-localhost:9193} ZHOST=${ZHOST:-localhost:2181} CLIENT_JAAS="${BASEDIR}/setup/kafka-setup/client-jaas.conf" echo "Kafka host: ${KAFKA_HOST} // ZHost: ${ZHOST}" create_client_properties () { if [ -z "${CLIENT_PROPERTIES}" ]; then mkdir -p /tmp/kafka-data cp ${BASEDIR}/setup/kafka-setup/client.properties /tmp/kafka-data/client.properties echo "bootstrap.servers=${KAFKA_HOST}" >> /tmp/kafka-data/client.properties echo "ssl.truststore.location=${BASEDIR}/certs/docker.kafka.server.truststore.jks" >> /tmp/kafka-data/client.properties echo "ssl.keystore.location=${BASEDIR}/certs/docker.kafka.server.keystore.jks" >> /tmp/kafka-data/client.properties CLIENT_PROPERTIES="/tmp/kafka-data/client.properties" fi } case "$COMMAND" in "consume") echo "Consume on ${TOPIC} topic." create_client_properties KAFKA_LOG4J_OPTS="-Djava.security.auth.login.config=${CLIENT_JAAS}" kafka-console-consumer --from-beginning --bootstrap-server=${KAFKA_HOST} --topic=${TOPIC} --consumer.config=${CLIENT_PROPERTIES} ;; "produce") echo "Produce on ${TOPIC} topic." create_client_properties KAFKA_LOG4J_OPTS="-Djava.security.auth.login.config=${CLIENT_JAAS}" kafka-console-producer --broker-list=${KAFKA_HOST} --topic=${TOPIC} --producer.config=${CLIENT_PROPERTIES} ;; "create-topic") echo "Create ${TOPIC} topic:" kafka-topics --create --zookeeper=${ZHOST} --replication-factor=1 --partitions=1 --topic=${TOPIC} ;; "topics") echo "Topic list:" kafka-topics --zookeeper=${ZHOST} --list ;; *) echo "Invalid command." echo "Usage: $0 {consume|produce|create-topic|topics}" echo " consume : Consume on ${TOPIC} topic." echo " produce : Produce on ${TOPIC} topic." echo " create-topic : Create the ${TOPIC} topic." echo " topics : Show topic list." ;; esac
C++
UTF-8
6,698
2.59375
3
[ "MIT" ]
permissive
#ifndef RX_CORE_JSON_H #define RX_CORE_JSON_H #include "rx/core/concurrency/atomic.h" #include "rx/core/traits/return_type.h" #include "rx/core/traits/is_same.h" #include "rx/core/traits/detect.h" #include "rx/core/utility/declval.h" #include "rx/core/utility/exchange.h" #include "rx/core/string.h" #include "rx/core/optional.h" #include "lib/json.h" namespace Rx { // 32-bit: 8 bytes // 64-bit: 16 bytes struct RX_API JSON { constexpr JSON(); JSON(Memory::Allocator& _allocator, const char* _contents, Size _length); JSON(Memory::Allocator& _allocator, const char* _contents); JSON(Memory::Allocator& _allocator, const String& _contents); JSON(const char* _contents, Size _length); JSON(const char* _contents); JSON(const String& _contents); JSON(const JSON& _json); JSON(JSON&& json_); ~JSON(); JSON& operator=(const JSON& _json); JSON& operator=(JSON&& json_); enum class Type { k_array, k_boolean, k_null, k_number, k_object, k_string, k_integer }; operator bool() const; Optional<String> error() const; bool is_type(Type _type) const; bool is_array() const; bool is_array_of(Type _type) const; bool is_array_of(Type _type, Size _size) const; bool is_boolean() const; bool is_null() const; bool is_number() const; bool is_object() const; bool is_string() const; bool is_integer() const; JSON operator[](Size _index) const; bool as_boolean() const; Float64 as_number() const; Float32 as_float() const; Sint32 as_integer() const; JSON operator[](const char* _name) const; String as_string() const; String as_string_with_allocator(Memory::Allocator& _allocator) const; template<typename T> T decode(const T& _default) const; // # of elements for objects and arrays only Size size() const; bool is_empty() const; template<typename F> bool each(F&& _function) const; constexpr Memory::Allocator& allocator() const; private: template<typename T> using HasFromJSON = decltype(Utility::declval<T>().from_json(Utility::declval<JSON>())); struct Shared { Shared(Memory::Allocator& _allocator, const char* _contents, Size _length); ~Shared(); Shared* acquire(); void release(); Memory::Allocator& m_allocator; struct json_parse_result_s m_error; struct json_value_s* m_root; Concurrency::Atomic<Size> m_count; }; JSON(Shared* _shared, struct json_value_s* _head); Shared* m_shared; struct json_value_s* m_value; }; inline constexpr JSON::JSON() : m_shared{nullptr} , m_value{nullptr} { } inline JSON::JSON(Memory::Allocator& _allocator, const String& _contents) : JSON{_allocator, _contents.data(), _contents.size()} { } inline JSON::JSON(const char* _contents, Size _length) : JSON{Memory::SystemAllocator::instance(), _contents, _length} { } inline JSON::JSON(const String& _contents) : JSON{Memory::SystemAllocator::instance(), _contents.data(), _contents.size()} { } inline JSON::JSON(const JSON& _json) : m_shared{_json.m_shared->acquire()} , m_value{_json.m_value} { } inline JSON::JSON(JSON&& json_) : m_shared{Utility::exchange(json_.m_shared, nullptr)} , m_value{Utility::exchange(json_.m_value, nullptr)} { } inline JSON::~JSON() { if (m_shared) { m_shared->release(); } } inline JSON& JSON::operator=(const JSON& _json) { RX_ASSERT(&_json != this, "self assignment"); if (m_shared) { m_shared->release(); } m_shared = _json.m_shared->acquire(); m_value = _json.m_value; return *this; } inline JSON& JSON::operator=(JSON&& json_) { RX_ASSERT(&json_ != this, "self assignment"); m_shared = Utility::exchange(json_.m_shared, nullptr); m_value = Utility::exchange(json_.m_value, nullptr); return *this; } inline JSON::operator bool() const { return m_shared && m_shared->m_root; } inline bool JSON::is_array() const { return is_type(Type::k_array); } inline bool JSON::is_array_of(Type _type) const { if (!is_array()) { return false; } return each([_type](const JSON& _value) { return _value.is_type(_type); }); } inline bool JSON::is_array_of(Type _type, Size _size) const { if (!is_array()) { return false; } if (size() != _size) { return false; } return each([_type](const JSON& _value) { return _value.is_type(_type); }); } inline bool JSON::is_boolean() const { return is_type(Type::k_boolean); } inline bool JSON::is_null() const { return is_type(Type::k_null); } inline bool JSON::is_number() const { return is_type(Type::k_number); } inline bool JSON::is_object() const { return is_type(Type::k_object); } inline bool JSON::is_string() const { return is_type(Type::k_string); } inline bool JSON::is_integer() const { return is_type(Type::k_integer); } inline bool JSON::is_empty() const { return size() == 0; } inline String JSON::as_string() const { return as_string_with_allocator(Memory::SystemAllocator::instance()); } template<typename T> inline T JSON::decode(const T& _default) const { if constexpr(traits::is_same<T, Float32> || traits::is_same<T, Float64>) { if (is_number()) { return as_number(); } } else if constexpr(traits::is_same<T, Sint32>) { if (is_integer()) { return as_integer(); } } else if constexpr(traits::is_same<T, String>) { if (is_string()) { return as_string(); } } else if constexpr(traits::detect<T, HasFromJSON>) { return T::from_json(*this); } return _default; } template<typename F> inline bool JSON::each(F&& _function) const { const bool array = is_array(); const bool object = is_object(); RX_ASSERT(array || object, "not enumerable"); if (array) { auto array = reinterpret_cast<struct json_array_s*>(m_value->payload); for (auto element = array->start; element; element = element->next) { if constexpr(traits::is_same<traits::return_type<F>, bool>) { if (!_function({m_shared, element->value})) { return false; } } else { _function({m_shared, element->value}); } } } else { auto object = reinterpret_cast<struct json_object_s*>(m_value->payload); for (auto element = object->start; element; element = element->next) { if constexpr(traits::is_same<traits::return_type<F>, bool>) { if (!_function({m_shared, element->value})) { return false; } } else { _function({m_shared, element->value}); } } } return true; } RX_HINT_FORCE_INLINE constexpr Memory::Allocator& JSON::allocator() const { RX_ASSERT(m_shared, "reference count reached zero"); return m_shared->m_allocator; } } // namespace rx #endif // RX_CORE_JSON_H
Java
GB18030
145
2.109375
2
[]
no_license
package subject; /** * ǶҪʵֵĽӿ * @author swh * */ public interface Subject { public void buyMac(); }
Java
UTF-8
1,096
3.640625
4
[]
no_license
package com.demo.gyw.java.multi_thread.create; /** * @Description: 创建多线程之实现Runnable * @Author: gyw * @CreateDate: 2019/11/5 11:20 * @Version: 1.0 */ public class ImplementsRunnable implements Runnable { private String name; public ImplementsRunnable(String name) { this.name = name; } @Override public void run() { System.out.println(this.name); } public static void main(String[] args) { //创建真实线程对象 ImplementsRunnable implementsOne = new ImplementsRunnable("线程-one"); ImplementsRunnable implementsTwo = new ImplementsRunnable("线程-two"); ImplementsRunnable implementsThree = new ImplementsRunnable("线程-three"); //创建代理线程对象,并引用真实对象 Thread threadOne = new Thread(implementsOne); Thread threadTwo = new Thread(implementsTwo); Thread threadThree = new Thread(implementsThree); //开启线程 threadOne.start(); threadTwo.start(); threadThree.start(); } }
Java
UTF-8
2,906
1.828125
2
[]
no_license
package com.howell.activity; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.howell.action.ClientManager; import com.howell.litenademo.R; import com.howell.server.MyHttpServer; import com.howell.utils.Constant; import com.howell.utils.Utils; import org.json.JSONException; import butterknife.ButterKnife; import butterknife.OnClick; /** * 使用iotnorthsdk model中自行封装 */ public class MainActivity extends AppCompatActivity { ClientManager mMgr = ClientManager.getInstance(); ImageView iv; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); iv = findViewById(R.id.imageView); Intent intent = new Intent(this, MyHttpServer.class); bindService(intent,conn,BIND_AUTO_CREATE); } @Override protected void onDestroy() { unbindService(conn); super.onDestroy(); } @OnClick(R.id.btn_login) void login(){ mMgr.init(MainActivity.this,true,Constant.SELFCERTPATH,Constant.SELFCERTPWD,Constant.BASE_URL); mMgr.login(Constant.APPID,Constant.SECRET); } @OnClick(R.id.btn_query) void query(){ mMgr.queryDevices(Constant.APPID); } @OnClick(R.id.btn_send) void sendTestMsg(){ String myIp = Utils.getIpAddressString(); mMgr.init(MainActivity.this,false,null,null,"http://"+myIp+":8743"); mMgr.testNotify(); } @OnClick(R.id.btn_scribe) void scribe(){ mMgr.subcribeNotify(Constant.APPID); } @OnClick(R.id.btn_discovery) void discovery(){ try { mMgr.discoveryDevice(Constant.APPID); } catch (JSONException e) { e.printStackTrace(); } } @OnClick(R.id.btn_pic) void getPic(){ mMgr.queryPicHistory(Constant.APPID,iv); } @OnClick(R.id.btn_test) void test(){ // mMgr.queryDeviceStatus(Constant.APPID); // mMgr.queryDevice(Constant.APPID); mMgr.queryHistory(Constant.APPID); // mMgr.queryCapability(Constant.APPID); // mMgr.queryDeviceCmd(Constant.APPID); } @OnClick(R.id.btn_next) void nextPage(){ startActivity(new Intent(this,ApiActivity.class)); } }
C#
UTF-8
1,226
2.59375
3
[]
no_license
using PresentationProjectDomainDb; using PresentationProjectDomainModels.Implementation; using PresentationProjectDomainServices.Abstraction; using System; using System.Collections.Generic; using System.Linq; namespace PresentationProjectDomainServices.Implementation { public class AccountService : IAccountService { public static List<UserAccount> _allAccount = default; private readonly string connectionString = @"Data Source=DESKTOP-0FM65T2;Initial Catalog=Account;Integrated Security=True"; public bool CreateUserAccount(string username, string password, string email) { try { // query for account to add info on SQL Server string myAccountSQL = string.Empty; myAccountSQL += "INSERT INTO AccountTbl (Username, Password, Email) "; myAccountSQL += "VALUES ('" + username + "', '" + password + "', '" + email + "')"; // posting account on Server SQLDatabaseServerConnection.ExecuteSQL(myAccountSQL, connectionString); return true; } catch { return false; } } } }
Python
UTF-8
1,210
3.265625
3
[]
no_license
#!/usr/bin/env python3 # # Advent of Code 2016 - Day 5 # import hashlib from itertools import count INPUT = 'ugkcyxxp' # PART 1 def next_char(door_id, start=0): for idx in count(start): text = "{}{}".format(door_id, idx).encode() hashi = hashlib.md5(text).hexdigest() if hashi.startswith('00000'): return (hashi[5], idx) def next_char2(door_id, start=0): for idx in count(start): text = "{}{}".format(door_id, idx).encode() hashi = hashlib.md5(text).hexdigest() if hashi.startswith('00000'): return (hashi[6], hashi[5], idx) pwd = [] idx = -1 for i in range(8): c, idx = next_char(INPUT, idx+1) print("char: {} idx: {}".format(c, idx)) pwd.append(c) print("DoorID: {} Password: {}".format(INPUT, "".join(pwd))) print('- ' * 32) # PART 2 VALID_POS = '01234567' pwd2 = [' '] * 8 idx = -1 while ' ' in pwd2: c, pos, idx = next_char2(INPUT, idx+1) print("char: {} pos: {} idx: {}".format(c, pos, idx)) if pos in VALID_POS and pwd2[int(pos)] == ' ': pwd2[int(pos)] = c else: print("-- INVALID") print("DoorID: {} Password: {}".format(INPUT, "".join(pwd2))) print('- ' * 32)
Python
UTF-8
615
2.65625
3
[]
no_license
import sys sys.stdin = open('sample_input.txt') T = int(input()) for tc in range(1,T+1): F = int(input()) numbers = list(map(int,input().split())) for i in range(len(numbers)): for j in range(len(numbers)-1): if numbers[j] > numbers[j+1]: numbers[j], numbers[j+1] = numbers[j+1], numbers[j] result = [] for idx in range(len(numbers)//2): result.append(numbers[idx*(-1)-1]) result.append(numbers[idx]) result2 = [] for idx in range(10): result2.append(result[idx]) print('#{} {}'.format(tc, ' '.join(map(str, result2))))
Python
UTF-8
556
3.078125
3
[]
no_license
''' using hashmap time: O(N) space: O(N) ''' class Solution: def maxOperations(self, nums: List[int], k: int) -> int: counter = collections.Counter(nums) ans = 0 for n in nums: if n == k / 2: ans += counter[n] // 2 del counter[n] elif counter[k - n] > 0: min_pairs = min(counter[n], counter[k - n]) ans += min_pairs counter[n] -= min_pairs counter[k - n] -= min_pairs return ans
Python
UTF-8
5,151
3.203125
3
[]
no_license
import sys import io from math import floor from random import randint import pygame from pygame.locals import QUIT, MOUSEBUTTONDOWN while True: a = input("난이도를 몇으로 하시겠습니까? 1, 2, 3, 4:\n") if a == '1': WIDTH = 10 HEIGHT = 10 BOMBS = 10 break elif a == '2': WIDTH = 15 HEIGHT = 15 BOMBS = 15 break elif a == '3': WIDTH = 25 HEIGHT = 20 BOMBS = 22 break elif a == '4': WIDTH = 30 HEIGHT = 20 BOMBS = 30 break else: print("잘못입력하셨습니다, 1에서 4까지 다시 입력하세요\n") continue SIZE =30 #1칸의 가로세로 곱의 크기 EMPTY = 0 #맵상의 타일에 아무것도 없는 상태 BOMB = 1 #맵상의 타일에 폭탄이 있는 상태 OPENED =2 # 맵상의 타일이 이미 비어진 상태 OPEN_COUNT = 0 #열린 타일의 수 CHECKED = [[0 for _ in range(WIDTH)] for _ in range(HEIGHT)] #타일의 상태를 이미 확인했는지 기록하는 배열 pygame.init() SURFACE = pygame.display.set_mode([WIDTH * SIZE, HEIGHT * SIZE]) FPSCLOCK = pygame.time.Clock() sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8') def bomb(field, x_pos, y_pos):#주위의 폭탄 수를 반환한다. #-1 0 1 순으로 좌표를 확인하여 폭탄수를 세어나간다. count = 0 for yoffset in range(-1,2): for xoffset in range(-1,2): xpos, ypos = (x_pos + xoffset, y_pos+ yoffset) if 0 <=xpos <WIDTH and 0<=ypos <HEIGHT and field[ypos][xpos] == BOMB: count += 1 return count def open_tile(field, x_pos, y_pos):# 타일을 오픈 global OPEN_COUNT if CHECKED[y_pos][x_pos]: #이미 확인된 타일 return #확인된후 무한반복을 막기위한 return 반환값 CHECKED[y_pos][x_pos] =True for yoffset in range(-1,2): for xoffset in range(-1,2): xpos, ypos = (x_pos + xoffset, y_pos + yoffset) if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and field[ypos][xpos] == EMPTY: field[ypos][xpos] = OPENED OPEN_COUNT += 1 count = bomb(field,xpos,ypos) if count == 0 and not (xpos== x_pos and ypos == y_pos): open_tile(field,xpos,ypos) def main(): smallfont = pygame.font.Font('NanumGothic.ttf',18) largefont = pygame.font.Font('NanumGothic.ttf',36) message_clear = largefont.render("축하합니다", True, (0, 255, 255)) message_over = largefont.render("아쉽습니다", True, (0, 255, 255)) message_F5 = smallfont.render("다시하려면 F5를 클릭하세요", True, (0,255,255)) message_rect = message_clear.get_rect() message_rect.center = (WIDTH*SIZE/2, HEIGHT*SIZE/2) game_over = False field = [[EMPTY for xpos in range(WIDTH)] for ypos in range(HEIGHT)] #폭탄을 설치, 같은곳에 폭탄을 설치하지않기위한 검사코드 count = 0 while count < BOMBS: xpos, ypos = randint(0, WIDTH-1), randint(0, HEIGHT-1) if field[ypos][xpos] == EMPTY: field[ypos][xpos] = BOMB count += 1 while True: for event in pygame.event.get(): if event.type ==QUIT: pygame.quit() sys.exit() if event.type == MOUSEBUTTONDOWN and event.button == 1: xpos, ypos = floor(event.pos[0] / SIZE), floor(event.pos[1]/ SIZE) if field[ypos][xpos] == BOMB: game_over = True else: open_tile(field,xpos,ypos) #그리기 SURFACE.fill((0,0,0)) for ypos in range(HEIGHT): for xpos in range(WIDTH): tile = field[ypos][xpos] rect = (xpos*SIZE,ypos*SIZE,SIZE,SIZE) if tile == EMPTY or tile == BOMB: pygame.draw.rect(SURFACE,(192,192,192),rect) if game_over and tile == BOMB: pygame.draw.ellipse(SURFACE,(225,225,0),rect) elif tile == OPENED: count = bomb(field,xpos,ypos) if count>0: num_image = smallfont.render("{}".format(count),True,(255,255,0)) SURFACE.blit(num_image,(xpos*SIZE+10,ypos*SIZE+10)) # 선 그리기 for index in range(0,WIDTH*SIZE, SIZE): pygame.draw.line(SURFACE, (96,96,96),(index,0),(index,HEIGHT*SIZE)) for index in range(0, HEIGHT * SIZE, SIZE): pygame.draw.line(SURFACE,(96,96,96),(0,index),(WIDTH*SIZE,index)) #메세지 나타내기 if OPEN_COUNT == WIDTH *HEIGHT - BOMBS: SURFACE.blit(message_clear,message_rect.topleft) elif game_over: SURFACE.blit(message_over, message_rect.topleft) SURFACE.blit(message_F5, message_rect.bottomleft) pygame.display.update() FPSCLOCK.tick(15) if __name__ == "__main__": main()
Java
UTF-8
9,061
2.328125
2
[]
no_license
package com.danqiu.myapplication.socket; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import com.danqiu.myapplication.utils.MLog; import org.greenrobot.eventbus.EventBus; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.Timer; import java.util.TimerTask; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * 使用服务连接Socket */ public class JWebSocketClientService extends Service { private final static String TAG="zz"; // ---------websocket心跳检测------------------ private static final long HEART_BEAT_RATE = 5 * 1000;//每隔10秒进行一次对长连接的心跳检测 // private Handler mHandler = new Handler(); // private Runnable heartBeatRunnable = new Runnable() { // @Override // public void run() { // Log.e(TAG, "心跳包检测websocket连接状态"+System.currentTimeMillis()); // if (socketClient != null) { // if (socketClient.isClosed()) { // reconnectWs(); // }else { // sendMsg("心跳检测消息"); // } // } else { // //如果client已为空,重新初始化连接 // socketClient = null; // initSocketClient(); // } // //每隔一定的时间,对长连接进行一次心跳检测 // mHandler.postDelayed(this, HEART_BEAT_RATE); // } // }; public JWebSocketClient socketClient; private JWebSocketClientBinder mBinder = new JWebSocketClientBinder(); public JWebSocketClientService() { } //用于Activity和service通讯 public class JWebSocketClientBinder extends Binder { public JWebSocketClientService getService() { return JWebSocketClientService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public boolean onUnbind(Intent intent) { MLog.i(TAG,"-------------onUnbind----"); closeConnect(); return super.onUnbind(intent); } @Override public void onCreate() { super.onCreate(); MLog.i(TAG,"-------------onCreate---------"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { MLog.i(TAG,"-------------onStartCommand---------"); //初始化websocket initSocketClient(); //mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测 startTimer(); return START_STICKY; } @Override public void onDestroy() { MLog.i(TAG,"-------------onDestroy---------"); closeConnect(); super.onDestroy(); } /** * 初始化websocket连接 */ private void initSocketClient() { URI uri = URI.create("ws://10.0.255.169:11211"); socketClient = new JWebSocketClient(uri) { @Override public void onMessage(String message) { Log.e(TAG, "收到服务消息:" + message); //接收到服务消息 eventbus或广播更新ui //EventBus.getDefault().post("收到服务消息:"+message); } @Override public void onOpen(ServerHandshake handshakedata) { super.onOpen(handshakedata); Log.e(TAG, "websocket连接成功"); EventBus.getDefault().post("连接成功"); } @Override public void onClose(int code, String reason, boolean remote) { Log.e(TAG, "websocket连接关闭"); EventBus.getDefault().post("连接关闭"); } }; connect(); } /** * 连接websocket */ private void connect() { new Thread() { @Override public void run() { try { //设置ssl证书 可不设置 // SSLSocketFactory factory = getSSL().getSocketFactory(); // socketClient.setSocket(factory.createSocket()); socketClient.connectBlocking(); // 或socketClient.connect(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } /** * 发送消息 * @param msg */ public void sendMsg(String msg) { if (null != socketClient&&socketClient.isOpen()) { Log.e(TAG, "发送的消息:" + msg); socketClient.onMessage(msg); }else { EventBus.getDefault().post("断开连接"); Log.e(TAG, "发送的消息:当前断连无法发送"); } } /** * 断开连接 */ public void closeConnect() { try { if (null != socketClient) { socketClient.close(); } // if(null != mHandler){ // mHandler.removeCallbacks(heartBeatRunnable); // } if(null!=handler){ handler.removeCallbacksAndMessages(null); stopTimer(); } } catch (Exception e) { e.printStackTrace(); } finally { socketClient = null; } } /** * 开启重连 */ private void reconnectWs() { //mHandler.removeCallbacks(heartBeatRunnable); handler.removeCallbacksAndMessages(null); new Thread() { @Override public void run() { try { Log.e(TAG, "开启重连"); socketClient.reconnectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } /** * ssl证书 * @return */ public SSLContext getSSL() { SSLContext sslContext=null; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sslContext; } private Timer mTimer=null;//定时器 private MyTimerTask mTimerTask=null; @SuppressLint("HandlerLeak") private Handler handler= new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: Log.e(TAG, "心跳包检测websocket连接状态"+System.currentTimeMillis()); if (socketClient != null) { if (socketClient.isClosed()) { reconnectWs(); }else { sendMsg("心跳检测消息"); } } else { //如果client已为空,重新初始化连接 socketClient = null; initSocketClient(); } break; } } }; class MyTimerTask extends TimerTask { @Override public void run() { Message msg = new Message(); msg.what = 1; //消息(一个整型值) handler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler //handler.sendEmptyMessage(1001); } } /** * 开启定时器 */ public void startTimer() { if (mTimer == null) { mTimer = new Timer(); } if(mTimerTask==null){ mTimerTask=new MyTimerTask(); } mTimer.schedule(mTimerTask, 3000, 1000*5); } /** * 停止定时器 */ public void stopTimer(){ if(mTimer!=null){ mTimer.cancel(); mTimer = null; } if(mTimerTask!=null){ mTimerTask.cancel(); mTimerTask = null; } } }
PHP
UTF-8
4,721
2.59375
3
[]
no_license
<?php # редактирование записи if (isset($_GET['uri']) and $page['uri'] = $_GET['uri']) { require_once 'db.php'; require_once 'simpleMySQLi.class.php'; # создание объекта для работы с БД $sql = new simpleMySQLi($db, pathinfo(__FILE__, PATHINFO_DIRNAME)); # поиск записи по URI $sql->str = 'select * from apodUnits where link like ' . $sql->varchar('%' . $page['uri']); $r = $sql->execute() ? $sql->assoc() : false; $sql->free(); if (!$sql->rows) { $page['err'] = 'запись не найдена'; goto foo; } $page = array_merge($page, $r); } else { $page['err'] = 'URI не задан или неверен'; } foo: ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><?php echo isset($page['err']) ? 'apod test' : $page['title'] ?></title> <link rel="stylesheet" href="/apod/spectre.min.css"> </head> <body> <?php if (isset($page['err'])) { ?> <div class="container" style="width: 128rem"> <ul class="breadcrumb"> <li class="breadcrumb-item"> <a href="/apod/">Home</a> </li> <li class="breadcrumb-item"> error </li> </ul> <div class="columns"> <div class="column col-12"> <p class="toast toast-danger">Ошибка: <?php echo $page['err']; ?></p> </div> </div> </div> <?php } else { ?> <input id="unit" type="hidden" data-id="<?php echo $page['id'] ?>"> <div class="container" style="width: 128rem"> <div class="columns"> <ul class="breadcrumb"> <li class="breadcrumb-item"> <a href="/apod/">Home</a> </li> <li class="breadcrumb-item"> <a href="/apod/<?php echo $page['uri']; ?>"><?php echo $page['title'] ?></a> </li> <li class="breadcrumb-item"> редактирование записи </li> </ul> <div class="column col-12"> <div class="form-horizontal"> <div class="form-group"> <div class="col-2"> <label class="form-label" for="title">заголовок:</label> </div> <div class="col-10"> <input class="form-input" type="text" id="title" placeholder="обязательно введите текст заголовка!" value="<?php echo htmlspecialchars($page['title']) ?>"> </div> </div> <div class="form-group"> <div class="col-2"> <label class="form-label" for="description">описание:</label> </div> <div class="col-10"> <textarea class="form-input" id="description" placeholder="введите сюда текст описания, но можно оставить и пустым" rows="3"><?php echo htmlspecialchars($page['description']) ?></textarea> </div> </div> <div class="form-group"> <div class="col-2"></div> <div class="col-2"> <button class="btn btn-block btn-primary" id="save">сохранить</button> </div> </div> </div> </div> </div> </div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> var settings = { loading : false }; $(function() { settings.id = $('#unit').data('id'); $('#save').on('click', {'action': 'save'}, actionHandler); $.ajaxSetup({ type : 'post', dataType : 'json', url : '/apod/ajax.php', cache : false, timeout : 300000, beforeSend : function() { settings.loading = true; }, complete : function() { settings.loading = false; }, error : function(xhr, status) { if (status == 'timeout') alert('Превышено время ожидания ответа'); } }); }); function actionHandler(e) { if (settings.loading || !settings.id) return; var post = {}; $.each(e.data, function(key, val) { post[key] = val; }); try { console.log(post) } catch(err) {}; post.id = settings.id; if (post.action == 'save') { var $this = $('#title'); post.title = $.trim($this.val()); if (post.title.length == 0) { alert('обязательно введите текст заголовка!'); $this.focus(); return; } post.description = $.trim($('#description').val()); $.ajax({ data : post, success : function(data) { if (data.ok) { location.href = location.href.replace('\/edit', ''); } else { alert(data.err); } } }); } } </script> <?php } ?> </body> </html>
JavaScript
UTF-8
2,357
2.734375
3
[]
no_license
const LANGUAGE_MAP = require('./languages'); function findTextNodes(nodeList) { return Array.from(nodeList) .filter((node) => node.nodeType === 3); } module.exports = function consumeIndex(document) { return Array.from(document.querySelectorAll('.sectiontable tr')) .filter((row) => row.childElementCount) .map((row) => { const data = {}; // Get IDs from list data.id = findTextNodes(row.querySelector('.col2, .col6').childNodes) .map((node) => node.textContent.trim()) .filter((text) => text); // Infer disc count from IDs const discs = data.id.length; // If only one ID, switch to a string if (data.id.length === 1) { data.id = data.id.shift(); } // Parse out just the title (ignore disc count) const titleColumn = row.querySelector('.col3, .col7'); data.title = titleColumn.firstChild.textContent .replace(/\[\s*\d DISCS\s*\]\]?/g, '') .replace(/^[\s-]+|[\s-]+$/g, '') // Parse out any extra title info, such as disc titles const extraHeadings = Array.from(row.querySelectorAll('.col3 > span > u, .col7 > span > u')); if (extraHeadings.length) { extraHeadings .forEach((heading) => { const headingTitle = heading.textContent.toLowerCase().replace(/^\s*|[\:\s]*$/g, ''); const headingDetailEntries = findTextNodes(heading.nextElementSibling.childNodes) .map((text) => ( text.textContent .replace(/[\s\n]+/g, ' ') .trim() )); if (headingDetailEntries.length === 1) { data[headingTitle] = headingDetailEntries.shift(); } else if (headingDetailEntries.length > 1) { data[headingTitle] = headingDetailEntries; } }); } data.discs = discs; // Parse language list const languages = row.querySelector('.col4, .col8').textContent.match(/\w+/g); if (languages) { data.languages = languages .map((language) => LANGUAGE_MAP[language.toLowerCase()] || language); } // Parse PSXDataCenter detail link const link = row.querySelector('.col1 a[href], .col5 a[href]'); if (link) { data.link = link.href; } return data; }); };
Python
UTF-8
2,260
3.078125
3
[]
no_license
#! /usr/bin/env python3 from pathlib import Path import git def search_upwards_for_file(d, filename): """Search in the current directory and all directories above it for a file of a particular name. https://stackoverflow.com/a/68994012/79125 Arguments: --------- filename :: Path, the directory to start looking in. filename :: string, the filename to look for. Returns ------- pathlib.Path, the location of the first file found or None, if none was found """ d = Path.cwd() root = Path(d.root) while d != root: attempt = d / filename if attempt.exists(): return attempt d = d.parent return None def remove_prefix(text, prefix): """Strip a prefix from beginning and return the new string. https://stackoverflow.com/a/16891418/79125 """ if text.startswith(prefix): text = text[len(prefix) :] return text root = search_upwards_for_file(Path.cwd(), ".git") repo = git.Repo(root) for remote in repo.remotes: remote.fetch() for local_branch in repo.branches: remote_branch = local_branch.tracking_branch() if not remote_branch or local_branch.commit == remote_branch.commit: continue remote_branch_name = remove_prefix( str(remote_branch), remote_branch.remote_name + "/" ) if local_branch.name != remote_branch_name: continue if repo.active_branch == local_branch: print( f"fast forwarding active branch '{local_branch}' to match upstream {remote_branch.remote_name}/{remote_branch}." ) print(" repo.git.pull(ff_only=True)") try: repo.git.pull(ff_only=True) except git.exc.GitCommandError as e: print(e) else: print(f"updating '{local_branch}' to match upstream {remote_branch}.") print(f" repo.git.fetch {local_branch}:{remote_branch_name}") # Seems that fetch with this refspec only works when the local branch # name matches the remote branch name. try: repo.git.fetch( remote_branch.remote_name, f"{local_branch}:{remote_branch_name}" ) except git.exc.GitCommandError as e: print(e)
Markdown
UTF-8
318
2.5625
3
[]
no_license
# Assignment-4.2 d=list(map(str,input("enter the words: ").split(" "))) def lenlet(x): return len(x) ans=list(map(lenlet, d)) print("lenght of words are: ", ans) a=input("Enter the charecter to check vowel: ") def vche(x): if x in "AEIOUaeiou": return True else: return False ans=list(map(vche, a)) print(ans)
Ruby
UTF-8
1,433
2.5625
3
[ "LGPL-2.1-or-later", "LGPL-3.0-only", "Apache-2.0" ]
permissive
/** * Validators can not delegate validation while registered as validators. */ rule no_validate_delegation_when_validating { env _e; env eF; address account = eF.msg.sender; bool _isAccountValidating = sinvoke _isValidating(_e,account); calldataarg arg; invoke delegateValidating(eF,arg); bool succeededDelegate = !lastReverted; assert( _isAccountValidating => !succeededDelegate, "Account successfully delegated validating even though it is already a validator" ); } /** * Accounts can not delegate votes if already voting. */ rule no_vote_delegation_when_voting { env _e; env eF; address account = eF.msg.sender; bool _isAccountVoting = sinvoke isVoting(_e,account); calldataarg arg; invoke delegateVoting(eF,arg); bool succeededDelegate = !lastReverted; assert( _isAccountVoting => !succeededDelegate, "Account successfully delegated voting even though it is already a voter" ); } /** * Accounts can not change account weight while already voting. */ rule no_weight_changing_when_voting(method f, address account) { env _e; uint256 _accountWeight = sinvoke _weight(_e,account); bool isAccountVoting = sinvoke isVoting(_e,account); env eF; calldataarg arg; invoke f(eF,arg); env e_; uint256 accountWeight_ = sinvoke _weight(e_,account); assert( isAccountVoting => _accountWeight == accountWeight_, "Method changed weight of account if voting" ); }
SQL
UTF-8
670
3.265625
3
[]
no_license
#针对某个库做授权 GRANT ALL ON ecshop.* TO study@'192.168.1.%'; #授权后show DATABASES可以看到ecshop #查看user权限 SELECT * FROM user WHERE user='study'; #查看db库权限 SELECT * FROM db; #收回库级别的权限 REVOKE ALL ON ecshop.* FROM study@'192.168.1.%'; #针对表级别授权 GRANT INSERT,UPDATE,SELECT ON ecshop.ecs_goods TO study@'192.168.1.%'; #查看表级别的权限 SELECT * FROM tables_priv; #提示:如果在开发中某张表的数据是原始数据,不能被删除,除了在PHP的业务逻辑控制 #还需要在运维层面进行数据权限控制 #mysql的权限控制甚至可以精确到列(自行看手册)
Java
UTF-8
293
1.59375
2
[]
no_license
package com.sdk.core; import android.app.Application; /** * author xander on 2017/6/9. * function 使用前可以先继承这个类 */ public class AppHelper extends Application { @Override public void onCreate() { super.onCreate(); InitSDK.init(this); } }
Java
UTF-8
6,875
1.789063
2
[]
no_license
package kidzania.vehiclespuzzlegame; import android.content.ClipData; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import kidzania.vehiclespuzzlegame.libClass.CountDownAnimation; import kidzania.vehiclespuzzlegame.libClass.DragObject; import static kidzania.vehiclespuzzlegame.libClass.DragObject.PosKananAtas; import static kidzania.vehiclespuzzlegame.libClass.DragObject.PosKananBawah; import static kidzania.vehiclespuzzlegame.libClass.DragObject.PosKiriAtas; import static kidzania.vehiclespuzzlegame.libClass.DragObject.PosKiriBawah; import static kidzania.vehiclespuzzlegame.libClass.DragObject.fixKananAtas; import static kidzania.vehiclespuzzlegame.libClass.DragObject.fixKananBawah; import static kidzania.vehiclespuzzlegame.libClass.DragObject.fixKiriAtas; import static kidzania.vehiclespuzzlegame.libClass.DragObject.fixKiriBawah; import static kidzania.vehiclespuzzlegame.libClass.GlobalVar.TAG_DRAG; import static kidzania.vehiclespuzzlegame.libClass.GlobalVar.TAG_MOBIL; public class SliceBan extends AppCompatActivity { TextView textView; CountDownAnimation countDownAnimation; int StartTimer = 3; private static int SPLASH_TIME_OUT = 500; CountDownAnimation.CountDownListener mListener; ImageView ban_belum_utuh, kanan_atas, kiri_bawah, kiri_atas, kanan_bawah; ImageView kosong_kiri_atas, kosong_kanan_atas, kosong_kiri_bawah, kosong_kanan_bawah; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slice_ban); TAG_MOBIL = "BAN"; textView = (TextView) findViewById(R.id.textView); initialization(); setDragComponent(); } private void initialization(){ ban_belum_utuh = (ImageView) findViewById(R.id.ban_belum_utuh); kanan_atas = (ImageView) findViewById(R.id.kanan_atas); kiri_bawah = (ImageView) findViewById(R.id.kiri_bawah); kiri_atas = (ImageView) findViewById(R.id.kiri_atas); kanan_bawah = (ImageView) findViewById(R.id.kanan_bawah); kosong_kiri_atas = (ImageView) findViewById(R.id.kosong_kiri_atas); kosong_kanan_atas = (ImageView) findViewById(R.id.kosong_kanan_atas); kosong_kiri_bawah = (ImageView) findViewById(R.id.kosong_kiri_bawah); kosong_kanan_bawah = (ImageView) findViewById(R.id.kosong_kanan_bawah); } private void setDragComponent(){ kosong_kanan_atas.setOnDragListener(new DragObject( SliceBan.this, R.drawable.kanan_atas, R.drawable.kosong_kanan_atas, PosKananAtas)); kosong_kanan_bawah.setOnDragListener(new DragObject( SliceBan.this, R.drawable.kanan_bawah, R.drawable.kosong_kanan_bawah, PosKananBawah)); kosong_kiri_atas.setOnDragListener(new DragObject( SliceBan.this, R.drawable.kiri_atas, R.drawable.kosong_kiri_atas, PosKiriAtas)); kosong_kiri_bawah.setOnDragListener(new DragObject( SliceBan.this, R.drawable.kiri_bawah, R.drawable.kosong_kiri_bawah, PosKiriBawah)); kosong_kanan_atas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fixKananAtas = false; kanan_atas.setVisibility(View.VISIBLE); kosong_kanan_atas.setImageResource(R.drawable.kosong_kanan_atas); } }); kosong_kanan_bawah.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fixKananBawah = false; kanan_bawah.setVisibility(View.VISIBLE); kosong_kanan_bawah.setImageResource(R.drawable.kosong_kanan_bawah); } }); kosong_kiri_atas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fixKiriAtas = false; kiri_atas.setVisibility(View.VISIBLE); kosong_kiri_atas.setImageResource(R.drawable.kosong_kiri_atas); } }); kosong_kiri_bawah.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fixKiriBawah = false; kiri_bawah.setVisibility(View.VISIBLE); kosong_kiri_bawah.setImageResource(R.drawable.kosong_kiri_bawah); } }); kanan_atas.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { TAG_DRAG = "KANAN_ATAS"; ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(data, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } }); kanan_bawah.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { TAG_DRAG = "KANAN_BAWAH"; ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(data, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } }); kiri_atas.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { TAG_DRAG = "KIRI_ATAS"; ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(data, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } }); kiri_bawah.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { TAG_DRAG = "KIRI_BAWAH"; ClipData data = ClipData.newPlainText("", ""); View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); view.startDrag(data, shadowBuilder, view, 0); view.setVisibility(View.INVISIBLE); return true; } }); } @Override public void onBackPressed() { } }
Markdown
UTF-8
3,053
2.5625
3
[]
no_license
# What does Webpack do? * Compress * Packaging * Compile of files (Less, Sass...) * Scaffold * Generating... # Set up Webpack ## Install Webpack npm i webpack-cli -g ## Webpack file webpack.config.js<br/> This is the 'default'. But you can change it if you really want to. ## Run Webpack webpack # Webpack file ## mode: how it is optimized * **none**: no optimization<br/> * **development**: output console info, set up process.env.NODE_ENV<br/> * **production**: highest optimization: compress, ignore... ## entry single entry ---- SPA<br/> multi entries ---- MPA ## output must be a json ``` { path: must be absolute path: path.resolve() filename: filename } ``` # Loaders Deal with data besides JS and JSON ## css-loader && style-loader loaders have order, they are executed from back to front<br/> `use: ['style-loader', 'css-loader']`: first css-loader, then style-loader<br/> * **css-loader**: read and parse css (no compile errors) and put into bundle<br/> * **style-loader**: get the result of css-loader, put result into <style> tag ## postcss-loader && autoprofixer * **postcss-loader**: add browser prefix * **autoprofixer**: tell postcss-loaders which to add/not add (>= 5%) `npx autoprefixer --info`: Show target browsers and used prefixes<br/> "browerselist" in package.json ## file-loader && url-loader * **file-loader**: options -> outputPath & publicPath * **url-loader**: images smaller than limit will be stored as base64 in css directly Usually use url-loader for some small things like: small icons....<br/> url-loader cannot be used without file-loader, as it uses file-loader when greater than limit ## less-loader && babel-loader npm i less-loader less<br/> npm i babel-loader @babel/core @babel/preset-env<br/> `devtool: 'source-map'` # dev-server * **webpack**: core * **webpack-cli**: command line * **webpack-dev-server**: server Have to put `"start": "webpack-dev-server"` into package.json. Cannot run `webpack-dev-server` directly, because it is webpack-cli that run webpack-dev-server<br/> If webpack.config.js is updated, you need to restart the dev-server<br/> dev-server will not put compiled files into folders like /dest, but put them into memory, so bundle.js in under http://localhost:8080/bundle.min.js<br/> And you cannot use /dest for file reference, remove /dest<br/> Putting the compiled files into memory will make the hot update fast, much faster than reading and writing to disk<br/> If you want to have production compilation, you need: `"build": "xxx"`<br/> So that is why we need separate config for dev and production<br/> `module.exports = function (env, argv) {}`<br/> env can be passed by `webpack --env.production` ## Handle HTML * **html-webpack-plugin**: auto generate HTML file under /dest This can use your index.html file as the template # eslint ## eslint `npm i eslint eslint-loader` `node node_modules/eslint/bin/eslint.js --init`: init eslint<br/> OR<br/> `"eslint_init": "eslint --init"` in package.json # Testing `npm i jest jest-webpack`<br/> `"test_jest": "jest"`
Java
UTF-8
6,171
2.125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2013 International Health Terminology Standards Development Organisation. * * 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 gov.vha.isaac.ochre.api.util; import java.util.Arrays; import java.util.UUID; import java.util.function.BiConsumer; import gov.vha.isaac.ochre.api.DataTarget; import gov.vha.isaac.ochre.api.Get; import gov.vha.isaac.ochre.api.component.sememe.version.dynamicSememe.DynamicSememeData; import gov.vha.isaac.ochre.api.component.sememe.version.dynamicSememe.DynamicSememeDataType; import gov.vha.isaac.ochre.api.component.sememe.version.dynamicSememe.dataTypes.DynamicSememeNid; import gov.vha.isaac.ochre.api.logic.LogicalExpression; /** * * @author kec */ public class UuidFactory { private static final String MEMBER_SEED_STRING = "MEMBER_SEED_STRING"; /** * * @param namespace * @param assemblage * @param refComp * @param le * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForLogicGraphSememe(UUID namespace, UUID assemblage, UUID refComp, LogicalExpression le, BiConsumer<String, UUID> consumer) { byte[][] leBytes = le.getData(DataTarget.EXTERNAL); return UuidT5Generator.get(namespace, createUuidTextSeed(assemblage.toString(), refComp.toString(), toString(leBytes)), consumer); } private static String toString(byte[][] b) { StringBuilder temp = new StringBuilder(); temp.append("["); for (byte[] bNested : b) { temp.append(Arrays.toString(bNested)); } temp.append("]"); return temp.toString(); } /** * * @param namespace * @param assemblage * @param refComp * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForMemberSememe(UUID namespace, UUID assemblage, UUID refComp, BiConsumer<String, UUID> consumer) { return UuidT5Generator.get(namespace, createUuidTextSeed(assemblage.toString(), refComp.toString(), MEMBER_SEED_STRING), consumer); } /** * * @param namespace * @param assemblage * @param refComp * @param data * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForDynamicSememe(UUID namespace, UUID assemblage, UUID refComp, DynamicSememeData[] data, BiConsumer<String, UUID> consumer) { StringBuilder temp = new StringBuilder(); temp.append(assemblage.toString()); temp.append(refComp.toString()); temp.append(data == null ? "0" : data.length + ""); if (data != null) { for (DynamicSememeData d : data) { if (d == null) { temp.append("null"); } else { temp.append(d.getDynamicSememeDataType().getDisplayName()); if (d.getDynamicSememeDataType() == DynamicSememeDataType.NID) { temp.append(Get.identifierService().getUuidPrimordialForNid(((DynamicSememeNid)d).getDataNid())); } else { temp.append(new String(ChecksumGenerator.calculateChecksum("SHA1", d.getData()))); } } } } return UuidT5Generator.get(namespace, temp.toString(), consumer); } /** * * @param namespace * @param assemblage * @param refComp * @param component * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForComponentNidSememe(UUID namespace, UUID assemblage, UUID refComp, UUID component, BiConsumer<String, UUID> consumer) { return UuidT5Generator.get(namespace, createUuidTextSeed(assemblage.toString(), refComp.toString(), component.toString()), consumer); } /** * * @param namespace * @param assemblage * @param refComp * @param value * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForStringSememe(UUID namespace, UUID assemblage, UUID refComp, String value, BiConsumer<String, UUID> consumer) { return UuidT5Generator.get(namespace, createUuidTextSeed(assemblage.toString(), refComp.toString(), value), consumer); } /** * * @param namespace * @param assemblage * @param concept * @param caseSignificance * @param descriptionType * @param language * @param descriptionText * @param consumer an optional parameter that will get a callback with the string used to calculate the UUID - no impact on generation * @return */ public static UUID getUuidForDescriptionSememe(UUID namespace, UUID assemblage, UUID concept, UUID caseSignificance, UUID descriptionType, UUID language, String descriptionText, BiConsumer<String, UUID> consumer) { return UuidT5Generator.get(namespace, createUuidTextSeed(assemblage.toString(), concept.toString(), caseSignificance.toString(), descriptionType.toString(), language.toString(), descriptionText), consumer); } /** * Create a new Type5 UUID using the provided name as the seed in the * configured namespace. * * Throws a runtime exception if the namespace has not been configured. */ private static String createUuidTextSeed(String... values) { StringBuilder uuidKey = new StringBuilder(); for (String s : values) { if (s != null) { uuidKey.append(s); uuidKey.append("|"); } } if (uuidKey.length() > 1) { uuidKey.setLength(uuidKey.length() - 1); } else { throw new RuntimeException("No string provided!"); } return uuidKey.toString(); } }
Java
UTF-8
539
1.789063
2
[ "Apache-2.0" ]
permissive
package pl.allegro.tech.hermes.tracker.frontend; import java.util.Map; public interface LogRepository { void logPublished(String messageId, long timestamp, String topicName, String hostname, Map<String, String> extraRequestHeaders); void logError(String messageId, long timestamp, String topicName, String reason, String hostname, Map<String, String> extraRequestHeaders); void logInflight(String messageId, long timestamp, String topicName, String hostname, Map<String, String> extraRequestHeaders); void close(); }
Java
UTF-8
2,749
3.296875
3
[]
no_license
package algo; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class Main { public static void main(String args[]) throws IOException { new Task().run(); } static class Task { private final int N = 8; private char[][] map = new char[N][N]; private StringTokenizer st = null; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); private StringTokenizer getStringTokenizer() throws IOException { return new StringTokenizer(br.readLine(), " "); } private void input() throws IOException { for(int i=0; i<N; i++) { st = getStringTokenizer(); char[] input = st.nextToken().toCharArray(); for(int j=0; j<N; j++) { map[i][j] = input[j]; } } } private boolean checkRow() { int cnt = 0; for(int i=0; i<N; i++) { cnt = 0; for(int j=0; j<N; j++) { if(map[i][j] == '*') { cnt++; } } if(cnt != 1) return false; } return true; } private boolean checkCol() { int cnt = 0; for(int j=0; j<N; j++) { cnt = 0; for(int i=0; i<N; i++) { if(map[i][j] == '*') { cnt++; } } if(cnt != 1) return false; } return true; } private boolean checkDiagonal() { int cnt = 0; for(int i=0; i<N; i++) { cnt = 0; for(int j=0; j<N; j++) { int x = i; int y = j; cnt = 0; while(true) { if(!checkArea(x, y)) break; if(map[x][y] == '*') { cnt++; } x = x+1; y = y+1; } if(cnt > 1) return false; } } for(int i=0; i<N; i++) { cnt = 0; for(int j=N-1; j>=0; j--) { int x = i; int y = j; cnt = 0; while(true) { if(!checkArea(x, y)) break; if(map[x][y] == '*') { cnt++; } x = x+1; y = y-1; } if(cnt > 1) return false; } } return true; } private boolean checkCount() { int cnt = 0; for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { if(map[i][j] == '*') cnt++; } } if(cnt == 8) return true; else return false; } private boolean checkArea(int x, int y) { return x>=0 && x<N && y>=0 && y<N; } private boolean checkQueen() { return checkRow() && checkCol() && checkDiagonal() && checkCount(); } public void run() throws IOException { input(); if(checkQueen()) bw.write("valid"); else bw.write("invalid"); close(); } private void close() throws IOException { bw.close(); br.close(); } } }
Java
UTF-8
2,961
3.59375
4
[]
no_license
package com.ganht.algorithm.leetcode; import com.ganht.algorithm.base.BinaryTreeProblem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Given a binary tree root. Split the binary tree into two subtrees by removing 1 edge such that the product of the sums * of the subtrees are maximized. * * Since the answer may be too large, return it modulo 10^9 + 7. * * * * Example 1: * * * * Input: root = [1,2,3,4,5,6] * Output: 110 * Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) * Example 2: * * * * Input: root = [1,null,2,3,4,null,null,5,6] * Output: 90 * Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6) * Example 3: * * Input: root = [2,3,9,10,7,8,6,5,4,11,1] * Output: 1025 * Example 4: * * Input: root = [1,1] * Output: 1 * * * Constraints: * * Each tree has at most 50000 nodes and at least 2 nodes. * Each node's value is between [1, 10000]. * @author haitian.gan */ public class MaximumProductOfSplittedBinaryTree extends BinaryTreeProblem { private Map<TreeNode, Integer> cache = new HashMap<>(); private int maxProduct = 0; private int totalSum = 0; private List<Integer> allSums = new ArrayList<>(); // 思路是对的,差他妈的最后一步 public int maxProduct1(TreeNode root) { // long is a 64-bit integer. long totalSum = treeSum(root); long best = 0; for (long sum : allSums) { best = Math.max(best, sum * (totalSum - sum)); } // We have to cast back to an int to match return value. return (int)(best % 1000000007); } private int treeSum(TreeNode subroot) { if (subroot == null) return 0; int leftSum = treeSum(subroot.left); int rightSum = treeSum(subroot.right); int totalSum = leftSum + rightSum + subroot.val; allSums.add(totalSum); return totalSum; } public int maxProduct(TreeNode root) { calSum(root); this.totalSum = cache.get(root); traverse(root); return maxProduct; } private void traverse(TreeNode node) { if (node == null) { return; } traverse(node.left); traverse(node.right); Integer sum1 = cache.get(node); int sum = sum1 * (this.totalSum - sum1); if (sum > maxProduct) { maxProduct = sum; } } private int calSum(TreeNode node){ if(node == null){ return 0; } int sum = node.val + calSum(node.left) + calSum(node.right); cache.put(node, sum); return sum; } public static void main(String[] args){ Integer[] input = {1,null,2,3,4,null,null,5,6}; new MaximumProductOfSplittedBinaryTree().maxProduct(buildTreeFromArray(input)); } }
Java
UTF-8
1,288
2.5
2
[]
no_license
package exp45users; public class users { private String name; private String pwd; private String sex; private String [] hobbies; private String hobbies1; private String hobbies2; private String hobbies3; private String hobbies4; public String getHobbies1() { return hobbies1; } public void setHobbies1(String hobbies1) { this.hobbies1 = hobbies1; } public String getHobbies2() { return hobbies2; } public void setHobbies2(String hobbies2) { this.hobbies2 = hobbies2; } public String getHobbies3() { return hobbies3; } public void setHobbies3(String hobbies3) { this.hobbies3 = hobbies3; } public String getHobbies4() { return hobbies4; } public void setHobbies4(String hobbies4) { this.hobbies4 = hobbies4; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String[] getHobbies() { return hobbies; } public void setHobbies(String[] hobbies) { this.hobbies = hobbies; } }
Java
UTF-8
758
2.359375
2
[]
no_license
package lu.ftn.kpservice.model.dto; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class BitcoinPaymentDTO { @NotNull @NotBlank private String token; private String pairingCode; public BitcoinPaymentDTO() { } public BitcoinPaymentDTO(@NotNull @NotBlank String token, String pairingCode) { this.token = token; this.pairingCode = pairingCode; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getPairingCode() { return pairingCode; } public void setPairingCode(String pairingCode) { this.pairingCode = pairingCode; } }
C++
UTF-8
1,063
2.546875
3
[]
no_license
/************************************************************************* > File Name: 1005-rooks.cpp > Author: mengshangqi > Mail: mengshangqi@gmail.com > Created Time: 2014年03月14日 星期五 21时13分58秒 ************************************************************************/ #include<iostream> #include<cstdio> #include<set> #include<map> #include<algorithm> #include<vector> #include<cstring> #include<string> #include<bitset> #include<sstream> #include<queue> #include<stack> #include<cmath> using namespace std; typedef long long ll; ll c[35][35]; void init() { for(int i=0;i<=30;i++) { c[i][0]=1; c[i][i]=1; } for(int i=2;i<=30;i++) { for(int j=1;j<i;j++) { c[i][j]=c[i-1][j]+c[i-1][j-1]; } } } int main() { //freopen("/home/mengshangqi/input.txt","r",stdin); int t; int n,m; init(); cin>>t; for(int cs=1;cs<=t;cs++) { cin>>n>>m; cout<<"Case "<<cs<<": "; if(m>n) { cout<<0<<endl; continue; } ll ans=c[n][m]; ans*=ans; while(m>1) { ans*=m; m--; } cout<<ans<<endl; } return 0; }
Python
UTF-8
705
2.609375
3
[]
no_license
from keras.models import model_from_json import numpy as np class DiseaseDetectionModel(object): RICEDISEASELIST = ["Blast", "Blight", "Brownspot", "Sheath Blight", "Tungro"] def __init__(self, model_json_file, model_weight_file): with open(model_json_file, "r") as json_file: loaded_model_json = json_file.read() self.loaded_model = model_from_json(loaded_model_json) self.loaded_model.load_weights(model_weight_file) self.loaded_model._make_predict_function() def predict_disease(self, img): self.preds = self.loaded_model.predict(img) return DiseaseDetectionModel.RICEDISEASELIST[np.argmax(self.preds)]
C#
UTF-8
3,464
2.671875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; // Main author: Hugo Bailey // Additional author: N/A // Description: Used to store data about a quest // Development window: Prototype phase // Inherits from: ScriptableObject [CreateAssetMenu(fileName = "Quest data", menuName = "Quests/Quest data/New single quest", order = 1)] [System.Serializable] public class QuestData : ScriptableObject { [Header("Quest attributes (Shown to players)")] [TextArea(1, 4)] public string questName; // Stores "name" of quest [TextArea(5, 10)] public string questDescription; // Stores description of quest (shown to player when offered quest) [TextArea(5, 10)] public string questCompleteDialogue; // Dialogue that's spoken when quest is completed [Header("Quest objectives, rewards, quest line progression")] [SerializeField] public List<QuestData> nextQuests = new List<QuestData>(); // List of quests that lead on from this one (quest line functionality) public List<ItemGroup> rewards = new List<ItemGroup>(); // Rewards given to the player for completing this quest public List<QuestObjective> objectives = new List<QuestObjective>(); // Objectives needed to complete this quest [Header("Hand-in data")] public string handInNPCName; // ID of NPC that completes this quest public string handOutNPCName; // ID of NPC that hands out this quest public string questLineName = ""; // Name of the "quest line" quest is a part of public bool questCompleted = false; // Flags if all quest objectives have been completed public bool questHandedIn = false; // Flags if quest has been handed in yet public bool handInToGiver = true; // Used to determine if quest needs handing in to NPC or is completed as soon as all objectives are met // Returns whether all quest objectives have been completed public bool CheckCompleted() { int objectiveCount = 0; // Cycles each objective associated with quest - if it's completed, incriment objectiveCount foreach(QuestObjective task in objectives) { if(task.taskComplete) { ++objectiveCount; } else { // If quest is not already flagged as complete, check if it's just been completed if (task.CheckCcompleted()) { task.taskComplete = true; ++objectiveCount; } } } // If all quests have been completed, flag questCompleted as true questCompleted = (objectiveCount == objectives.Count); return questCompleted; //if(objectiveCount == objectives.Count) //{ // questCompleted = true; // return true; //} // //return false; } }
Python
UTF-8
6,628
2.71875
3
[]
no_license
import re import glob import os import logging import os.path as op import numpy as np def last_checkpoint(prefixes, snapshot_interval=None, max_iter=None, snapshot_ext=".solverstate", weights_ext=".caffemodel"): """Find the last checkpoints inside given prefix paths Look at the paths in prefixes, and return once found :param prefixes: paths to check for the solverstate and weights :type prefixes: list or str :param snapshot_interval: valid snapshot intervals :param max_iter: maximum number of iterations that could be found :param snapshot_ext: file extension of snapshot (pass None to ignore snapshots) :param weights_ext: file extension of saved weights (pass None to ignore weights) :return: snapshot, iterations, weights :rtype: (str, int, str) """ if not isinstance(prefixes, list): prefixes = [prefixes] if not snapshot_interval: snapshot_interval = 1 model_iter_pattern = None solver_iter_pattern = None if snapshot_ext: solver_iter_pattern = re.compile(r'iter_(?P<ITER>\d+){}$'.format(re.escape(snapshot_ext))) if weights_ext: model_iter_pattern = re.compile(r'iter_(?P<ITER>\d+){}$'.format(re.escape(weights_ext))) snapshot = '' iterations = -1 model_iterations = 0 weights = '' found_solver = False found_model = False for prefix in prefixes: path = op.dirname(prefix) base = op.basename(prefix) if not op.isdir(path): if path: logging.info('last_checkpoint ignored invalid path: "{}"'.format(path)) continue if iterations >= 0: found_solver = True if model_iterations: found_model = True if found_solver and found_model: break solver = model = None for fname in os.listdir(path): if not fname.startswith(base): continue if solver_iter_pattern: solver = re.search(solver_iter_pattern, fname) if not found_solver else None if model_iter_pattern: model = re.search(model_iter_pattern, fname) if not found_model else None if solver: iters = int(solver.group('ITER')) if iters == max_iter: found_solver = True if not found_solver and (iters % snapshot_interval != 0 or iters > max_iter): logging.info('Ignore snapshot interval: {} snapshot: {} max_iter: {}'.format( snapshot_interval, fname, max_iter)) elif iters > iterations or found_solver: snapshot = op.join(path, fname) iterations = iters if model: iters = int(model.group('ITER')) if iters == max_iter: found_model = True if not found_model and (iters % snapshot_interval != 0 or iters > max_iter): logging.info('Ignore snapshot interval: {} snapshot: {} max_iter: {}'.format( snapshot_interval, fname, max_iter)) elif iters > model_iterations or found_model: weights = op.join(path, fname) model_iterations = iters if iterations < 0: iterations = 0 return snapshot, iterations, weights def iterate_weights(prefixes, snapshot_intervals, max_iters, caffemodel=None, weights_ext=".caffemodel", processed_ext=".report.class_ap.json"): """Iterate over all the models without evaluation result Find in descending order, in each of the paths in prefixes :param prefixes: paths to check for the solverstate and weights :type prefixes: list :param snapshot_intervals: list of valid snapshot intervals :type snapshot_intervals: list :param max_iters: lsit of maximum number of iterations that could be found :type max_iters: list :param caffemodel: single caffemodel path to return :param weights_ext: file extension of saved weights (pass None to ignore weights) :param processed_ext: file extension of the already-processed model :return: index: index of the prefix iteration: total iterations already computed cur_iter: current iteration number weights: caffe weights fiel paht done: if all the prefixes have reached the max_iter more: if there are more model weights :rtype: (int, int, int, str, bool, bool) """ assert len(prefixes) == len(snapshot_intervals) == len(max_iters) model_iter_pattern = re.compile(r'iter_(?P<ITER>\d+){}$'.format(re.escape(weights_ext))) if caffemodel: model = re.search(model_iter_pattern, caffemodel) if not model: logging.error("caffemodel {} does not have standard filename pattern".format(caffemodel)) yield 0, 1, caffemodel, True, False return iters = int(model.group('ITER')) yield 0, 0, iters, caffemodel, True, False return iteration = 0 more = False done = [False] * len(prefixes) for idx, (prefix, interval, max_iter) in enumerate(zip(prefixes, snapshot_intervals, max_iters)): model_iterations = 0 weights = '' path = op.dirname(prefix) base = op.basename(prefix) done[idx] = False for fname in os.listdir(path): if not fname.startswith(base): continue model = re.search(model_iter_pattern, fname) if not model: continue iters = int(model.group('ITER')) if iters == max_iter: done[idx] = True elif iters % interval != 0 or iters > max_iter: logging.debug('Ignore snapshot interval: {} snapshot: {} max_iter: {}'.format( interval, fname, max_iter )) continue new_weights = op.join(path, fname) if len(glob.glob(new_weights + ".*" + processed_ext)) == len(prefixes): # model is already evaluated against all of its test data iteration += interval continue if iters == max_iter: logging.info('Last model checkpoint found: {}'.format(fname)) more = True if iters > model_iterations: model_iterations = iters weights = new_weights if weights: yield idx, iteration, model_iterations, weights, np.all(done), more
PHP
UTF-8
339
2.78125
3
[]
no_license
<?php namespace Awuxtron\Web3\Exceptions; use Exception; class HexException extends Exception { /** * The exception value. */ protected mixed $value; /** * Set the exception value. */ public function setValue(mixed $value): static { $this->value = $value; return $this; } }
Java
UTF-8
793
2.28125
2
[]
no_license
package de.christopherstock.lib.io.d3ds; import de.christopherstock.lib.ui.*; class LibMaxMaterial { public String name = null; public LibColors color = null; public float offsetU = 0.0f; public float offsetV = 0.0f; public float tilingU = 0.0f; public float tilingV = 0.0f; public LibMaxMaterial( String name, LibColors color, float offsetU, float offsetV, float tilingU, float tilingV ) { this.name = name; this.color = color; this.offsetU = offsetU; this.offsetV = offsetV; this.tilingU = tilingU; this.tilingV = tilingV; } }
Markdown
UTF-8
9,053
3.234375
3
[ "CC-BY-4.0" ]
permissive
--- description: These techniques allow breaking large changes into chunks of smaller changes that don't break the system last_modified: 2022-01-31T10:44:35.327Z --- # Branch By Abstraction and application strangulation ## Contents - [Branch by abstraction](#branch-by-abstraction) - [Basic idea](#basic-idea) - [Anatomy of the abstraction layer](#anatomy-of-the-abstraction-layer) - [Why not real branches?](#why-not-real-branches) - [Real-world example](#real-world-example) - [Application strangulation (also known as Strangler pattern)](#application-strangulation-also-known-as-strangler-pattern) - [Basic idea](#basic-idea-1) - [Real-world example](#real-world-example-1) - [Resources](#resources) ## Branch by abstraction ### Basic idea Branch by Abstraction is useful if the team needs to replace a certain component of the system, but this needs to be spread out over multiple commits. Basically, this is how it works: - Write an abstraction layer on top of the component you need to replace - Make clients call the abstraction layer instead of the original component - Could happen in multiple commits - Now, use the abstraction layer to switch over to the new component as it is being built. The new layer of indirection could already forward some calls to the new component, or there could be a toggle indicating which component implementation to use. - Will typically happen in multiple commits - Once the new component is fully built and the abstraction layer doesn’t call the old component anymore, get rid of the old component - Get rid of the abstraction layer ### Anatomy of the abstraction layer Several possibilities: - Interface that both old and new implementation implement - Allows you to choose which of the implementations (old or new) to instantiate when a consumer requires an object conforming to that interface - Actual class that delegates to old or new implementation as needed - Could be based on some flag (built into the code or in a configuration file) that allows developers working on the new implementation to test it while others are not affected by it yet. - Could use the new implementation for some calls and the old implementation for others. - Actual layer in application’s architecture - Example: if you are moving to a new persistence framework and you are using a layered architecture, you could already have an abstraction layer in the form of repositories that encapsulate all interaction with the database. This could allow you to make the change one repository at a time, while repositories you didn’t touch are still using the old persistence framework ### Why not real branches? Drawbacks of using branches for these kinds of big changes: - Making large changes means that your branch will probably touch a large part of the codebase. The fact that the changes are large also means you will probably spend a long time working on them, giving the rest of the team plenty of time to make changes to the parts of the codebase you touch in a way that conflicts with what you are doing. - It’s even worse if your team also uses long-lived branches for regular feature development, because that increases the chances that the rest of the team are making incompatible changes that you don’t know about until the team has already invested a lot of time in them. Benefits Branch by Abstraction: - Allows making changes in an incremental way while keeping the system running at all times - You can still collaborate with other developers in one single branch, meaning that potential conflicts are detected immediately - Because the system keeps on working, you could choose to release a working version of the system containing a half-completed migration See also [Trunk Based Development](./Trunk-Based-Development.md) ### Real-world example See [Move Fast and Fix Things](https://github.blog/2015-12-15-move-fast/) GitHub saw the need to replace a critical part of their platform (merges) with a new implementation - change needs to happen without downtimes while deploying on average 60 times a day - unacceptable to break existing functionality The solution: branch by abstraction! Their abstraction layer: [Scientist](https://github.com/github/scientist) - wraps both old and new behavior - always runs the old behavior - decides whether to also run new behavior or not - measures the durations of all behaviors - always returns what old behavior returns - swallows and logs any exceptions thrown by new behavior - logs any discrepancies between the results obtained from the old and new behavior - similar to the _Duplicate Writes_ and _Dark Reads_ in Expand-Contract data migrations (see [Data schema migration](../data/Data-schema-migration.md)) This allowed them to test the new implementation on actual production data, comparing both results and performance. After fixing some bugs, it allowed them to be confident enough to completely switch over to the new behavior in production ## Application strangulation (also known as Strangler pattern) ### Basic idea Very similar to Branch by Abstraction, but operates at different level: - Branch by Abstraction happens within a single codebase, using abstraction mechanisms of the programming language - Application strangulation could be used to migrate between different applications potentially written in completely different languages. The abstraction layer typically comes in the form of a reverse proxy that decides whether to call the API of the old application or the API of the new application (this could depend on the specific call being made and will likely change throughout the migration) See the real-world example below, or another real-world example: [How Shopify Reduced Storefront Response Times with a Rewrite](https://engineering.shopify.com/blogs/engineering/how-shopify-reduced-storefront-response-times-rewrite). ### Real-world example See [Bye bye Mongo, Hello Postgres](https://www.theguardian.com/info/2018/nov/30/bye-bye-mongo-hello-postgres) The Guardian used application strangulation to move from MongoDB to PostgreSQL, keeping their system working while performing the migration. MongoDB would stay their main source of truth until the migration was completed, but in the meantime they also needed to make sure that all of their data got migrated into PostgreSQL and that the system was able to run on PostgreSQL only once fully switched over. Branch By Abstraction could have been an option here, but there was very little separation of concerns in the original application so introducing an abstraction layer would have been costly and risky. Instead, decision was made to build a whole new application next to the old one. Once the new application was running next to the other one, the team created a reverse proxy that worked as follows: 1. Accept incoming traffic 2. Forward the traffic to the primary API and return the result to the caller 3. Asynchronously forward the traffic to the secondary API 4. Compare the results from both APIs and log any differences After migrating the existing data, any differences between the results from both APIs would indicate bugs that needed to be solved. If the team got to the point where there were no differences being logged, they could be confident that the new API works in the same way as the old API. Switching the primary and secondary API in the proxy allowed the team to essentially switch to the new API while still having a fallback in the form of the old API that was still receiving all requests. The migration of existing data itself also made use of the fact that both applications had the same API. The flow was as follows: 1. Get content from the API backed by MongoDB 2. Save that content to the API backed by PostgreSQL 3. Get the content from the API backed by PostgreSQL 4. Verify that the responses from (1) and (3) are identical Finally, when everything was working with the new API as primary, the team got rid of the proxy and the old API in order to complete the migration. Note that, during the period in which both APIs were running next to each other, calls for both reads and writes were being forwarded to each API and the results were compared. This is very similar to the _Duplicate Writes_ and _Dark Reads_ in Expand-Contract data migrations (see [Data schema migration](../data/Data-schema-migration.md)) ## Resources - [Introducing Branch By Abstraction](https://paulhammant.com/blog/branch_by_abstraction.html) - [Branch By Abstraction](https://trunkbaseddevelopment.com/branch-by-abstraction/) - [BranchByAbstraction](https://martinfowler.com/bliki/BranchByAbstraction.html) - [Make Large Scale Changes Incrementally with Branch By Abstraction](https://continuousdelivery.com/2011/05/make-large-scale-changes-incrementally-with-branch-by-abstraction/) - [Application strangulation](https://trunkbaseddevelopment.com/strangulation/)
Java
UTF-8
513
2.265625
2
[]
no_license
package com.opensoft.motanx.proxy.support; import com.opensoft.motanx.proxy.ProxyFactory; import com.opensoft.motanx.rpc.Invoker; /** * Created by kangwei on 2016/8/28. */ public abstract class AbstractProxyFactory implements ProxyFactory { @Override public <T> T getProxy(Class<T> cls, Invoker<T> invoker) { if (invoker == null) { return null; } return doGetProxy(cls, invoker); } protected abstract <T> T doGetProxy(Class<T> cls, Invoker<T> invoker); }
Python
UTF-8
1,227
2.84375
3
[]
no_license
from DataLayer.OpenFile import * from DataLayer.read_pastFlights import * from ModelClasses.flightRoute import * from LogicLayer.Date import * from ModelClasses.Voyage import* def voyageStatus(dep, ret, input_date, input_time): inptDay = str(input_date[0:2]) inptMonth = str(input_date[3:5]) inptYear = str(input_date[6:10]) stdInptDate = inptYear + '-' + inptMonth + '-' + inptDay + 'T' + input_time #innslegin dagsetning a standard formati status=[] #fer i gegnum oll dep og ret flug og finn viðeigandi status flugs for i in range(len(dep)): if dep[i].departure < stdInptDate < dep[i].arrival: status.append('In air outbound') elif ret[i].departure < stdInptDate < ret[i].arrival: status.append('In air homebound') elif stdInptDate < ret[i].departure and stdInptDate > dep[i].arrival: status.append('On ground at destination') elif stdInptDate > ret[i].arrival and stdInptDate > ret[i].departure and stdInptDate > dep[i].arrival and stdInptDate > dep[i].departure: status.append('Completed') else: status.append('Awaiting departure') return status #skila streng með status flugs ut
TypeScript
UTF-8
3,961
2.53125
3
[]
no_license
import {SessionCollection} from "../Collections/SessionCollection"; import {Session} from "../Sessions/Session"; import {SkatingEvent} from "../SkatingEvent"; import {SkatingEventCollection} from "../Collections/SkatingEventCollection"; import {SessionSchedule} from "./SessionSchedule"; import {ScheduledSession} from "../Sessions/ScheduledSession"; import {ScheduledSessionCollection} from "../Collections/ScheduledSessionCollection"; import {SessionLike, SessionType} from "../../contracts/AppContracts"; import {CreditStateData} from "../../contracts/data/DataContracts"; /** * @refactor: remove unused members and methods */ export class SkaterSchedule { //@refactor: refactor to see if we need sessions on top of scheduled_sessions sessions: SessionCollection; private _schedule: SessionSchedule; private _registered_events: SkatingEventCollection; private scheduled_sessions: ScheduledSessionCollection; constructor(scheduled_sessions: ScheduledSession[], events: SkatingEvent[]) { this.scheduled_sessions = new ScheduledSessionCollection(scheduled_sessions); this.sessions = new SessionCollection(this.scheduled_sessions.sessions()); this._schedule = new SessionSchedule(this.scheduled_sessions); this._registered_events = new SkatingEventCollection(events); } get schedule(): SessionSchedule { return this._schedule; } get registered_events(): SkatingEvent[] { return this._registered_events.all(); } get event_ids(): number[] { return this._registered_events.ids(); } get session_ids() { return this.scheduled_sessions.ids(); } public findEvent(event_id: number) { return this._registered_events.find(event_id); } public getScheduledSessionsForEvent(event_id: number): ScheduledSessionCollection { return this.scheduled_sessions.eventId(event_id); } contains(session: Session) { return this.sessions.contains(session); } add(scheduled_session: ScheduledSession) { this.scheduled_sessions.add(scheduled_session); this.sessions.add(scheduled_session.session); this._schedule.add(scheduled_session); } findScheduledSession(session_id: number): ScheduledSession | null { return this.scheduled_sessions.find(session_id); } remove(scheduled_session: ScheduledSession) { this.scheduled_sessions.remove(scheduled_session.session.id); this.sessions.remove(scheduled_session.session); this._schedule.remove(scheduled_session.session) } //@refactor: remove if unused public getfirstDate(): (Date | null) { let ordered = this.sessions.orderDate(); if (ordered.count()) { let date = ordered.sessions[0].date; return new Date(date.getFullYear(), date.getMonth(), date.getDate()); } return null; } getfirstRinkDate(rink_id: number) { let filtered = this.sessions.filterRink(rink_id).orderDate(); if (filtered.count()) { let date = filtered.sessions[0].date; return new Date(date.getFullYear(), date.getMonth(), date.getDate()); } return null; } getEventScheduledTypeAmount(event_id: number, session_type: SessionType): number { return this.scheduled_sessions.eventId(event_id).creditsUsed()[session_type]; } getEventScheduledTypeCounts(event_id: number): CreditStateData { return this.scheduled_sessions.eventId(event_id).creditsUsed(); } /** * Return an array of event ids contained within the session that the skater is registered for */ filterAvailableSessionEventIds(session: SessionLike): number[] { let schedulable_event_ids = this.event_ids; return session.event_ids.filter(function (event_id: number) { return schedulable_event_ids.indexOf(event_id) !== -1; }) } }
Java
UTF-8
3,543
2.421875
2
[ "BSD-3-Clause" ]
permissive
/* * Phys2D - a 2D physics engine based on the work of Erin Catto. * * This source is provided under the terms of the BSD License. * * Copyright (c) 2006, Phys2D * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Phys2D/New Dawn Software nor the names of * its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package net.phys2d.raw.collide; import java.util.Iterator; import net.phys2d.math.Vector2f; import net.phys2d.raw.Body; import net.phys2d.raw.Contact; import net.phys2d.raw.shapes.Box; import net.phys2d.raw.shapes.Polygon; /** * Collide a Convex Polygon with a Box. * * @author Gideon Smeding * */ public class PolygonBoxCollider extends PolygonPolygonCollider { /** * @see net.phys2d.raw.collide.Collider#collide(net.phys2d.raw.Contact[], net.phys2d.raw.Body, net.phys2d.raw.Body) */ public int collide(Contact[] contacts, Body bodyA, Body bodyB) { Polygon poly = (Polygon) bodyA.getShape(); Box box = (Box) bodyB.getShape(); // TODO: this can be optimized using matrix multiplications and moving only one shape // specifically the box, because it has fewer vertices. Vector2f[] vertsA = poly.getVertices(bodyA.getPosition(), bodyA.getRotation()); Vector2f[] vertsB = box.getPoints(bodyB.getPosition(), bodyB.getRotation()); // TODO: use a sweepline that has the smallest projection of the box // now we use just an arbitrary one Vector2f sweepline = new Vector2f(vertsB[1]); sweepline.sub(vertsB[2]); EdgeSweep sweep = new EdgeSweep(sweepline); sweep.addVerticesToSweep(true, vertsA); sweep.addVerticesToSweep(false, vertsB); Iterator<EdgeSweep.EdgePairs.EdgePair> collEdgeCands = sweep.getOverlappingEdges(); // FeaturePair[] featurePairs = getFeaturePairs(contacts.length, vertsA, vertsB, collEdgeCands); // return populateContacts(contacts, vertsA, vertsB, featurePairs); Intersection[][] intersections = getIntersectionPairs(vertsA, vertsB, collEdgeCands); return populateContacts(contacts, vertsA, vertsB, intersections); } }
Python
UTF-8
1,218
2.859375
3
[]
no_license
from bs4 import BeautifulSoup import requests html_text = requests.get('https://www.worldometers.info/world-population/india-population/').text info = BeautifulSoup(html_text,'lxml') with open(f'population stats.text','w') as f: country_name=info.find('div',id='maincounter-wrap').h1.text.split()[0] f.write(f"country name: {country_name}\n") country_detail= info.find('div',class_ ='col-md-8 country-pop-description').text f.write(country_detail+'\n') population_table=info.find('div',class_='table-responsive') country_population_info =population_table.find('table',class_ ='table table-striped table-bordered table-hover table-condensed table-list') all_head=country_population_info.find('thead') head=all_head.find('tr') titles=head.find_all('th') f.write("\nPOPULATION HISTORY OF "+country_name+'\n') for title in titles: f.write(title.text.replace(' ','')+'\t\t\t') f.write('\n') all_content=country_population_info.find('tbody') contents=all_content.find_all('tr') for content in contents: datas=content.find_all('td') for data in datas: f.write(data.text.replace(' ','')+'\t\t\t') f.write('\n')
SQL
UTF-8
2,571
3.578125
4
[]
no_license
DROP DATABASE IF EXISTS DB_ANTI_SOCIAL; CREATE DATABASE DB_ANTI_SOCIAL; USE DB_ANTI_SOCIAL; CREATE TABLE TAS_ACCOUNT( ACCOUNT_ID INTEGER NOT NULL AUTO_INCREMENT, USER_NAME VARCHAR(64) NOT NULL, PASSWORD VARCHAR(64) NOT NULL, DATE_OF_BIRTH DATE NOT NULL, FIRST_NAME VARCHAR(64) NOT NULL, LAST_NAME VARCHAR(64) NOT NULL, PRIMARY KEY(ACCOUNT_ID) ); CREATE TABLE TAS_GENDER( GENDER_ID INTEGER NOT NULL AUTO_INCREMENT, GENDER_DESCRIPTION VARCHAR(64) NOT NULL, PRIMARY KEY(GENDER_ID) ); CREATE TABLE TAS_ROLE( ROLE_ID INTEGER NOT NULL AUTO_INCREMENT, ROLE_DESCRIPTION VARCHAR(64) NOT NULL, PRIMARY KEY(ROLE_ID) ); CREATE TABLE TAS_ACCOUNT_ROLES( ACCOUNT_ROLES_ID INTEGER NOT NULL AUTO_INCREMENT, ACCOUNT_ID INTEGER NOT NULL, ROLE_ID INTEGER NOT NULL, PRIMARY KEY(ACCOUNT_ROLES_ID) ); CREATE TABLE TAS_GROUP( GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, GROUP_NAME VARCHAR(64) NOT NULL, PRIMARY KEY(GROUP_ID) ); CREATE TABLE TAS_ACCOUNT_GROUP( ACCOUNT_GROUP_ID INTEGER NOT NULL AUTO_INCREMENT, ACCOUNT_ID INTEGER NOT NULL, GROUP_ID INTEGER NOT NULL, PRIMARY KEY(ACCOUNT_GROUP_ID) ); CREATE TABLE TAS_ACCOUNT_STATUS( ACCOUNT_STATUS_ID INTEGER NOT NULL AUTO_INCREMENT, STATUS_TEXT VARCHAR(64) NOT NULL, ACCOUNT_ID INTEGER NOT NULL, PRIMARY KEY(ACCOUNT_STATUS_ID) ); CREATE TABLE TAS_POST( POST_ID INTEGER NOT NULL AUTO_INCREMENT, POST_TITLE VARCHAR(128) NOT NULL, POST_CONTENT VARCHAR(8192) NOT NULL, ACCOUNT_ID INTEGER NOT NULL, PRIMARY KEY(POST_ID) ); CREATE TABLE TAS_TAG( TAG_ID INTEGER NOT NULL AUTO_INCREMENT, TAG_NAME VARCHAR(32) NOT NULL, PRIMARY KEY(TAG_ID) ); CREATE TABLE TAS_POST_TAG( POST_TAG_ID INTEGER NOT NULL AUTO_INCREMENT, POST_ID INTEGER NOT NULL, TAG_ID INTEGER NOT NULL, PRIMARY KEY(POST_TAG_ID) ); CREATE TABLE TAS_COMMENT( COMMENT_ID INTEGER NOT NULL AUTO_INCREMENT, COMMENT_CONTENT VARCHAR(256) NOT NULL, POST_ID INTEGER NOT NULL, ACCOUNT_ID INTEGER NOT NULL, PRIMARY KEY(COMMENT_ID) ); CREATE TABLE TAS_LIKE( LIKE_ID INTEGER NOT NULL AUTO_INCREMENT, POST_ID INTEGER NOT NULL, ACCOUNT_ID INTEGER NOT NULL, LIKE_TYPE_ID INTEGER NOT NULL, PRIMARY KEY(LIKE_ID) ); CREATE TABLE TAS_LIKE_TYPE( LIKE_TYPE_ID INTEGER NOT NULL AUTO_INCREMENT, LIKE_TYPE_NAME VARCHAR(64) NOT NULL, PRIMARY KEY(LIKE_TYPE_ID) );
Java
UTF-8
17,005
2.09375
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
/** * Copyright 2012 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.facebook; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; /* * <p> * An implementation of {@link TokenCachingStrategy TokenCachingStrategy} that uses Android SharedPreferences * to persist information. * </p> * <p> * The data to be cached is passed in via a Bundle. Only non-null key-value-pairs where * the value is one of the following types (or an array of the same) are persisted: * boolean, byte, int, long, float, double, char. In addition, String and List<String> * are also supported. * </p> */ public class SharedPreferencesTokenCachingStrategy extends TokenCachingStrategy { private static final String DEFAULT_CACHE_KEY = "com.facebook.SharedPreferencesTokenCachingStrategy.DEFAULT_KEY"; private static final String TAG = SharedPreferencesTokenCachingStrategy.class.getSimpleName(); private static final String JSON_VALUE_TYPE = "valueType"; private static final String JSON_VALUE = "value"; private static final String JSON_VALUE_ENUM_TYPE = "enumType"; private static final String TYPE_BOOLEAN = "bool"; private static final String TYPE_BOOLEAN_ARRAY = "bool[]"; private static final String TYPE_BYTE = "byte"; private static final String TYPE_BYTE_ARRAY = "byte[]"; private static final String TYPE_SHORT = "short"; private static final String TYPE_SHORT_ARRAY = "short[]"; private static final String TYPE_INTEGER = "int"; private static final String TYPE_INTEGER_ARRAY = "int[]"; private static final String TYPE_LONG = "long"; private static final String TYPE_LONG_ARRAY = "long[]"; private static final String TYPE_FLOAT = "float"; private static final String TYPE_FLOAT_ARRAY = "float[]"; private static final String TYPE_DOUBLE = "double"; private static final String TYPE_DOUBLE_ARRAY = "double[]"; private static final String TYPE_CHAR = "char"; private static final String TYPE_CHAR_ARRAY = "char[]"; private static final String TYPE_STRING = "string"; private static final String TYPE_STRING_LIST = "stringList"; private static final String TYPE_ENUM = "enum"; private String cacheKey; private SharedPreferences cache; /** * Creates a default {@link SharedPreferencesTokenCachingStrategy SharedPreferencesTokenCachingStrategy} * instance that provides access to a single set of token information. * * @param context * The Context object to use to get the SharedPreferences object. * * @throws NullPointerException if the passed in Context is null */ public SharedPreferencesTokenCachingStrategy(Context context) { this(context, null); } /** * Creates a {@link SharedPreferencesTokenCachingStrategy SharedPreferencesTokenCachingStrategy} instance * that is distinct for the passed in cacheKey. * * @param context * The Context object to use to get the SharedPreferences object. * * @param cacheKey * Identifies a distinct set of token information. * * @throws NullPointerException if the passed in Context is null */ public SharedPreferencesTokenCachingStrategy(Context context, String cacheKey) { Validate.notNull(context, "context"); this.cacheKey = Utility.isNullOrEmpty(cacheKey) ? DEFAULT_CACHE_KEY : cacheKey; // If the application context is available, use that. However, if it isn't // available (possibly because of a context that was created manually), use // the passed in context directly. Context applicationContext = context.getApplicationContext(); context = applicationContext != null ? applicationContext : context; this.cache = context.getSharedPreferences( this.cacheKey, Context.MODE_PRIVATE); } /** * Returns a Bundle that contains the information stored in this cache * * @return A Bundle with the information contained in this cache */ public Bundle load() { Bundle settings = new Bundle(); Map<String, ?> allCachedEntries = cache.getAll(); for (String key : allCachedEntries.keySet()) { try { deserializeKey(key, settings); } catch (JSONException e) { // Error in the cache. So consider it corrupted and return null Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "Error reading cached value for key: '" + key + "' -- " + e); return null; } } return settings; } /** * Persists all supported data types present in the passed in Bundle, to the * cache * * @param bundle * The Bundle containing information to be cached */ public void save(Bundle bundle) { Validate.notNull(bundle, "bundle"); SharedPreferences.Editor editor = cache.edit(); for (String key : bundle.keySet()) { try { serializeKey(key, bundle, editor); } catch (JSONException e) { // Error in the bundle. Don't store a partial cache. Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "Error processing value for key: '" + key + "' -- " + e); // Bypass the commit and just return. This cancels the entire edit transaction return; } } boolean successfulCommit = editor.commit(); if (!successfulCommit) { Logger.log(LoggingBehavior.CACHE, Log.WARN, TAG, "SharedPreferences.Editor.commit() was not successful"); } } /** * Clears out all token information stored in this cache. */ public void clear() { cache.edit().clear().commit(); } private void serializeKey(String key, Bundle bundle, SharedPreferences.Editor editor) throws JSONException { Object value = bundle.get(key); if (value == null) { // Cannot serialize null values. return; } String supportedType = null; JSONArray jsonArray = null; JSONObject json = new JSONObject(); if (value instanceof Byte) { supportedType = TYPE_BYTE; json.put(JSON_VALUE, ((Byte)value).intValue()); } else if (value instanceof Short) { supportedType = TYPE_SHORT; json.put(JSON_VALUE, ((Short)value).intValue()); } else if (value instanceof Integer) { supportedType = TYPE_INTEGER; json.put(JSON_VALUE, ((Integer)value).intValue()); } else if (value instanceof Long) { supportedType = TYPE_LONG; json.put(JSON_VALUE, ((Long)value).longValue()); } else if (value instanceof Float) { supportedType = TYPE_FLOAT; json.put(JSON_VALUE, ((Float)value).doubleValue()); } else if (value instanceof Double) { supportedType = TYPE_DOUBLE; json.put(JSON_VALUE, ((Double)value).doubleValue()); } else if (value instanceof Boolean) { supportedType = TYPE_BOOLEAN; json.put(JSON_VALUE, ((Boolean)value).booleanValue()); } else if (value instanceof Character) { supportedType = TYPE_CHAR; json.put(JSON_VALUE, value.toString()); } else if (value instanceof String) { supportedType = TYPE_STRING; json.put(JSON_VALUE, (String)value); } else if (value instanceof Enum<?>) { supportedType = TYPE_ENUM; json.put(JSON_VALUE, value.toString()); json.put(JSON_VALUE_ENUM_TYPE, value.getClass().getName()); } else { // Optimistically create a JSONArray. If not an array type, we can null // it out later jsonArray = new JSONArray(); if (value instanceof byte[]) { supportedType = TYPE_BYTE_ARRAY; for (byte v : (byte[])value) { jsonArray.put((int)v); } } else if (value instanceof short[]) { supportedType = TYPE_SHORT_ARRAY; for (short v : (short[])value) { jsonArray.put((int)v); } } else if (value instanceof int[]) { supportedType = TYPE_INTEGER_ARRAY; for (int v : (int[])value) { jsonArray.put(v); } } else if (value instanceof long[]) { supportedType = TYPE_LONG_ARRAY; for (long v : (long[])value) { jsonArray.put(v); } } else if (value instanceof float[]) { supportedType = TYPE_FLOAT_ARRAY; for (float v : (float[])value) { jsonArray.put((double)v); } } else if (value instanceof double[]) { supportedType = TYPE_DOUBLE_ARRAY; for (double v : (double[])value) { jsonArray.put(v); } } else if (value instanceof boolean[]) { supportedType = TYPE_BOOLEAN_ARRAY; for (boolean v : (boolean[])value) { jsonArray.put(v); } } else if (value instanceof char[]) { supportedType = TYPE_CHAR_ARRAY; for (char v : (char[])value) { jsonArray.put(String.valueOf(v)); } } else if (value instanceof List<?>) { supportedType = TYPE_STRING_LIST; @SuppressWarnings("unchecked") List<String> stringList = (List<String>)value; for (String v : stringList) { jsonArray.put((v == null) ? JSONObject.NULL : v); } } else { // Unsupported type. Clear out the array as a precaution even though // it is redundant with the null supportedType. jsonArray = null; } } if (supportedType != null) { json.put(JSON_VALUE_TYPE, supportedType); if (jsonArray != null) { // If we have an array, it has already been converted to JSON. So use // that instead. json.putOpt(JSON_VALUE, jsonArray); } String jsonString = json.toString(); editor.putString(key, jsonString); } } private void deserializeKey(String key, Bundle bundle) throws JSONException { String jsonString = cache.getString(key, "{}"); JSONObject json = new JSONObject(jsonString); String valueType = json.getString(JSON_VALUE_TYPE); if (valueType.equals(TYPE_BOOLEAN)) { bundle.putBoolean(key, json.getBoolean(JSON_VALUE)); } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); boolean[] array = new boolean[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getBoolean(i); } bundle.putBooleanArray(key, array); } else if (valueType.equals(TYPE_BYTE)) { bundle.putByte(key, (byte)json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_BYTE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); byte[] array = new byte[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (byte)jsonArray.getInt(i); } bundle.putByteArray(key, array); } else if (valueType.equals(TYPE_SHORT)) { bundle.putShort(key, (short)json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_SHORT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); short[] array = new short[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (short)jsonArray.getInt(i); } bundle.putShortArray(key, array); } else if (valueType.equals(TYPE_INTEGER)) { bundle.putInt(key, json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_INTEGER_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int[] array = new int[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getInt(i); } bundle.putIntArray(key, array); } else if (valueType.equals(TYPE_LONG)) { bundle.putLong(key, json.getLong(JSON_VALUE)); } else if (valueType.equals(TYPE_LONG_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); long[] array = new long[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getLong(i); } bundle.putLongArray(key, array); } else if (valueType.equals(TYPE_FLOAT)) { bundle.putFloat(key, (float)json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_FLOAT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); float[] array = new float[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (float)jsonArray.getDouble(i); } bundle.putFloatArray(key, array); } else if (valueType.equals(TYPE_DOUBLE)) { bundle.putDouble(key, json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); double[] array = new double[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getDouble(i); } bundle.putDoubleArray(key, array); } else if (valueType.equals(TYPE_CHAR)) { String charString = json.getString(JSON_VALUE); if (charString != null && charString.length() == 1) { bundle.putChar(key, charString.charAt(0)); } } else if (valueType.equals(TYPE_CHAR_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); char[] array = new char[jsonArray.length()]; for (int i = 0; i < array.length; i++) { String charString = jsonArray.getString(i); if (charString != null && charString.length() == 1) { array[i] = charString.charAt(0); } } bundle.putCharArray(key, array); } else if (valueType.equals(TYPE_STRING)) { bundle.putString(key, json.getString(JSON_VALUE)); } else if (valueType.equals(TYPE_STRING_LIST)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int numStrings = jsonArray.length(); ArrayList<String> stringList = new ArrayList<String>(numStrings); for (int i = 0; i < numStrings; i++) { Object jsonStringValue = jsonArray.get(i); stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String)jsonStringValue); } bundle.putStringArrayList(key, stringList); } else if (valueType.equals(TYPE_ENUM)) { try { String enumType = json.getString(JSON_VALUE_ENUM_TYPE); @SuppressWarnings({ "unchecked", "rawtypes" }) Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType); @SuppressWarnings("unchecked") Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE)); bundle.putSerializable(key, enumValue); } catch (ClassNotFoundException e) { } catch (IllegalArgumentException e) { } } } }
Markdown
UTF-8
1,957
2.796875
3
[]
no_license
--- title: Smashed Just Smashed the Lower East Side Burger Game author: Brendan Doyle date: 2021-05-08 hero: ./images/SmashedMac.jpeg excerpt: I had a double cheeseburger lunch times 2, and felt great! --- Smashed, a hip new Lower East Side burger joint, is dishing out ultra-thin, crispy patties that feel about as true to the original midwest smashburger form as you can get. The menu is almost entirely burger-focused — with single, double and triple patty smashes, Impossible meat options and a trio of signature burgers. I went for a double-smash for my first go-round this afternoon, and opted out of the beef fat fries — which are supposedly excellent — with the intuition that I may want to save room for more burger. The double-smash came out to the patio in about five minutes, a compact handheld dynamo of a sandwich. The American cheese and ‘Smash sauce’, peeking over lacey, crispy beef, melded the whole composition into a caramelized masterpiece. Fireworks went off in my taste buds with every chew. I was back at the register mere seconds after my last bite, craving another smashburger. My next pick-up was The Big Shmacc (pictured above), which looked mildly intimidating upon arrival — two patties separated by an extra poppyseed bun, stacked on top of an abundance of cheese and lettuce. I proceeded with caution, worried I had ordered more than I could handle. But after the first cheesy bite, full of special sauce, pickle and umami-crusted beef, I threw all inhibitions to the wind. The Shmacc was vanquished within minutes. Did I still have room for a slice of pepperoni pizza from Zazzy’s after? Maybe. But that’s what happens when you skip fries — you save more room for the good stuff. I give Smashed five out of five stars — probably the best burgers I’ve had all year, and I’d predict, soon to be one of the Lower East Side’s most popular lunch options as hot vax summer gets underway. Until next time.
PHP
UTF-8
1,911
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "hs_bet". * * @property int $id * @property int $game_id * @property int $choosed_option * @property int $user_id * @property int $created_at * @property int $updated_at * @property int $status * @property int $type [int(11)] * @property int $goals_a [int(11)] * @property int $goals_b [int(11)] * @property int $type2 [int(11)] * @property string $goals [varchar(1024)] * @property string $half_game [varchar(1024)] * @property string $score [varchar(1024)] * @property int $repeat [int(11)] * @property string $guess [varchar(1024)] * @property string $odds [varchar(512)] * @property string $fee [varchar(32)] */ class HsBet extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'hs_bet'; } /** * {@inheritdoc} */ public function rules() { return [ [['game_id', 'choosed_option', 'user_id', 'created_at', 'updated_at', 'status', 'goals_a', 'goals_b', 'repeat'], 'integer'], ['goals', 'string', 'max' => 1024], ['half_game', 'string', 'max' => 1024], ['score', 'string', 'max' => 1024], ['guess', 'string', 'max' => 1024], ['odds', 'string', 'max' => 512], ['fee', 'string', 'max' => 32], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'game_id' => 'Game ID', 'choosed_option' => 'Choosed Option', 'user_id' => 'User ID', 'created_at' => 'Created At', 'updated_at' => 'Updated At', 'status' => 'Status', ]; } public function behaviors() { return [TimestampBehavior::class]; } }
C#
UTF-8
823
2.515625
3
[]
no_license
using UnityEngine; using System.Collections; public class ResourcesManager : Singleton<ResourcesManager> { public override void Initialize() { } public override void UnInitialize() { } public Object Load(string path) { return Resources.Load(path); } public T Load<T>(string path) where T : Object { return Resources.Load<T>(path); } public GameObject LoadUIView(string name, GameObject parent) { GameObject prefab = Resources.Load<GameObject>(name); if (prefab == null) { return null; } GameObject go = GameObject.Instantiate(prefab); go.transform.SetParent(parent.transform); go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; return go; } }
Java
UTF-8
569
3.25
3
[]
no_license
public class LPP{ public LPP(){ System.out.println(init()); } public int init(){ int num; int hNum = 0; String string; for(int i = 999; i > 0; i--){ for(int x = 999; x > 0; x--){ num = x * i; if(num < hNum) break; string = Integer.toString(num); for(int r = 0; r <= string.length() / 2; r++){ if(!(string.charAt(r) == string.charAt(string.length() - r - 1))) break; if(r == string.length() / 2) hNum = num; } } } return hNum; } public static void main(String[] args){ LPP lpp = new LPP(); } }
TypeScript
UTF-8
610
2.65625
3
[]
no_license
import { Md5 } from 'ts-md5/dist/md5'; import { ResetPassword } from './reset-password'; /** * ResetPasswordAPIRequestData */ export class ResetPasswordAPIRequestData { public r: string; // reset code public p: string; // password public p2: string; // confirm password public static fillResetPassword = (requestData: ResetPasswordAPIRequestData, resetPassword: ResetPassword) => { requestData.r = resetPassword.resetCode; requestData.p = <string> Md5.hashStr(resetPassword.newPassword); requestData.p2 = <string> Md5.hashStr(resetPassword.confirmPassword); } }
C++
UTF-8
990
2.65625
3
[]
no_license
#include<cstdio> #include<algorithm> #include<queue> #include<vector> const int maxn = 1010; struct Mouse{ int weight,R; }; int main(){ std::vector<Mouse> mouse; int np,ng,order; Mouse node; scanf("%d %d",&np,&ng); for(int i = 0;i<np;++i){ scanf("%d",&node.weight); node.R = 0; mouse.push_back(node); } std::queue<int> q; for(int i = 0;i<np;++i){ scanf("%d",&order); q.push(order); } int temp = np,group; while(q.size()!=1){ if(temp% ng ==0) group = temp / ng; else group = temp/ng +1; for(int i=0;i<group;++i){ int k = q.front(); for(int j = 0;j<ng;++j){ if(i*ng +j >=temp) break; int front = q.front(); if(mouse[front].weight > mouse[k].weight) k = front; mouse[front].R = group + 1; q.pop(); } q.push(k); } temp = group; } mouse[q.front()].R = 1; for(int i = 0;i<np;++i){ printf("%d",mouse[i].R); if(i<np-1) printf(" "); } printf("\n"); return 0; }
Ruby
UTF-8
6,023
3.125
3
[]
no_license
require "pry" class Anfis SIGMOIDAL_PARAMS = [:a, :b, :c, :d] # precondition params OUT_PARAMS = [:p, :q, :r] # consequent params PARAMS = SIGMOIDAL_PARAMS + OUT_PARAMS attr_reader :errors, :rules def initialize(num_of_rules) # m rules @rules = Array.new(num_of_rules) do { a: { val: rand(-1.0..1.0), der: 0.0 }, b: { val: rand(-1.0..1.0), der: 0.0 }, c: { val: rand(-1.0..1.0), der: 0.0 }, d: { val: rand(-1.0..1.0), der: 0.0 }, p: { val: rand(-1.0..1.0), der: 0.0 }, q: { val: rand(-1.0..1.0), der: 0.0 }, r: { val: rand(-1.0..1.0), der: 0.0 }, sigm_A_out: 0.0, sigm_B_out: 0.0, weight: 0.0, out: 0.0 } end end def train(type: :stohastic, samples:, max_iterations: 100_000, print_progress_flag: true, status_every_n_iterations: 100, learing_rate_precondition: 0.0001, learing_rate_consequent: 0.01, target_error: 1e-6, save_error_every_n_iterations: 100) return false if type != :stohastic && type != :batch @samples = samples @type = type @max_iterations = max_iterations @print_progress_flag = print_progress_flag @status_every_n_iterations = status_every_n_iterations @learing_rate_precondition = learing_rate_precondition @learing_rate_consequent = learing_rate_consequent @target_error = target_error @save_error_every_n_iterations = save_error_every_n_iterations @iteration = 0 @learned = false @errors = [] while @iteration < @max_iterations || @learned do stohastic_step(@samples) if @type == :stohastic batch_step(@samples) if @type == :batch @learned = learned?(@samples) @iteration += 1 print_progress if @print_progress_flag end puts "n_p: #{@learing_rate_precondition}, n_c_ #{learing_rate_consequent}: error: #{@current_error}" end def stohastic_step(samples) samples.each do |sample| calculate_gradients(sample) update_params end end def batch_step(samples) samples.each do |sample| calculate_gradients(sample) end update_params end def output(sample) # i in index indicates current_rule, goes from 1 to m @rules.each do |rule| # A_i_x rule[:sigm_A_out] = sigmoidal_function(rule[:a][:val], rule[:b][:val], sample[:x]) # B_i_y rule[:sigm_B_out] = sigmoidal_function(rule[:c][:val], rule[:d][:val], sample[:y]) # w_i = t_norm(A_i_x, B_i_y) rule[:weight] = rule[:sigm_A_out] * rule[:sigm_B_out] # f_i = p_i * x + q_i * y + r_i rule[:out] = rule[:p][:val] * sample[:x] + rule[:q][:val] * sample[:y] + rule[:r][:val] end # sum(w_0...w_m), for each rule i weights_sum = @rules.map{ |rule| rule[:weight] }.sum # sum( w_i * f_i), for each rule i weights_outs_product_sum = @rules.map { |rule| rule[:weight] * rule[:out] }.sum # y = (w_1 * f_1 + ... + w_m * f_m) / (w_1 + ... w_m) weights_outs_product_sum / weights_sum end def update_params @rules.each do |rule| PARAMS.each do |param| param_der = @type == :stohastic ? rule[param][:der] : rule[param][:der] / @samples.count if SIGMOIDAL_PARAMS.include?(param) rule[param][:val] = rule[param][:val] - @learing_rate_precondition * param_der else rule[param][:val] = rule[param][:val] - @learing_rate_consequent * param_der end end end reset_derivatives end def calculate_gradients(sample) offset = output(sample) - sample[:z] weights_sum = @rules.map{ |rule| rule[:weight] }.sum @rules.each do |rule| partial_der_out_by_w = 0.0 @rules.each do |rule2| partial_der_out_by_w += rule2[:weight] * (rule[:out] - rule2[:out]) end partial_der_out_by_w = partial_der_out_by_w / (weights_sum**2) common_part_precondition = offset * partial_der_out_by_w * rule[:sigm_A_out] * rule[:sigm_B_out] common_part_consequent = offset * (rule[:weight] / weights_sum ) partial_der = {} partial_der[:a] = common_part_precondition * (1 - rule[:sigm_A_out]) * rule[:b][:val] partial_der[:b] = common_part_precondition * (1 - rule[:sigm_A_out]) * (rule[:a][:val] - sample[:x]) partial_der[:c] = common_part_precondition * (1 - rule[:sigm_B_out]) * rule[:d][:val] partial_der[:d] = common_part_precondition * (1 - rule[:sigm_B_out]) * (rule[:c][:val] - sample[:y]) partial_der[:p] = common_part_consequent * sample[:x] partial_der[:q] = common_part_consequent * sample[:y] partial_der[:r] = common_part_consequent if @type == :stohastic PARAMS.each do |param| rule[param][:der] = partial_der[param] end else PARAMS.each do |param| rule[param][:der] += partial_der[param] end end end end def learned?(samples) @current_error = calculate_error(samples) if @current_error < @target_error puts "Learned :)" return true end false end def get_outputs_and_errors_for_samples(samples) outputs = [] samples.each do |sample| out = output(sample) outputs << { x: sample[:x], y: sample[:y], z: out, err: sample[:z] - out} end outputs end private def reset_derivatives @rules.each do |rule| PARAMS.each do |param| rule[param][:der] = 0.0 end end end def print_progress puts "Iteracija #{@iteration};\tTrenutna pogreška #{@current_error}" if @iteration % @status_every_n_iterations == 0 binding.pry if @iteration % 100_000 == 0 end def sigmoidal_function(a, b, x) 1.0 / (1 + Math.exp(b * (x - a))) end def calculate_error(samples) error_sum = 0.0 samples.each do |sample| out = self.output(sample) error_sum += (sample[:z] - out )**2 end current_error = error_sum / samples.count @errors << current_error if @iteration % @save_error_every_n_iterations == 0 current_error end end
Swift
UTF-8
5,069
2.734375
3
[]
no_license
import UIKit class ViewController3: UIViewController { // MARK: - IBOutlet @IBOutlet weak var ScrollView: UIScrollView! @IBOutlet weak var ViewInScroll: UIView! @IBOutlet weak var ImageFoodScroll: UIScrollView! // Видимый UIView @IBOutlet weak var ViewUp: UIView! @IBOutlet weak var Label: UILabel! @IBOutlet weak var KitchenType: UILabel! @IBOutlet weak var SkidkaText: UILabel! @IBOutlet weak var SkindaNubmer: UILabel! @IBOutlet weak var RatingNumberLabel: UILabel! @IBOutlet weak var CentralTextLabel: UILabel! @IBOutlet weak var MenuButton: UIButton! @IBOutlet weak var Star: UIImageView! @IBOutlet weak var CentalTextLabel2: UILabel! @IBOutlet weak var MapView: UIImageView! @IBOutlet weak var Button1: UIButton! @IBOutlet weak var Button2: UIButton! // MARK: - Screen & Frames let ScreenHeight = CGFloat(UIScreen.main.bounds.height) let ScreenWidth = CGFloat(UIScreen.main.bounds.width) lazy var Height = ScreenHeight * 1.75 lazy var Width = ScreenWidth lazy var ScrollFoodsHeight = ScreenHeight / 3 lazy var ScrollFoodsWidth = ScreenWidth // MARK: - Images Food var ImagesFoodArray = ["food1", "food2", "food3", "food4", "food5"] var Index = 0 lazy var ImageViewHeight = ScrollFoodsHeight lazy var ImageViewWidth = ScrollFoodsWidth / 2 lazy var X = CGFloat(0) lazy var Y = CGFloat(0) // Вытаскивает "картинку" из массива и выдает UIImageView с ней func FoodDemonstration () -> UIImageView { Index += 1 let ImageFood = UIImageView() ImageFood.frame = CGRect(x: X, y: Y, width: ImageViewWidth * 2, height: ImageViewHeight) if (UIScreen.main.bounds.height / UIScreen.main.bounds.width) > 1.5 { ImageFood.contentMode = .scaleToFill } else { ImageFood.contentMode = .scaleAspectFill } ImageFood.image = UIImage.init(named: ImagesFoodArray[Index % ImagesFoodArray.count]) X += ScreenWidth return ImageFood } // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() // print("Высота экрана: \(ScreenHeight)") // print("Ширина экрана: \(ScreenWidth)") ViewUp.layer.zPosition = 1 // Перелистывание картинок в шапке ImageFoodScroll.isPagingEnabled = true } // MARK: - viewDidLayoutSubviews override func viewDidLayoutSubviews() { Label.text = "Ресторан 5 звезд Мишлен" KitchenType.text = "Универсальная кухня" SkindaNubmer.text = "20%" RatingNumberLabel.text = "5.0" CentralTextLabel.text = "Ресторатор так заморочился, что даже \n картинки в шапке можно полистать" CentalTextLabel2.text = "Вроде это барахло неплохо работает \n проверял на 6s, 8+, 11 max и ipad 12.9" Star.layer.frame.size = CGSize(width: 42, height: 42) // Всякие закругления ViewUp.layer.cornerRadius = 30 // MARK: - Размер шрифтов if (UIScreen.main.bounds.height / UIScreen.main.bounds.width) > 1.5 { Label.font = UIFont.systemFont(ofSize: 30) KitchenType.font = UIFont.systemFont(ofSize: 15) SkidkaText.font = UIFont.systemFont(ofSize: 20) SkindaNubmer.font = UIFont.systemFont(ofSize: 30) RatingNumberLabel.font = UIFont.systemFont(ofSize: 30) CentralTextLabel.font = UIFont.systemFont(ofSize: 20) } else { Label.font = UIFont.systemFont(ofSize: 40) KitchenType.font = UIFont.systemFont(ofSize: 25) SkidkaText.font = UIFont.systemFont(ofSize: 30) SkindaNubmer.font = UIFont.systemFont(ofSize: 40) RatingNumberLabel.font = UIFont.systemFont(ofSize: 40) CentralTextLabel.font = UIFont.systemFont(ofSize: 40) } // Переопределяем размеры ViewInScroll.translatesAutoresizingMaskIntoConstraints = true ViewInScroll.layer.frame = CGRect(x: 0, y: 0, width: Width, height: Height) ImageFoodScroll.translatesAutoresizingMaskIntoConstraints = true ImageFoodScroll.layer.frame = CGRect(x: 0, y: 0, width: ScrollFoodsWidth, height: ScrollFoodsHeight) ImageFoodScroll.contentSize = CGSize(width: ScrollFoodsWidth * CGFloat(ImagesFoodArray.count), height: ScrollFoodsHeight) // Добавляем картинки в скролл в шапке for _ in 0...ImagesFoodArray.count - 1 { if ScrollFoodsWidth * CGFloat(ImagesFoodArray.count) < X { break } ImageFoodScroll.addSubview(FoodDemonstration()) } } }
JavaScript
UTF-8
523
2.640625
3
[]
no_license
var url = "https://5d04064fd1471e00149bb174.mockapi.io/api/v1/blogs" fetch(url) .then(function(response){ if(response.ok) { response.json() .then( function(data){ var blogWrapper = document.getElementById("demo"); var allPosts = data.map(item => { var title = `<h2>${item.title}</h2>` return title; }) .join("") blogWrapper.innerHTML = allPosts; }); } }); //function reqListener () { // //}
Java
UTF-8
125
1.703125
2
[]
no_license
package com.luoyan.thread; public interface QueryAction { public void execute(Context context); void execute(); }
Java
UTF-8
15,874
1.953125
2
[]
no_license
package nebraska; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.sql.Time; import java.util.Date; import javax.security.auth.x500.X500Principal; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import org.bouncycastle.asn1.pkcs.CertificationRequestInfo; import org.bouncycastle.jce.PKCS10CertificationRequest; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMWriter; import org.bouncycastle.x509.X509V3CertificateGenerator; import utils.DatFunk; import utils.JCompTools; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; public class NebraskaPanel extends JPanel implements ActionListener{ JButton[] but = {null,null,null,null,null,null,null,null}; KeyPair kp; JTextArea jta; JScrollPane jsca; /** * */ private static final long serialVersionUID = -2328868562054207798L; public NebraskaPanel(){ //setBackground(Color.WHITE); setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); // 1 2 3 4 5 6 7 8 FormLayout lay = new FormLayout("5dlu,50dlu,5dlu,50dlu,5dlu,50dlu,5dlu,50dlu,"+ // 9 10 11 "5dlu,50dlu,fill:0:grow(1.0)", "fill:0:grow(1.0),2dlu,p,2dlu,p,2dlu"); CellConstraints cc = new CellConstraints(); setLayout(lay); but[0] = new JButton("Key-Pair erzeugen"); but[0].setActionCommand("generatekey"); but[0].addActionListener(this); add(but[0],cc.xy(2,3)); but[1] = new JButton("Zertifikat erzeugen"); but[1].setActionCommand("generatecert"); but[1].addActionListener(this); add(but[1],cc.xy(4,3)); but[2] = new JButton("Request erzeugen"); but[2].setActionCommand("generaterequest"); but[2].addActionListener(this); add(but[2],cc.xy(6,3)); but[3] = new JButton("Annahme einlesen"); but[3].setActionCommand("annahmeeinlesen"); but[3].addActionListener(this); add(but[3],cc.xy(8,3)); but[3] = new JButton("KeyStore erzeugen"); but[3].setActionCommand("createkeystore"); but[3].addActionListener(this); add(but[3],cc.xy(10,3)); but[4] = new JButton("Zertifikate zeigen"); but[4].setActionCommand("showcerts"); but[4].addActionListener(this); add(but[4],cc.xy(2,5)); but[5] = new JButton("Einzelnes lesen"); but[5].setActionCommand("readsingle"); but[5].addActionListener(this); add(but[5],cc.xy(4,5)); but[6] = new JButton("Verschl�sseln"); but[6].setActionCommand("verschluesseln"); but[6].addActionListener(this); add(but[6],cc.xy(6,5)); but[7] = new JButton("l�schen Zertifikate"); but[7].setActionCommand("deletecert"); but[7].addActionListener(this); add(but[7],cc.xy(8,5)); jta = new JTextArea(); jta.setFont(new Font("Courier",Font.PLAIN,11)); jta.setLineWrap(true); jta.setName("saetze"); jta.setWrapStyleWord(true); jta.setEditable(true); jta.setBackground(Color.WHITE); jta.setForeground(Color.BLUE); jsca = JCompTools.getTransparentScrollPane(jta); jsca.validate(); add(jsca,cc.xyw(1, 1,11)); /* try { KeyPair kp = generateRSAKeyPair(); System.out.println("Private key:\n"+kp.getPrivate()); System.out.println("Public key:\n"+kp.getPublic()); X509Certificate cert = generateV3Certificate(kp); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); System.out.println("G�ltiges Zertifikat wurde generiert"); //System.out.println(new String(cert.getEncoded())); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); bOut.write(cert.getEncoded()); bOut.flush(); bOut.close(); InputStream in = new ByteArrayInputStream(bOut.toByteArray()); CertificateFactory fact = CertificateFactory.getInstance("X.509",Constants.SECURITY_PROVIDER); X509Certificate x509Cert; Collection collection = new ArrayList(); x509Cert = (X509Certificate) fact.generateCertificate(in); */ System.out.println("/*****************/"); //System.out.println(new String(bOut.toByteArray())); //System.out.println(new String(x509Cert.getEncoded())); /* System.out.println(x509Cert.getSigAlgOID()); System.out.println(x509Cert.getType()); System.out.println(x509Cert.getVersion()); System.out.println(x509Cert.getIssuerDN()); System.out.println(x509Cert.getIssuerUniqueID()); System.out.println(x509Cert.getIssuerAlternativeNames()); System.out.println(x509Cert.getSubjectDN()); System.out.println(x509Cert.getSubjectUniqueID()); System.out.println(x509Cert.getSubjectX500Principal()); */ System.out.println("/*****************/"); //System.out.println(x509Cert); System.out.println("/*****************/"); /* PKCS10CertificationRequest request = generateRequest(kp); //PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(new FileWriter("C:/Lost+Found/verschluesselung/51084110.crq"))); bOut = new ByteArrayOutputStream ( ) ; PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(bOut)); pemWrt.writeObject(request); pemWrt.close(); System.out.println(bOut); */ //System.out.println("/*****************/"); //System.out.close(); //System.out.println(x509Cert); /* Thread.sleep(100); //RSAPublicKey pubkey = getPubKeyFromFile("C:/Lost+Found/verschluesselung/einschluessel.pem.txt"); //RSAPublicKey pubkey = getPubKeyFromFile("C:\\Lost+Found\\verschluesselung\\ANNAHME.KEY"); getPubKeyFromFile("C:\\Lost+Found\\verschluesselung\\51084110.CRP"); Thread.sleep(100); //System.out.println(new String( pubkey.getEncoded()) ); //System.exit(0); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (CertificateExpiredException e) { e.printStackTrace(); } catch (CertificateNotYetValidException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException, CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException{ Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(19620502)); certGen.setIssuerDN(new X500Principal("O=ITSG TrustCenter fuer sonstige Leistungserbringer,C=DE")); /* certGen.setIssuerDN(new X500Principal("CN=Herr Steinhilber,OU=IK510844109," + "OU=Reutlinger Therapie- und Analysezentrum GmbH,O=ITSG TrustCenter fuer sonstige Leistungserbringer,C=DE")); */ certGen.setNotBefore(new Date(BCStatics.certifikatsDatum(DatFunk.sHeute(), 0))); certGen.setNotAfter(new Date(BCStatics.certifikatsDatum(DatFunk.sHeute(), 3))); certGen.setSubjectDN(new X500Principal("CN=Herr Steinhilber,OU=IK510844109," + "OU=RTA GmbH, O=ITSG TrustCenter fuer sonstige Leistungserbringer,C=DE")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(Constants.SIGNATURE_ALGORITHM); //DateFormat df = new DateFormat("hh:mm:ss"); Date d = new Date(BCStatics.certifikatsDatum(DatFunk.sHeute(), 0)); Time time = new Time(d.getTime()); System.out.println("Zeit = "+time.toString()); try { Signature sig = Signature.getInstance(Constants.MD5_WITH_RSA); sig.initSign(pair.getPrivate()); System.out.println(sig); System.out.println("HashCode des PublicKey = "+pair.getPublic().hashCode()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return certGen.generate(pair.getPrivate(),Constants.SECURITY_PROVIDER); } public static PKCS10CertificationRequest generateRequest(KeyPair pair) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException{ return new PKCS10CertificationRequest(Constants.SHA1WITH_RSA, new X500Principal("CN=Herr Steinhilber," + "OU=IK510844109,OU=Reutlinger Therapie- und Analysezentrum GmbH,"+ "O=ITSG TrustCenter fuer sonstige Leistungserbringer,C=DE"), pair.getPublic(), null, pair.getPrivate() ); } public static int unsignedByteToInt(byte b) { return (int) b & 0xFF; } @Override public void actionPerformed(ActionEvent arg0) { String cmd = arg0.getActionCommand(); if(cmd.equals("generatekey")){ doKeyPair(); }else if(cmd.equals("generatecert")){ if(kp==null){ JOptionPane.showMessageDialog(null, "Bitte zuerst ein Keypair generieren"); return; } doCertificate(); }else if(cmd.equals("generaterequest")){ doGenerateRequest(); }else if(cmd.equals("annahmeeinlesen")){ BCStatics.readMultipleAnnahme(Nebraska.keystoredir); //BCStatics.readMultiple2("C:/Lost+Found/verschluesselung/annahme-pkcs.key.p7b.pem"); }else if(cmd.equals("createkeystore")){ try { if(kp==null){ JOptionPane.showMessageDialog(null, "Bitte zuerst ein Keypair generieren"); return; } kp = BCStatics.generateRSAKeyPair(); BCStatics.createKeyStore(kp); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(cmd.equals("showcerts")){ BCStatics.showAllCertsInStore(); }else if(cmd.equals("readsingle")){ try { BCStatics.readSingleCert(Nebraska.keystoredir); } catch (Exception e) { e.printStackTrace(); } }else if(cmd.equals("verschluesseln")){ BCStatics.verschluesseln("IK510841109"); }else if(cmd.equals("deletecert")){ try { BCStatics.deleteCertFromStore(null); } catch (Exception e) { e.printStackTrace(); } } } public void doGenerateRequest(){ try { if(kp==null){ JOptionPane.showMessageDialog(null,"Bitte zuerts das Key-Pair generieren"); return; } PKCS10CertificationRequest request = generateRequest(kp); File f = new File(Constants.CRYPTO_FILES_DIR + File.separator +"51084110.p10"); FileOutputStream fos = new FileOutputStream(f); fos.write(request.getEncoded()); fos.flush(); fos.close(); FileWriter file = new FileWriter(new File(Constants.CRYPTO_FILES_DIR + File.separator + "51084110.pem")); PEMWriter pemWriter = new PEMWriter(file); pemWriter.writeObject(request); pemWriter.close(); file.close(); CertificationRequestInfo inf = request.getCertificationRequestInfo(); System.out.println(inf.getSubject()); System.out.println(inf.getSubjectPublicKeyInfo()); jta.setText("Certifikation Request Encoded = :\n"+request.getCertificationRequestInfo()+jta.getText()); System.out.println(request.verify()); System.out.println(request.getPublicKey()); System.out.println(request.getSignature()); System.out.println(request.hashCode()); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SignatureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doKeyPair(){ try { kp = BCStatics.generateRSAKeyPair(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } jta.setText("Private key:\n"+kp.getPrivate()+"\n"+jta.getText()); jta.setText("********************************************************************\n\n"+jta.getText()); jta.setText("Public key:\n"+kp.getPublic()+"\n"+jta.getText()); jta.setText("********************************************************************\n\n"+jta.getText()); } public void doCertificate(){ X509Certificate cert; try { cert = generateV3Certificate(kp); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); System.out.println("G�ltiges Zertifikat wurde generiert"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); bOut.write(cert.getEncoded()); bOut.flush(); bOut.close(); InputStream in = new ByteArrayInputStream(bOut.toByteArray()); Provider provBC = Security.getProvider(Constants.SECURITY_PROVIDER); CertificateFactory fact = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE,provBC); //CertificateFactory fact = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE,Constants.SECURITY_PROVIDER); X509Certificate x509Cert; //Collection collection = new ArrayList(); x509Cert = (X509Certificate) fact.generateCertificate(in); byte[] b = x509Cert.getEncoded(); String name = Constants.CRYPTO_FILES_DIR + File.separator + System.currentTimeMillis(); File f = new File(name+".p7b"); FileOutputStream fos = new FileOutputStream(f); fos.write(b); fos.flush(); fos.close(); f = new File(name+".pem"); fos = new FileOutputStream(f); fos.write(x509Cert.toString().getBytes()); fos.flush(); fos.close(); jta.setText("Zerifikat:\n"+x509Cert+"\n"+jta.getText()); jta.setText("********************************************************************\n\n"+jta.getText()); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SignatureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateExpiredException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateNotYetValidException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
C++
UTF-8
2,050
2.703125
3
[]
no_license
#include <cstdio> #include <iostream> #include <vector> using namespace std; struct item { int h, t, cnt; item(int _h, int _t, int _cnt) { h = _h; t = _t; cnt = _cnt; } }; const int MAX_N = 1000, inf = 1000 * 1000 * 1000; int f[MAX_N][MAX_N], A[MAX_N][2], B[MAX_N][2]; bool used[MAX_N][MAX_N], used1[MAX_N][MAX_N]; int n, m, R; bool _draw = 0, b_iv = 0; int _iv = inf, _zm = 0; vector <item> Q; int find(int h, int t, int cnt) { int s = 0; Q.push_back(item(h, t, cnt)); while (s < Q.size()) { int h = Q[s].h, t = Q[s].t, cnt = Q[s].cnt; ++s; if (h + t > R) { // f[h][t] = 2 + 1; _zm = max(_zm, cnt); //return 2; continue; } if (h + t == 0) { _iv = min(_iv, cnt); b_iv = 1; continue; } if (used[h][t]) { // _draw = 1; continue; } used[h][t] = 1; for (int i = 1; i <= min(h, n); ++i) Q.push_back(item(h - i + A[i][0], t + A[i][1], cnt + 1)); for (int i = 1; i <= min(t, m); ++i) Q.push_back(item(h + B[i][0], t - i + B[i][1], cnt + 1)); } } int find1(int h, int t, int cnt) { if (h + t > R) return 1; if (f[h][t]) return f[h][t] - 1; if (used1[h][t]) { _draw = 1; return 0; } used1[h][t] = 1; int _res = 0; for (int i = 1; i <= min(h, n); ++i) { int res = find1(h - i + A[i][0], t + A[i][1], cnt + 1); _res = max(_res, res); } for (int i = 1; i <= min(t, m); ++i) { int res = find1(h + B[i][0], t - i + B[i][1], cnt + 1); _res = max(_res, res); } f[h][t] = _res + 1; if (!_res) return 0; else { ++f[h][t]; return _res + 1; } } int main() { int h, t; cin >> h >> t >> R; cin >> n; for (int i = 1; i <= n; ++i) cin >> A[i][0] >> A[i][1]; cin >> m; for (int i = 1; i <= m; ++i) cin >> B[i][0] >> B[i][1]; find(h, t, 0); int res = find1(h, t, 0); /*if (!res) cout << "Draw"; else if (res == 1) cout << "Ivan" << endl << _iv; else cout << "Zmey" << endl << _zm; */ if (b_iv) cout << "Ivan" << endl << _iv; else if (_draw) cout << "Draw"; else cout << "Zmey" << endl << max(res - 1, _zm); return 0; }
Java
UTF-8
526
1.757813
2
[]
no_license
package com.microsoft.identity.common.internal.authorities; public class AnyOrganizationalAccount extends AzureActiveDirectoryAudience { public AnyOrganizationalAccount() { setTenantId("organizations"); } public AnyOrganizationalAccount(String paramString) { setCloudUrl(paramString); setTenantId("organizations"); } } /* Location: * Qualified Name: com.microsoft.identity.common.internal.authorities.AnyOrganizationalAccount * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
C#
UTF-8
9,111
3.078125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Nito.UniformResourceIdentifiers.Implementation { /// <summary> /// Provides utility methods for parsing URIs. /// </summary> public static class Parser { /// <summary> /// See Appendix B, except we make use of a non-capturing group for the scheme. /// </summary> // scheme (group 1) = (?:([^:/?#]+):)? // authority (groups 2-3) = (//([^/?#]*))? // path (group 4) = ([^?#]*) // query (groups 5-6) = (\?([^#]*))? // fragment (groups 7-8) = (#(.*))? private static readonly Regex UriReferenceRegex = new Regex(@"^(?:([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$", RegexOptions.CultureInvariant); /// <summary> /// Breaks a URI reference into its components, without any decoding or verification of them. /// </summary> /// <param name="uriReference">The string to parse.</param> /// <param name="scheme">On return, contains the scheme. May be <c>null</c>, but cannot be the empty string.</param> /// <param name="authority">On return, contains the authority. May be <c>null</c> or the empty string.</param> /// <param name="path">On return, contains the path. May be the empty string, but cannot be <c>null</c>.</param> /// <param name="query">On return, contains the query. May be <c>null</c> or the empty string.</param> /// <param name="fragment">On return, contains the fragment. May be <c>null</c> or the empty string.</param> public static bool TryCoarseParseUriReference(string uriReference, out string? scheme, out string? authority, out string path, out string? query, out string? fragment) { path = ""; scheme = authority = query = fragment = null; var match = UriReferenceRegex.Match(uriReference); if (!match.Success) return false; scheme = match.Groups[1].Value.Length == 0 ? null : match.Groups[1].Value; authority = match.Groups[2].Value.Length == 0 ? null : match.Groups[3].Value; path = match.Groups[4].Value; query = match.Groups[5].Value.Length == 0 ? null : match.Groups[6].Value; fragment = match.Groups[7].Value.Length == 0 ? null : match.Groups[8].Value; return true; } /// <summary> /// Breaks an authority into its components, without any decoding or verification of them. /// </summary> /// <param name="authority">The authority. May be <c>null</c> or the empty string.</param> /// <param name="userInfo">On return, contains the user info. May be <c>null</c> or the empty string.</param> /// <param name="host">On return, contains the host. May be <c>null</c> or the empty string.</param> /// <param name="port">On return, contains the port. May be <c>null</c> or the empty string.</param> public static void CoarseParseAuthority(string? authority, out string? userInfo, out string? host, out string? port) { userInfo = host = port = null; if (authority == null) return; // Strip off the UserInfo, which can never contain '@'. var atDelimiter = authority.IndexOf('@'); if (atDelimiter != -1) { userInfo = authority.Substring(0, atDelimiter); authority = authority.Substring(atDelimiter + 1); } // Strip off the Port. int colonDelimiter; if (authority.StartsWith("[", StringComparison.Ordinal)) { // If the host starts with '[', then it can contain ':', so we have to first find the ']' and only look for a ':' after that. var closeBracketIndex = authority.LastIndexOf(']'); if (closeBracketIndex == -1) closeBracketIndex = authority.Length - 1; colonDelimiter = authority.IndexOf(':', closeBracketIndex + 1); } else { // If the host doesn't start with '[', then it can't contain ':'. colonDelimiter = authority.LastIndexOf(':'); } if (colonDelimiter != -1) { port = authority.Substring(colonDelimiter + 1); authority = authority.Substring(0, colonDelimiter); } // All that remains is the Host. host = authority; } /// <summary> /// Breaks a URI reference into its components. Performs decoding and verification of them. /// </summary> /// <param name="uriReference">The string to parse.</param> /// <param name="scheme">On return, contains the scheme. May be <c>null</c>, but cannot be the empty string.</param> /// <param name="userInfo">On return, contains the user info. May be <c>null</c> or the empty string.</param> /// <param name="host">On return, contains the host. May be <c>null</c> or the empty string.</param> /// <param name="port">On return, contains the port. May be <c>null</c> or the empty string.</param> /// <param name="pathSegments">On return, contains the path segments. May be empty, but cannot be <c>null</c>.</param> /// <param name="query">On return, contains the query. May be <c>null</c> or the empty string.</param> /// <param name="fragment">On return, contains the fragment. May be <c>null</c> or the empty string.</param> public static void ParseUriReference(string uriReference, out string? scheme, out string? userInfo, out string? host, out string? port, out IReadOnlyList<string> pathSegments, out string? query, out string? fragment) { // Unescape unreserved characters; this is always a safe operation, and only needs to be done once because "%%" is not a valid input anyway. uriReference = Utility.DecodeUnreserved(uriReference); // Coarse-parse it into sections. var isUri = TryCoarseParseUriReference(uriReference, out scheme, out var authority, out var path, out query, out fragment); CoarseParseAuthority(authority, out userInfo, out host, out port); if (!isUri) throw new FormatException($"Invalid URI reference \"{uriReference}\"."); // Decode and verify each one. if (scheme != null && !Utility.IsValidScheme(scheme)) throw new FormatException($"Invalid scheme \"{scheme}\" in URI reference \"{uriReference}\"."); if (userInfo != null) userInfo = PercentDecode(userInfo, Utility.UserInfoCharIsSafe, "user info", uriReference); if (host != null) host = Utility.HostIsIpAddress(host) ? host : PercentDecode(host, Utility.HostRegNameCharIsSafe, "host", uriReference); if (port != null && !Utility.IsValidPort(port)) throw new FormatException($"Invalid port \"{port}\" in URI reference \"{uriReference}\"."); pathSegments = path.Split('/').Select(x => PercentDecode(x, Utility.PathSegmentCharIsSafe, "path segment", uriReference)).ToList(); if (query != null) query = PercentDecode(query, Utility.QueryCharIsSafe, "query", uriReference); if (fragment != null) fragment = PercentDecode(fragment, Utility.FragmentCharIsSafe, "fragment", uriReference); } /// <summary> /// Breaks a URI reference into its components. Performs decoding and verification of them. /// </summary> /// <param name="uriReference">The string to parse.</param> public static UriParseResult ParseUriReference(string uriReference) { var result = new UriParseResult(); ParseUriReference(uriReference, out result.Scheme, out result.UserInfo, out result.Host, out result.Port, out result.PathSegments, out result.Query, out result.Fragment); return result; } /// <summary> /// Validates and percent-decodes a given string. /// </summary> /// <param name="value">The string to decode.</param> /// <param name="isSafe">A function defining which characters do not need percent-encoding.</param> /// <param name="part">The name of the part of the URI. This is used for a detailed exception message.</param> /// <param name="uriReference">The full URI being parsed. This is used for a detailed exception message.</param> public static string PercentDecode(string value, Func<byte, bool> isSafe, string part, string uriReference) { try { return Utility.PercentDecode(value, isSafe); } catch (Exception ex) { throw new FormatException($"Invalid {part} \"{value}\" in URI reference \"{uriReference}\".", ex); } } } }
Python
UTF-8
777
2.84375
3
[]
no_license
class Solution(object): def thirdMax(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return max(nums) m_map = {} for v in nums: m_map[v] = m_map.get(v, 0) + 1 if len(m_map.keys()) < 3: return max(nums) max_v, sec_v, third_v = -sys.maxint, -sys.maxint, -sys.maxint for v in nums: if v > max_v: third_v = sec_v sec_v = max_v max_v = v elif v > sec_v and v != max_v: third_v = sec_v sec_v = v elif v > third_v and v != sec_v and v != max_v: third_v = v return third_v
Python
UTF-8
181
2.9375
3
[]
no_license
screenSize = (900, 700) print(screenSize[0]) testTuple = ('screen size', ) + screenSize print(len(testTuple)) print("screen size" in testTuple) for var in testTuple: print(var)
JavaScript
UTF-8
2,361
3.109375
3
[]
no_license
let arrayTask3 = [ { "id": "37ad3865-ccce-48c0-ab78-ec16b5968f58", "age": 31, "firstName": "Elise", "lastName": "Levine", }, { "id": "fc78e8af-c560-42bd-8a50-0bb73e241025", "lastName": "Welch", "gender": "male", "email": "williamswelch@kangle.com", "address": "948 Wolcott Street, Wauhillau, Wisconsin, 2206" }, { "id": "501ea83a-1136-4f68-960c-913c722f2fb3", "age": 19, "firstName": "Maritza", "email": "maritzairwin@kangle.com", "address": "995 Dearborn Court, Homestead, Florida, 9076" }, { "id": "e9f027ec-f71c-42f4-8a52-0b7e3bee6703", "age": 55, }, { "id": "89e6c19a-2084-4da3-9230-17ed9bf5ba0a", }, { "id": "096589d2-f332-4dd4-95ff-ed0f98c5ce18", "age": 55, "firstName": "Evelyn", "lastName": "Banks", "gender": "female", "email": "evelynbanks@kangle.com", "address": "709 Beach Place, Bethpage, Delaware, 4554", "id": "f92e9eaa-300f-4f53-af16-8ba69c73a1dd", "age": 47, "firstName": "Knowles", "lastName": "Davenport", "gender": "male", "email": "knowlesdavenport@kangle.com", "address": "726 Hale Avenue, Veyo, North Dakota, 1041" } ]; let arraysTask3 = (function (arr) { const task = "Task 3"; const problem = `Да се сортира масив от обекти в зависимост от броя на пропъртитата.`; let array = arr; function sortArrayOfObject(array){ if (!Array.isArray(array)){ result = 'Argument is not array.'; return result; } if (array.length < 1){ result = 'Array is empty.'; return result; } else{ array.sort(function(a, b) { if (Object.keys(a).length > Object.keys(b).length) { return 1; } }); return array; } } let resultsortArrayOfObject = JSON.stringify(sortArrayOfObject(array)); arrayTask3 = JSON.stringify(arrayTask3); document.write(`<div><div class="background"><h3>${task}</h3><p class="problem">${problem}</p></div><p>Sort array is:<br/> ${arrayTask3}.</p><p>${resultsortArrayOfObject}</p</div>`); return { sortArrayOfObject }; })(arrayTask3);
SQL
UTF-8
2,051
2.953125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 08, 2019 at 06:09 AM -- Server version: 10.3.16-MariaDB -- PHP Version: 7.3.6 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: `tutorial` -- -- -------------------------------------------------------- -- -- Table structure for table `course` -- CREATE TABLE `course` ( `Name` varchar(50) NOT NULL, `Id` varchar(10) NOT NULL, `Duration` varchar(15) NOT NULL, `Price` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `course` -- INSERT INTO `course` (`Name`, `Id`, `Duration`, `Price`) VALUES ('FullStack', '1', '6 weeks', '11770'), ('Core Java', '2', '6 weeks', '15000'), ('Python', '3', '7weeks', '10000'), ('Machine Learning', '4', '8 weeks', '20000'), ('Data Science', '5', '8 weeks', '20000'), ('Cyber Security', '6', '6 weeks', '20000'); -- -------------------------------------------------------- -- -- Table structure for table `register` -- CREATE TABLE `register` ( `Username` varchar(75) NOT NULL, `Email` varchar(52) NOT NULL, `Password` varchar(75) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `register` -- INSERT INTO `register` (`Username`, `Email`, `Password`) VALUES ('abhinav', 'abhinav@gmail.com', 'abhinav'), ('admin123', 'admin123@gmail.com', 'admin123'), ('shivam', 'shivam@gmail.com', 'shivam'); -- -- Indexes for dumped tables -- -- -- Indexes for table `register` -- ALTER TABLE `register` ADD PRIMARY KEY (`Email`); 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 */;
JavaScript
UTF-8
4,152
2.5625
3
[]
no_license
var ahn_url = "https://geodata.nationaalgeoregister.nl/ahn2/wms?"; function getAhnFoto(minX, minY, maxX, maxY,size, onSucces) { var url = ahn_url; url += "bbox=" + minX + "," + minY + "," + maxX + "," + maxY; url += "&service=wms"; url += "&VERSION=1.1.1"; url += "&REQUEST=GetMap"; url += "&LAYERS=ahn2_05m_ruw"; url += "&WIDTH="+size; url += "&HEIGHT="+size; url += "&FORMAT=image/png"; url += "&SRS=EPSG:28992"; url += "&styles='ahn2:ahn2_05m_detail'" console.log(url); var loader = new THREE.ImageLoader(); loader.crossOrigin = true; loader.load(url, onSucces); } function color2height(color) { console.log(color.r + ', '+color.g+', '+color.b); var best_delta = 10000000; var best_c2h; for (var i = 0; i < rgb2height.length; i++) { var c2h = rgb2height[i]; console.log() var color_delta = Math.abs(c2h.r - color.r)+Math.abs(c2h.g - color.g)+Math.abs(c2h.b - color.b); if (color_delta < best_delta) { best_delta = color_delta; best_c2h = c2h; } } //console.log("default height: "+color.r + ', '+color.g+', '+color.b); return best_c2h.h; } function getHeightMap(image) { var imageData = getImageData(image); var heightMap = []; var min = 10000; var max = -10000; for (var x = 0; x < image.width; x++) { for (var y = 0; y < image.height; y++) { var c = getPixel(imageData, y, x); var h = color2height(c); min = Math.min(min,h); max = Math.max(max,h); heightMap.push(h); } } console.log("min height: "+min); console.log("max height: "+max); return heightMap; } function getImageData(image) { var canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0); return context.getImageData(0, 0, image.width, image.height); } function getPixel(imagedata, x, y) { var position = (x + imagedata.width * y) * 4; var data = imagedata.data; return { r : data[position], g : data[position + 1], b : data[position + 2], a : data[position + 3] }; } rgb2height = [ { r : 255, g : 255, b : 255, h : -8 }, { r : 8, g : 56, b : 123, h : -7.5 }, { r : 8, g : 69, b : 132, h : -6.5 }, { r : 16, g : 81, b : 132, h : -5.5 }, { r : 16, g : 93, b : 132, h : -4.5 }, { r : 16, g : 105, b : 140, h : -3.5 }, { r : 24, g : 117, b : 140, h : -2.75 }, { r : 24, g : 130, b : 140, h : -2.25 }, { r : 24, g : 146, b : 148, h : -1.75 }, { r : 33, g : 150, b : 148, h : -1.25 }, { r : 33, g : 158, b : 140, h : -0.75 }, { r : 24, g : 162, b : 132, h : -0.25 }, { r : 24, g : 170, b : 123, h : 0.25 }, { r : 24, g : 178, b : 107, h : 0.75 }, { r : 16, g : 186, b : 99, h : 1.25 }, { r : 16, g : 190, b : 82, h : 1.75 }, { r : 8, g : 199, b : 66, h : 2.25 }, { r : 8, g : 207, b : 49, h : 2.75 }, { r : 8, g : 207, b : 49, h : 3.25 }, { r : 0, g : 219, b : 0, h : 3.75 }, { r : 16, g : 223, b : 0, h : 4.25 }, { r : 41, g : 227, b : 0, h : 4.75 }, { r : 66, g : 231, b : 0, h : 5.5 }, { r : 99, g : 235, b : 0, h : 6.5 }, { r : 123, g : 239, b : 0, h : 7.5 }, { r : 148, g : 243, b : 0, h : 8.5 }, { r : 181, g : 247, b : 0, h : 9.5 }, { r : 206, g : 247, b : 0, h : 11 }, { r : 239, g : 255, b : 0, h : 13 }, { r : 255, g : 251, b : 0, h : 15 }, { r : 255, g : 243, b : 0, h : 17 }, { r : 255, g : 231, b : 0, h : 19 }, { r : 247, g : 215, b : 0, h : 22.5 }, { r : 247, g : 207, b : 8, h : 27.5 }, { r : 247, g : 199, b : 8, h : 32.5 }, { r : 247, g : 190, b : 8, h : 37.5 }, { r : 247, g : 182, b : 16, h : 42.5 }, { r : 239, g : 166, b : 16, h : 47.5 }, { r : 239, g : 162, b : 16, h : 55 }, { r : 239, g : 154, b : 16, h : 65 }, { r : 231, g : 142, b : 24, h : 75 }, { r : 231, g : 134, b : 33, h : 85 }, { r : 222, g : 121, b : 33, h : 95 }, { r : 214, g : 109, b : 41, h : 112.5 }, { r : 214, g : 105, b : 41, h : 137.5 }, { r : 206, g : 97, b : 49, h : 162.5 }, { r : 206, g : 89, b : 49, h : 187.5 }, { r : 198, g : 85, b : 57, h : 225 }, { r : 198, g : 81, b : 57, h : 275 } ];
Markdown
UTF-8
3,112
2.90625
3
[]
no_license
# Buidler Hackathon Boilerplate This repository contains a sample project that you can use as the starting point for your Ethereum project. It's also a great fit for learning the basics of smart contract development. This project is intended to be used with the [Buidler Beginners Tutorial](http://buidler.dev/tutorial), but you should be able to follow it by yourself by reading the README and exploring its `contracts`, `tests`, `scripts` and `frontend` directories. ## Quick start The first things you need to do are cloning this repository and installing its dependencies: ```sh git clone https://github.com/nomiclabs/buidler-hackathon-boilerplate.git cd buidler-hackathon-boilerplate npm install ``` Once installed, let's run Buidler's testing network: ```sh npx buidler node ``` Then, on a new terminal, go to the repository's root folder and run this to deploy your contract: ```sh npx buidler run scripts/deploy.js --network localhost ``` Finally, we can run the frontend with: ```sh cd frontend npm install npm start ``` Open [http://localhost:3000/](http://localhost:3000/) to see your Dapp. You will need to have [Metamask](http://metamask.io) installed and listening to `localhost 8545`. ## User Guide You can find detailed instructions on using this repository and many tips in [its documentation](http://buidler.dev/tutorial). - [Project description (Token.sol)](http://buidler.dev/tutorial/4-contracts/) - [Setting up the environment](http://buidler.dev/tutorial/1-setup/) - [Testing with Buidler, Mocha and Waffle](http://buidler.dev/tutorial/5-test/) - [Setting up Metamask](http://buidler.dev/tutorial/8-frontend/#setting-up-metamask) - [Buidler's full documentation](https://buidler.dev/getting-started/) For a complete introduction to Buidler, refer to [this guide](https://buidler.dev/getting-started/#overview). ## What’s Included? Your environment will have everything you need to build a Dapp powered by Buidler and React. - [Buidler](https://buidler.dev/): An Ethereum development task runner and testing network. - [Mocha](https://mochajs.org/): A JavaScript test runner. - [Chai](https://www.chaijs.com/): A JavaScript assertion library. - [ethers.js](https://docs.ethers.io/ethers.js/html/): A JavaScript library for interacting with Ethereum. - [Waffle](https://github.com/EthWorks/Waffle/): To have Ethereum-specific Chai assertions/mathers. - [A sample frontend/Dapp](./frontend): A Dapp which uses [Create React App](https://github.com/facebook/create-react-app). ## Troubleshooting - `Invalid nonce` errors: if you are seeing this error on the `buidler node` console, try resetting your Metamask account. This will reset the account's transaction history and also the nonce. Open Metamask, click on your account followed by `Settings > Advanced > Reset Account`. ## Feedback, help and news We'd love to have your feedback on this tutorial. Feel free to reach us through this repository or [our Telegram Support Group](https://t.me/BuidlerSupport). Also you can [follow Nomic Labs on Twitter](https://twitter.com/nomiclabs). **Happy _buidling_!**
Python
UTF-8
1,398
4.09375
4
[]
no_license
from lib import assertion def insertion_sort(l): for i in range(1, len(l)): current = l[i] j = i while j > 0 and current < l[j - 1]: l[j] = l[j - 1] j -= 1 l[j] = current def main(): l1 = [2,5,3,4,1] l2 = [5,4,3,2,1] l3 = [1] l4 = [5,1] insertion_sort(l1) insertion_sort(l2) insertion_sort(l3) insertion_sort(l4) assertion.equals([1,2,3,4,5], l1) assertion.equals([1,2,3,4,5], l2) assertion.equals([1], l3) assertion.equals([1,5], l4) if __name__ == '__main__': main() # why are we using this value 'current' instead of just truly swapping with a multiple # assignment like : # for j in range(i, 0, -1): # if l[j] < l[j -1]: # l[j - 1], l[j] = l[j], l[j - 1] # The answer is that we don't actually need to do a true swap # because the current value only needs to be assigned once # (when the jth value is finally <= to current) # worst case running time (list is in reverse order) is O(n**2) # but in the best case (l is nearly sorted) we have O(n) because # there are very few iterations of the inner loop. average case is # quadratic. # insertion sort is very fast for small arrays but impractically slow for large ones # use it when: data is nearly sorted or problem size is small (because it has low overhead)
C++
UTF-8
561
2.9375
3
[]
no_license
/** * @file test_default_ctor.cpp * * Tests bigint default ctor. * * @author Michael John Decker, Ph.D. <mdecke@bsgu.edu> */ #include <iostream> #include <cassert> #include "bigint.hpp" int main() { { // setup bigint b(4); bigint a; // test a = 4; // verification assert(b==a); } { // setup bigint b(2147483647); bigint a; // test a = 2147483647; // verification assert(b==a); } { // setup bigint b; // test // verification assert(b==0); } return 0; }
Markdown
UTF-8
5,962
2.59375
3
[]
no_license
一八三 第十八章 不入虎穴 忆君小心翼翼,很缓慢地靠近这扇大铁门,从外形看来这扇铁门较前一扇更厚更重。表面油漆得光滑无比,在黑暗中发出那淡淡的亮光。 忆君轻轻推了推,竟是纹封未动,他不敢全力以赴,生怕自己的冒失,换来轻易的牺牲,因为他不敢讲,自己人洞以来,对方是否完全未曾发觉。 他再度举起了手往门上按去,掌上内力往外徐增,突然觉出门上冰凉得出奇,立刻猛将手掌撤回,细细一看掌上又没有什么异样。 “嘿!这模样那算得上天下第一奇人玄机子的传人!”忆君陡地豪气大发。气涌丹田,一蓬!蓬厂两掌直往铁门拍去——只闻铁门发出一阵刺耳的倾轧声,突地飞打开来——“叮当!叮当!” 一串铃声随着铁门的打开直向甬道内里传出。这两道好长好黑,地势竞渐渐往下低伸去。 忆君知道身形已是败露,于是再也不顾忌什么,一身真气充布四梢,握着金蛇灵鞭似飞般往内里闯去。 突然一阵微小的声浪传来——“妈的!这风云洞也会出事情,今天看来大势不妙!” 忆君警觉地一飘身上了洞顶,背脊往洞顶一靠,那晓背心一阵刺痛,敢情顶上竞布满如蜂针一般细小钢刺。幸喜忆君周身罩着天池宝衫,否则也是着了道儿。 一盏灯火从洞里一摇一幌而来,两条人影拖着沉重步子,口出怨言道:“老李自己不敢出手,硬要咱们来看。哼,还不一定又是上次那只该死的老鼠去玩这铃绳!那个小于敢不要命闯这风云洞!” 另一人依依吾吾答应着,突然他张口喊道:“啊!老张,那铁门…铁门开了…”语气未落两人已如木偶般呆住,油灯错黯的光辉照映下,两人的脸孔扭曲而恐怖。 忆君“呼”地飘身下来,突然他头顶一昏,一个踉跄几乎跌了一跤。 “咦!”他惊叹一声,连忙运真气,却丝毫没有异样,他一掌往那提灯者颈上拍去,立刻那人被封的穴道解了下来。 “这里是什么地方?”忆君一手将油灯提过,另一手飞快往那人手腕脉胳。 那人面上惊骇已极,张口嚅嚅道:“门门……你手!你手!” 突然他面上一阵紫气翻冒,眼上一挑墓地死去。 前次的教训犹如昨日,他来不及再解开另一人的穴道,赶紧盘膝坐下,他知道金蛇灵鞭有解毒之功效,立刻将金蛇灵鞭拿了出来。 “老张……嘿!李四……”一阵呼唤往地道中传出,隐约能觉出有十整条人影朝此方行来。 忆君心蓦地紧张,虽然金蛇灵鞭的一双利齿已隐入他右掌,正将毒素丝丝吸出,但再快也不能人来之前吸尽,何况还有一只左掌。 逃走他可不愿意,索性闭日打坐,除了护住心肺的真力外,其他的迸发而出,只见天池宝衫似吹气般鼓起,隐隐有风雷之声,这可正是阴阳相会的功夫。 “嘿!…白衣人,快……快禀告长老去!” 其中一人觉出白衣人有些不对,立刻止住他们道:“哈!这白衣人不过是瓮中之鳖,何需劳动长老!咱们将他擒了吧!” 又一人道:“是啊!那门被他推开,门上有全长老断魂五毒之一。哈!看来咱们哥儿有乐可享了。” 忆君闭目不言,但心中已大觉轻松——“凭你们这几块料也管得住我!”心中想着,竟将护身真力收去大半,天地室衫立刻平了下去。 “嘿!好重!”十作人将忆君抬了起来,另一人去拉那李四。突然“呼轰!”一声,忆君护身真气蓦地暴发,只闻十余人同时惨叫。忆君稳稳地回复跌坐的姿式,而抬他之人竟被震得四面飞出,轻的跌翻地昏死过去,重的撞在壁上脑浆迸裂,只余下那去拉李四之人,骇得他掉头如飞奔去。 忆君要追杀已来不及,此时他行功正至紧要关头,一丝也大意不得。 “当!当!”锣声急如骤雨,在洞中回复来,忆君听得嘴角泛起冷笑。 “咱今天不闹他个地覆天翻真愧为白衣人了!”他心中如此想着,望望那甬道深处。盏茶不到突地站了起来,手握金鞭龙行虎步般直往内去。 “这风云洞中也让人进了来!”飘来一个焦灼的声音,内里含着责备也含着煌急。忆君这次再也不避让,昂然地迎上前去。 转过数曲弯道,前面豁然开阔,偌大一间石室迎面在他身前展开。 数十个劲装黑眼汉子分列两侧,当中立着三人。一个银须尺许的老者,看着白衣人的来临,微微一笑,道:“白衣人侠仙驾此处,咱风云洞主灵山之狐洪武有失远迎讶!”但忆君看得出这风云洞主一盏灯火从洞里一摇一幌而来,两条人影拖着沉重步子,口出怨示道:“老李自己不敢出手,硬要咱们来看。哼,还不一定又是上次那只该死的老鼠去玩这铃绳!那个小于敢不要命闯这风云洞!” 另一人依依吾吾答应着,突然他张口喊道:“啊!老张,那铁门…… 铁门开了……”语气未落两人已如木偶般呆住,油灯错黯的光辉照映下,两人的脸孔扭曲而恐怖。 忆君“呼”地飘身下来,突然他头顶一昏,一个踉跄几乎跌了一跤。 “咦!”他惊叹一声,连忙运直气,却丝毫没有异样,他一掌往那提灯者颈上拍去,立刻那人被封的穴道解了下来。 “这里是什么地方?”忆君一手将油灯提过,另一手飞快往那人手腕脉胳。 那人面上惊骇已极,张口儒儒道:“门门……你手!你手!” 突然他面上一阵紫气翻冒,眼上一挑墓地死去。
Java
UTF-8
3,127
2.125
2
[ "Apache-2.0" ]
permissive
package com.clakestudio.pc.everyday.password; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.clakestudio.pc.everyday.R; import com.clakestudio.pc.everyday.forgotpassword.ForgotPasswordActivity; import com.clakestudio.pc.everyday.showgoal.ShowGoalActivity; public class PasswordFragment extends Fragment implements PasswordContract.View, View.OnClickListener, TextWatcher { private PasswordPresenter presenter; private EditText etPassword; public PasswordFragment() { // Required empty public constructor } public static PasswordFragment newInstance() { return new PasswordFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_password, container, false); Button btForgotPassword = view.findViewById(R.id.btForgotPassword); etPassword = view.findViewById(R.id.etPassword); etPassword.addTextChangedListener(this); btForgotPassword.setOnClickListener(this); return view; } // TODO: Rename method, update argument and hook method into UI event @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); } @Override public void setPresenter(PasswordContract.Presenter presenter) { this.presenter = (PasswordPresenter) presenter; } @Override public void stop() { } @Override public void onClick(View v) { presenter.startForgotPasswordActivity(); } @Override public void showStartShowGoalActivity() { startActivity(new Intent(getActivity(), ShowGoalActivity.class)); if (getActivity() != null) getActivity().finish(); } @Override public void showStartForgotPasswordActivity() { startActivity(new Intent(getActivity(), ForgotPasswordActivity.class)); if (getActivity() != null) getActivity().finish(); } @Override public void showWrongPasswordToast() { Toast.makeText(getContext(), "Wrong password", Toast.LENGTH_SHORT).show(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { presenter.checkPasswordCorrectness(etPassword.getText().toString()); } }
Swift
UTF-8
1,359
2.84375
3
[]
no_license
// // GameBodyView.swift // Memorize // // Created by Chad Smith on 6/14/21. // import SwiftUI struct GameBodyView: View { @ObservedObject var game: EmojiMemoryGame var namespace: Namespace.ID var body: some View { AspectVGrid(items: game.cards, aspectRatio: CardConstants.aspectRatio) { card in if game.isUndealt(card) || card.isMatched && !card.isFaceUp { Color.clear } else { CardView(card: card) .matchedGeometryEffect(id: card.id, in: namespace) .padding(4) .transition(.asymmetric(insertion: .identity, removal: .scale)) .zIndex(game.calculateZIndex(for: card)) .onTapGesture { withAnimation { game.choose(card) } } } } .foregroundColor(game.themeColor) } } struct GameBodyView_Previews: PreviewProvider { @Namespace static var dealingNamespace static var previews: some View { let game = EmojiMemoryGame() game.choose(game.cards.first!) return ForEach(ColorScheme.allCases, id: \.self) { GameBodyView(game: game, namespace: dealingNamespace).preferredColorScheme($0) } } }
Java
UTF-8
505
2.453125
2
[]
no_license
/** * */ package edu.sjsu.library.dto; /** * @author balex * */ public class ItemContext { private ItemState itemState ; public ItemContext() { setState(new ItemDelistedState()); } // normally only called by classes implementing the State interface public void setState(ItemState newState) { this.itemState = newState; } public void changeItemState(Item item) { if(itemState!=null) { itemState.changeItemState(item); } } }
JavaScript
UTF-8
2,148
2.53125
3
[]
no_license
var Event = YAHOO.util.Event; var Element = YAHOO.util.Element; var Dom = YAHOO.util.Dom; function getFormName( form ){ return form.className.split(' ')[0]; } function useNullForThisField(field){ return Dom.hasClass(field, 'identifier') && field.value == ''; } function toJSON( obj ){ return YAHOO.lang.JSON.stringify(obj); } function buttonClicked(e, options){ var buttonClicked = Event.getTarget(e); if( buttonClicked.type != 'button' ) return; if( !options ){ var options = new Object(); } if( !options.params ){ options.params = new Object(); } var requestForm = Dom.getAncestorByClassName( buttonClicked, 'saveParent' ); var formName = getFormName( requestForm ); var fields = Dom.getElementsByClassName( formName+'Field', '', requestForm ); // Since this is a div and not a form, we must assign manually. // If it were a form, the browser would do this automatically. for( var i=0; i<fields.length; i++ ){ if (useNullForThisField(fields[i])){ options.params[fields[i].name] = null; } else{ options.params[fields[i].name] = fields[i].value; } } // if it exists, get the parent entity's identifier and // set it as part of the request object var requestFormParent = Dom.getAncestorByClassName( requestForm, 'saveParent' ); if( requestFormParent ){ var saveParentName = getFormName( requestFormParent ); var identifiers = Dom.getElementsByClassName( saveParentName+'Field', 'input', requestFormParent ); if( identifiers ){ for( var i=0; i<identifiers.length; i++ ){ if( Dom.hasClass(identifiers[i], 'identifier') ){ options.params[identifiers[i].name] = identifiers[i].value; break; } } } } var operation = '/ajax/'+buttonClicked.name; var callback = {success: options.saveSuccess}; var body = YAHOO.lang.JSON.stringify(options.params); ajax( 'POST', operation, callback, body ); } function ajax( method, operation, callback, body ){ YAHOO.util.Connect.setDefaultPostHeader(false); YAHOO.util.Connect.initHeader('CONTENT-TYPE','application/json'); var request = YAHOO.util.Connect.asyncRequest(method, operation, callback, body); return request; }
C++
GB18030
747
3.140625
3
[]
no_license
#include<iostream> #include<algorithm> #include<cstring> using namespace std; char str[25]; void Reverse(char s[]) { int tail=0; while(isdigit(s[tail])) tail++; tail--; int head=0; while(s[tail]=='0'&&tail>0) tail--;//ȥ0 while(s[head]=='0'&&tail>0) ++head;//ȥǰ0 for(;tail>=head;--tail) cout<<s[tail]; } int main() { int i=0,j,k; char s1[25],s2[25]; while(cin>>str[i]) i++;// int l=strlen(str)-1; for(j=0;j<=l;++j) if(isdigit(str[j])) s1[j]=str[j]; else break; Reverse(s1); if(j<=l) cout<<str[j++]; if(str[j-1]=='/'||str[j-1]=='.'){ for(k=0;j<=l;) s2[k]=str[j],j++,k++; Reverse(s2); } return 0; }
Java
UTF-8
414
2.171875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jmegame.networking; /** * * @author campbell */ public interface IBulletSource { void fireBullet(int damage); void addCooldown(float cooldown); void setCooldown(float cooldown); float getCooldown(); }
Java
UTF-8
1,445
2.375
2
[]
no_license
/** * 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.example.jing.phone.commands.engine; import com.example.jing.phone.commands.ObdCommand; import com.example.jing.phone.enums.AvailableCommandNames; public class MassAirFlowObdCommand extends ObdCommand { private float maf = -1.0f; public MassAirFlowObdCommand() { super("01 10"); } public MassAirFlowObdCommand(MassAirFlowObdCommand other) { super(other); } @Override protected void performCalculations() { maf = (buffer.get(2) * 256 + buffer.get(3)) / 100.0f; } @Override public String getFormattedResult() { return String.format("%.2f%s", maf, "g/s"); } public double getMAF() { return maf; } @Override public String getName() { return AvailableCommandNames.MAF.getValue(); } }
PHP
UTF-8
1,017
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "medchart". * * @property string $id * @property string $date_created * @property string $date_updated */ class Medchart extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'medchart'; } /** * @inheritdoc */ public function rules() { return [ [['date_created', 'date_updated'], 'safe'] ]; } public function getMeds() { // Customer has_many Order via Order.customer_id -> id return $this->hasMany(Med::className(), ['medchart_id' => 'id']); } public function extraFields() { return [ 'meds', ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'date_created' => 'Date Created', 'date_updated' => 'Date Updated', ]; } }
Markdown
UTF-8
3,487
3.6875
4
[]
no_license
#### 什么叫柯里化? > 维基百科:把接收多个参数的函数变换成接收一个单一参数(最初函数的第一个参数)的函数,并返回接受剩余的参数而且返回结果的新函数的技术。其由数学家Haskell Brooks Curry提出,并以curry命名。 > 个人理解:利用闭包,将一个具有多个参数的函数,拆分成多个只有一个参数的函数。 #### 柯里化用途? 1. 参数复用 > 假如一个函数有三个参数,第一个参数比较固定,其余两个参数不固定。可以用柯里化将第一题一个参数的调用当作缓存。 ``` function uri(protocol, hostname, pathname){ return `${protocol}${hostname}${pathname}` } uri('https://', 'baidu.com', '/img') uri('https://', 'jd.com', '/orders') // 第一个参数每次调用都需要重新写一遍,假如第一个参数很长就恶心了 function uri(prototype){ return function(hostname, pathname) { return `${protocol}${hostname}${pathname}` } } let httpsUri = uri('https'); httpsUri('baidu.com', '/img') httpsUri('jd.com', '/orders') ``` 2. 提前确认/提前返回 ``` // 多浏览器兼容注册事件 const registEvent = (function(){ if (window.addEventListener) { return function(element, eventType, callback, useCapture) { element.addEventListener(eventType, function(event) { callback.call(element, event) }, useCapture); } } else if (winbdow.attachEvent) { return function(element, eventType, callback) { element.attachEvent(`on${eventType}`, function(event) { callback.call(element, event) }); } } }) (); registEvent(window, 'click', function(e){ console.log(this, e) }) ``` 3. 延迟执行 // 实现一个函数add,add(1)(2)(3) = 6;add(1, 2, 3)(4) = 10;add(1)(2)(3)(4)(5) = 15; ``` function add(...args){ const inner = function(...innerArgs) { args.push(...innerArgs); return inner } // 函数返回会发生隐式转换,从而调用toString。所以在同String里进行加工 inner.toString = () => { return Number(args.reduce((total, current) => total + current)) } return inner } function add (...args) { const inner = function () { if (arguments.length === 0) { return args.reduce((total, curr) => total + curr); } else { args.push(...arguments); return inner } } return inner } console.log(add(2)(1, 3, 4)(1)(1)()); // 12 ``` #### 实现一个通用的柯里化工具函数 ``` function commonCurrying(fn, args = []) { let _this = this let len = fn.length; return function(..._args) { args.push(..._args) if (args.length < len) { return commonCurrying.call(_this, fn, args); } // 递归边界条件: 收集的参数个数等于原函数的参数个数时, 再将原函数执行。 return fn.apply(this, args); } } function uri(protocol, hostname, pathname){ return `${protocol}${hostname}${pathname}` } let getUri = commonCurrying(uri); let baiduUri = getUri('http://')('baidu.com')('/img') console.log(baiduUri) const addOne = x => x + 1; const addTwo = x => x + 2; const pipe = (input) => (...functions) => functions.reduce( (accumulator, currentFunc) => { input = currentFunc(accumulator); return input; }, input ) let finalVal = pipe(5)(addOne, addTwo) console.log(finalVal)
PHP
UTF-8
634
2.59375
3
[ "MIT" ]
permissive
<?php namespace Joseki\Form; use Joseki\Form\Controls\SubmitButton; use Nextras\Forms\Controls\DatePicker; class Container extends \Nette\Forms\Container { /** * @param $name * @param null $caption * @return SubmitButton|\Nette\Forms\Controls\SubmitButton */ public function addSubmit($name, $caption = NULL) { return $this[$name] = new SubmitButton($caption); } /** * Adds DatePicker to enable user-friendly GUI for picking date * @param $name * @param null $label * @return DatePicker */ public function addDatePicker($name, $label = NULL) { return $this[$name] = new DatePicker($label); } }
Markdown
UTF-8
1,000
2.53125
3
[]
no_license
--- layout: event title: Planning Inspectorate Rainbow Network talks Bristol Pride excerpt: "Join the Planning Inspectorate's LGBT+ Network for a talk on Bristol Pride's history and relevance. " date: 2023-05-22T08:35:58.158Z event: host: Planning Inspectorate Rainbow Network start: 2023-06-15T13:00:58.211Z end: "" deadline: 2023-06-15T12:45:58.279Z email: jean.russell.6g@planninginspectorate.gov.uk location: MS Teams category: - south-west --- The Rainbow Network is delighted to welcome Daryn Carter MBE, Director of Programming and Partnerships at Bristol Pride. Daryn will talk about the history and relevance of Bristol Pride, and why Pride is important to him. The Planning Inspectorate is also sponsoring Bristol Pride 2023 in order to further our outreach as well as equality aims. This meeting will add value to that sponsorship, allow colleagues to learn more about Bristol Pride and give Daryn an opportunity to meet us. All welcome! Please contact [Jeanie Russell](mailto:jean.russell.6g@planninginspectorate.gov.uk) for more details or the Teams link.
Python
UTF-8
4,930
2.59375
3
[]
no_license
import re import os home = os.path.expanduser("~") + "/" #TODO get file link from arguments main_tex_file = "%sDocuments/hiwi/funkeybox/00_documentation/2019-xx_FunkeyBox_Paper/Text/" % home # RegExp Pattern input_pattern = "\\input\{(.)*.tex\}" cite_pattern = "\\cite\{[a-zA-Z0-9, ]*\}" bibtex_pattern = "\\bibliography\{[a-zA-Z0-9/_.]*\}" source_pattern = "@([a-zA-Z]+{)" # Bibtex file that will be sorted bibtex_file = "NOT_FOUND" bib_dict = dict() cite_list = list() def get_bibtex_entry(): global bibtex_file global bib_dict if bibtex_file == "NOT_FOUND": print("\t[!] No bibtex file was found!") return bib = open(bibtex_file,"r") line = bib.readline() while(line): #print("Line: '%s'" % line) begin = re.match(source_pattern,line) #start of source definition if begin: print("") #get identifier ident = line.replace(begin.group(0),"") ident = ident.replace(",\n","") print("\t[+] Found ident: '%s'" % ident) source =line source_line = bib.readline() #read current source definition while(source_line[-2:] != "}\n"): source += source_line source_line = bib.readline() source +=source_line braket_open = source.count('{') braket_close = source.count('}') if(braket_open > braket_close): #print("\t[!] Warning, braket count wrong: %s (%i:%i)! Adding one" % (ident,braket_open, braket_close)) source += "}\n" source += "\n" # store identifier and source in dictionary #print("\t[+] Adding source to dictionary") bib_dict.update( {ident : source }) source = "" ident = "" print("\t[+] Done reading current source!") line = bib.readline() # print("\t[+] Keys: ", bib_dict.keys()) def get_bib_tex_file(main_tex): global bibtex_file global bibtex_pattern bibtex = open(main_tex,"r") for line in bibtex: if "\\bibliography{" in line: bibtex_file = line.replace(" ", "") bibtex_file = bibtex_file.replace("\\bibliography{", "") bibtex_file = bibtex_file.replace("}", "") bibtex_file = bibtex_file.replace("\n","") print("\t[+] Bibtex_file: %s" % bibtex_file) bibtex.close() return #this regexp simply does not want to work #TODO file = re.match("\\bibliography\{(.*?)\}", line) if file: print("\t[+] FINALY FOUND WITH REGEX") file = file.group(1).split(",") file = file.replace("\\bibliography{","") file = file.replace("}","") print("\t[+] Found bibtex file: '%s'",file) return print("\t[-] No bibtex file found!") bibtex.close() def read_tex_file(tex_file): global cite_pattern global input_pattern global main_tex_folder global cite_list file = open(tex_file,"r") for i,line in enumerate(file): #print("[-] Testing: (%i): %s" % (i, line.replace("\n",""))) input_match = re.search(input_pattern,line) cite_match = re.search(cite_pattern, line) if input_match: new_file = (re.search("\{(.)*\}",line)).group(0)[1:-1] new_file = "%s%s" % (main_tex_folder,new_file) print("\t[+] Input request found, adding file ") read_tex_file(new_file) if cite_match: cites = re.findall(cite_pattern,line) for cite in cites: cite = (((cite.replace("cite{","")).replace("}","")).replace(" ","")).split(",") #print("\t[-] Testing cite: ", cite) for c in cite: if(c not in cite_list): #print("\t[+] Adding cite: ", c) cite_list.append(c) def create_new_bibtex(): global bib_dict global cite_list global bibtex_file new_file_name = "%s_temp.bib" % bibtex_file[:-4] file = open(new_file_name, "w+") print("\t[+] Creating new bibtext file: '%s'" % new_file_name) for i,c in enumerate(cite_list): #print("\t[+] Adding entry %s at \t\t%i" % (c,i)) #print("\t", bib_dict.get(c), "\n") if(bib_dict.get(c) != None): file.write(bib_dict.get(c)) file.close() main_tex_folder = (main_tex_file) os.chdir(main_tex_folder) print("[+] Starting to look for bibtex file") get_bib_tex_file("box.tex") get_bibtex_entry() print("[+] Starting to gather cites!") read_tex_file("box.tex") print("\n[+] Sorted %i entries from cites from documents: \n" %(len(cite_list))) print("[+] Creating new bibtex file") create_new_bibtex()
C++
KOI8-R
900
3.1875
3
[]
no_license
#include<iostream> #include<stack> using namespace std; const int r=10; struct Pos { int X; int Y; Pos(int x,int y) :X(x), Y(y) {} Pos() :X(0),Y(0) {} }; class Maze { public: Maze(char (*maze)[10],int entryX,int entryY) { _maze = maze; _entry.X = entryX; _entry.Y = entryY; _col = sizeof(_maze[0])/sizeof(_maze[0][0]); _row = _col; } ~Maze() {} private: char (*_maze)[10]; stack<Pos> _track; Pos _entry; size_t _row; size_t _col; public: bool FindExit(); void ShowMaze(); }; bool Maze::FindExit() { _trace.push(_entry); Pos curPos(_entry.X,_entry.Y); while(!_track.empty()) { //̽ Pos nextPos(curPos.X,curPos.Y); if(_maze[nextPos.X+1][curPos.Y] == 0) { } } return false; } void Maze::ShowMaze() { for(size_t i=0; i<_row; ++i) { for(size_t j=0; j<_col; ++j) { cout<<_maze[i][j]<<" "; } cout<<endl; } }
Java
UTF-8
695
2.234375
2
[ "MIT" ]
permissive
package page.objects; import driver.manager.DriverManager; import logger.manager.LoggerManager; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class FishListPage { //elements on side @FindBy(css = "a[href='/jpetstore/actions/Catalog.action?viewProduct=&productId=FI-SW-01']") WebElement angelFish; public FishListPage() { PageFactory.initElements(DriverManager.getWebDriver(), this); } public AngelFishPage clickOnTheAngelFish() { angelFish.click(); LoggerManager.setLoggerInfo("Clicked on the Angelfish"); return new AngelFishPage(); } }
Java
UTF-8
704
2.265625
2
[]
no_license
package com.example.dell.stripepaymentgateway.service; import com.example.dell.stripepaymentgateway.Response.GetResponse; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rx.Observable; /** * The {@link retrofit2.Retrofit} interface that creates our API service. */ public interface StripeService { // For simplicity, we have URL encoded our body data, but your code will likely // want a model class send up as JSON @FormUrlEncoded @POST("stripe.php") Observable<Response<GetResponse>> createQueryCharge( @Field("amount") String amount, @Field("source") String source); }
PHP
UTF-8
8,091
2.78125
3
[]
no_license
<?php /** * @group post */ class Tests_Post_Objects extends WP_UnitTestCase { function test_get_post() { $id = self::factory()->post->create(); $post = get_post( $id ); $this->assertInstanceOf( 'WP_Post', $post ); $this->assertSame( $id, $post->ID ); $this->assertTrue( isset( $post->ancestors ) ); $this->assertSame( array(), $post->ancestors ); // Unset and then verify that the magic method fills the property again unset( $post->ancestors ); $this->assertSame( array(), $post->ancestors ); // Magic get should make meta accessible as properties add_post_meta( $id, 'test', 'test' ); $this->assertSame( 'test', get_post_meta( $id, 'test', true ) ); $this->assertSame( 'test', $post->test ); // Make sure meta does not eclipse true properties add_post_meta( $id, 'post_type', 'dummy' ); $this->assertSame( 'dummy', get_post_meta( $id, 'post_type', true ) ); $this->assertSame( 'post', $post->post_type ); // Excercise the output argument $post = get_post( $id, ARRAY_A ); $this->assertIsArray( $post ); $this->assertSame( 'post', $post['post_type'] ); $post = get_post( $id, ARRAY_N ); $this->assertIsArray( $post ); $this->assertFalse( isset( $post['post_type'] ) ); $this->assertTrue( in_array( 'post', $post, true ) ); $post = get_post( $id ); $post = get_post( $post, ARRAY_A ); $this->assertIsArray( $post ); $this->assertSame( 'post', $post['post_type'] ); $this->assertSame( $id, $post['ID'] ); // Should default to OBJECT when given invalid output argument $post = get_post( $id, 'invalid-output-value' ); $this->assertInstanceOf( 'WP_Post', $post ); $this->assertSame( $id, $post->ID ); // Make sure stdClass in $GLOBALS['post'] is handled $post_std = $post->to_array(); $this->assertIsArray( $post_std ); $post_std = (object) $post_std; $GLOBALS['post'] = $post_std; $post = get_post( null ); $this->assertInstanceOf( 'WP_Post', $post ); $this->assertSame( $id, $post->ID ); unset( $GLOBALS['post'] ); // If no global post and passing empty value, expect null. $this->assertNull( get_post( null ) ); $this->assertNull( get_post( 0 ) ); $this->assertNull( get_post( '' ) ); $this->assertNull( get_post( false ) ); } function test_get_post_ancestors() { $parent_id = self::factory()->post->create(); $child_id = self::factory()->post->create(); $grandchild_id = self::factory()->post->create(); $updated = wp_update_post( array( 'ID' => $child_id, 'post_parent' => $parent_id, ) ); $this->assertSame( $updated, $child_id ); $updated = wp_update_post( array( 'ID' => $grandchild_id, 'post_parent' => $child_id, ) ); $this->assertSame( $updated, $grandchild_id ); $this->assertSame( array( $parent_id ), get_post( $child_id )->ancestors ); $this->assertSame( array( $parent_id ), get_post_ancestors( $child_id ) ); $this->assertSame( array( $parent_id ), get_post_ancestors( get_post( $child_id ) ) ); $this->assertSame( array( $child_id, $parent_id ), get_post( $grandchild_id )->ancestors ); $this->assertSame( array( $child_id, $parent_id ), get_post_ancestors( $grandchild_id ) ); $this->assertSame( array( $child_id, $parent_id ), get_post_ancestors( get_post( $grandchild_id ) ) ); $this->assertSame( array(), get_post( $parent_id )->ancestors ); $this->assertSame( array(), get_post_ancestors( $parent_id ) ); $this->assertSame( array(), get_post_ancestors( get_post( $parent_id ) ) ); } /** * @see https://core.trac.wordpress.org/ticket/22882 */ function test_get_post_ancestors_with_falsey_values() { foreach ( array( null, 0, false, '0', '' ) as $post_id ) { $this->assertIsArray( get_post_ancestors( $post_id ) ); $this->assertSame( array(), get_post_ancestors( $post_id ) ); } } function test_get_post_category_property() { $post_id = self::factory()->post->create(); $post = get_post( $post_id ); $this->assertIsArray( $post->post_category ); $this->assertSame( 1, count( $post->post_category ) ); $this->assertEquals( get_option( 'default_category' ), $post->post_category[0] ); $term1 = wp_insert_term( 'Foo', 'category' ); $term2 = wp_insert_term( 'Bar', 'category' ); $term3 = wp_insert_term( 'Baz', 'category' ); wp_set_post_categories( $post_id, array( $term1['term_id'], $term2['term_id'], $term3['term_id'] ) ); $this->assertSame( 3, count( $post->post_category ) ); $this->assertSame( array( $term2['term_id'], $term3['term_id'], $term1['term_id'] ), $post->post_category ); $post = get_post( $post_id, ARRAY_A ); $this->assertSame( 3, count( $post['post_category'] ) ); $this->assertSame( array( $term2['term_id'], $term3['term_id'], $term1['term_id'] ), $post['post_category'] ); } function test_get_tags_input_property() { $post_id = self::factory()->post->create(); $post = get_post( $post_id ); $this->assertIsArray( $post->tags_input ); $this->assertEmpty( $post->tags_input ); wp_set_post_tags( $post_id, 'Foo, Bar, Baz' ); $this->assertIsArray( $post->tags_input ); $this->assertSame( 3, count( $post->tags_input ) ); $this->assertSame( array( 'Bar', 'Baz', 'Foo' ), $post->tags_input ); $post = get_post( $post_id, ARRAY_A ); $this->assertIsArray( $post['tags_input'] ); $this->assertSame( 3, count( $post['tags_input'] ) ); $this->assertSame( array( 'Bar', 'Baz', 'Foo' ), $post['tags_input'] ); } function test_get_page_template_property() { $post_id = self::factory()->post->create(); $post = get_post( $post_id ); $this->assertIsString( $post->page_template ); $template = get_post_meta( $post->ID, '_wp_page_template', true ); $this->assertSame( $template, $post->page_template ); update_post_meta( $post_id, '_wp_page_template', 'foo.php' ); $template = get_post_meta( $post->ID, '_wp_page_template', true ); $this->assertSame( 'foo.php', $template ); $this->assertSame( $template, $post->page_template ); } function test_get_post_filter() { $post = get_post( self::factory()->post->create( array( 'post_title' => "Mary's home", ) ) ); $this->assertSame( 'raw', $post->filter ); $this->assertIsInt( $post->post_parent ); $display_post = get_post( $post, OBJECT, 'js' ); $this->assertSame( 'js', $display_post->filter ); $this->assertSame( esc_js( "Mary's home" ), $display_post->post_title ); // Pass a js filtered WP_Post to get_post() with the filter set to raw. // The post should be fetched from cache instead of using the passed object. $raw_post = get_post( $display_post, OBJECT, 'raw' ); $this->assertSame( 'raw', $raw_post->filter ); $this->assertNotEquals( esc_js( "Mary's home" ), $raw_post->post_title ); $raw_post->filter( 'js' ); $this->assertSame( 'js', $post->filter ); $this->assertSame( esc_js( "Mary's home" ), $raw_post->post_title ); } function test_get_post_identity() { $post = get_post( self::factory()->post->create() ); $post->foo = 'bar'; $this->assertSame( 'bar', get_post( $post )->foo ); $this->assertSame( 'bar', get_post( $post, OBJECT, 'display' )->foo ); } function test_get_post_array() { $id = self::factory()->post->create(); $post = get_post( $id, ARRAY_A ); $this->assertSame( $id, $post['ID'] ); $this->assertIsArray( $post['ancestors'] ); $this->assertSame( 'raw', $post['filter'] ); } /** * @see https://core.trac.wordpress.org/ticket/22223 */ function test_get_post_cache() { global $wpdb; $id = self::factory()->post->create(); wp_cache_delete( $id, 'posts' ); // get_post( stdClass ) should not prime the cache $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id ) ); $post = get_post( $post ); $this->assertEmpty( wp_cache_get( $id, 'posts' ) ); // get_post( WP_Post ) should not prime the cache get_post( $post ); $this->assertEmpty( wp_cache_get( $id, 'posts' ) ); // get_post( ID ) should prime the cache get_post( $post->ID ); $this->assertNotEmpty( wp_cache_get( $id, 'posts' ) ); } }
Java
UTF-8
1,635
2.390625
2
[]
no_license
package com.oocl.ita.starkxiao.project2.admin.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet Filter implementation class PermissionJudgeFilter */ public class PermissionJudgeFilter implements Filter { /** * Default constructor. */ public PermissionJudgeFilter() { } /** * @see Filter#destroy() */ public void destroy() { } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // pass the request along the filter chain HttpServletRequest httpServletRequest = (HttpServletRequest)request; HttpServletResponse httpServletResponse = (HttpServletResponse)response; Boolean boolTemp = (Boolean)httpServletRequest.getSession().getAttribute("pass"); //if the request have a permission to reach the page, let it pass if(boolTemp != null && boolTemp){ chain.doFilter(httpServletRequest, response); } else{ String requestOriginPath = httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(requestOriginPath+"/Login"); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { } }
Markdown
UTF-8
4,035
2.875
3
[]
no_license
#### 第三百七十三章 天主诞生玄无上 玄主法钦镇无边 天主归位 玄主归位 欢声雷动……………… 而玄主,就是用这片天为基础立道的法成就。 天主就是这片天的主,的功法成就,为天主玄功。 天主身成就时候,注册,时候其他片天里有金身伸出手,挡住不准注册成道则,我一巴掌拍飞,直接护住,立马注册成功,道则诞生,其他片天格子世界里一阵哀嚎…… 那个阻挡的,其他天世界金身,被我吞噬金身活吞吃下,消化…… 二次考验类似中蛊术,手臂长出那些树苗嫩芽。,不断长,割下来,不断长割下来,有治疗,然后自己嗜血,想吃人,我不愿意,我叫那些人赶紧离开,醒来,考验通过。 晨时候通过考验就是得了这个,天主玄功,为这天主。 …………………………………… 行不行 本尊不行了,得想办法 其他天联合攻打打我私门,因为我罩这片天 造化玄机诞生,莫不过来地球抢夺造化 非我族类 ,其心必异,其行当诛…… 而我得到了天主玄功,天主道,需要练出来,我一路拿着自己的护身印,圣人身有一团精气在里面,为圣印 只是拿了照,全部化灰灰…… 而我得大法消耗虚弱,因为每得一个东西都是必须要配得起的,功德气运等如同火烧一样消耗快速,沸腾如火,如烟…… 而那些其他天强者不允许 这地球这片天诞生主人,必须弄死掉的,而且多年它们虽然厉害,但是无法有道 因此诞生不了天主,也怕地球这片天诞生天主道,吞并威胁它们,所以努力杀我 我又饿………… 握着我的印,回来买菜做饭吃…… 分身们抵抗,它们围攻我私门,儿郎们努力杀敌………… 血火如烟……………… 抵挡不住了本尊……分身呼喊…… 我停止吃饭,念了一个决,虚空出现无数强者,只是一下就把那些杀光,再度隐藏起来………… 这…………这是什么…… 分身目瞪口呆……这是我的其他势力啊…… 你不要脸,靠……分身怒火,怎么我们不知道…… 你知道干嘛,这是我的隐藏势力,私门只是门面,或者明面 而且你们哪个被控制怎么办,我们或者有内奸怎么办…… 你……太不要脸……分身无话可说 这样大家都安全,一隐一显,谁知道我有有多少…… 靠,以前说你叫留一手我还不信 哼……………………………… 我无语埋头吃饭,那小时候记得那个时候,人家修房子去砖厂拉砖,就是小四轮车,而去那里,那个人他没有伴,就让我一起去呢…… 吃饭时候就一个菜,一大骨头,好多肉,大白萝卜切了丢煮,用辣椒粉,盐味精酱油,调了,泼油做的辣椒,放碗里,把萝卜,肉放里蘸了吃 啊哟那个叫美味,童年的味道…… 我也买了做了吃,回味那个味道,而心愿得解,心念通达,神心空明,境界一直飙……………… 这境界与心灵有极大关系…… 终于吃饱满足了,盘腿开始修行起来 分身们又学一招,名曰,留一手,不满看着我嘟囔…… 去准备隐势力去了………… 再不愿出现这次这种情况………… 一边说我,人说你,小奸巨滑,真没错,哼……………… 我只做没有看见,开始行功 两个练成 虚空提示,玄主归位,天主归位…… 天主身满脸寒煞,面皮起跳…… 糙尼玛……愣死你们………… 死……………… 一伸手,金身法身法相,齐齐伸手,一把镇死那些天的强者…… 玄主身飞升占高,分金身布镇,大吞噬轮回法阵,一阵猛转………… 其他身也是出手,杀得如火如荼…………
Java
UTF-8
1,160
2.0625
2
[ "Apache-2.0" ]
permissive
package com.baiyi.opscloud.event.listener; import com.baiyi.opscloud.common.event.NoticeEvent; import com.baiyi.opscloud.event.consumer.EventConsumerFactory; import com.baiyi.opscloud.event.consumer.IEventConsumer; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import static com.baiyi.opscloud.common.config.ThreadPoolTaskConfiguration.TaskPools.CORE; /** * @Author baiyi * @Date 2021/8/17 4:29 下午 * @Version 1.0 */ @Slf4j @Component public class EventListener<T> implements ApplicationListener<NoticeEvent<T>> { @SuppressWarnings("unchecked") @Override @Async(value = CORE) public void onApplicationEvent(NoticeEvent<T> noticeEvent) { log.debug("监听事件: eventType={}, action={}", noticeEvent.getMessage().getEventType(), noticeEvent.getMessage().getAction()); IEventConsumer<T> consumer = EventConsumerFactory.getConsumer(noticeEvent.getMessage().getEventType()); if (consumer != null) { consumer.onMessage(noticeEvent); } } }
JavaScript
UTF-8
1,429
3.65625
4
[]
no_license
// from data.js var tableData = data; console.log(tableData) // selected tbody in html var tbody = d3.select("tbody"); //built function to add data from data file to table function tableBuild(data) { //used to clear current data on table tbody.html(""); //used forEach to itrate through each ro of data data.forEach((row) => { //created variable to create a new row on the table var dataRow = tbody.append('tr'); //read values from each row of the dataset Object.values(row).forEach((value) => { //appened the new row in order to accept the values var cell = dataRow.append('td'); //inserted the values into each corresponing cell on the table cell.text(value); }) }) } //called the function with the data from the dat.js file tableBuild(tableData); //created filter function to filter dataset by user inputted date function filter() { //created variable to read the user's input var date = d3.select('#datetime').property('value'); //used if to determine if user has add an input date if (date) { var filterData = tableData.filter(row => row.datetime === date); } //called the function with the filtered data from the dat.js file tableBuild(filterData); } //set up event lister to apply the filter on a click of the filter button d3.selectAll("#filter-btn").on("click", filter);
C++
UTF-8
3,805
3.359375
3
[]
no_license
// // // // // // // // // // // // // // Dijkstra's algorithm by // www.cedricve.me // // // // // // // // // // // // // #ifndef __DIJKSTRA__ #define __DIJKSTRA #include "ggraaf.h" #include <iostream> #include <queue> #include <vector> using namespace std; // connection (struct) // to keep from node, to node and the cost between // 1 object, this will make everything easier struct connection { int from; int to; double cost; connection(int f,int t,int c){ from = f; to = t; cost = c; } // we need to overload this method because // we will use a priority queue that will contain // connection objects bool operator<(const connection & c) const{ // we want a min priority queue (or heap) // that's why we say false // if 15 > 18 => return true; if(c.cost>cost) return false; else return true; } }; template<typename T> class Dijkstra{ private: // Starting node int start; // TRUE if we looped a node his neighbors // if v[5] == true => means we discovered (node 5) all his neighbors vector<bool> connected; // Represents the cost to every node from // the starting node vector<double> costs; // priority queue to get the connection with // the lowest cost priority_queue<connection> pq; public: Dijkstra(GewogenGraaf<ONGERICHT,T> &):start(0){} Dijkstra(GewogenGraaf<ONGERICHT,T> &,int); void discover_neighbors(GewogenGraaf<ONGERICHT,T> &,int); }; template<typename T> Dijkstra<T>::Dijkstra(GewogenGraaf<ONGERICHT,T> &g,int s){ start = s; // initialize both vectors, with the amount of nodes // that the graph contains connected.resize(g.aantal_knopen()); costs.resize(g.aantal_knopen()); // Increase costs to MAX for(unsigned int i = 0; i < costs.size(); i++) costs[i] = 99999999; // All connected are false for(unsigned int i = 0; i < connected.size();i++) connected[i] = false; // The cost to himself is zero (0) => DUUh! costs[s]=0; discover_neighbors(g,s); while(!pq.empty()) { connection c = pq.top(); // if this neighbor isn't connected // get all his neighbors if(!connected[c.to]) discover_neighbors(g,c.to); pq.pop(); } for(unsigned int i = 0; i < costs.size(); i++) { cout << "From ("<< s <<") To ("<< i <<"): " << costs[i] << endl; } } template<typename T> void Dijkstra<T>::discover_neighbors(GewogenGraaf<ONGERICHT,T> &g,int node_id){ // we discovered this node connected[node_id]=true; // get the current cost of this node // look in the costs vector double current_cost = costs[node_id]; // Get all neighbors from this node // we can call the [] operator from the graph class // this methode will return all connections from this node // This will be stored in an object Knoop => this is just a map<int,int> object // The map contains the neighbor_id and the connection_id (connection_id we will need to get the cost from a specific connection) Knoop connections = g[node_id]; // we will loop this map or Knoop object with an iterator int cost_neighbor; int total_cost; int neighbor; for(Knoop::iterator itr = connections.begin(); itr != connections.end();itr++){ // get the neighbor id from the map neighbor = itr->first; // check if this neighbor is allready connected if(!connected[neighbor]) { // get the cost from the current node to this neighbor cost_neighbor = g.gewicht(itr->second); // sum the current cost and the cost of the neighbor total_cost = current_cost + cost_neighbor; // check is this cost is smaller than the original cost in the costs vector // if so change his cost and push it on the priority queue if(total_cost<costs[neighbor]) { connection c(node_id,neighbor,total_cost); pq.push(c); // change the NEW (lower) cost costs[neighbor]=total_cost; } } } } #endif
C#
UTF-8
1,474
2.609375
3
[ "MIT" ]
permissive
using NestedWorld.Classes.ElementsGame.Item; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Xml.Linq; using Windows.Storage.Streams; namespace NestedWorld.Classes.ElementsGame.Shop { public class Shop { public List<ItemGroup> list { get; set; } public ObservableCollection<ItemGroup> content { get { return new ObservableCollection<ItemGroup>(list); } set { int i = 0; i++; } } public Shop() { list = new List<ItemGroup>(); init(); } public async void init() { try { IRandomAccessStream data = await Utils.IO.GetDataAsStream("DataModel", "ShopData.xml"); XDocument doc = XDocument.Load(data.AsStream()); ItemGroup groupetmp; foreach (XElement element in doc.Element("Root").Elements("Groupe")) { groupetmp = new ItemGroup((string)element.Attribute("name"), (string)element.Attribute("image")); groupetmp.Load(element); list.Add(groupetmp); } } catch (System.Exception ex) { Debug.WriteLine(ex); } } } }
Java
UTF-8
2,538
3.046875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package at.ac.fh_kufstein.uebung_2.Classes; /** * * @author lessi */ public class Fahrzeug { private short reifen; private String farbe; private short PS; private short tueren; private boolean gestartet; private short geschwindigkeit; public static int anzahl; void starten() { gestartet=true; } void stoppen() { gestartet=false; } void beschleunigen(short aenderung) { if (gestartet==true && geschwindigkeit <=250) { geschwindigkeit += aenderung; } else { System.out.println("Das Fahrzeug kann nicht beschleunigt werden!"); } } void bremsen(short aenderung) { if(gestartet==true && geschwindigkeit>0) { geschwindigkeit -= aenderung; } else { System.out.println("Das Fahrzeug kann nicht gebremst werden!"); } } public short getReifen() { return reifen; } public String getFarbe() { return farbe; } public short getPS() { return PS; } public short getTueren() { return tueren; } public boolean getGestartet() { return gestartet; } public short getGeschwindigkeit() { return geschwindigkeit; } public static int getAnzahl() { return anzahl; } public void setReifen(short r) { reifen=r; } public void setFarbe(String f) { farbe=f; } public void setPS(short ps) { PS=ps; } public void setTueren(short t) { tueren=t; } public void setGestartet(boolean ge) { gestartet=ge; } public void setGeschwindigkeit(short g) { geschwindigkeit=g; } public void setAnzahl(int a) { anzahl=a; } public Fahrzeug(short reifen,short PS, short tueren, boolean gestartet, short geschwindigkeit) { this.reifen = reifen; this.PS = PS; this.tueren = tueren; this.gestartet = gestartet; this.geschwindigkeit = geschwindigkeit; } }