language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
3,353
2.53125
3
[]
no_license
# Ansible module: ansible.module_netapp_e_amg NetApp E-Series create, remove, and update asynchronous mirror groups ## Description Allows for the creation, removal and updating of Asynchronous Mirror Groups for NetApp E-series storage arrays ## Requirements TODO ## Arguments ``` json { "api_password": "{'required': True, 'description': ['The password to authenticate with the SANtricity Web Services Proxy or Embedded Web Services API.']}", "api_url": "{'required': True, 'description': ['The url to the SANtricity Web Services Proxy or Embedded Web Services API.'], 'example': ['https://prod-1.wahoo.acme.com/devmgr/v2']}", "api_username": "{'required': True, 'description': ['The username to authenticate with the SANtricity Web Services Proxy or Embedded Web Services API.']}", "interfaceType": "{'description': ['The intended protocol to use if both Fibre and iSCSI are available.'], 'choices': ['iscsi', 'fibre']}", "manualSync": "{'description': ['Setting this to true will cause other synchronization values to be ignored'], 'type': 'bool', 'default': False}", "name": "{'description': ['The name of the async array you wish to target, or create.', "If C(state) is present and the name isn't found, it will attempt to create."], 'required': True}", "recoveryWarnThresholdMinutes": "{'description': ['Recovery point warning threshold (minutes). The user will be warned when the age of the last good failures point exceeds this value'], 'default': 20}", "repoUtilizationWarnThreshold": "{'description': ['Recovery point warning threshold'], 'default': 80}", "secondaryArrayId": "{'description': ['The ID of the secondary array to be used in mirroing process'], 'required': True}", "ssid": "{'required': True, 'description': ['The ID of the array to manage. This value must be unique for each array.']}", "state": "{'description': ['A C(state) of present will either create or update the async mirror group.', 'A C(state) of absent will remove the async mirror group.'], 'choices': ['absent', 'present'], 'required': True}", "syncIntervalMinutes": "{'description': ['The synchronization interval in minutes'], 'default': 10}", "syncWarnThresholdMinutes": "{'description': ['The threshold (in minutes) for notifying the user that periodic synchronization has taken too long to complete.'], 'default': 10}", "validate_certs": "{'required': False, 'default': True, 'description': ['Should https certificates be validated?'], 'type': 'bool'}", } ``` ## Examples ``` yaml - name: AMG removal na_eseries_amg: state: absent ssid: "{{ ssid }}" secondaryArrayId: "{{amg_secondaryArrayId}}" api_url: "{{ netapp_api_url }}" api_username: "{{ netapp_api_username }}" api_password: "{{ netapp_api_password }}" new_name: "{{amg_array_name}}" name: "{{amg_name}}" when: amg_create - name: AMG create netapp_e_amg: state: present ssid: "{{ ssid }}" secondaryArrayId: "{{amg_secondaryArrayId}}" api_url: "{{ netapp_api_url }}" api_username: "{{ netapp_api_username }}" api_password: "{{ netapp_api_password }}" new_name: "{{amg_array_name}}" name: "{{amg_name}}" when: amg_create ``` ## License TODO ## Author Information - ['Kevin Hulquest (@hulquest)']
C++
UTF-8
805
2.625
3
[]
no_license
#ifndef MOVIE_H #define MOVIE_H #include <QImage> #include <QString> #include <QVector> #include "GenericRegistry.h" #include "IdentifiedObject.h" class Movie : public IdentifiedObject { public: Movie(); QString name() const; void setName(const QString &name); QString description() const; void setDescription(const QString &description); QImage poster() const; void setPoster(const QImage &poster); unsigned long directorId() const; void setDirectorId(unsigned long directorId); QVector<unsigned long> actorIds() const; void setActorIds(const QVector<unsigned long> &actorIds); private: QString mName; QString mDescription; QImage mPoster; unsigned long mDirectorId; QVector<unsigned long> mActorIds; }; template class GenericRegistry<Movie>; #endif // MOVIE_H
JavaScript
UTF-8
776
2.828125
3
[]
no_license
window.onload = function() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if(this.readyState == XMLHttpRequest.DONE && this.status == 200) { var data = this.responseText; var jsonResult = JSON.parse(data); console.log(jsonResult); document.getElementById('usrName').textContent = jsonResult.name; document.getElementById('usrTitle').textContent = jsonResult.title; document.getElementById('usrPhone').textContent = jsonResult.contact.phone; document.getElementById('usrEmail').textContent = jsonResult.contact.email; } }; xmlhttp.open('get','http://maamw30505:9001/api/getData',true); xmlhttp.send(); }
Java
UTF-8
2,614
2.796875
3
[]
no_license
package com.lipan.crud.test; import java.io.*; import java.text.*; import java.util.*; public class poidata { /** * @param args */ public static void main(String[] args) { try { long starTime = System.currentTimeMillis(); int recordNum=7389;//记录条数 String ID[]=new String[recordNum]; String filename[]=new String[recordNum]; //String foldername[]=new String[20]; String text[]=new String[recordNum]; String longitude[]=new String[recordNum];//经度 String latitude[]=new String[recordNum];//纬度 String str1; // 读取文件 File filePath=new File("D:\\graduation project\\data1.txt"); File filePath2=new File("D:\\graduation project\\data2.txt"); InputStreamReader ips =new InputStreamReader(new FileInputStream(filePath), "UTF-8"); //gb2312 BufferedReader file=new BufferedReader(ips); for (int i = 0; i < recordNum; i++) { String attributeItem[] = file.readLine().split(","); ID[i]=attributeItem[0];//ID //foldername[i]=attributeItem[2]; filename[i]=attributeItem[3];//原始文件名 str1=attributeItem[4]; for(int j=1;j<(attributeItem.length-4);j++){//关键词 str1=str1+","+attributeItem[j+4]; } str1=str1+","+attributeItem[2];//最后加了个原始文件夹名 //System.out.println(str1); text[i]=str1; //System.out.println(text[i]); } file.close(); ips.close(); InputStreamReader ips2 =new InputStreamReader(new FileInputStream(filePath2), "UTF-8"); //gb2312 BufferedReader file2=new BufferedReader(ips2); for (int i = 0; i < recordNum; i++) { String attributeItem[] = file2.readLine().split(","); longitude[i]=attributeItem[5]; latitude[i]=attributeItem[6]; } file2.close(); ips2.close(); //写入文件 FileWriter file_writer; BufferedWriter out; File file1 = new File("D:\\poidata1.txt"); file_writer = new FileWriter(file1); out = new BufferedWriter(file_writer); String str; for (int j = 0; j < recordNum; j++) { str=ID[j]+"\t"+longitude[j]+"\t"+latitude[j]+"\t"+text[j]+"\t"+filename[j]; out.write(str, 0, str.length());//文件第一行记录不同关键字的个数 out.flush(); out.newLine(); } out.close(); file_writer.close(); long endTime1 = System.currentTimeMillis(); double Time1 = endTime1 - starTime; System.out.println("运行时间: " + Time1 + " ms"); } catch (IOException e) { e.printStackTrace(); } } }
Python
UTF-8
4,473
2.796875
3
[ "MIT" ]
permissive
from gtts import gTTS import pyaudio import queue import base64 import os SYS_BEEP_PATH = os.path.join(os.getcwd(),"assets/beepbeep.wav") class MicrophoneStream(object): """Opens a recording stream as a generator yielding the audio chunks.""" def __init__(self, rate, chunk): self._rate = rate self._chunk = chunk # Create a thread-safe buffer of audio data self._buff = queue.Queue() self.cur_frame = [] self.closed = True self.enabled = False def __enter__(self): self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, # The API currently only supports 1-channel (mono) audio # https://goo.gl/z757pE channels=1, rate=self._rate, input=True, frames_per_buffer=self._chunk, # Run the audio stream asynchronously to fill the buffer object. # This is necessary so that the input device's buffer doesn't # overflow while the calling thread makes network requests, etc. stream_callback=self._fill_buffer, ) self.closed = False return self def __exit__(self, type, value, traceback): self._audio_stream.stop_stream() self._audio_stream.close() self.closed = True # Signal the generator to terminate so that the client's # streaming_recognize method will not block the process termination. self._buff.put(None) self._audio_interface.terminate() def _fill_buffer(self, in_data, frame_count, time_info, status_flags): """Continuously collect data from the audio stream, into the buffer if enabled""" if self.enabled: self._buff.put(in_data) self.cur_frame = in_data # Update the current frame for wakeword detection return None, pyaudio.paContinue # Synchronously get 1 chunk from the audio stream def get_sync_frame(self): self.start_buf() chunk = self._buff.get() # Blocking get self.stop_buf() return chunk def start_buf(self): self._buff = queue.Queue() # Create a new queue (clear), otherwise there might be remanents of the old queue data for the sync get chunk self.enabled = True def stop_buf(self): self.enabled = False def generator(self): while not self.closed: # Use a blocking get() to ensure there's at least one chunk of # data, and stop iteration if the chunk is None, indicating the # end of the audio stream. chunk = self._buff.get() if chunk is None: return data = [chunk] # Now consume whatever other data's still buffered. while True: try: chunk = self._buff.get(block=False) if chunk is None: return data.append(chunk) except queue.Empty: break yield b"".join(data) # Process response from Google ASR def process(responses): for response in responses: if not response.results: continue # The `results` list is consecutive. For streaming, we only care about # the first result being considered, since once it's `is_final`, it # moves on to considering the next utterance. result = response.results[0] if not result.alternatives: continue # Display the transcription of the top alternative. transcript = result.alternatives[0].transcript if result.is_final: print("Utterance: " + transcript) return transcript # Play audio/mpeg MIME content def play(encoding_str): filename = '/tmp/response.mp3' decode_bytes = base64.b64decode(encoding_str.split("data:audio/mpeg;base64,",1)[1]) with open(filename, "wb") as wav_file: wav_file.write(decode_bytes) mp3_play(filename) # Text-to-speech using Google TTS def speak(text): tts = gTTS(text=text, lang='en') filename = '/tmp/tts.mp3' tts.save(filename) mp3_play(filename) def beep(): wav_play(SYS_BEEP_PATH) def mp3_play(filename): os.system('mpg123 ' + filename + '>/dev/null 2>&1') def wav_play(filename): os.system('aplay ' + filename + '>/dev/null 2>&1')
Markdown
UTF-8
431
2.546875
3
[]
no_license
# Pokemón Local Search This is a `vanilla.js` implementation using the data from the [Pokémon Api](https://pokeapi.co). Currently the search does partial match, shows the images of the Pokémon (front and back) and shows the results paginated in groups of 12 items. ## Tested on * Chrome (>= 60) * Opera (>= 47) * Safari for macOS (>= 10.1) * Firefox (>= 55) ## ToDo * Integrate with Pokemón API to get more detailed data
Java
UTF-8
7,073
1.84375
2
[]
no_license
package b.a.a.x; import android.view.Choreographer; import b.a.a.c; import b.a.a.d; public class e extends a implements Choreographer.FrameCallback { /* renamed from: d reason: collision with root package name */ public float f2319d = 1.0f; /* renamed from: e reason: collision with root package name */ public boolean f2320e = false; /* renamed from: f reason: collision with root package name */ public long f2321f = 0; /* renamed from: g reason: collision with root package name */ public float f2322g = 0.0f; public int h = 0; public float i = -2.14748365E9f; public float j = 2.14748365E9f; public d k; public boolean l = false; public Object getAnimatedValue() { return Float.valueOf(h()); } public float h() { d dVar = this.k; if (dVar == null) { return 0.0f; } return (this.f2322g - dVar.o()) / (this.k.f() - this.k.o()); } public float getAnimatedFraction() { if (this.k == null) { return 0.0f; } if (n()) { return (k() - this.f2322g) / (k() - l()); } return (this.f2322g - l()) / (k() - l()); } public long getDuration() { d dVar = this.k; if (dVar == null) { return 0; } return (long) dVar.d(); } public float i() { return this.f2322g; } public boolean isRunning() { return this.l; } public void doFrame(long frameTimeNanos) { q(); if (this.k != null && isRunning()) { c.a("LottieValueAnimator#doFrame"); long j2 = this.f2321f; long timeSinceFrame = 0; if (j2 != 0) { timeSinceFrame = frameTimeNanos - j2; } float dFrames = ((float) timeSinceFrame) / j(); float f2 = this.f2322g + (n() ? -dFrames : dFrames); this.f2322g = f2; boolean ended = !g.d(f2, l(), k()); this.f2322g = g.b(this.f2322g, l(), k()); this.f2321f = frameTimeNanos; e(); if (ended) { if (getRepeatCount() == -1 || this.h < getRepeatCount()) { c(); this.h++; if (getRepeatMode() == 2) { this.f2320e = !this.f2320e; u(); } else { this.f2322g = n() ? k() : l(); } this.f2321f = frameTimeNanos; } else { this.f2322g = this.f2319d < 0.0f ? l() : k(); r(); b(n()); } } B(); c.b("LottieValueAnimator#doFrame"); } } public final float j() { d dVar = this.k; if (dVar == null) { return Float.MAX_VALUE; } return (1.0E9f / dVar.h()) / Math.abs(this.f2319d); } public void f() { this.k = null; this.i = -2.14748365E9f; this.j = 2.14748365E9f; } public void v(d composition) { boolean keepMinAndMaxFrames = this.k == null; this.k = composition; if (keepMinAndMaxFrames) { y((float) ((int) Math.max(this.i, composition.o())), (float) ((int) Math.min(this.j, composition.f()))); } else { y((float) ((int) composition.o()), (float) ((int) composition.f())); } float frame = this.f2322g; this.f2322g = 0.0f; w((float) ((int) frame)); e(); } public void w(float frame) { if (this.f2322g != frame) { this.f2322g = g.b(frame, l(), k()); this.f2321f = 0; e(); } } public void z(int minFrame) { y((float) minFrame, (float) ((int) this.j)); } public void x(float maxFrame) { y(this.i, maxFrame); } public void y(float minFrame, float maxFrame) { if (minFrame <= maxFrame) { d dVar = this.k; float compositionMinFrame = dVar == null ? -3.4028235E38f : dVar.o(); d dVar2 = this.k; float compositionMaxFrame = dVar2 == null ? Float.MAX_VALUE : dVar2.f(); this.i = g.b(minFrame, compositionMinFrame, compositionMaxFrame); this.j = g.b(maxFrame, compositionMinFrame, compositionMaxFrame); w((float) ((int) g.b(this.f2322g, minFrame, maxFrame))); return; } throw new IllegalArgumentException(String.format("minFrame (%s) must be <= maxFrame (%s)", Float.valueOf(minFrame), Float.valueOf(maxFrame))); } public void u() { A(-m()); } public void A(float speed) { this.f2319d = speed; } public float m() { return this.f2319d; } public void setRepeatMode(int value) { super.setRepeatMode(value); if (value != 2 && this.f2320e) { this.f2320e = false; u(); } } public void p() { this.l = true; d(n()); w((float) ((int) (n() ? k() : l()))); this.f2321f = 0; this.h = 0; q(); } public void g() { r(); b(n()); } public void o() { r(); } public void t() { this.l = true; q(); this.f2321f = 0; if (n() && i() == l()) { this.f2322g = k(); } else if (!n() && i() == k()) { this.f2322g = l(); } } public void cancel() { a(); r(); } public final boolean n() { return m() < 0.0f; } public float l() { d dVar = this.k; if (dVar == null) { return 0.0f; } float f2 = this.i; return f2 == -2.14748365E9f ? dVar.o() : f2; } public float k() { d dVar = this.k; if (dVar == null) { return 0.0f; } float f2 = this.j; return f2 == 2.14748365E9f ? dVar.f() : f2; } public void q() { if (isRunning()) { s(false); Choreographer.getInstance().postFrameCallback(this); } } public void r() { s(true); } public void s(boolean stopRunning) { Choreographer.getInstance().removeFrameCallback(this); if (stopRunning) { this.l = false; } } public final void B() { if (this.k != null) { float f2 = this.f2322g; if (f2 < this.i || f2 > this.j) { throw new IllegalStateException(String.format("Frame must be [%f,%f]. It is %f", Float.valueOf(this.i), Float.valueOf(this.j), Float.valueOf(this.f2322g))); } } } }
Python
UTF-8
392
3.734375
4
[]
no_license
print('ЛИСТЫ', '\n', '***'*10) a = [2,3,4,5,7,6] print(a) a.append('Python') print('First:', a[0], 'Last:', a[-1]) print(a[2:4]) print(len(a)) print(a.index(6)) a.remove('Python') print(a) print('СЛОВАРИ', '\n', '***'*10) user = {'name':'Masha', 'age':25, 'have_airplain':False} print(user['name']) print(user.get('name'), user.get('value')) del user['age'] print(user)
Markdown
UTF-8
4,407
2.609375
3
[ "MIT" ]
permissive
--- layout: post title: Spark 作业执行流程 subtitle: date: 2019-11-05 author: danner header-img: img/post-bg-ios9-web.jpg catalog: true tags: - Spark - YARN --- 本文是接着 [spark-shell 脚本剖析](https://vendanner.github.io/2019/10/25/spark-shell-%E8%84%9A%E6%9C%AC%E5%89%96%E6%9E%90/),上文描述作业最终是通过 `org.apache.spark.deploy.SparkSubmit` 提交任务。那么这次就来看看具体的执行流程。 ### 选择集群 ```scala // org.apache.spark.deploy.SparkSubmit override def main(args: Array[String]): Unit = { val submit = new SparkSubmit() { self => override protected def parseArguments(args: Array[String]): SparkSubmitArguments = { new SparkSubmitArguments(args) { ... } } ... override def doSubmit(args: Array[String]): Unit = { try { super.doSubmit(args) } catch { ... } } } submit.doSubmit(args) } def doSubmit(args: Array[String]): Unit = { ... // 创建 SparkSubmitArguments 来解析 参数 val appArgs = parseArguments(args) if (appArgs.verbose) { logInfo(appArgs.toString) } // action 不同调用对应的函数,本例是 submit appArgs.action match { case SparkSubmitAction.SUBMIT => submit(appArgs, uninitLog) case SparkSubmitAction.KILL => kill(appArgs) case SparkSubmitAction.REQUEST_STATUS => requestStatus(appArgs) case SparkSubmitAction.PRINT_VERSION => printVersion() } } private def submit(args: SparkSubmitArguments, uninitLog: Boolean): Unit = { def doRunMain(): Unit = { ... runMain(args, uninitLog) ... } ... doRunMain() ... } private def runMain(args: SparkSubmitArguments, uninitLog: Boolean): Unit = { // 解析参数并准备环境变量 (args,sparkConf) val (childArgs, childClasspath, sparkConf, childMainClass) = prepareSubmitEnvironment(args) ... // classpath for (jar <- childClasspath) { addJarToClasspath(jar, loader) } // 不同的运行环境 yarn,k8s,mesos,mainclass不同,是对应环境的 application // 反射,本例中 org.apache.spark.deploy.yarn.YarnClusterApplication // 如果是 client 模式,childMainClass 就是 --class_name 指定的类 mainClass = Utils.classForName(childMainClass) ... val app: SparkApplication = if (classOf[SparkApplication].isAssignableFrom(mainClass)) { mainClass.newInstance().asInstanceOf[SparkApplication] } else { // SPARK-4170 if (classOf[scala.App].isAssignableFrom(mainClass)) { logWarning("Subclasses of scala.App may not work correctly. Use a main() method instead.") } new JavaMainApplication(mainClass) } ... // 启动 application app.start(childArgs.toArray, sparkConf) } ``` > 总结起来就是一句话:解析参数准备运行时环境变量,启动对应集群的Application Master ### 集群 ```scala // org.apache.spark.deploy.yarn.YarnClusterApplication private[spark] class YarnClusterApplication extends SparkApplication { override def start(args: Array[String], conf: SparkConf): Unit = { // SparkSubmit would use yarn cache to distribute files & jars in yarn mode, // so remove them from sparkConf here for yarn mode. conf.remove("spark.jars") conf.remove("spark.files") new Client(new ClientArguments(args), conf).run() } } // org.apache.spark.deploy.yarn.Client // 先确定 Executor、Driver 内存资源、创建 job 目录 def run(): Unit = { this.appId = submitApplication() // 查看任务提交状态 ... } def submitApplication(): ApplicationId = { // 任务提交到 yarn 之前的准备工作 ... // Get a new application from our RM val newApp = yarnClient.createApplication() ... // Set up the appropriate contexts to launch our AM // 包含把 spark jar 上产到 job 目录,详细看 Spark on YARN 加速启动 val containerContext = createContainerLaunchContext(newAppResponse) // 包含 JVM 参数,GC val appContext = createApplicationSubmissionContext(newApp, containerContext) // Finally, submit and monitor the application logInfo(s"Submitting application $appId to ResourceManager") // 实际调用 YarnClientImpl.submitApplication yarnClient.submitApplication(appContext) ... } ```
JavaScript
UTF-8
527
2.59375
3
[]
no_license
var axios = require("axios"); var cheerio = require("cheerio"); var scrape = function() { return axios.get("http://www.nytimes.com").then(function(res) { var $ = cheerio.load(res.data); var articles = []; $(".theme-summary").each(function(i, element) { var head = $(this) .children(".story-heading") .text() .trim(); articles.push(dataToAdd); } }); return articles; }); }; module.exports = scrape;
C
UTF-8
454
4.46875
4
[ "MIT" ]
permissive
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { int mark1,mark2,tot; float avg; printf("Enter mark for subject 1 :"); scanf("%d",&mark1); printf("Enter mark for subject 2 :"); scanf("%d",&mark2); tot = mark1 + mark2; avg = tot / 2.0; printf("Total : %d\n",tot); printf("Average : %.2f\n",avg); return 0; }
JavaScript
UTF-8
1,811
3.03125
3
[]
no_license
const faker = require('faker'); const fs = require('fs'); let generateFishermen = () => { let fishermen = []; for (let id = 1; id < 11; id++) { let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let email = faker.internet.email(); let contact = faker.phone.phoneNumber(); let equipment = faker.lorem.words(2); let baits = faker.lorem.words(2); let techniques = faker.lorem.words(2); let poles = faker.lorem.words(1); fishermen.push({ "id": id, "firstName": firstName, "lastName": lastName, "email": email, "contact": contact, "equipment": equipment, "baits": baits, "techniques": techniques, "poles": poles }); } return { "fishermen": fishermen } } let generateCatch = () => { let catches = []; for (let id = 1; id < 31; id++) { let location = faker.address.state(); let timestamp = faker.date.between('2015-01-01', '2020-05-20'); let weight = faker.random.number(); let species = faker.random.word(); let fishermanId = faker.random.number({min:0, max:10}); catches.push({ "id": id, "timestamp": timestamp, "location": location, "weight": weight, "species": species, "fishermanId": fishermanId }); } return { "catches": catches } } module.exports = generateCatch; module.exports = generateFishermen(); fs.writeFile('fakeData.json', JSON.stringify({fishermen: this.fishermen}), (err) => {console.log(err)}); fs.writeFile('fakeCatch.json', JSON.stringify({catches: this.catches}), (err) => {console.log(err)});
Python
UTF-8
9,306
2.640625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
from pox.core import core from collections import defaultdict import pox.openflow.libopenflow_01 as of from pox.lib.packet.ethernet import ethernet from pox.lib.packet.arp import arp from pox.lib.util import str_to_bool import networkx as nx import json from itertools import islice import random log = core.getLogger() # [src][dst][curr-sw] -> port path_map = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:None))) # [ip addr] -> mac addr arp_table = defaultdict(lambda:None) class Tutorial (object): """ A Tutorial object is created for each switch that connects. A Connection object for that switch is passed to the __init__ function. """ def __init__ (self, connection): # Keep track of the connection to the switch so that we can # send it messages! self.connection = connection self.dpid = connection.dpid # This binds our PacketIn event listener connection.addListeners(self) def resend_packet (self, packet_in, out_port): """ Instructs the switch to resend a packet that it had sent to us. "packet_in" is the ofp_packet_in object the switch had sent to the controller due to a table-miss. """ msg = of.ofp_packet_out() msg.data = packet_in # Add an action to send to the specified port action = of.ofp_action_output(port = out_port) msg.actions.append(action) # Send message to switch self.connection.send(msg) def act_like_switch (self, packet, packet_in): """ Implement switch-like behavior. """ # Here's some psuedocode to start you off implementing a learning # switch. You'll need to rewrite it as real Python code. # Learn the port for the source MAC log.debug("packet is %s", packet) ipp = packet.find('ipv4') a = packet.find('arp') if ipp is not None: paths = path_map[str(ipp.srcip)][str(ipp.dstip)][self.dpid] log.debug("Got packet from %s to %s at switch %d", ipp.srcip, ipp.dstip, self.dpid) path_num = random.randint(0, len(paths) - 1) port = paths[path_num] log.debug("port to send to: %d", port) self.resend_packet(packet_in, port) elif a is not None: if packet.payload.opcode == arp.REQUEST: log.debug("protodst is %s", a.protodst) else: log.warning("ERROR: packet is not IP. Dropping") def _handle_PacketIn (self, event): """ Handles packet in messages from the switch. """ print "**got packet at switch " + str(event.dpid) + "***" packet = event.parsed # This is the parsed packet data. if not packet.parsed: log.warning("Ignoring incomplete packet") return packet_in = event.ofp # The actual ofp_packet_in message. # Comment out the following line and uncomment the one after # when starting the exercise. #print "Src: " + str(packet.src) #print "Dest: " + str(packet.dst) #print "Event port: " + str(event.port) #log.info("packet in") self.act_like_switch(packet, packet_in) # NOT USED: JUST FOR DEBUGGING def write_paths_wrapper(): hosts = ['10.0.0.1','10.0.0.2','10.0.0.3','10.0.0.4'] paths = defaultdict(lambda:defaultdict(lambda:[])) link_to_port = defaultdict(lambda:defaultdict(lambda:None)) ip_to_dpid = defaultdict(lambda:None) # src dst - [[path 1] [path2]]; path 1: [first hop....dst] paths['10.0.0.1']['10.0.0.2'] = [['10.1.0.0', '10.0.0.2']] paths['10.0.0.1']['10.0.0.3'] = [['10.1.0.0', '10.2.0.0', '10.3.0.0', '10.0.0.3']] paths['10.0.0.1']['10.0.0.4'] = [['10.1.0.0', '10.2.0.0', '10.3.0.0', '10.0.0.4']] paths['10.0.0.2']['10.0.0.1'] = [['10.1.0.0', '10.0.0.1']] paths['10.0.0.2']['10.0.0.3'] = [['10.1.0.0', '10.2.0.0', '10.3.0.0', '10.0.0.3']] paths['10.0.0.2']['10.0.0.4'] = [['10.1.0.0', '10.2.0.0', '10.3.0.0', '10.0.0.4']] paths['10.0.0.3']['10.0.0.1'] = [['10.3.0.0', '10.2.0.0', '10.1.0.0', '10.0.0.1']] paths['10.0.0.3']['10.0.0.2'] = [['10.3.0.0', '10.2.0.0', '10.1.0.0', '10.0.0.2']] paths['10.0.0.3']['10.0.0.4'] = [['10.3.0.0', '10.0.0.4']] paths['10.0.0.4']['10.0.0.1'] = [['10.3.0.0', '10.2.0.0', '10.1.0.0', '10.0.0.1']] paths['10.0.0.4']['10.0.0.2'] = [['10.3.0.0', '10.2.0.0', '10.1.0.0', '10.0.0.2']] paths['10.0.0.4']['10.0.0.3'] = [['10.3.0.0', '10.0.0.3']] link_to_port['10.1.0.0']['10.2.0.0'] = 1 link_to_port['10.2.0.0']['10.1.0.0'] = 2 link_to_port['10.2.0.0']['10.3.0.0'] = 3 link_to_port['10.3.0.0']['10.2.0.0'] = 4 link_to_port['10.0.0.1']['10.1.0.0'] = 9 link_to_port['10.1.0.0']['10.0.0.1'] = 10 link_to_port['10.0.0.2']['10.1.0.0'] = 11 link_to_port['10.1.0.0']['10.0.0.2'] = 12 link_to_port['10.0.0.3']['10.3.0.0'] = 13 link_to_port['10.3.0.0']['10.0.0.3'] = 14 link_to_port['10.0.0.4']['10.3.0.0'] = 15 link_to_port['10.3.0.0']['10.0.0.4'] = 16 ip_to_dpid['10.1.0.0'] = 1 ip_to_dpid['10.2.0.0'] = 2 ip_to_dpid['10.3.0.0'] = 3 ip_to_dpid['10.4.0.0'] = 4 write_paths(hosts, paths, link_to_port, ip_to_dpid) def jellyfish_graph_to_dicts(useEcmp): # true if use ECMP, false if use k-shortest-paths def host_ip(node): return '10.0.0.' + str(node) def switch_ip(node): return '10.' + str(node) + '.0.0' data = None with open('generated_rrg', 'r') as infile: data = json.load(infile) graph = nx.readwrite.node_link_graph(data) calc_path_map = defaultdict(lambda:defaultdict(lambda:defaultdict(lambda:None))) link_to_port = defaultdict(lambda:defaultdict(lambda:None)) ip_to_dpid = defaultdict(lambda:None) hosts = [] host_to_ip = {} switch_to_ip = {} # set host and switch ips (every switch gets one host) for node_orig in graph.nodes(): node = node_orig + 1 switch_to_ip[node] = switch_ip(node) host_to_ip[node] = host_ip(node) hosts.append(host_to_ip[node]) # dpids for switches ip_to_dpid[switch_to_ip[node]] = node # links to ports for node_orig in graph.nodes(): node = node_orig + 1 host_ip = host_to_ip[node] switch_ip = switch_to_ip[node] link_to_port[host_ip][switch_ip] = node link_to_port[switch_ip][host_ip] = node for neigh_orig in graph.neighbors(node_orig): neigh = neigh_orig + 1 neigh_switch_ip = switch_to_ip[neigh] link_to_port[neigh_switch_ip][switch_ip] = node link_to_port[switch_ip][neigh_switch_ip] = neigh # set path ips for node_i_orig in graph.nodes(): node_i = node_i_orig + 1 node_j = node_i + 1 if (node_j == len(graph.nodes()) + 1): node_j = 1 if (useEcmp): calc_paths = list(islice(nx.all_shortest_paths(graph, node_i_orig, node_j - 1), 7)) else: calc_paths = list(islice(nx.shortest_simple_paths(graph, node_i_orig, node_j - 1), 8)) calc_ip_paths = [] calc_ip_rev_paths = [] for calc_path in calc_paths: calc_ip_path = [] calc_ip_rev_path = [] print "path" + str(calc_path) for i in range(0, len(calc_path)): calc_ip_path.append(switch_to_ip[calc_path[i] + 1]) calc_ip_rev_path.insert(0, switch_to_ip[calc_path[i] + 1]) # add end host calc_ip_path.append(host_to_ip[calc_path[len(calc_path) - 1] + 1]) calc_ip_rev_path.append(host_to_ip[calc_path[0] + 1]) calc_ip_paths.append(calc_ip_path) calc_ip_rev_paths.append(calc_ip_rev_path) src_ip = host_to_ip[node_i] dst_ip = host_to_ip[node_j] print "source node: " + str(node_i) print "dst node: " + str(node_j) print "source ip: " + src_ip print "dst ip: " + dst_ip print "paths: " + str(calc_ip_paths) print "reverse paths: " + str(calc_ip_rev_paths) print "" calc_path_map[src_ip][dst_ip] = calc_ip_paths calc_path_map[dst_ip][src_ip] = calc_ip_rev_paths #print ecmp_path_map return hosts, calc_path_map, link_to_port, ip_to_dpid def jellyfish_write_paths(useEcmp): # true if ECMP, false if k-shortest-paths hosts, ecmp_path_map, link_to_port, ip_to_dpid = jellyfish_graph_to_dicts(useEcmp) write_paths(hosts, ecmp_path_map, link_to_port, ip_to_dpid) def write_paths(hosts, paths, link_to_port, ip_to_dpid): # hosts is list of all host IPs # paths is [srcip][dstip] -> switch dpids # link_to_port is [sw1-dpid][sw2-dpid] -> port for src in hosts: for dst in hosts: paths_list = paths[src][dst] for path in paths_list: sw1 = None for sw2 in path: if sw1 is not None: port = link_to_port[sw1][sw2] if path_map[src][dst][ip_to_dpid[sw1]] is None: path_map[src][dst][ip_to_dpid[sw1]] = [] path_map[src][dst][ip_to_dpid[sw1]].append(port) log.debug("pathmap[%s][%s][%d] = %d", src, dst, ip_to_dpid[sw1], port) sw1 = sw2 def launch (ecmp=True): """ Starts the component """ def start_switch (event): log.debug("Controlling %s" % (event.connection,)) Tutorial(event.connection) print "ecmp is %s" % ecmp jellyfish_write_paths(str_to_bool(ecmp)) core.openflow.addListenerByName("ConnectionUp", start_switch)
Java
UTF-8
305
1.773438
2
[]
no_license
package com.busan.cw.clsp20120924.interfaces; import com.busan.cw.clsp20120924.model.PointModel; public interface PointModelCallback { public void onPointLoadStart(PointModel model); public void onPointLoadComplete(PointModel model); public void onPointLoadError(PointModel model, String message); }
Python
UTF-8
275
3.171875
3
[]
no_license
def convert_to_dict(args: dict): json = dict() for key, value in args.items(): if "len" in key: pass key_vals = str(key).split("_") last_index = len(key_vals) json[str(key_vals[last_index-1])] = value return json
TypeScript
UTF-8
167
2.828125
3
[]
no_license
import Turn from 'src/Enums/Turn'; const updateTurn = (currentTurn: Turn): Turn => { return currentTurn === Turn.X ? Turn.O : Turn.X; }; export default updateTurn;
Markdown
UTF-8
5,519
2.53125
3
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
# Docs & Community SIG meeting - 2021-05-11 Facilitator and meeting notes: Stephen Tramer ## Overall notes * For this first meeting participants are encouraged to submit a pull request to these notes adding contact information, filling out names, and other information that will help us collaborate as we start bringing participants together in the SIG. ## Agenda ### Introductions *Presenters:* Any/all * Amazon leads: * Documentation: Stephen Tramer (lead), Doug Erickson (manager), Chanelle Mosquera (Atom renderer), Mike Cronin (animation, art, contribution guides, and Gems), William Hayward (scripting, content architecture) * Community: Melissa Austin (manager/lead), Alex Damarjian (A/V content, tutorials), Phillip Wang (community manager) * `sig-ux` liaisons: Yuyu Hsu (manager), Joshua Rainbolt (site design) Please contact members of the Amazon team if you need assistance with accessing the documentation site or any O3DE foundation repositories. * Partner participants: * Apocalypse: Denis Dyack (tutorials and samples support, O3DE user) * Kythera: Robin, Matthew Jack (AI Gem) * RedHat: Erik Jacobs (copy support, OSS expert) * Backtrace: Jason D (debugging Gem(s)) ### Site and docs state *Presenter*: Stephen Tramer Visual runthrough of the site as it exists at the moment, and the general content architecture. The most important thing for contributors onboarding is: [Follow the contributor guide](https://o3deorg.netlify.app/docs/contributing/). It contains all kinds of information regarding site structure, style, terminology, Hugo shortcodes, PR submission, and review. * Suggestion: Rather than using 'Welcome', we may want to consider the more standard 'Get Started' or some other similar nomenclature. The User Guide landing page should link directly to Welcome, rather than leading into the "available features". Possible onboarding funnel issue. *Recommended action:* Further discussion or a pull request demonstrating a good fix for the problem. ### Content priorities and issue backlog *Presenter*: Stephen Tramer Runthrough of the current state of GitHub Issues for the o3de.org repo. Overview of `good-first-issue` and how the tagging system is currently used. As of this meeting there is no automation or templates. They're on an internal roadmap: Templates should be in place by 5/31 and automation before launch date. * Tutorials: Apocalypse and Denis to discuss the following with Alex Damarjian: * Default or template assets pre-approved for use with tutorials. Based on information from Royal O'Brien, we may be able to use some Kitbash3D resources for this exact purpose. Make sure to loop Royal in. * Video tutorial content * AI Gem documentation: Representatives from Kythera to take on AI Gem documentation tasks. Still needed to discuss (w/existing site architects & AMZN business): * How/if Kythera licensing for the Gem will affect its representation in open source documentation * How the Gem will be distributed (presumably core O3DE?) * Whether AI should be its own section of the guide, or remain exclusively part of the Gem Reference * Backtrace Gem and debugging: Representatives from Backtrace will take on some of these documentation tasks. Still need to discuss: * Exactly which topics will be owned by Backtrace before launch, and which cover "general debugging" vs. Backtrace-specific features. ### SIG business * Charter: Overview of the [Docs and Community SIG charter](https://github.com/o3de/foundation/blob/master/sigs/sig-docs/sig-docs-community-charter.md) roles and responsibilities. * **Issue:** Raised the fact that it hasn't been clear that this is a documentation "and community" SIG. The SIG is being (incrementally) renamed to reflect this, as `sig-docs-community` and referred to as the "D&C SIG" rather than "Docs SIG". * Cute animal mascot: Suggested that as part of the default asset set we have some sort of community collaboration to create a character/mascot suitable for them. **Followup:** A brief internal Amazon discussion essentially said: "Good idea, but not right now." Any further discussions postponed until after launch to avoid the perception that we're "wasting time on unimportant things" (a valid criticism people would have, even if cute animal design is unrelated to engineering tasks.) * Code of conduct: Our official code of conduct isn't established yet. For now we are using the CNCF (Cloud Native Computing Foundation) code of conduct. Amazon is working internally with a number of DEI stakeholders, including individuals in AGS and GameTech, to help identify areas of concern unique to this project and how we can address them effectively. * Terminology and style: We recommend interested partners take a look at these pages and submit issues, pull requests, or start discussions on the SIG mailing list or in Discord. * [Terminology](https://o3deorg.netlify.app/docs/contributing/to-docs/terminology/) * [Style Guide](https://o3deorg.netlify.app/docs/contributing/to-docs/style-guide/) **Of special interest to our copyeditor friends:** We do not currently follow or advise any particular manual of style. For contributors and partners who are more invested in making sure the copy passes of content go smoothly, please suggest _as much as you need to_ for the style guide. ## Postponed due to time These items from the agenda will be prioritized for the next SIG meeting. * Tutorial planning - "Day One" and "Week One" content types * *Presenter:* Melissa Austin * Community strategy * *Presenter:* Melissa Austin ## Other remarks Thank you for attending!
C
UTF-8
305
3.03125
3
[]
no_license
#include"CircularQueue.h" int main() { CQueue *q; QueueInit(&q); QueuePush(&q, 1); QueuePush(&q, 2); QueuePush(&q, 3); QueuePush(&q, 4); QueuePush(&q, 5); QueuePrintf(&q); QueuePop(&q); QueuePop(&q); QueuePrintf(&q); printf("%d ", QueueFront(&q)); printf("%d ", QueueBack(&q)); return 0; }
Ruby
UTF-8
1,024
3.96875
4
[]
no_license
# 해쉬 생성 방법 # {}로 감싸고 , 로 성분을 구분한다 # 각 성분은 :키 => 값 형태로 입력한다 # : 이것은 심볼이라고 부른다. resume = {:name => "Steve", :isMale => true, :age => 30} puts "Avengers resume" puts resume # 빈 해쉬 만들고 성분 추가하기 avengers = Hash.new avengers[:name] = "Tony Stark" avengers[:isMale] = true avengers[:age] = 45 puts "Tony Stark's information" puts avengers # 해쉬 성분 불러오기 puts "Who is the Iron-man?" puts "Name : #{avengers[:name]}" puts "Male : #{avengers[:isMale]}" puts "Age : #{avengers[:age]}" # 배열 안의 성분으로 해쉬가 들어가 있는 경우 avengers_list =[ {:name => "Tony Stark", :codename => "Iron-man"}, {:name => "Steve Rogers", :codename =>"Captain America"}, {:name => "Natasha Romanoff",:codename => "Black Widow"}, {:name => "Torr",:codename =>"Torr"} ] puts "Avengers List" avengers_list.each do |avengers| puts "Name : #{avengers[:name]}" puts "CodeName : #{avengers[:codename]}" puts "-----------" end
Java
UTF-8
2,825
2.109375
2
[]
no_license
package pageobjects.EmailAdmin.ManageList; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import pageobjects.AbstractPageObject; import pageobjects.PageObject; import static specs.AbstractSpec.propUIEmailAdmin; /** * Created by philipsushkov on 2016-12-06. */ public class MailingLists extends AbstractPageObject { private static By moduleTitle, grid, gridMailingLists, inputSearch, buttonSearch, firstListActive; private final Integer columnsNumber = 5; public MailingLists(WebDriver driver) { super(driver); moduleTitle = By.xpath(propUIEmailAdmin.getProperty("spanModule_Title")); grid = By.xpath(propUIEmailAdmin.getProperty("table_GridManage")); gridMailingLists = By.xpath(propUIEmailAdmin.getProperty("table_GridItem")); inputSearch = By.xpath(propUIEmailAdmin.getProperty("input_Search")); buttonSearch = By.xpath(propUIEmailAdmin.getProperty("button_Search")); firstListActive = By.xpath(propUIEmailAdmin.getProperty("first_ListActive")); } public String getUrl() { return driver.getCurrentUrl(); } public String getTitle() { waitForElement(moduleTitle); return getText(moduleTitle); } public Integer getTitleQuantity() { wait.until(ExpectedConditions.visibilityOf(findElement(grid)) ); return findElement(grid).findElements(gridMailingLists).size()/columnsNumber; } public WebElement getSearchField() { WebElement element = null; try { wait.until(ExpectedConditions.visibilityOf(findElement(inputSearch))); element = findElement(inputSearch); } catch (PageObject.ElementNotFoundException e1) { } catch (ElementNotVisibleException e2) { } return element; } public WebElement getSearchButton() { WebElement element = null; try { wait.until(ExpectedConditions.visibilityOf(findElement(buttonSearch))); element = findElement(buttonSearch); } catch (PageObject.ElementNotFoundException e1) { } catch (ElementNotVisibleException e2) { } return element; } public Boolean listActive(String name) { this.getSearchField().sendKeys(name); this.getSearchButton().click(); try { wait.until(ExpectedConditions.visibilityOf(findElement(firstListActive))); String listActive = findElement(firstListActive).getText(); return listActive.equals("True"); } catch (ElementNotVisibleException e) { e.printStackTrace(); } return null; } }
C#
UTF-8
1,024
3.265625
3
[]
no_license
using System; namespace pelda_if_shortcircuit { class Program { static bool Teszt1() { Console.WriteLine("Teszt1 kiértékelése..."); return false; } static bool Teszt2() { Console.WriteLine("Teszt2 kiértékelése..."); return true; } static void Main(string[] args) { if (Teszt1() & Teszt2()) { //Mindkét metódus lefut a tesztelés közben } Console.WriteLine(); if (Teszt1() | Teszt2()) { //Mindkét metódus lefut a tesztelés közben } Console.WriteLine(); if (Teszt1() && Teszt2()) { //Teszt2 nem hívódik meg } Console.WriteLine(); if (Teszt2() || Teszt1()) { //Teszt1 nem hívódik meg } Console.ReadLine(); } } }
Swift
UTF-8
1,259
2.78125
3
[]
no_license
// // ViewController.swift // StopJavaScript // // Created by Juanjo Ramos Rodriguez on 31/10/2019. // Copyright © 2019 JJR. All rights reserved. // import JavaScriptCore import UIKit class ViewController: UIViewController { @IBOutlet private weak var startButton: UIButton! @IBOutlet private weak var cancelButton: UIButton! // private let javaScriptContext = CustomJSContext() private let javaScriptContext: CustomJSContextProtocol = WKWebViewJSCore() override func viewDidLoad() { super.viewDidLoad() } @IBAction func startTapped(_ sender: Any) { startButton.isEnabled = false let code = readJSCode() runJavaScript(code: code) } @IBAction func cancelTapped(_ sender: Any) { javaScriptContext.kill() } private func runJavaScript(code: String) { DispatchQueue.global().async { [weak self] in self?.javaScriptContext.evaluateScript(code) DispatchQueue.main.async { [weak self] in self?.startButton.isEnabled = true } } } } private func readJSCode() -> String { let url = Bundle.main.url(forResource: "code", withExtension: "js")! return try! String(contentsOf: url) }
Python
UTF-8
665
2.921875
3
[]
no_license
from bs4 import BeautifulSoup import requests URL_LINK="<URL_LINK_HERE>" body = requests.get(URL_LINK) soup = BeautifulSoup(body.text, 'html.parser') list_of_images = soup.find_all('img') #print(list_of_images) source = [img['src'] for img in list_of_images] imageCount=0 for i,link in enumerate(source): with open(f"images/images{i+1}.jpg","wb+") as f: if ".svg" not in link: #print(link) if 'http' not in link: link = '{}{}'.format(URL_LINK, link) response = requests.get(link) imageCount+=1 f.write(response.content) print("{} images were found".format(imageCount))
C#
UTF-8
1,704
2.515625
3
[]
no_license
using GoldenLion.Entity; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace GoldenLion { public partial class MainPage : ContentPage { UserAccountManager userAccountManager; public MainPage() { InitializeComponent(); var entry = new Entry { Placeholder = "Username", PlaceholderColor = Color.Olive }; userAccountManager = UserAccountManager.DefaultUserAccount; } async void ButtonEntry_Clicked(object sender, EventArgs e) { string username = EntryUsername.Text; string password = EntryPassword.Text; ButtonEntry.IsEnabled = false; LabelToast.Text = "Logining in. Please wait"; if (await userAccountManager.CheckUserAccount(username, password, Device.RuntimePlatform)) { Application.Current.Properties["UserName"] = userAccountManager.GetUserName(); await Navigation.PushAsync(new Menu()); ClearEntry(); } else { ClearEntry(); await DisplayAlert("Alert", "Incorrect Password or Username", "Okay"); } } private void ClearEntry() { EntryUsername.Text = string.Empty; EntryPassword.Text = string.Empty; LabelToast.Text = string.Empty; } async void ButtonSignUp_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new SignUp()); //Go to SignUp.xaml } } }
C#
UTF-8
4,297
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Routing_Info_Viewer { /// <summary> /// Interaction logic for UserControlNumericUpdown.xaml /// </summary> public partial class UserControlNumericUpdown : UserControl { public UserControlNumericUpdown() { InitializeComponent(); /// http://stackoverflow.com/questions/34869302/c-sharp-defaultvalue-attribute-not-working Value = 3; Maximum = 10; Minimum = 1; PrefixIntro = "Prefix"; PostfixMetric = "KM"; } private void buttonIncrease_Click(object sender, RoutedEventArgs e) { slider.Value += slider.LargeChange; } private void buttonDecrease_Click(object sender, RoutedEventArgs e) { slider.Value -= slider.LargeChange; } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(UserControlNumericUpdown)); /// <summary> /// The value that this control represent. /// </summary> [Description("Current slider value."), DefaultValue(3.0)] public double Value { get { return (double)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty PrefixIntroProperty = DependencyProperty.Register("PrefixIntro", typeof(string), typeof(UserControlNumericUpdown)); /// <summary> /// Prefix of the shown text. /// </summary> [Description("Prefix of the shown text."), DefaultValue("Prefix")] public string PrefixIntro { get { return GetValue(PrefixIntroProperty).ToString(); } set { SetValue(PrefixIntroProperty, value); } } public static readonly DependencyProperty PostfixMetricProperty = DependencyProperty.Register("PostfixMetric", typeof(string), typeof(UserControlNumericUpdown)); /// <summary> /// Postfix of the shown text, such as: km, kg, ℃, °, etc. /// </summary> [Description("Current slider value."), DefaultValue("meters")] public string PostfixMetric { get { return GetValue(PostfixMetricProperty).ToString(); } set { SetValue(PostfixMetricProperty, value); } } public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(UserControlNumericUpdown)); /// <summary> /// Max number allowed. /// </summary> [Description("The Maximum"), DefaultValue(10.0)] public double Maximum { get { return (double)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(UserControlNumericUpdown)); /// <summary> /// Min number allowed. /// </summary> [Description("The minimum"), DefaultValue(1)] public double Minimum { get { return (double)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } } }
C++
UTF-8
734
2.59375
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; map<char, int> mp; queue<char> qu; char x; for(int i=0; i<n; i++){ cin>>x; if(mp.find(x) == mp.end()){ qu.push(x); mp[x] = 1; } else mp[x] += 1; while(!qu.empty()) if(mp[qu.front()] == 1){ cout<<qu.front()<<" "; break; } else qu.pop(); if(qu.empty()) cout<<-1<<" "; } cout<<endl; } return 0; }
Python
UTF-8
1,310
3.109375
3
[]
no_license
import Tkinter as tk import tkFileDialog from src.main.com.personal.conversions.ImagesToPDF import ImagesToPDF directory = "" def display_in_center(window, width=400, height=400, title="My App"): """ :param window: :param width: :param height: :param title: :return: """ ws = window.winfo_screenwidth() hs = window.winfo_screenheight() # calculate x and y coordinates for the Tk root window x = (ws/2) - (width/2) y = (hs/2) - (height/2) # set the dimensions of the screen # and where it is placed window.geometry('%dx%d+%d+%d' % (width, height, x, y)) window.title(title) return window def add_label(text='Sample Label', column=0, row=0): tk.Label(text=text).grid(column=column, row=row) def add_button(text="Sample Button", column=0, row=0): tk.Button(text=text).grid(column=column, row=row) def browse(): print "im called" curr_dir = tkFileDialog.askdirectory() msg = ImagesToPDF().convertToPDF(curr_dir) print 'msg --> ', msg def main(): window = tk.Tk() window = display_in_center(window=window, title="Image To PDF Converter") add_label(text="Select Location of Images : ", column=0, row=0) tk.Button(text='Browse', command=browse()) window.mainloop() main()
Java
UTF-8
3,307
2.203125
2
[]
no_license
package org.rz.midiplayer.xmlmodule.midispec; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Spec complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Spec"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}reset"/> * &lt;element ref="{}melopart"/> * &lt;element ref="{}drumpart"/> * &lt;/sequence> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Spec", propOrder = { "reset", "melopart", "drumpart" }) public class Spec { @XmlElement(required = true) protected Reset reset; @XmlElement(required = true) protected MeloPart melopart; @XmlElement(required = true) protected DrumPart drumpart; @XmlAttribute(required = true) protected String name; /** * Gets the value of the reset property. * * @return * possible object is * {@link Reset } * */ public Reset getReset() { return reset; } /** * Sets the value of the reset property. * * @param value * allowed object is * {@link Reset } * */ public void setReset(Reset value) { this.reset = value; } /** * Gets the value of the melopart property. * * @return * possible object is * {@link MeloPart } * */ public MeloPart getMelopart() { return melopart; } /** * Sets the value of the melopart property. * * @param value * allowed object is * {@link MeloPart } * */ public void setMelopart(MeloPart value) { this.melopart = value; } /** * Gets the value of the drumpart property. * * @return * possible object is * {@link DrumPart } * */ public DrumPart getDrumpart() { return drumpart; } /** * Sets the value of the drumpart property. * * @param value * allowed object is * {@link DrumPart } * */ public void setDrumpart(DrumPart value) { this.drumpart = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
Swift
UTF-8
474
2.703125
3
[ "MIT" ]
permissive
// // Parser.swift // uncomplicated-todo // // Created by Vladislav Morozov on 27/04/2019. // Copyright © 2019 misshapes. All rights reserved. // import Foundation class Parser<T: Decodable> { static func decode(_ data: Data) throws -> T { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase let object = try decoder.decode(T.self, from: data) return object } }
Rust
UTF-8
290
2.8125
3
[]
no_license
pub trait Stack<T> { fn empty(&self) -> bool; fn push(&mut self, x: T); fn pop(&mut self) -> T; fn length(&self) -> usize; } pub trait Queue<T> { fn empty(&self) -> bool; fn enqueue(&mut self, x: T); fn dequeue(&mut self) -> T; fn length(&self) -> usize; }
Java
UTF-8
1,604
3.28125
3
[]
no_license
package CCC._06; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class J4_ItsToughBeingATeen { static HashMap<Integer, ArrayList<Integer>> limit=new HashMap<>(); static HashMap<Integer,ArrayList<Integer>> lock=new HashMap<>(); static void add(int from, int to) { limit.get(from).add(to); lock.get(to).add(from); } static int scan() { for(int count=1;count<8;count++) { if(!canDo.contains(count)) { if(lock.get(count).size()==0) { return count; } } } return -1; } static HashSet<Integer> canDo=new HashSet<Integer>(); public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); for(int count=1;count<8;count++) { limit.put(count, new ArrayList<Integer>()); lock.put(count, new ArrayList<Integer>()); } add(1,7); add(1,4); add(2,1); add(3,4); add(3,5); int from=sc.nextInt(); int to=sc.nextInt(); while(from!=0&&to!=0) { add(from,to); //System.out.println("ok"); from=sc.nextInt(); to=sc.nextInt(); } int[] out=new int[7]; for(int count=0;count<7;count++) { int lol=scan(); if(lol==-1) { break; } ArrayList<Integer> next=limit.get(lol); Integer secLol=lol; for(int release:next) { lock.get(release).remove(secLol); } out[count]=lol; canDo.add(lol); } if(canDo.size()==7) { for(int next:out) { System.out.println(next); } } else { System.out.println("Cannot complete these tasks. Going to bed."); } sc.close(); } }
Rust
UTF-8
3,659
2.65625
3
[]
no_license
use mc_core::block::{Block, BlockState}; use mc_core::rand::JavaRandom; use mc_vanilla::block::*; use mc_vanilla::block::material::TAG_LEAVES; use crate::view::LevelView; use super::Feature; pub struct PlantFeature { block: &'static BlockState, try_count: u32, // search_floor: bool, can_plant_predicate: fn(&'static Block) -> bool } impl PlantFeature { pub fn new(block: &'static Block, try_count: u32, /*search_floor: bool,*/ can_plant_predicate: fn(&'static Block) -> bool) -> Self { Self { block: block.get_default_state(), try_count, // search_floor, can_plant_predicate } } pub fn new_flower(block: &'static Block) -> Self { Self::new(block, 64, can_plant_living) } pub fn new_grass(block: &'static Block) -> Self { Self::new(block, 128, can_plant_living) } pub fn new_dead_bush() -> Self { Self::new(&DEAD_BUSH, 4, can_plant_dead) } pub fn new_lily_pad() -> Self { Self::new(&LILY_PAD, 10, can_plant_lily_pad) } } impl Feature for PlantFeature { fn generate(&self, level: &mut dyn LevelView, rand: &mut JavaRandom, x: i32, mut y: i32, z: i32) -> bool { for _ in 0..self.try_count { let bx = (x + rand.next_int_bounded(8)) - rand.next_int_bounded(8); let by = (y + rand.next_int_bounded(4)) - rand.next_int_bounded(4); let bz = (z + rand.next_int_bounded(8)) - rand.next_int_bounded(8); if by > 0 && by < 256 { let current_block = level.get_block_at(bx, by, bz).unwrap().get_block(); if current_block == &AIR /* && (block light >= 8 || see sky) */ { let ground_block = level.get_block_at(bx, by - 1, bz).unwrap().get_block(); if (self.can_plant_predicate)(ground_block) { level.set_block_at(bx, by, bz, self.block).unwrap(); } } } } true } } fn can_plant_living(block: &'static Block) -> bool { block == &GRASS_BLOCK || block == &DIRT || block == &FARMLAND } fn can_plant_dead(block: &'static Block) -> bool { block == &SAND } fn can_plant_lily_pad(block: &'static Block) -> bool { block == &WATER } pub struct SugarCaneFeature; impl Feature for SugarCaneFeature { fn generate(&self, level: &mut dyn LevelView, rand: &mut JavaRandom, x: i32, y: i32, z: i32) -> bool { for _ in 0..20 { let bx = (x + rand.next_int_bounded(4)) - rand.next_int_bounded(4); let bz = (z + rand.next_int_bounded(4)) - rand.next_int_bounded(4); if level.get_block_at(bx, y, bz).unwrap().is_block(&AIR) && ( level.get_block_at(bx - 1, y - 1, bz + 0).unwrap().is_block(&WATER) || level.get_block_at(bx + 1, y - 1, bz + 0).unwrap().is_block(&WATER) || level.get_block_at(bx + 0, y - 1, bz - 1).unwrap().is_block(&WATER) || level.get_block_at(bx + 0, y - 1, bz + 1).unwrap().is_block(&WATER) ) { let height = rand.next_int_bounded(3); let height = rand.next_int_bounded(height + 1) + 2; let ground_block = level.get_block_at(bx, y - 1, bz).unwrap().get_block(); if ground_block == &GRASS_BLOCK || ground_block == &DIRT || ground_block == &SAND { for by in y..(y + height) { level.set_block_at(bx, by, bz, SUGAR_CANE.get_default_state()).unwrap(); } } } } true } }
C++
UTF-8
261
2.703125
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main() { string str; int size; getline(cin,str); size = str.size(); int data[size ]; int out[size + 1]; out[0] = 0; out[1] = 1; for(int i = 0; i < size; i++) data[i] = str[i] - '0'; }
C
UTF-8
839
4
4
[]
no_license
/*25. Write a C program that reads an integer between 1 and 12 and print the month of the year in English. Go to the editor Test Data : Input a number between 1 to 12 to get the month name: 8 Expected Output: August */ #include<stdio.h> int main() { int a; printf("Input a number between 1 to 12 to get the month name : "); scanf("%d",&a); if(a==1) { printf("January "); } else if(a==2) { printf(" February "); } else if(a==3) {printf("March"); } else if(a==4) {printf("April"); } else if(a==5) {printf(" May"); } else if(a==6) {printf("June "); } else if(a==7) {printf("July "); } else if(a==8) {printf("August"); } else if(a==9) {printf("September "); } else if(a==10) {printf("October "); } else if(a==11) {printf("November "); } else if(a==12) {printf(" December"); } else {printf("Invalid Input"); } return 0; }
Java
UTF-8
607
2.71875
3
[]
no_license
package coreservlets; /** From <a href="http://courses.coreservlets.com/Course-Materials/">the * coreservlets.com tutorials on servlets, JSP, Struts, JSF, Ajax, GWT, and Java</a>. */ public class Employee { private Name name; private Company company; public Employee(Name name, Company company) { setName(name); setCompany(company); } public Name getName() { return (name); } public void setName(Name name) { this.name = name; } public Company getCompany() { return (company); } public void setCompany(Company company) { this.company = company; } }
Java
UTF-8
893
2.546875
3
[]
no_license
package com.example.gxtspringdemo.client.event; import com.example.gxtspringdemo.shared.model.Book; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; public class BookAddedEvent extends GwtEvent<BookAddedEvent.BookAddedHandler> { private static Type<BookAddedHandler> TYPE; private final Book book; public BookAddedEvent(Book book) { this.book = book; } @Override public Type<BookAddedHandler> getAssociatedType() { return TYPE(); } public static Type<BookAddedHandler> TYPE() { if (TYPE == null) { TYPE = new Type<>(); } return TYPE; } @Override protected void dispatch(BookAddedHandler handler) { handler.onBookAdded(book); } public interface BookAddedHandler extends EventHandler { void onBookAdded(Book book); } }
C
UTF-8
699
2.609375
3
[]
no_license
#include<stdio.h> #include<string.h> int main() {//memset(c,0,sizeof(c)); long long int n,k=0,i,j; long long int c[105],mark=0,sum=1; long long int num=0,first=0,last=0,first1=0,last1=0; memset(c,0,sizeof(c)); scanf("%lld",&n); for(i=0;i<n;i++) scanf("%lld",&c[i]); for(i=0;i<n;i++) {if(c[i]==1) {first=i; break; } } for(i=n-1;i>0;i--) {if(c[i]==1) {last=i; break; } } if(c[0]==1&&last==0) printf("1"); else if(c[0]==0&&last==0) printf("0"); first1=first; last1=last; for(i=(first1+1);i<=last1;i++) { if(c[i]==1) k=i-first1; if(c[i]==1&&c[first1]==1) {sum=k*sum; //num=0; first1=i; } if(first1==last1) break; } if(last!=0) printf("%lld",sum); system("pause"); return 0; }
PHP
UTF-8
4,498
3.0625
3
[]
no_license
<?php class User{ protected $db; protected $user_name; protected $user_email; protected $user_pass; protected $has_pass; function __construct($db_connection) { $this->db = $db_connection; } // signUp User function signUp($username, $email, $password){ try { $this->user_name = trim($username); $this->user_email = trim($email); $this->user_pass = trim($password); if (!empty($this->user_name) && !empty($this->user_email) && !empty($this->user_pass)) { if (filter_var($this->user_email, FILTER_VALIDATE_EMAIL)) { $check_email = $this->db->prepare("SELECT * FROM users WHERE user_email = ?"); $check_email->execute([$this->user_email]); if ($check_email->rowCount() > 0) { return ['errorMessage' => 'This email address is already registered!! Try another one!']; } else { $user_image = rand(1, 12); $this->hash_pass = password_hash($this->user_pass, PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, user_email, user_password, user_image) VALUES (:username, :user_email, :user_pass, :user_image)"; $register_stmt = $this->db->prepare($sql); $register_stmt->bindValue(':username', htmlspecialchars($this->user_name), PDO::PARAM_STR); $register_stmt->bindValue(':user_email', $this->user_email, PDO::PARAM_STR); $register_stmt->bindValue(':user_pass', $this->hash_pass, PDO::PARAM_STR); $register_stmt->bindValue(':user_image', $user_image . '.png', PDO::PARAM_STR); $register_stmt->execute(); return ['successMessage' => 'You have signed up successfully.']; } } else { return ['errorMessage' => 'Invalid email address!']; } } else { return ['errorMessage' => 'Please fill in all required fields.']; } } catch ( PDOException $errorMsg){ die($errorMsg->getMessage()); } } //login function login($email, $password){ try{ $this->user_email = trim($email); $this->user_pass = trim($password); $find_email = $this->db->prepare("SELECT * FROM users WHERE user_email = ?"); $find_email->execute([$this->user_email]); if($find_email -> rowCount() ===1){ $row = $find_email-> fetch(PDO::FETCH_ASSOC); $match_pass = password_verify($this->user_pass, $row['user_password']); if($match_pass){ $_SESSION = [ 'user_id' => $row['id'], 'email' => $row['user_email'] ]; header('Location: profile.php'); } else{ return ['errorMessage' => 'Invalid password']; } } else{ return ['errorMessage' => 'Invalid email address!']; } } catch (PDOException $errorMsg){ die($errorMsg->getMessage()); } } //find user by ID function find_user_by_id($id){ try{ $find_user = $this->db->prepare("SELECT * FROM users WHERE id=?"); $find_user->execute([$id]); if($find_user->rowCount() === 1){ return $find_user->fetch(PDO::FETCH_OBJ); } else{ return false; } } catch(PDOException $errMsg){ die($errMsg->getMessage()); } } //Fetch all users function all_users($id){ try{ $get_users = $this->db->prepare("SELECT id,username,user_image FROM users WHERE id != ?"); $get_users->execute([$id]); if($get_users->rowCount() >0){ return $get_users->fetchAll(PDO::FETCH_OBJ); } else{ return false; } } catch( PDOException $errMsg){ die($errMsg->getMessage()); } } }
Swift
UTF-8
1,506
2.734375
3
[]
no_license
// // FlickerPic.swift // virtualTourist // // Created by Sergio Costa on 31/07/18. // Copyright © 2018 Sergio Costa. All rights reserved. // // let flickerPic = try? JSONDecoder().decode(FlickerPic.self, from: jsonData) import Foundation struct FlickerPic: Codable { let photoAlbum: PhotoAlbum? let stat: String? enum CodingKeys: String, CodingKey { case photoAlbum = "photos" case stat = "stat" } } struct PhotoAlbum: Codable { let page: Int? let pages: Int? let perpage: Int? let total: String? let photo: [FlickPhoto]? enum CodingKeys: String, CodingKey { case page = "page" case pages = "pages" case perpage = "perpage" case total = "total" case photo = "photo" } } struct FlickPhoto: Codable { let id: String? let owner: String? let secret: String? let server: String? let farm: Int? let title: String? let ispublic: Int? let isfriend: Int? let isfamily: Int? let urlM: String? let heightM: String? let widthM: String? enum CodingKeys: String, CodingKey { case id = "id" case owner = "owner" case secret = "secret" case server = "server" case farm = "farm" case title = "title" case ispublic = "ispublic" case isfriend = "isfriend" case isfamily = "isfamily" case urlM = "url_m" case heightM = "height_m" case widthM = "width_m" } }
TypeScript
UTF-8
1,163
3.71875
4
[ "MIT" ]
permissive
/** * 포맷팅 기능을 제공합니다. * * @export * @class StringFormatter */ export class StringFormatter { /** * 숫자에 1000 단위 구분자를 추갛해서 문자열로 출력합니다. * * @param {(number | string)} value * @param {string} delimiter 구분자; 기본값: **,** 콤마 문자 * @returns {string} * @memberof StringFormatter */ public NumberWithDelimiter( value: number | string, delimiter = ',', ): string { let stringValue = ''; let fraction = ''; if (typeof value === 'number') { stringValue = value.toString(); } if (typeof value === 'string') { stringValue = value; } if (stringValue.indexOf('.') >= 0) { const splittedValue = stringValue.split('.'); if (splittedValue.length > 1) { stringValue = splittedValue[0]; fraction = splittedValue[1]; } } stringValue = stringValue.replace(/\B(?=(\d{3})+(?!\d))/g, delimiter); return `${stringValue}${fraction ? `.${fraction}` : ''}`; } }
C#
UTF-8
1,223
2.703125
3
[]
no_license
using Ionic.Zip; using System; using System.Drawing; using System.Drawing.Imaging; using System.Threading; namespace _91appExcelCreator { internal class PictureTheme { public Color BackgroundColor { get; set; } public string Words { get; set; } public int Width { get; set; } public int Height { get; set; } public Font FontCounter { get; set; } public ImageFormat ImageFormat { get; set; } public Color GetRandomColor() { var random = new Random(); var r = random.Next(0, 255); Thread.Sleep(5); var g = random.Next(0, 255); Thread.Sleep(5); var b = random.Next(0, 255); return Color.FromArgb(r, g, b); } public void CreateZip(int count) { using (var zip = new ZipFile("Test")) { for (var i = 1; i <= count; i++) { zip.AddFile(this.locate + i + ".jpg", string.Empty); } zip.Save(this.locate + DateTime.Now.ToString("yyyy-MM-dd,HH-mm-ss") + @"_test.zip"); } } public string locate { get; set; } } }
Python
UTF-8
991
3.171875
3
[]
no_license
class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ stack = [] result, number, sign = 0, 0, 1 for n in s: if n.isdigit(): number = number * 10 + int(n) else: if n == "+": result += sign * number number = 0 sign = 1 if n == "-": result += sign * number number = 0 sign = -1 if n == "(": stack.append(result) stack.append(sign) result = 0 sign = 1 if n == ")": result = number * sign + result number = 0 result *= stack.pop() result += stack.pop() if (number != 0): result += sign * number return result
SQL
UTF-8
2,430
3.109375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 26-Nov-2020 às 21:39 -- Versão do servidor: 10.4.14-MariaDB -- versão do PHP: 7.2.34 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 */; -- -- Banco de dados: `bancotcc` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `tb_login` -- CREATE TABLE `tb_login` ( `id_login` int(11) NOT NULL, `usuario` varchar(255) DEFAULT NULL, `senha` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `tb_login` -- INSERT INTO `tb_login` (`id_login`, `usuario`, `senha`) VALUES (1, 'pedro', '12'); -- -------------------------------------------------------- -- -- Estrutura da tabela `tb_orientacao` -- CREATE TABLE `tb_orientacao` ( `id_orientacao` int(11) NOT NULL, `orientador` varchar(255) DEFAULT NULL, `aluno` varchar(255) DEFAULT NULL, `texto` text DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `tb_orientacao` -- INSERT INTO `tb_orientacao` (`id_orientacao`, `orientador`, `aluno`, `texto`) VALUES (1, 'Joser', 'Pedro', 'oi '), (2, 'Joser', 'Pedro', 'ola'), (3, 'Joser', 'Pedro', 'ola'), (4, 'Joser', 'Pedro', 'ol'), (5, 'Joser', 'Pedro', 'ol'), (6, 'Joser', 'Jefferson', 'Boi '); -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `tb_login` -- ALTER TABLE `tb_login` ADD PRIMARY KEY (`id_login`); -- -- Índices para tabela `tb_orientacao` -- ALTER TABLE `tb_orientacao` ADD PRIMARY KEY (`id_orientacao`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `tb_login` -- ALTER TABLE `tb_login` MODIFY `id_login` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT de tabela `tb_orientacao` -- ALTER TABLE `tb_orientacao` MODIFY `id_orientacao` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; 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 */;
Go
UTF-8
1,880
3.625
4
[]
no_license
package boogie import "github.com/davecgh/go-spew/spew" /* CtxState defines a state machine we can use to parse lines of code. */ type CtxState int const ( // START sets an undefined state, used as a jumping off point. START CtxState = 0 + iota // LABEL sets the label state LABEL // KEYWORD sets the keyword state. KEYWORD ) /* Lexeme is a type that structures a raw line of code string. */ type Lexeme struct { ID string str string } /* Lexer is a wrapper for all data and methods needed for converting lines of codes to Lexemes. */ type Lexer struct { ctxState CtxState curCtx Context curChar string buf string curLexeme Lexeme LCh chan string delims []string keys []string } /* NewLexer returns a reference to a new instance of Lexer. */ func NewLexer() *Lexer { return &Lexer{ ctxState: START, LCh: make(chan string), delims: []string{":"}, keys: []string{"echo", "exit"}, } } /* Run a new instance of Lexer to receive lines of code over its channel. */ func (lexer *Lexer) Run() { for { select { case loc := <-lexer.LCh: // Convert the line of code to a Lexeme. for _, r := range loc { lexer.curChar = string(r) switch lexer.ctxState { case START: lexer.curCtx = Context{Start{}} case LABEL: lexer.curCtx = Context{Label{}} } // Append the new character to the transient buffer. lexer.buf += lexer.curCtx.getNextState(lexer) if lexer.curLexeme.ID != "" { spew.Dump(lexer.curLexeme) } } } } } func (lexer *Lexer) isDelim(str string) bool { return lexer.stringInSlice(str, lexer.delims) } func (lexer *Lexer) isKey(str string) bool { return lexer.stringInSlice(str, lexer.keys) } func (lexer *Lexer) stringInSlice(str string, list []string) bool { for _, v := range list { if v == str { return true } } return false }
Java
UTF-8
1,086
2.921875
3
[]
no_license
package com.hibernate.hibernateproj; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Client { //public void save1(int id, String name) method for servlet public void save1(Employee emp) { System.out.println("Save() calles"); Configuration cfg = new Configuration(); cfg.configure(); SessionFactory factory =null; Session session=null; try { factory = cfg.buildSessionFactory(); session = factory.openSession(); }catch (Exception e) { System.out.println(e); } Transaction tx = session.beginTransaction(); System.out.println("Transection Begin"); /* code for servlet Employee e1=new Employee(); e1.setId(id); e1.setName(name); */ session.save(emp); System.out.println("Object saved successfully.....!!"); tx.commit(); session.close(); factory.close(); } }
Markdown
UTF-8
1,107
2.953125
3
[ "Apache-2.0" ]
permissive
# shadow-relay 没有什么阻碍是一个搭载 shadowsocks 的 vps 翻不过去的;如果有,那就再来一个! 此命令可以将连接到本台电脑的指定端口的流量转发至目标机器的目标端口, 并接收返回的报文转发至源Ip, 用来转接Shadowsocks再合适不过了。 值得注意的是,此命令重启后需要重新设置。 命令: ``` relay local_ip local_port dest_ip dest_port ``` 其中, + local_ip 表示本机想要用来处理流量转发的网上的ip + local_port 表示本机接收流量的端口号 + dest_ip 表示目标机器的ip + dest_port 表示目标机器的端口号 主要适用于内网连接外网机器速度较慢,需要添加新的机器作为中转的情况。 ## 典型示例: 内网机器 ip 为 ip0,外网为 ip1,中转为 ip2。外网端口为 port1,中转端口为 port2。 ### 添加中转之前的设置 内网机器: + 目标ip: ip1 + 目标端口: port1 ### 添加中转之后的设置 内网机器: + 目标ip: ip2 + 目标端口: port2 中转机器: ``` relay ip2 port2 ip1 port 1 ```
Java
UTF-8
1,989
2.453125
2
[]
no_license
package ohopro.com.ohopro.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import java.util.ArrayList; import ohopro.com.ohopro.R; /** * Created by sai on 03-02-2017. */ public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.ViewHolder> { ArrayList<String> strings; NavigationListener navigationListener; public interface NavigationListener { void clickOnItem(String s); } public NavigationDrawerAdapter(ArrayList<String> strings) { this.strings = strings; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); navigationListener = (NavigationListener) context; LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return new ViewHolder(layoutInflater.inflate(R.layout.row_navigator, parent, false)); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.tv_type.setText(strings.get(position)); holder.ll_type.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { navigationListener.clickOnItem(holder.tv_type.getText().toString()); } }); } @Override public int getItemCount() { return strings.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView tv_type; FrameLayout ll_type; public ViewHolder(View itemView) { super(itemView); tv_type = (TextView) itemView.findViewById(R.id.tv_type); ll_type = (FrameLayout) itemView.findViewById(R.id.ll_type); } } }
PHP
UTF-8
1,226
2.609375
3
[]
no_license
<?php function match_get_raw($conn, $userid = null) { $stmt=mysqli_stmt_init($conn); $stmt->prepare("SELECT id, username, firstname, lastname, prefs FROM users"); $stmt->execute(); $result = mysqli_stmt_get_result($stmt); $rowCount = mysqli_num_rows($result); $data = array(); for($i = 0; $i < $rowCount; $i++) { $row = mysqli_fetch_assoc($result); if($row["id"] != $userid) { array_push($data, array( "id" => $row["id"], "username" => $row["username"], "firstname" => $row["firstname"], "lastname" => $row["lastname"], "prefs" => json_decode($row["prefs"], true) )); } } $stmt->close(); return $data; } function match_get_pics($conn, $userid = null) { $stmt=mysqli_stmt_init($conn); $stmt->prepare("SELECT id, profile_photo FROM users"); $stmt->execute(); $result = mysqli_stmt_get_result($stmt); $rowCount = mysqli_num_rows($result); $data = array(); for($i = 0; $i < $rowCount; $i++) { $row = mysqli_fetch_assoc($result); if($row["id"] != $userid) { array_push($data, array( "id" => $row["id"], "profile_photo" => $row["profile_photo"] )); } } $stmt->close(); return $data; } ?>
Markdown
UTF-8
2,299
3.046875
3
[]
no_license
![](https://github.com/JoannePeel/A-deadly-mexican-story/blob/master/A%20Deadly%20Mexican%20History.jpg) # A-deadly-mexican-story ## Project background In Mexico, there have been important changes in the **epidemiological occurrence of diseases**, related to: Environmental, demographic, economic, social, and cultural changes, which have influenced the epidemiological profile, as well as the characteristics related to the **presence of disease and death in the Mexican population**. This has been described as a _phenomenon of risk transition_, since during the first half of the 20th century, the population was exposed to the inherent risks of a country in social development, characterized by poor hygiene and underutilization of health services, while in the second half there was a transition to health problems associated with development and urbanization. As a result, risks of exposure to a sedentary lifestyle, stress, tobacco and drug use, violence, as well as unhealthy eating habits have increased, resulting in high cholesterol and high blood pressure, **factors responsible for much of the global burden of the disease.** This transition has resulted in problems such as obesity and other chronic degenerative diseases at increasingly younger ages. Therefore, the main objective of this project is to analyze the mortality and defunctions indicators that the Mexican population has been presenting in the period 2012-2017. ## Methods *Data* For this purpose, we used the following databases: 1) [Inegi deaths ( 2012-2017)](https://www.inegi.org.mx/programas/mortalidad/) *ETL Process* We [cleaned, organized and upload the databases to a relational database (sqlite)](https://github.com/JoannePeel/1001-ways-to-die-in-Mexico/tree/master/etl_process). Then we created all views necessary for analysis and deployment. *Machine learning* We used sklearn [random forest model](https://github.com/JoannePeel/A-deadly-mexican-story/blob/master/main.ipynb) to build a model able to predict the cause of death based on data found in death certificates. *Data visualization* Finally, we build a [deadly dashboard](https://public.tableau.com/profile/daniel.cespedes2591#!/vizhome/ADeadlyMexicanStory/ADeadlyMexicanStory?publish=yes) to present insights, using tableau public.
Python
UTF-8
1,095
2.90625
3
[]
no_license
import pyarex as pa import datetime def unix_time_ms(dt): epoch = datetime.datetime.utcfromtimestamp(0) return int((dt - epoch).total_seconds() * 1000.0) # Initalize the needed datasources. Right now this is hardcoded into the initializer, so for config you need to manage this yourself. data_provider = pa.init_param_sampleprovider() # Get some params that you want to look for and of course some times as well params = ['ALPHA_AN', 'SOLAR_AA'] #timestamp_start = 1387324800000 #timestamp_end = 1388584759000 timestamp_start = unix_time_ms(datetime.datetime(2021,1,1,0,0)) timestamp_end = unix_time_ms(datetime.datetime(2021,1,10,0,0)) # Get the data from HBase and transform into Pandas DF df = data_provider.get_parameter_data_df(params, timestamp_start, timestamp_end) print(df.shape) # Or, if you prefer, get them into sample objects and get information from the objects. # The method returns a nested generator. samples = data_provider.get_parameter_data_objs(params, timestamp_start, timestamp_end) for sample in samples: for s in sample: print(s.get_value())
Markdown
UTF-8
5,690
3.171875
3
[]
no_license
# DataFrame 向量化运算 ### Pandas shift() Pandas shift() 函数的文档可以在[这里](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html)找到。如果你仍不确定函数的运行机制,请一边尝试一边了解! ### pandas.DataFrame.shift `DataFrame.``shift`(*periods=1*, *freq=None*, *axis=0*)[[source\]](http://github.com/pandas-dev/pandas/blob/v0.23.1/pandas/core/frame.py#L3800-L3803) Shift index by desired number of periods with an optional time freq | Parameters: | **periods** : int。 Number of periods to move, can be positive or negative。**freq** : DateOffset, timedelta, or time rule string, optionalIncrement to use from the tseries module or time rule (e.g. ‘EOM’). See Notes.**axis** : {0 or ‘index’, 1 or ‘columns’} | | ----------- | ------------------------------------------------------------ | | Returns: | **shifted** : DataFrame | | 参数 | periods: 移动的周期数可以是正数或负数. freq:DateOffset,timedelta或时间规则字符串,要从tseries模块或时间规则使用的optionalIncrement(例如'EOM')。 请参阅Notes.axis:{0或'index',1或'columns'} | | ---- | ------------------------------------------------------------ | | | | ### 实例 ```python entries_and_exits = pd.DataFrame({ 'ENTRIESn': [3144312, 3144335, 3144353, 3144424, 3144594, 3144808, 3144895, 3144905, 3144941, 3145094], 'EXITSn': [1088151, 1088159, 1088177, 1088231, 1088275, 1088317, 1088328, 1088331, 1088420, 1088753] ``` ```python print entries_and_exits.shift(1) ``` ```python ENTRIESn EXITSn 0 NaN NaN #显示为NaN 1 3144312.0 1088151.0 2 3144335.0 1088159.0 3 3144353.0 1088177.0 4 3144424.0 1088231.0 5 3144594.0 1088275.0 6 3144808.0 1088317.0 7 3144895.0 1088328.0 8 3144905.0 1088331.0 9 3144941.0 1088420.0 ``` ```python print entries_and_exits.shift(2) ``` ```python ENTRIESn EXITSn 0 NaN NaN # 1 NaN NaN # 2 3144312.0 1088151.0 3 3144335.0 1088159.0 4 3144353.0 1088177.0 5 3144424.0 1088231.0 6 3144594.0 1088275.0 7 3144808.0 1088317.0 8 3144895.0 1088328.0 9 3144905.0 1088331.0 ``` ### 另一种方法 还有一种方法是通过向量化运算,你还可以使用代码 `return entries_and_exits.diff()` 在单个步骤中计算答案。 ### 实例 ```python import pandas as pd # Examples of vectorized operations on DataFrames: # Change False to True for each block of code to see what it does # Adding DataFrames with the column names if True: df1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) df2 = pd.DataFrame({'a': [10, 20, 30], 'b': [40, 50, 60], 'c': [70, 80, 90]}) print df1 + df2 ``` ```python a b c 0 11 44 77 1 22 55 88 2 33 66 99 ``` 实例 ```python # Adding DataFrames with overlapping column names #列 if True: df1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) df2 = pd.DataFrame({'d': [10, 20, 30], 'c': [40, 50, 60], 'b': [70, 80, 90]}) print df1 + df2 ``` 和第一个运行结果相比 ```python a b c 0 11 44 77 1 22 55 88 2 33 66 99 #第一个实例运行结果 a b c d 0 NaN 74 47 NaN #只加载索引对应的位置,其余的为空值,不保留原值 1 NaN 85 58 NaN 2 NaN 96 69 NaN ``` ```python # Adding DataFrames with overlapping row indexes #行 if True: df1 = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}, index=['row1', 'row2', 'row3']) df2 = pd.DataFrame({'a': [10, 20, 30], 'b': [40, 50, 60], 'c': [70, 80, 90]}, index=['row4', 'row3', 'row2']) #对应的行顺序不一样 print df1 + df2 ``` ```python a b c row1 NaN NaN NaN row2 32.0 65.0 98.0 row3 23.0 56.0 89.0 row4 NaN NaN NaN ``` 指定对应的元素相加,不是两个数组的都有的就会标记为NaN 还有自己定义编写部分未完成。 ```python There was an error running your code: Traceback (most recent call last): File "vm_main.py", line 33, in import main File "/tmp/vmuser_bjdylprdnf/main.py", line 2, in import aiMain File "/tmp/vmuser_bjdylprdnf/aiMain.py", line 129, in correct, comment, feedback = get_feedback() File "/tmp/vmuser_bjdylprdnf/aiMain.py", line 122, in get_feedback test_correct, test_comment = test_case.grade(vectorized_operations) File "/tmp/vmuser_bjdylprdnf/aiMain.py", line 67, in grade student_result = student_lib.get_hourly_entries_and_exits(self.df) File "/tmp/vmuser_bjdylprdnf/vectorized_operations.py", line 44, in get_hourly_entries_and_exits return entries_and_exits.shift(periods=9,freq=1,axis=0) File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 2847, in shift axis=axis) File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 4858, in shift return self.tshift(periods, freq) File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 4951, in tshift new_data.axes[block_axis] = index.shift(periods, freq) File "/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.py", line 1766, in shift type(self).name) NotImplementedError: Not supported for type RangeIndex ```
PHP
UTF-8
2,414
2.671875
3
[]
no_license
<?php namespace App\Telegram\Classes; use Telegram\Bot\Keyboard\Keyboard; use Telegram\Bot\Laravel\Facades\Telegram; class Characters extends TelegramBase { private $inlineKeyboard; private $requestPage; public function __construct($chatId, $requestPage = 1) { parent::__construct($chatId); $this->inlineKeyboard = []; $this->requestPage = $requestPage; } public static function getPageCallbackDataPrefix() { return 'page='; } public static function getQuoteCallbackDataPrefix() { return 'quotes&characterId='; } public function handle() { $requestPage = $this->requestPage; $this->sendChatAction(); $this->get(sprintf('characters?%s&limit=3', self::getPageCallbackDataPrefix() . $requestPage)); $pagination = $this->apiResponse['pagination']; $this->sendMessage("Characters list. Page $requestPage from " . $pagination['totalPages']); foreach ($this->apiResponse['data'] as $i => $character) { $this->addInlineKeyboardBtn(self::getQuoteCallbackDataPrefix() . $character['id'], 'Quotes'); $this->sendMessage(sprintf('%s - %s', $i + 1, $character['name']), $this->generateInlineKeyboard()); $this->inlineKeyboard = []; } if ($pagination['currentPage'] > 1) { $this->addInlineKeyboardBtn(self::getPageCallbackDataPrefix() . ($requestPage - 1), 'prev'); } if ($pagination['currentPage'] != $pagination['totalPages']) { $this->addInlineKeyboardBtn(self::getPageCallbackDataPrefix() . ($requestPage + 1), 'next'); } $this->sendMessage('See more:', $this->generateInlineKeyboard()); } private function addInlineKeyboardBtn(string $callBackData, string $btnText) { array_push( $this->inlineKeyboard, Keyboard::inlineButton([ 'callback_data' => $callBackData, 'text' => $btnText ])); } private function generateInlineKeyboard() { return $this->inlineKeyboard ? Keyboard::make([ 'inline_keyboard' => [ $this->inlineKeyboard ], 'resize_keyboard' => true, 'one_time_keyboard' => false ]) : Telegram::replyKeyboardHide(); } }
JavaScript
UTF-8
1,072
2.53125
3
[]
no_license
import React, { Component} from 'react'; import { connect } from 'react-redux'; import moment from 'moment' import { submitForm } from '../actions'; class Greeting extends Component { render() { const { user } = this.props; if (!user) { return <div className='greeting-box'></div> } const birthday = moment(user.birthday, 'YYYY-MM-DD'); const years = moment().diff(birthday, 'years') + 1; return ( <div className='greeting-box'> <p> {'Hello '} <span className='userName'> {`${user.name.toUpperCase()} ${user.surname.toUpperCase()}`} </span> {` from ${user.country.value}, on ${birthday.format("D of MMMM")} `} {`you will have ${years}!`} </p> </div> ); }; }; function mapStateToProps({ visitors }) { return { user: visitors.currentUser }; } export default connect(mapStateToProps, { submitForm })(Greeting);
Go
UTF-8
447
2.5625
3
[]
no_license
package main import ( "Gin/src/controllerUse/routers" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() //方法一 把匿名函数写到一个文件里变成实名的抽离出去,缺点是无法实现controller的继承 routers.AdminRouters(router) //方法二 把路由中处理业务的个个方法绑定到结构体,这样可以继承,推荐使用! routers.ApiRouters(router) router.Run(":8888") }
Java
UTF-8
1,272
2.203125
2
[]
no_license
/** * Proyecto: IMSS - SSDC * * Archivo: MenuDaoImpl.java * * Creado: Nov 7, 2011 * * Derechos Reservados de copia (c) - INAP / * * Instituto Mexicano del Seguro Social - 2011 */ package mx.gob.imss.cia.ssdc.cdv.integracion.dao.impl; import java.util.ArrayList; import java.util.List; import mx.gob.imss.cia.ssdc.cdv.integracion.dao.MenuDao; import mx.gob.imss.cia.ssdc.cdv.integracion.entity.MenuEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * @author propietario * */ @SuppressWarnings("unchecked") @Repository("menuDao") public class MenuDaoImpl extends AbstractPersistenceDaoGenericHibernate<MenuEntity, Long> implements MenuDao { @Autowired public MenuDaoImpl(HibernateTemplate hibernateTemplate) { super(hibernateTemplate); } @Override @Transactional(readOnly = true) public List<MenuEntity> filtrarMenuPorRol(String tipo) { List<MenuEntity> lista = (ArrayList<MenuEntity>) getHibernateTemplate() .find("from MenuEntity m " + "where m."+tipo+"=1"); return lista; } }
PHP
UTF-8
2,253
3.1875
3
[ "MIT" ]
permissive
<?php /** * CouchRequest * * @author Alexander Thiemann */ class CouchRequest { const COUCH_GET = 'GET'; const COUCH_DELETE = 'DELETE'; const COUCH_POST = 'POST'; const COUCH_PUT = 'PUT'; private $url = ""; private $method = CouchRequest::COUCH_GET; private $data = null; private $headers = array(); /** * Create a CouchRequest * * @throws Exception if invalid method is passed * * @param string $url * @param string $method * @param string $data * @param string $username * @param string $password */ public function __construct($url, $method = CouchRequest::COUCH_GET, $data = null, $username = null, $password = null) { $this->url = $url; $allowed = array(CouchRequest::COUCH_GET, CouchRequest::COUCH_DELETE, CouchRequest::COUCH_POST, CouchRequest::COUCH_PUT); if (!in_array($method, $allowed)) { throw new Exception('Error, invalid HTTP-METHOD: '.$method); } $this->method = $method; $this->data = $data; if (null !== $this->data) { $this->headers['Content-Type'] = 'application/json'; $this->headers['Content-Length'] = strlen($this->data); } if (null !== $username && null != $password) { $this->headers['Authorization'] = 'Basic '.base64_encode($username . ':' . $password); } } /** * Fire the request * * @return CouchResponse */ public function send() { $headers = array(); foreach ($this->headers as $key => $value) { $headers[] = $key.': '.$value; } $curl = curl_init($this->url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->method); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data); curl_setopt($curl, CURLOPT_USERAGENT, 'SimplePHPCouch 1.0'); $body = curl_exec($curl); $info = curl_getinfo($curl); $response = new CouchResponse($info['http_code'], $info['content_type'], $body); curl_close($curl); return $response; } }
C++
UTF-8
3,030
2.9375
3
[ "MIT" ]
permissive
// Given an undirected graph, find all bridges and articulation points // Idea: perform a DFS to form a DFS spanning tree, an edge u-v is a bridge if and only if there is a back edge connecting a descendant of v and an ancestor of u // This is an important to concept in Tarjan's algorithm to find strongly connected components // Time complexity: O(V + E) // There is a great tutorial on Codeforces about this topic: https://codeforces.com/blog/entry/68138 #include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; const int MAX_N = 100000 + 5; const int MAX_L = 20; // ~ Log N const long long MOD = 1e9 + 7; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vi> vvi; #define LSOne(S) (S & (-S)) #define isBitSet(S, i) ((S >> i) & 1) // dfs_num[u] stores the iteration counter when DFS visits node u for the 1st time // dfs_low[u] stores the lowest dfs_num reachable from the current DFS spanning subtree of node u // then dfs_low[u] can only be made smaller if there is a back edge to form a cycle and v is currently visited int V, E, dfsCounter = 0; int dfs_num[MAX_N], dfs_low[MAX_N], visited[MAX_N]; vector<int> adj[MAX_N]; void dfs(int u, int p = -1) { dfs_num[u] = dfs_low[u] = dfsCounter++; visited[u] = 1; int num_child = 0; for (int v : adj[u]) { if (v == p) continue; //ignore the case when a child is connected to its parent if (visited[v]) // back edge dfs_low[u] = min(dfs_low[u], dfs_num[v]); // update else { // tree edge dfs(v, u); dfs_low[u] = min(dfs_low[u], dfs_low[v]); // subtree, always update num_child++; if (dfs_low[v] > dfs_num[u]) // bridge cout << "Edge " << u << "-" << v << " is a bridge\n"; if (dfs_low[v] >= dfs_num[u] && p != -1) // articulation point, the root node need to be treated separately cout << "Node " << u << " is an articulation point\n"; } } if (p == -1 && num_child > 1) // check whether the root node is an articulation point if has more than 1 child cout << "Node " << u << " is an articulation point\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); cin >> V >> E; for (int i = 0; i < E; i++) { int x, y; cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } memset(dfs_low, -1, sizeof dfs_low); memset(dfs_num, -1, sizeof dfs_num); memset(visited, 0, sizeof visited); for (int i = 1; i <= V; i++) if (!visited[i]) dfs(i); } /* Example input: 12 16 1 3 3 5 5 7 3 7 3 8 1 5 1 6 3 6 6 2 2 8 2 4 4 10 1 9 9 11 11 12 9 12 Expected output: Edge 4-10 is a bridge Node 4 is an articulation point Edge 2-4 is a bridge Node 2 is an articulation point Node 9 is an articulation point Edge 1-9 is a bridge Node 1 is an articulation point */
Python
UTF-8
794
3.84375
4
[]
no_license
class FancyPrint: # declare needed ANSI escape sequences for colorful output to console __BLUE = '\033[94m' __RED = '\033[91m' __YELLOW = '\033[93m' __END = '\033[0m' # string "message" will be displayed in the corresponding color # when highlighting a single character, "line_end" can be modified so that no line break is added after the message def text_blue(self, message: str, line_end: str) -> None: print(type(self).__BLUE + message + type(self).__END, end=line_end) def text_red(self, message: str, line_end: str) -> None: print(type(self).__RED + message + type(self).__END, end=line_end) def text_yellow(self, message: str, line_end: str) -> None: print(type(self).__YELLOW + message + type(self).__END, end=line_end)
Python
UTF-8
657
3.9375
4
[]
no_license
# https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dictionaries-hashmaps def twoStrings(s1, s2): """ Determines whether two strings share a common substring. Parameters: s1 (string): s2 (string): Returns: string: "YES" or "NO" if there is a common substring or not. """ return "YES" if set(s1).intersection(set(s2)) else "NO" # return "YES" if set(s1) & set(s2) else "NO" p = int(input()) # Number of test cases. for _ in range(p): s1 = input().strip() s2 = input().strip() print(twoStrings(s1,s2))
Java
UTF-8
480
1.789063
2
[]
no_license
package com.twowaits.password.kuncika.ui.main; import java.util.ArrayList; import androidx.recyclerview.widget.LinearLayoutManager; import dagger.Module; import dagger.Provides; @Module public class MainViewModule { @Provides AppsAdapter provideAppsAdapter() { return new AppsAdapter(new ArrayList<>()); } @Provides LinearLayoutManager provideLinearLayoutManager(MainActivity activity) { return new LinearLayoutManager(activity); } }
Python
UTF-8
136
3.359375
3
[]
no_license
n = int(input()) count = 0 for i in range(0,n): inp = input() inps = inp.split(" ") if inps.count("1") >= 2: count+=1 print(count)
Java
UTF-8
1,091
2.0625
2
[]
no_license
package com.xiguo.www.group.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.*; import org.hibernate.annotations.Table; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import java.io.Serializable; /** * @author ZGC * @date Created in 下午 5:31 2018/8/25 */ @ToString(callSuper = true, exclude = {"product"}) @EqualsAndHashCode(callSuper = true, exclude = {"product"}) @Getter @Setter @Data @Entity @Table(appliesTo = "product_image", comment = "团购商品图片表") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "fieldHandler", "createAt", "updateAt"}) public class ProductImage extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Column(nullable = false, columnDefinition = "varchar(250) COMMENT '图片地址' ") private String url; @ManyToOne(fetch = FetchType.LAZY) @JsonIgnore private Product product; }
Python
UTF-8
11,467
2.78125
3
[]
no_license
import pygame #from pygame import mixer from enum import Enum from player import Player from switch import Switch from collections import OrderedDict import world import graphics from pygame.locals import * pygame.font.init() myfont = pygame.font.SysFont('Times New Roman', 30) pygame.init() pygame.display.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 underswitch = False #pygame.mixer.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Nameless Eldritch") clock = pygame.time.Clock() screen.fill((0, 0, 0)) class GameState: NONE = 0 RUNNING = 1 QUIT = 2 class LevelState: STREET = 0 SEWER = 1 class Game: def __init__(self,screenWindow): self.screen = screenWindow self.status = GameState.NONE self.level = LevelState.STREET self.keyPressed = None self.underswitch = None self.levelcheck = False def start(self): #self.initPlayerModel() self.status = GameState.RUNNING def update(self): screen.fill((0, 0, 0)) self.handleEvents() #self.initPlayerModel() #if player.levelflag == 2: #self.level = LevelState.SEWER #player.levelflag = 0 self.updateMap() #self.updateScreen() if player.is_alive() and not player.victory: self.chooseAction(self.room, player) def handleEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: #self.status = GameState.QUIT pygame.quit() quit() elif event.type == pygame.KEYDOWN: self.keyPressed = None if event.key == pygame.K_ESCAPE: self.status = GameState.QUIT #elif event.key == pygame.K_n: # print('Player chose N') # self.keyPressed = "N" #elif event.key == pygame.K_s: # print('Player chose S') # self.keyPressed = "S" #elif event.key == pygame.K_e: #print('Player chose E') #self.keyPressed = "E" #elif event.key == pygame.K_w: # print('Player chose W') # self.keyPressed = "W" # elif event.key == pygame.K_i: # print('Player chose I') #self.keyPressed = "I" #else: # print('Invalid option chosen') def updateMap(self): if player.is_alive() and not player.victory: self.room = world.tile_at(player.x, player.y, underswitch) #room.modify_player(player) if self.room.x == 1 and self.room.y == 0 : self.room.modify_player(player) print(self.room.intro_text(self.level)) self.room.modify_player(player) #action_input = Game.choose_action(self.room, player) elif not player.is_alive(): print("Through all you hard work, it seems it was all for nought.") game.status = GameState.QUIT def updateScreen(self): screen.fill((255, 0, 255)) textsurface = myfont.render(self.keyPressed, False, (0, 0, 0)) screen.blit(textsurface,(0,0)) def initPlayerModel(self): self.player_model = graphics.Player([0, 5]) self.all_sprites = pygame.sprite.Group() self.all_sprites.add(self.player_model) for entity in self.all_sprites: screen.blit(entity.surf, entity.rect) def under_switch_true(): #global underswitch self.underswitch = True def under_switch_false(): #global underswitch self.underswitch = False #If underswitch is not working, uncomment code def get_available_actions(room, player): actions = OrderedDict() print("Choose an action: ") if player.inventory: Game.action_adder(actions, 'I', player.print_inventory, "Print inventory") if isinstance(room, world.TraderTile): Game.action_adder(actions, 'T', player.trade, "Trade") if isinstance(room, world.EnemyTile1 or world.EnemyTile2 or world.EnemyTile3) and room.enemy.is_alive(): Game.action_adder(actions, 'A', player.attack, "Attack") Game.action_adder(actions, 'R', player.flee, "Run") Game.action_adder(actions, 'H', player.heal, "Heal") elif isinstance(room, world.EnemyTile2) and room.enemy.is_alive(): Game.action_adder(actions, 'A', player.attack, "Attack") Game.action_adder(actions, 'R', player.flee, "Run") Game.action_adder(actions, 'H', player.heal, "Heal") elif isinstance(room, world.EnemyTile3) and room.enemy.is_alive(): Game.action_adder(actions, 'A', player.attack, "Attack") Game.action_adder(actions, 'R', player.flee, "Run") Game.action_adder(actions, 'H', player.heal, "Heal") elif isinstance(room, world.EnemyTile4) and room.enemy.is_alive(): Game.action_adder(actions, 'A', player.attack, "Attack") Game.action_adder(actions, 'R', player.flee, "Run") Game.action_adder(actions, 'H', player.heal, "Heal") else: #if not underswitch: #Game.action_adder(actions, 'U', Game.under_switch_true, "Go to the underworld") #elif underswitch: #Game.action_adder(actions, 'U', Game.under_switch_false, "Go back to the real world") if world.tile_at(room.x, room.y - 1, underswitch): Game.action_adder(actions, 'N', player.move_north, "Go north") if world.tile_at(room.x, room.y + 1, underswitch): Game.action_adder(actions, 'S', player.move_south, "Go south") if world.tile_at(room.x + 1, room.y, underswitch): Game.action_adder(actions, 'E', player.move_east, "Go east") if world.tile_at(room.x - 1, room.y, underswitch): Game.action_adder(actions, 'W', player.move_west, "Go west") if player.health < 100: Game.action_adder(actions, 'H', player.heal, "Heal") if isinstance(room, world.PuzzleTile) and not room.solved(): Game.action_adder(actions, 'P', player.answer_puzzle, "Answer the puzzle" ) if isinstance(room, world.PuzzleTile2) and not room.solved(): Game.action_adder(actions, 'P', player.answer_puzzle, "Answer the puzzle" ) del actions['N'] elif isinstance(room, world.PuzzleTile2) and room.solved(): Game.action_adder(actions, 'N', player.move_north, "Go north") if isinstance(room, world.PuzzleTile3) and not room.solved(): Game.action_adder(actions, 'P', player.answer_puzzle, "Answer the puzzle" ) del actions['N'] elif isinstance(room, world.PuzzleTile3) and room.solved(): Game.action_adder(actions, 'N', player.move_north, "Go north") return actions def action_adder(action_dict, hotkey, action, name, *args): action_dict[hotkey.lower()] = action action_dict[hotkey.upper()] = action print("{}: {}".format(hotkey, name)) def chooseAction(self, room, player): action = None while not action: available_actions = Game.get_available_actions(room, player) action_input = input("Action: ") action_input = action_input.upper() action = available_actions.get(action_input) if action_input == 'N' or action_input == 'E' or action_input == 'S' or action_input == 'W': player.last_action = action_input if action_input == 'A': return action(underswitch) elif action_input == 'P': return action(underswitch) elif action_input == 'T': return action(underswitch) elif action_input == 'R': return action(underswitch) elif action_input != 'A' and action_input in available_actions : #screen.fill((255,0,255)) return action() else: #action_input != available_actions: print("Invalid Action!") game = Game(screen) game.start() world.parse_world_dsl(game.level) #world.parse_world_under_dsl() player = Player() game.updateScreen() #screen.fill((0, 0, 0)) while game.status == GameState.RUNNING: #pygame.mixer.music.load("Audio/Game Audio Files/Zone1/nw-bg1.ogg") #pygame.mixer.music.play(loops=-1) #pygame.mixer.music.set_volume(0.1) if player.levelflag == 2: game.level = LevelState.SEWER player.levelflag = 0 if game.level == LevelState.SEWER and not game.levelcheck: world.world_map = [] world.parse_world_dsl(game.level) player.x = world.start_tile_location[0] player.y = world.start_tile_location[1] #world.parse_world_dsl(game.level) game.levelcheck = True pygame.event.pump() game.update() pygame.display.flip() clock.tick(60) if game.status == GameState.QUIT: pygame.quit() #background = graphics.Street([0, 0]) #zone1 = pygame.sprite.Group() #zone1.add(background) #player_model = graphics.Player() #all_sprites = pygame.sprite.Group() #all_sprites.add(player_model) #def play(): # print("Nameless Eldritch") # pygame.mixer.music.load("Audio/Game Audio Files/Zone1/nw-bg1.ogg") # pygame.mixer.music.play(loops=-1) # pygame.mixer.music.set_volume(0.1) #world.parse_world_dsl() # # player = Player() # # while player.is_alive() and not player.victory: # #for event in pygame.event.get(): # if event.type == KEYDOWN: # if event.key == K_ESCAPE: # quit # elif event.type == QUIT: # quit #screen.fill((0, 0, 0)) # for entity in zone1: # screen.blit(entity.surf, entity.rect) #for entity in all_sprites: # screen.blit(entity.surf, entity.rect) # pygame.display.flip() #clock.tick(30) # room = world.tile_at(player.x, player.y, underswitch) # room.modify_player(player) # print(room.intro_text()) # if player.is_alive() and not player.victory: # action_input = choose_action(room, player) # elif not player.is_alive(): # print("Through all you hard work, it seems it was all for nought.") #action_input = get_player_command() #action_input = action_input.upper() #print(action_input)#Takes any input and converts it to upper case # if action_input in ["I", "A", "H"]: # switch.switcher(action_input, player)# The health in switch is different to player # else: # player.x, player.y = switch.switcher(action_input, player) #if action_input == "N" : #player.move_north() #elif action_input == "S": #player.move_south() #elif action_input == "E": #player.move_east() #elif action_input == "W": # plater.move_west() #else: #print("Invalid Action") #play()
Java
UTF-8
4,120
2.328125
2
[]
no_license
package com.yelp.android.g; public class j<E> implements Cloneable { private static final Object a = new Object(); private boolean b = false; private int[] c; private Object[] d; private int e; public j() { this(10); } public j(int paramInt) { if (paramInt == 0) { c = b.a; } for (d = b.c;; d = new Object[paramInt]) { e = 0; return; paramInt = b.a(paramInt); c = new int[paramInt]; } } private void d() { int m = e; int[] arrayOfInt = c; Object[] arrayOfObject = d; int i = 0; int k; for (int j = 0; i < m; j = k) { Object localObject = arrayOfObject[i]; k = j; if (localObject != a) { if (i != j) { arrayOfInt[j] = arrayOfInt[i]; arrayOfObject[j] = localObject; arrayOfObject[i] = null; } k = j + 1; } i += 1; } b = false; e = j; } public j<E> a() { try { j localj = (j)super.clone(); return localCloneNotSupportedException1; } catch (CloneNotSupportedException localCloneNotSupportedException1) { try { c = ((int[])c.clone()); d = ((Object[])d.clone()); return localj; } catch (CloneNotSupportedException localCloneNotSupportedException2) {} localCloneNotSupportedException1 = localCloneNotSupportedException1; return null; } } public E a(int paramInt) { return (E)a(paramInt, null); } public E a(int paramInt, E paramE) { paramInt = b.a(c, e, paramInt); if ((paramInt < 0) || (d[paramInt] == a)) { return paramE; } return (E)d[paramInt]; } public int b() { if (b) { d(); } return e; } public void b(int paramInt) { paramInt = b.a(c, e, paramInt); if ((paramInt >= 0) && (d[paramInt] != a)) { d[paramInt] = a; b = true; } } public void b(int paramInt, E paramE) { int i = b.a(c, e, paramInt); if (i >= 0) { d[i] = paramE; return; } int j = i ^ 0xFFFFFFFF; if ((j < e) && (d[j] == a)) { c[j] = paramInt; d[j] = paramE; return; } i = j; if (b) { i = j; if (e >= c.length) { d(); i = b.a(c, e, paramInt) ^ 0xFFFFFFFF; } } if (e >= c.length) { j = b.a(e + 1); int[] arrayOfInt = new int[j]; Object[] arrayOfObject = new Object[j]; System.arraycopy(c, 0, arrayOfInt, 0, c.length); System.arraycopy(d, 0, arrayOfObject, 0, d.length); c = arrayOfInt; d = arrayOfObject; } if (e - i != 0) { System.arraycopy(c, i, c, i + 1, e - i); System.arraycopy(d, i, d, i + 1, e - i); } c[i] = paramInt; d[i] = paramE; e += 1; } public void c() { int j = e; Object[] arrayOfObject = d; int i = 0; while (i < j) { arrayOfObject[i] = null; i += 1; } e = 0; b = false; } public void c(int paramInt) { b(paramInt); } public int d(int paramInt) { if (b) { d(); } return c[paramInt]; } public E e(int paramInt) { if (b) { d(); } return (E)d[paramInt]; } public String toString() { if (b() <= 0) { return "{}"; } StringBuilder localStringBuilder = new StringBuilder(e * 28); localStringBuilder.append('{'); int i = 0; if (i < e) { if (i > 0) { localStringBuilder.append(", "); } localStringBuilder.append(d(i)); localStringBuilder.append('='); Object localObject = e(i); if (localObject != this) { localStringBuilder.append(localObject); } for (;;) { i += 1; break; localStringBuilder.append("(this Map)"); } } localStringBuilder.append('}'); return localStringBuilder.toString(); } } /* Location: * Qualified Name: com.yelp.android.g.j * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
Python
UTF-8
7,784
2.84375
3
[]
no_license
# bigraph class # last edit: 7/28 ################CHANGES############ # ##########TODO############## # change variable and method names to be more clear ######################BUGS####################### # ##############CURRENTLY WORKING ON########## # from operator import itemgetter import string from decimal import Decimal class Bigraph: def __init__(self): self._joint1 = {} # list of bigram joint probs for beginning of word: [(char1,char2),prob] self._conditional1 = {} # dict of bigram conditional probs for beginnning of word self._prior = {} self._joint2 = {} # list of bigram joint probs for other positions in word self._conditional2 = {} # dict of bigram conditional probs for other positions in word self._topList = [] # list of top 3 most next most probable letters self._f1name = 'bgramFreq1.txt' self._f2name = 'bgramFreq2.txt' #self._test() self._start() #self._buildGraph(self._f1name, self._conditional1) #self._buildGraph(self._f2name, self._bigrph2) #########-----------no longer used-----------############# self._suggSymbList = [] self._bigrphLst = [ [('w','h'),9.7], [('h','a'),2.4], [('a','t'),0.8], [('h','e'),3.0], [('e','n'),2.7], [('e','r'),0.1], [('r','e'), 11.6], [('h','y'),0.1], [('h','o'),3.4], [('o','w'),2.7], [('y','e'),0.1], [('e','s'),0.5], [('g','o'),2.3], [('o','o'),4.6], [('o','d'),1.4], [('b','a'),1.1], [('a','d'),1.4], [(' ','a'),2.2], [(' ', 'c'),0.4], [(' ','e'),0.03] ] def _test(self): #print "testing" freqs = self._bigrphLst val = 1 freqs = self._addN(freqs,val) #get rid of all zeros self._prior = self._getPrior(freqs) temp = self._normalize(dict(freqs)) freqs = list((key,temp[key]) for key in temp) #flatten out dict to pass to graph self._joint1 = self._buildGraph(freqs) #self._print(self._joint1) for key in self._joint1: #build graph of conditional probs self._conditional1[key] = self._conditionalOn(self._joint1[key]) #print "conditional graph:" self._print(self._conditional1) freqs = self._bigrphLst freqs = self._addN(freqs,val) #get rid of all zeros temp = self._normalize(dict(freqs)) freqs = list((key,temp[key]) for key in temp) #flatten out dict to pass to graph self._joint2 = self._buildGraph(freqs) #self._print(self._joint2) for key in self._joint2: #build graph of conditional probs self._conditional2[key] = self._conditionalOn(self._joint2[key]) self._print(self._conditional2) def _start(self): val = 1 #flatten out distribution freqs = self._readFile(self._f1name) #print lst freqs = self._addN(freqs,val) #get rid of all zeros self._prior = self._getPrior(freqs) #print "prior:" #print self._prior temp = self._normalize(dict(freqs)) freqs = list((key,temp[key]) for key in temp) #flatten out dict to pass to graph self._joint1 = self._buildGraph(freqs) #self._print(self._joint1) for key in self._joint1: #build graph of conditional probs self._conditional1[key] = self._conditionalOn(self._joint1[key]) #self._conditional1.update(self._prior) #print "self._conditional1[" "] :", self._conditional1[" "] #print "conditional1 graph:" #self._print(self._conditional1) #print ## freqs = self._readFile(self._f2name) freqs = self._addN(freqs,val) #get rid of all zeros temp = self._normalize(dict(freqs)) freqs = list((key,temp[key]) for key in temp) #flatten out dict to pass to graph self._joint2 = self._buildGraph(freqs) #self._print(self._joint2) for key in self._joint2: #build graph of conditional probs self._conditional2[key] = self._conditionalOn(self._joint2[key]) #print "conditional2" #self._print(self._conditional2) ################################## hmm ####################### def _getPrior(self,joint): #print joint raw = self._buildGraph(joint) #print "raw:" #self._print(raw) #print ## temp = {} prior = {} for key in raw: temp[key] = sum(raw[key][k] for k in raw[key]) #print "key:", key #print "temp[key]", temp[key] #print ## #print temp #prior[" "] = self._normalize(temp) #print "prior:" #self._print(prior) #print ## #return prior return self._normalize(temp) # returns conditional prob for every val in dict def _conditionalOn(self,joint): #print joint temp = [] tot = sum(joint[key] for key in joint) return self._mult(joint, tot) ################################### hmm helper functions ############ #multiplies mplier to every value in dict def _mult(self, d, mplier): #print "in mult: d:", d #print #### for key in d: #print "val:", d[key] #print "mplier:", mplier d[key] = d[key] * mplier #print "after mult: d:", d #print #### return d # normalize prob graph so that they all sum to one #def normalize(self,flist): def _normalize(self,d): #print "in normalize: d:", #print sum(sum([d[k][key] for key in d[k]]) for k in d) tot = sum(d[key] for key in d) #print "in normalize: tot:", tot return self._mult(d, 1/tot) #adds n to every value in list def _addN(self,d,n): return [(item[0], item[1] + n) for item in d] #################################### graph fxns ##################### # build graph of conditional probs from joint list def _buildGraph(self,lst): #print lst grph = {} for item in lst: #print item[0][0] self._add(grph,item[0][0],item[0][1],item[1]) return grph # read in frequency values from a text file into a list def _readFile(self, flName): #fd = open('bgTst.txt', 'r') fd = open(flName, 'r') #print fd #print fd.readline() lst = [] for line in fd: #print line bits = string.split(line, ',') #print Decimal(bits[2].strip(' ')) + 1 del(bits[-1]) #print "bits:", bits #print #### for i in range(1,len(bits),2): item = [(bits[0], bits[i]), Decimal(bits[i+1]) ] #print item lst.append(item) #print lst return lst def _add(self,bgrph,lett1,lett2,weight): #print weight #item = {weight:lett1,lett2} if lett1 not in bgrph: bgrph[lett1] = {lett2:weight} elif lett2 not in bgrph[lett1]: tmp = bgrph[lett1] tmp[lett2] = weight bgrph[lett1] = tmp def _adjacent(self,lett1, lett2): return lett2 in self._bigrph[lett1] def _get_weight(self,lett1,lett2): if self._adjacent(lett1,lett2): tmp = self._bigrph[lett1] return tmp[lett2] else: return 0 def _print(self,grph): for key in grph: #print key print "--", key, "--" for key2 in grph[key]: print key2, " : ", grph[key][key2] print "###############" print # #################### no longer used ################### # read in frequency values from a text file and build dict with values if False: def _buildGraph(self,fname,grph): fd = open(fname, 'r') for line in fd: bits = string.split(line, ',') del(bits[len(bits)-1]) for i in range(1,len(bits),2): self._add(grph, bits[0], bits[i], Decimal(bits[i+1])) def _setSuggSymbList(self, lastTyped): #print "len of lastTyped:", len(str(lastTyped)) if len(str(lastTyped)) == 1: self._topList = sorted(self._bigrph[lastTyped].items(), key=itemgetter(1), reverse=True) #print "self._topList:", self._topList #print "####################" def _nxtProb(self, lastTyped, lastSuggSymb): #print "lastTyped: ", lastTyped #print "lastSuggSymb:", lastSuggSymb if lastSuggSymb == '': #nuthin suggested yet self._setSuggSymbList(lastTyped) elif self._topList == []: #reached end of list return '' nxtSuggSymb = self._topList[0][0] del self._topList[0] return nxtSuggSymb
Python
UTF-8
2,272
2.546875
3
[]
no_license
"""Socket client implementation.""" import selectors import socket from rcr.exception import CloseConnectionError, ConnectionError from rcr.type import ConnectionEvent from .base_client import BaseClient class SocketClient(BaseClient): """Socket client implementation class.""" def __init__(self, *args, **kwargs): self._selector = selectors.DefaultSelector() super().__init__(*args, **kwargs) def connect(self): """Connect to a port to send requests.""" self._conn = socket.socket(socket.AF_INET, self.protocol.value) try: self._conn.connect((self.host, self.port)) except OSError as e: self.close() raise ConnectionError(str(e)) self._conn.setblocking(False) self._selector.register(self._conn, selectors.EVENT_READ, self.receive) # Event callback. self.event_callback[ConnectionEvent.ON_CONNECT](self._conn) self._mainloop() def _mainloop(self): """Start listening to events and trigger related methods. Note: It blocks the process, so, it should be executed in a seperate thread. """ while not self._shutdown: events = self._selector.select(timeout=0.01) for key, _ in events: key.data(key.fileobj) self.close() def close(self): """Close the connection.""" if self._conn: try: self._selector.unregister(self._conn) self._conn.close() except Exception as e: # TODO: no general exception! raise CloseConnectionError(str(e)) self._selector.close() # Event callback. self.event_callback[ConnectionEvent.ON_DISCONNECT](self._conn) def send(self, message: str): """Send a message.""" self._conn.sendall(message.encode()) def receive(self, sock: socket.socket): """Receive messages.""" data = sock.recv(1024) if not data: return try: message = data.decode().strip() except UnicodeDecodeError: message = str(data) # Event callback. self.event_callback[ConnectionEvent.ON_MESSAGE](sock, message)
Python
UTF-8
1,630
2.546875
3
[ "Apache-2.0" ]
permissive
# coding=utf-8 # Copyright 2022 Google LLC. # # 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. """Helper module for parsing configuration file overrides.""" import ast import base64 import logging from typing import Any, Dict from flask import current_app def get_config_contents(config_override_key: str, config_filename: str) -> Dict[str, Any]: """Translates either an overridden config or local file into a dictionary. Args: config_override_key: The config override key to lookup in the Flask headers. config_filename: The local (container) filename of the config if not overridden. Returns: A Dictionary representation of the config file contents. """ config_override = current_app.config.get( 'DRIVE_CONFIG_OVERRIDES', {}).get(config_override_key, '') if config_override: config = ast.literal_eval( base64.b64decode(config_override).decode('UTF-8').strip('\n').strip( ' ')) logging.info('OVERRIDDEN CONFIG CONTENTS: %s', str(config)) else: config = current_app.config.get('CONFIGS', {}).get(config_filename, {}) return config
Shell
UTF-8
209
2.921875
3
[]
no_license
#!/bin/env bash cd `dirname $0` cat ../network.txt | while read line; do cfg=`bash config_filter.sh $line` sudo bash ../quagga/create_config.sh $cfg \ && echo "create config file ($cfg)" done
JavaScript
UTF-8
4,952
2.578125
3
[]
no_license
import React, { useState } from 'react' import '../../styles/components/ContactForm.scss' function ContactForm(props){ let btnTimeout = null const btnStates = { WAIT: { text: 'Sending message...', class: 'wait' }, DEFAULT: { text: 'Send message', class: 'default' }, SUCCESS: { text: '✔️ Message sent', msg: 'We appreaciate your feedback 🤓', class: 'success' }, ERROR: { text: '❌ Error', msg: 'Couldn\'t send the message 😞 you can try to send the message directly to our mail', class: 'error' } } const [state, setState] = useState({ mail: '', subject: '', msg: '', btn: btnStates.DEFAULT }) const setBtnState = (btnState) => { setState({ ...state, btn: btnState }) if(btnTimeout) clearTimeout(btnTimeout) btnTimeout = setTimeout(() => { if(btnState === btnStates.ERROR || btnState === btnStates.SUCCESS){ setBtnState(btnStates.DEFAULT) } }, 10000); } const sendMail = () => { const {mail, subject, msg} = state setBtnState(btnStates.WAIT) fetch('https://bloonbot.herokuapp.com/mail', { method: 'POST', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ mail, subject, msg }) }) .then(res => { if(!res.ok){ setBtnState(btnStates.ERROR) return } setBtnState(btnStates.SUCCESS) }) .catch(err => { setBtnState(btnStates.ERROR) }); } const handleChange = e => { const target = e.target setState({ ...state, [target.name]: target.value }) } const handleSubmit = e => { e.preventDefault() if(e.target.checkValidity()){ sendMail() } } return ( <section className='contact'> <header> <h1>Contact us</h1> </header> <div className="contactContent"> <form action="" onSubmit={ handleSubmit }> <div className="inputBox"> <label htmlFor="mail">Mail<span className="i4"> - required</span></label> <input type="email" id='mail' name='mail' required onChange={ handleChange } /> </div> <div className="inputBox"> <label htmlFor="subject">Subject</label> <input type="text" id='subject' name='subject' onChange={ handleChange } /> </div> <div className="inputBox"> <label htmlFor="message">Message<span className="i4"> - required</span></label> <textarea id='msg' name='msg' required onChange={ handleChange } /> </div> <button className={'btn ' + state.btn.class} type='submit'>{ state.btn.text }</button> <span className="reply">{state.btn.msg}</span> </form> <div className="container"> <div className='contactAside'> <svg className='icon' width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path d="M24 21h-24v-18h24v18zm-23-16.477v15.477h22v-15.477l-10.999 10-11.001-10zm21.089-.523h-20.176l10.088 9.171 10.088-9.171z"/></svg> <div className="mail content"> Our mail <a href="mailto:dallowwishstudios@gmail.com">dallowwishstudios@gmail.com</a> </div> </div> <div className='contactAside'> <svg className='icon' width="24" height="24" xmlns="http://www.w3.org/2000/svg"><path d="M12 21.593c-5.63-5.539-11-10.297-11-14.402 0-3.791 3.068-5.191 5.281-5.191 1.312 0 4.151.501 5.719 4.457 1.59-3.968 4.464-4.447 5.726-4.447 2.54 0 5.274 1.621 5.274 5.181 0 4.069-5.136 8.625-11 14.402m5.726-20.583c-2.203 0-4.446 1.042-5.726 3.238-1.285-2.206-3.522-3.248-5.719-3.248-3.183 0-6.281 2.187-6.281 6.191 0 4.661 5.571 9.429 12 15.809 6.43-6.38 12-11.148 12-15.809 0-4.011-3.095-6.181-6.274-6.181"/></svg> <div className='content'>If you like BloonBot, consider supporting us on <a href="https://www.patreon.com/dallowwish" target='blank'>Patreon</a> or through PayPal to our mail. We are adding at least one feature for every donate we get!</div> </div> </div> </div> </section> ) } export default ContactForm
Go
UTF-8
1,151
2.59375
3
[ "MIT" ]
permissive
package imports import ( "bytes" "encoding/csv" "fmt" "io" "testing" ) const csvData = ` "Mon, 02 Jan 1993 00:00:00 +0300";+25482;"start";start "Sat, 05 Nov 2016 19:39:58 +0300";-2010;"flat";flat "Sun, 06 Nov 2016 05:39:58 +0300";-19000;"flat";flat "Sun, 06 Nov 2016 05:39:58 +0300";-190;"fee";fee "Mon, 07 Nov 2016 10:52:02 +0300";-30;metro;transport "Mon, 07 Nov 2016 13:52:02 +0300";-35;"lunch";lunch "Mon, 07 Nov 2016 22:32:13 +0300";-102;"fruit";sweet "Mon, 07 Nov 2016 18:52:02 +0300";-30;"coffee";coffee "Mon, 07 Nov 2016 22:33:50 +0300";-51;"chocolate";sweet ` func DataProviderSimpleCSVParser_ReadTransaction() io.Reader { return bytes.NewBuffer([]byte(csvData)) } func TestSimpleCSVParser_ReadTransaction(t *testing.T) { reader := &SimpleCSVParser{ counter: 0, Reader: csv.NewReader(DataProviderSimpleCSVParser_ReadTransaction()), } reader.Reader.FieldsPerRecord = 4 reader.Reader.Comma = ';' reader.Reader.LazyQuotes = true reader.AddIDs = true //reader.Reader.TrimLeadingSpace for { transaction, err := reader.ReadTransaction() if err != nil { fmt.Println(err) break } fmt.Println(transaction) } }
Markdown
UTF-8
21,738
2.96875
3
[ "MIT" ]
permissive
# GridWorlds A package for creating grid world environments for reinforcement learning in Julia. This package is designed to be lightweight and fast. This package is inspired by [gym-minigrid](https://github.com/maximecb/gym-minigrid). In order to cite this package, please refer to the file `CITATION.bib`. Starring the repository on GitHub is also appreciated. For benchmarks, refer to `benchmarks/benchmarks.md`. ## Table of contents: * [Getting Started](#getting-started) * [Notes](#notes) [List of Environments](#list-of-environments) 1. [SingleRoomUndirected](#singleroomundirected) 1. [SingleRoomDirected](#singleroomdirected) 1. [GridRoomsUndirected](#gridroomsundirected) 1. [GridRoomsDirected](#gridroomsdirected) 1. [SequentialRoomsUndirected](#sequentialroomsundirected) 1. [SequentialRoomsDirected](#sequentialroomsdirected) 1. [MazeUndirected](#mazeundirected) 1. [MazeDirected](#mazedirected) 1. [GoToTargetUndirected](#gototargetundirected) 1. [GoToTargetDirected](#gototargetdirected) 1. [DoorKeyUndirected](#doorkeyundirected) 1. [DoorKeyDirected](#doorkeydirected) 1. [CollectGemsUndirected](#collectgemsundirected) 1. [CollectGemsDirected](#collectgemsdirected) 1. [CollectGemsMultiAgentUndirected](#collectgemsmultiagentundirected) 1. [DynamicObstaclesUndirected](#dynamicobstaclesundirected) 1. [DynamicObstaclesDirected](#dynamicobstaclesdirected) 1. [SokobanUndirected](#sokobanundirected) 1. [SokobanDirected](#sokobandirected) 1. [Snake](#snake) 1. [Catcher](#catcher) 1. [TransportUndirected](#transportundirected) 1. [TransportDirected](#transportdirected) ## Getting Started ```julia import GridWorlds as GW # Each environment `Env` lives in its own module `EnvModule` # For example, the `SingleRoomUndirected` environment lives inside the `SingleRoomUndirectedModule` module env = GW.SingleRoomUndirectedModule.SingleRoomUndirected() # reset the environment. All environments are randomized GW.reset!(env) # get names of actions that can be performed in this environment GW.get_action_names(env) # perform actions in the environment GW.act!(env, 1) # move up GW.act!(env, 2) # move down GW.act!(env, 3) # move left GW.act!(env, 4) # move right # play an environment interactively inside the terminal GW.play!(env) # play and record the interaction in a file called recording.txt GW.play!(env, file_name = "recording.txt", frame_start_delimiter = "FRAME_START_DELIMITER") # manually step through the frames in the recording GW.replay(file_name = "recording.txt", frame_start_delimiter = "FRAME_START_DELIMITER") # replay the recording inside the terminal at a given frame rate GW.replay(file_name = "recording.txt", frame_start_delimiter = "FRAME_START_DELIMITER", frame_rate = 2) # use the RLBase API import ReinforcementLearningBase as RLBase # wrap a game instance from this package to create an RLBase compatible environment rlbase_env = GW.RLBaseEnv(env) # perform RLBase operations on the wrapped environment RLBase.reset!(rlbase_env) state = RLBase.state(rlbase_env) action_space = RLBase.action_space(rlbase_env) reward = RLBase.reward(rlbase_env) done = RLBase.is_terminated(rlbase_env) rlbase_env(1) # move up rlbase_env(2) # move down rlbase_env(3) # move left rlbase_env(4) # move right ``` ## Notes ### Reinforcement Learning This package does not intend to reinvent a fully usable reinforcement learning API. Instead, all the games in this package provide the bare minimum of what is needed to for the game logic, which is the ability to reset an environment using `GW.reset!(env)` and to perform actions in the environment using `GW.act!(env, action)`. In order to utilize such a game for reinforcement learning, you would probably be using a higher level reinforcement learning API like the one offered by the `ReinforcementLearning.jl` package (`RLBase` API), for example. As of this writing, all the environments provide a default implementation for the `RLBase` API, which means that you can easily wrap a game from `GridWorlds.jl` and use it directly with the rest of the `ReinforcementLearning.jl` ecosystem. 1. ### States There are a few possible options for representing the state/observation for an environment. You can use the entire tile map. You can also augment that with other environment specific information like the agent's direction, target (in `GoToTargetUndirected`) etc. In several games, you can also use the `GW.get_sub_tile_map!` function to get a partial view of the tile map to be used as the observation. All environemnts provide a default implementation of the `RLBase.state` function. It is recommended that before performing reinforcement learning experiments using an environment, you carefully understand the information contained in the state representation for that environment. 1. ### Actions As of this writing, all actions in all environments are discrete. And so, to keep things simple and consistent, they are represented by elements of `Base.OneTo(NUM_ACTIONS)` (basically integers going from 1 to NUM_ACTIONS). In order to know which action does what, you can call `GW.get_action_names(env)` to get a list of names which gives a better description. For example: ```julia julia> env = GW.SingleRoomUndirectedModule.SingleRoomUndirected(); julia> GW.get_action_names(env) (:MOVE_UP, :MOVE_DOWN, :MOVE_LEFT, :MOVE_RIGHT) ``` The order of elements in this list corresponds to that of the actions. 1. ### Rewards and Termination As mentioned before, in order to use these for reinforcement learning experiments, you would mostly be using a higher level API like `RLBase`, which should already provide a way to get these values. For example, in RLBase, rewards can be accessed using `RLBase.reward(env)` and checking whether an environment has terminated or not can by done by calling `RLBase.is_terminated(env)`. In case you are using some other API and need more direct control, it is better to take a look at the implementation for that environment to access things like reward and check for termination. ### Tile Map Each environment contains a tile map, which is a `BitArray{3}` that encodes information about the presence or absence of objects in the grid world. It is of size `(num_objects, height, width)`. The second and third dimensions correspond to positions along the height and width of the tile map. The first dimension corresponds to the presence or absence of objects at a particular position using a multi-hot encoding along the first dimension. You can get the name and ordering of objects along the first dimension of the tile map by using the following method: ```julia julia> env = GW.SingleRoomUndirectedModule.SingleRoomUndirected(); julia> GW.get_object_names(env) (:AGENT, :WALL, :GOAL) ``` ### Navigation Several environments contain the word `Undirected` or `Directed` within their name. This refers to the navigation style of the agent. `Undirected` means that the agent has no direction associated with it, and navigates around by directly moving up, down, left, or right on the tile map. `Directed` means that the agent has a direction associated with it, and it navigates around by moving forward or backward along its current direction, or it could also turn left or right with respect to its current direction. There are 4 directions - `UP`, `DOWN`, `LEFT`, and `RIGHT`. ### Interactive Playing and Recording All the environments can be played directly inside the REPL. These interactive sessions can also be recorded in plain text files and replayed in the terminal. There are two ways to replay a recording: 1. The default way is to manually step through each recorded frame. This allows you to move through the frames one by one at your own pace using keyboard inputs. 1. The second way is to replay the frames at a given frame rate. This would loop through all the frames once and then (and only then) exit the replay. Here is an example: <img src="https://user-images.githubusercontent.com/32610387/126912986-83c112e4-feb2-4953-a4dc-06f7d67bb023.gif"> ### Programmatic Recording of Agent's Behavior In order to programmatically record the behavior of an agent during an episode, you can simply log the string representation of the environment at each step prefixed with a delimiter. You can also log other arbitrary information if you want, like the total reward so far, for example. You can then use the `GW.replay` functiton to replay the recording inside the terminal. The string representation of an environment can be obtained using `repr(MIME"text/plain"(), env)`. Here is an example: ```julia import GridWorlds as GW import ReinforcementLearningBase as RLBase game = GW.SingleRoomUndirectedModule.SingleRoomUndirected() env = GW.RLBaseEnv(game) total_reward = zero(RLBase.reward(env)) frame_number = 1 str = "" str = str * "FRAME_START_DELIMITER" str = str * "frame_number: $(frame_number)\n" str = str * repr(MIME"text/plain"(), env) str = str * "\ntotal_reward: $(total_reward)" while !RLBase.is_terminated(env) action = rand(RLBase.action_space(env)) env(action) reward = RLBase.reward(env) global total_reward += reward global frame_number += 1 global str = str * "FRAME_START_DELIMITER" global str = str * "frame_number: $(frame_number)\n" global str = str * repr(MIME"text/plain"(), env) global str = str * "\ntotal_reward: $(total_reward)" end write("recording.txt", str) GW.replay(file_name = "recording.txt", frame_start_delimiter = "FRAME_START_DELIMITER") ``` In `ReinforcementLearning.jl`, you can create a [hook](https://juliareinforcementlearning.org/docs/How_to_use_hooks/) for recording the agent's behavior at any point during training. ## List of Environments 1. ### SingleRoomUndirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909935-d6a1d303-9925-4fc9-9a9f-025fc133c64c.png"> <img src="https://user-images.githubusercontent.com/32610387/126909804-b53f43a7-98d0-4d53-874e-d8988494ae53.gif"> 1. ### SingleRoomDirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909946-b0b00a56-c48a-4e17-9aaf-08c054e72f9a.png"> <img src="https://user-images.githubusercontent.com/32610387/126909809-6b6b37ad-3ccb-41c5-b263-5709e6a322db.gif"> 1. ### GridRoomsUndirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909952-765ed7d4-f91c-4d31-8bfa-6f42fea791b7.png"> <img src="https://user-images.githubusercontent.com/32610387/126909820-037aa2fb-e332-46d2-8f6e-cea9a138db82.gif"> 1. ### GridRoomsDirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909955-81c9f724-45bb-40cb-ba91-ab124f27fe20.png"> <img src="https://user-images.githubusercontent.com/32610387/126909822-301db2eb-1bc3-42ce-9fa9-1c305cadb9c3.gif"> 1. ### SequentialRoomsUndirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909957-eaf2340a-f985-4b93-b677-1ad28a9fc671.png"> <img src="https://user-images.githubusercontent.com/32610387/126909834-c88338b7-06d4-4a78-a48a-84774f2450ff.gif"> 1. ### SequentialRoomsDirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909964-6c011d1a-59a9-4083-952a-ba46a016496f.png"> <img src="https://user-images.githubusercontent.com/32610387/126909842-f6007d93-59ba-4c2f-ab84-e77bff09ab71.gif"> 1. ### MazeUndirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909969-9b42380a-b96f-4448-be2c-bfe4c8a4a6ae.png"> <img src="https://user-images.githubusercontent.com/32610387/126909846-c6a86cd3-a80b-4519-a786-0e42beaa34ac.gif"> 1. ### MazeDirected The objective of the agent is to navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126909973-b06a42eb-cf87-40fa-b627-09e08716847f.png"> <img src="https://user-images.githubusercontent.com/32610387/126909852-4f096c83-11b2-406f-a6fe-64d87e6c1e8d.gif"> 1. ### GoToTargetUndirected The objective of the agent is to navigate its way to the desired target. When the agent reaches the desired target, it receives a reward of 1. When the agent reaches the other target, it receives a reward of -1. In either case, the environment terminates upon reaching a target. <img src="https://user-images.githubusercontent.com/32610387/126909978-63bed874-f994-4278-b6ca-06a5f42e85db.png"> <img src="https://user-images.githubusercontent.com/32610387/126909857-1b1159c7-df54-4b29-9c59-2bde48e667de.gif"> 1. ### GoToTargetDirected The objective of the agent is to navigate its way to the desired target. When the agent reaches the desired target, it receives a reward of 1. When the agent reaches the other target, it receives a reward of -1. In either case, the environment terminates upon reaching a target. <img src="https://user-images.githubusercontent.com/32610387/126910005-b226bd16-a5b3-46a4-8ed0-4e60e9b8142f.png"> <img src="https://user-images.githubusercontent.com/32610387/126909863-5d49fb4a-690a-4394-a391-81a5f068210e.gif"> 1. ### DoorKeyUndirected The objective of the agent is to collect the key and navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. Without picking up the key, the agent will not be able to pass through the door that separtes the agent and goal. <img src="https://user-images.githubusercontent.com/32610387/126910012-2c802689-0112-4c2b-8f08-cfa33792bece.png"> <img src="https://user-images.githubusercontent.com/32610387/126909869-4fff6bf7-7f4b-41c2-9710-ab6b76c5d184.gif"> 1. ### DoorKeyDirected The objective of the agent is to collect the key and navigate its way to the goal. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. Without picking up the key, the agent will not be able to pass through the door that separtes the agent and goal. <img src="https://user-images.githubusercontent.com/32610387/126910014-75f94b0a-88c5-462e-b9a8-fe97d537d8e6.png"> <img src="https://user-images.githubusercontent.com/32610387/126909871-c5951db4-6f2e-469e-a5bc-256038892200.gif"> 1. ### CollectGemsUndirected The objective of the agent is to collect all the randomly scattered gems. When the agent collects a gem, it receives a reward of 1. The environment terminates when the agent has collected all the gems. <img src="https://user-images.githubusercontent.com/32610387/126910020-3722de31-4fa4-4013-9e4e-b42e77061a84.png"> <img src="https://user-images.githubusercontent.com/32610387/126909874-15138b3f-25ce-4437-8e7a-eb31844dd228.gif"> 1. ### CollectGemsDirected The objective of the agent is to collect all the randomly scattered gems. When the agent collects a gem, it receives a reward of 1. The environment terminates when the agent has collected all the gems. <img src="https://user-images.githubusercontent.com/32610387/126910021-56c5cf39-4638-456d-ab67-cf442de3f341.png"> <img src="https://user-images.githubusercontent.com/32610387/126909881-d3aeed2e-0487-43c4-be58-ab43001e45c9.gif"> 1. ### CollectGemsMultiAgentUndirected The objective of the agents is to collect all the randomly scattered gems. The agents take turns for performing actions. When an agent collects a gem, the environment gives a reward of 1. The environment terminates when the agents have collected all the gems. <img src="https://user-images.githubusercontent.com/32610387/126910026-fcff97b1-f498-4b23-acfe-ffc393fe851e.png"> <img src="https://user-images.githubusercontent.com/32610387/126909885-fbc10e9c-3247-45ee-a354-946ebc77b513.gif"> 1. ### DynamicObstaclesUndirected The objective of the agent is to navigate its way to the goal while avoiding collision with obstacles. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. If the agent collides with an obstacle, the agent receives a reward of -1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126910030-d93a714d-10b7-4117-887c-773afe78c625.png"> <img src="https://user-images.githubusercontent.com/32610387/126909888-8fa8473f-deb6-4562-9004-419fa8080693.gif"> 1. ### DynamicObstaclesDirected The objective of the agent is to navigate its way to the goal while avoiding collision with obstacles. When the agent reaches the goal, it receives a reward of 1 and the environment terminates. If the agent collides with an obstacle, the agent receives a reward of -1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126910033-ee68bd19-06f3-42eb-8606-1042633bbe9b.png"> <img src="https://user-images.githubusercontent.com/32610387/126909890-9bb101aa-7fc8-4854-a9ad-f87ff81e7f73.gif"> 1. ### SokobanUndirected The agent needs to push the boxes onto the target positions. The levels are taken from https://github.com/deepmind/boxoban-levels. Upon each reset, a level is randomly selected from https://github.com/deepmind/boxoban-levels/blob/master/medium/train/000.txt. The level dataset can be dynamically swapped during runtime in case more levels are needed. One way to achieve this while using `ReinforcementLearning.jl` is with the help of [hooks](https://juliareinforcementlearning.org/docs/How_to_use_hooks/). <img src="https://user-images.githubusercontent.com/32610387/126910035-5746bba6-7692-4ad9-b081-5db34e66f0a5.png"> <img src="https://user-images.githubusercontent.com/32610387/126909897-621ee9eb-69e8-4be2-a5a2-e15929bd9acd.gif"> 1. ### SokobanDirected The agent needs to push the boxes onto the target positions. The levels are taken from https://github.com/deepmind/boxoban-levels. Upon each reset, a level is randomly selected from https://github.com/deepmind/boxoban-levels/blob/master/medium/train/000.txt. The level dataset can be dynamically swapped during runtime in case more levels are needed. One way to achieve this while using `ReinforcementLearning.jl` is with the help of [hooks](https://juliareinforcementlearning.org/docs/How_to_use_hooks/). <img src="https://user-images.githubusercontent.com/32610387/126910036-b8f5754d-abf6-40b7-b40a-495f528b89b2.png"> <img src="https://user-images.githubusercontent.com/32610387/126909900-b932420f-176c-4b95-8fff-db5efdf8fc9f.gif"> 1. ### Snake The objective of the agent is to eat as many food pellets as possible. As soon as the agent eats a food pellet, the length of its body incrases by one and it receives a reward of 1. When the agent tries to move into a wall or into its body, it receives a reward of `- tile_map_height * tile_map_width` and the environment terminates. When the agent collects all the food pellets possible, it receives a reward of `tile_map_height * tile_map_width` + 1 (for the last food pellet it ate). <img src="https://user-images.githubusercontent.com/32610387/126910039-aa960aa8-a1f6-4329-851f-1ebec350a7eb.png"> <img src="https://user-images.githubusercontent.com/32610387/126909904-63160435-d75b-4510-b439-58f3f419d961.gif"> 1. ### Catcher The objective of the agent is to keep catching the falling gems for as long as possible. It receives a reward of 1 when it catches a gem and a new gem gets spawned in the next step. When the agent misses catching a gem, it receives a reward of -1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126910040-e8e55c02-cb74-4089-b2c1-e5666143687e.png"> <img src="https://user-images.githubusercontent.com/32610387/126909911-236987ce-12f2-49c8-9b93-2147e7c9ea01.gif"> 1. ### TransportUndirected The objective of the agent is to pick up the gem and drop it to the target location. When the agent drops the gem at the target location, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126910044-1e4896f3-8fa9-421d-9a5b-ee90f1b68d81.png"> <img src="https://user-images.githubusercontent.com/32610387/126909918-87c80ac8-8015-4d96-a2f7-f775692118ac.gif"> 1. ### TransportDirected The objective of the agent is to pick up the gem and drop it to the target location. When the agent drops the gem at the target location, it receives a reward of 1 and the environment terminates. <img src="https://user-images.githubusercontent.com/32610387/126910050-723e100c-c5c7-4703-8eab-5ab86a15e41f.png"> <img src="https://user-images.githubusercontent.com/32610387/126909921-fdb3c853-4cac-4e6a-b20c-604caf5632e0.gif">
PHP
UTF-8
2,016
2.828125
3
[]
no_license
<?php namespace Ionut\Crud\Form; use Ionut\Crud\Crud; use Ionut\Crud\Utils\OptionsGroup; class Style { protected $defaults = [ 'before' => null, 'after' => null, 'wrap' => null ]; /** * @var Crud */ private $crud; public function __construct(Crud $crud) { $this->crud = $crud; $this->options = new OptionsGroup($crud->options['form.style'], $this->defaults); } public function getBefore($column) { $printable = ''; foreach ($this->options->items as $options) { if ($options['columns'][0] == $column) { if ($options['options']['before']) { $printable .= $this->crud->form->value($options['options']['before']); } if ($options['options']['wrap']) { $printable .= '<div class="'.$options['options']['wrap'].'">'; } } } return $printable; } public function getAfter($column) { $printable = ''; foreach ($this->options as $options) { if ($options['columns'][count($options['columns']) - 1] == $column) { if ($options['options']['after']) { $printable .= $this->crud->form->value($options['options']['after']); } if ($options['options']['wrap']) { $printable .= '</div>'; } } } return $printable; } public function getClass($column) { } public function formatStyles($styles) { $formated = []; foreach ($styles as $columns => $style) { $style += [ 'before' => null, 'after' => null, 'wrap' => null, ]; $columns = array_map('trim', explode(',', $columns)); $formated[] = compact('columns', 'style'); } return $formated; } }
Java
UTF-8
900
2.328125
2
[]
no_license
import java.awt.*; public class ShapeO extends Tetromino { public static final int rotationStep = 0; public static final int rotationStepMax = 0; public static final int[][][] grid2 = {{{1,1,0,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}}}; public static final int startX = 100; public static final int startY = 40; public static final int clear_right = 0; public static final int clear_left = 0; public static final int color = 5; public static final Color display = Color.YELLOW; public ShapeO() { super(rotationStep, rotationStepMax, grid2, startX, startY,color, display, clear_right, clear_left); } }
Shell
UTF-8
665
2.515625
3
[ "MIT" ]
permissive
#!/bin/sh alias c=clear if type hx >/dev/null 2>&1; then alias vim=hx fi if type exa >/dev/null 2>&1; then alias ls="exa --classify --icons --grid" alias ll='exa --classify --icons --long' alias tree="exa --tree --icons" else alias ls='ls -FG' alias ll='ls -lh' fi alias l="ls" alias la="l -a" alias lla="ll -a" alias mycc="cc -std=c99 -Wall -pedantic -Werror" alias m=make alias mc="make clean" alias mr="make run" alias bs="browser-sync start -c bs-config.js" alias youtube-dl=yt-dlp alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome" alias firefox="/Applications/Firefox\ Developer\ Edition.app/Contents/MacOS/firefox"
Python
UTF-8
3,433
2.890625
3
[]
no_license
import cv2 import numpy as np from matplotlib import pyplot as plt import scipy.misc import sys import os from sklearn.cross_validation import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import svm import itertools import operator #user defined import binarizeModule import textDetectionModule import trainingModule import featuresModule ''' first binarize the image ''' imgBlurredThresholded = binarizeModule.binarize(sys.argv[1]) ''' now we identify the text regions in image using MSER To identify word regions first we, dilate the image and then apply MSER. Once we get the word regions, we split them into best fitting rectangles and apply MSER inside it again to get the individual characters. To sort the characters in order of human reading, we first sort the individual words in Y axis and then X axis using a stable sort. Inside each word box, the characters are sorted in order of X axis. The output of this, each character box is then passed to feature extraction and classification algorithm. Features extracted are : 1. Mean x coordinate of character in box 2. Mean y coordinate of character in box 3. Black Islands 4. A n*n grid representing the character box where the grid entry has value 1 even if there is a single character pixel in that portion of grid else 0. This is eventually flattened to a 1-d list. 5. Hu-Moments ''' img = cv2.imread('imageBlurredThresholded.jpg',0) WordRectangleArray = textDetectionModule.getText(img,1,50) #print (len(WordRectangleArray)) img = cv2.resize(img,(0,0),fx=1,fy=1) img = 255-img count=1 ''' get the knn and svm classifiers ''' classifiers = trainingModule.getClassifiers(sys.argv[2]) knn = classifiers[0] svm = classifiers[1] def binarizeStandardize(img): #img = cv2.imread('/home/shinchan/patternrecognition/char/Sample001/'+ip,0) x = np.shape(img)[1] y = np.shape(img)[0] #img = 255-img temp,otsuimg = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) white = 0 black = 0 for i in range(x): for j in range(y): if(otsuimg[j][i]==0): black+=1 else: white+=1 #otsuimg = cv2.cvtColor(otsuimg,cv2.COLOR_GRAY2BGR) #print black,white if black<white: #print("black") otsuimg = 255-otsuimg #make all images white on black #else: # print("white") #otsuimg = 255 -otsuimg return otsuimg KNNWords = [] SVMWords = [] for i in range(len(WordRectangleArray)): count = 1 KNNWord = '' SVMWord = '' for j in range(len(WordRectangleArray[i].characterRectangle)): x = WordRectangleArray[i].characterRectangle[j][0] y = WordRectangleArray[i].characterRectangle[j][1] w = WordRectangleArray[i].characterRectangle[j][2] h = WordRectangleArray[i].characterRectangle[j][3] charBox = img[y:y+h,x:x+w] charBox = binarizeStandardize(charBox) scipy.misc.imsave('sciWord'+str(i+1)+'-'+str(count)+'.png',charBox) charFeatures = featuresModule.getFeatureVector('',charBox) n = len(charFeatures) #print n charFeatures = np.array(charFeatures) #print charFeatures charNames = charFeatures[0] charFeatures = charFeatures[1:n] #print 'sciWord'+str(i+1)+'-'+str(count)+'.png',str(knn.predict(charFeatures)) #print charFeatures KNNWord = KNNWord+ str(knn.predict(charFeatures)[0]) SVMWord = SVMWord + str(svm.predict(charFeatures)[0]) count+=1 KNNWords.append(KNNWord) SVMWords.append(SVMWord) print knn print svm print "KNN", KNNWords print "SVM", SVMWords
Java
UTF-8
1,523
2.15625
2
[]
no_license
package com.cg.ddms.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Pattern; import org.springframework.format.annotation.NumberFormat; @Entity @Table(name="user_datab") public class User { @Id @GeneratedValue private Long userId; private String userName; // @Pattern(regexp = "") // pattern for email validation private String userEmail; // @Pattern(regexp = "hgfhghgh") // your pattern private String userPassword; @NumberFormat private String userContact; private String gender; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserContact() { return userContact; } public void setUserContact(String userContact) { this.userContact = userContact; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
Java
UTF-8
4,895
3.125
3
[]
no_license
import java.util.ArrayList; //import util.Util; public class SupplierManager { // 거래처 관리 클래스 // 거래처 관리 기능 모음 SupplierManager(){ si.add(new SupplierBasicInfo("이천쌀전문","01099342242","서울시 종로구 어디어디","쌀",100)); si.add(new SupplierBasicInfo("단무지공장","01023456789","인천시 남동구 어디","단무지",50)); si.add(new SupplierBasicInfo("양반김","01000000000","서울시 종로구 광장시장","김",20)); } public static ArrayList<SupplierBasicInfo> si = new ArrayList<SupplierBasicInfo>(); public static ArrayList<BuyIngredient> bInfo = new ArrayList<BuyIngredient>(); public static BuyIngredient bi = new BuyIngredient(); // 포스 메인에서 불러와야 하기 때문에 public이어야함. public void printMenu() { // 거래처관리 메뉴 출력. while(true) { System.out.println("[거래처 관리]\n메뉴를 선택해주세요."); System.out.println("1. 거래처 등록\n2. 거래처 삭제\n3. 거래처 수정\n4. 발주 품목 관리\n5. 발주\n6. 거래처 목록\n7. 메인으로 돌아가기"); int choice = Util.sc.nextInt(); Util.sc.nextLine(); switch(choice) { case 1: insertSupplier(); break; case 2: deleteSupplier(); break; case 3: modifySupplier(); break; case 4: manageIngre(); case 5: orderSupplier(); break; case 6: showAllSupplier(); break; case 7: System.out.println("메인으로 돌아갑니다."); return; } } } void insertSupplier() { // 거래처 등록 기능 String name; String phoneNum; String address; String ingName; System.out.println("거래처 이름을 입력하세요."); name = Util.sc.nextLine(); System.out.println("거래처 전화번호를 입력하세요."); phoneNum = Util.sc.nextLine(); System.out.println("거래처 주소를 입력하세요."); address = Util.sc.nextLine(); System.out.println("거래할 품목을 적어주세요."); ingName = Util.sc.nextLine(); si.add(new SupplierBasicInfo(name,phoneNum,address,ingName)); } void deleteSupplier() { System.out.println("삭제할 거래처 이름을 입력하세요."); String name = Util.sc.nextLine(); int idx = searchIndex(name); if(idx>0) { si.remove(idx); System.out.println("삭제를 완료했습니다."); } else { System.out.println("다시 검색해주세요."); } // 거래처 삭제 } void modifySupplier() { // 거래처 수정 System.out.println("수정할 거래처 이름을 입력하세요."); String name = Util.sc.nextLine(); int idx = searchIndex(name); if(idx>0) { si.get(idx).showData(); System.out.println("수정하시겠습니까? 1. 네\n2. 아니오"); int select = Util.sc.nextInt(); switch(select) { case 1: insertSupplier(); System.out.println("수정을 완료했습니다."); case 2: System.out.println("취소하였습니다."); } } } int searchIndex(String keyword) { int idx = -1; for(int i=0;i<si.size();i++) { if(si.get(i).name.equals(keyword)) { idx = i; break; } } return idx; } void showAllSupplier() { // 거래처 현황 출력 System.out.println("현재 거래처 현황입니다."); for(int i=0;i<si.size();i++) { System.out.println("-----------"); si.get(i).showData(); System.out.println("-----------"); } } void manageIngre() { System.out.println("현재 거래하고 있는 품목 현황입니다."); for(int i=0;i<si.size();i++) { si.get(i).printIngredient(); } // orderSupplier(); } void orderSupplier() { System.out.println("발주할 재료의 이름을 입력하세요"); String name = Util.sc.nextLine(); int num = 0; int idx =0; num = Util.sc.nextInt(); for(int i=0;i<IngredientManager.ingredientList.size();i++) { if(IngredientManager.ingredientList.get(i).getName().equals(name)) { idx = i; } } if(idx>0) { // 재료 수량 추가 System.out.println("예상 재고 수량 : "+(int)(IngredientManager.ingredientList.get(idx).getNum()+(num))+"\n주문 하시겠습니까? 1. 네 2. 아니오"); int select = Util.sc.nextInt(); switch(select) { case 1: IngredientManager.ingredientList.get(idx).setNum(IngredientManager.ingredientList.get(idx).getNum()+num); System.out.println("발주를 완료했습니다."); break; case 2: System.out.println("취소했습니다."); break; } } else { System.out.println("재료가 일치하지 않습니다."); } } }
Python
UTF-8
2,645
3.453125
3
[]
no_license
Waldo = 'W' Other = '.' def all_row_exists_waldo(collection): """For all rows in the matrix, Waldo is in some column""" for row in collection: if Waldo not in row: return False return True def all_col_exists_waldo(collection): """For all columns in the matrix, Waldo is in some row""" col_true = 0 if len(collection) == 0: return True for col in range(len(collection[0])): for row in range(len(collection)): if Waldo == collection[row][col]: col_true += 1 break if col_true == len(collection[0]): return True return False def all_row_all_waldo(collection): """For all rows in the matrix, Waldo is in every column""" for row in collection: for col in row: if col != Waldo: return False return True def all_col_all_waldo(collection): """For all the columns in the matrix, Waldo is in every row""" for col in range(len(collection[0])): for row in range(len(collection)): if collection[row][col] != Waldo: return False return True def exists_row_all_waldo(collection): """There is some row in the matrix in which Waldo is in every column""" if (len(collection) > 0) and len(collection[0]) == 0: return True for row in range(len(collection)): row_true = 0 for col in range(len(collection[row])): if collection[row][col] == Waldo: row_true += 1 if row_true == len(collection[0]): return True return False def exists_col_all_waldo(collection): """There is some column in the matrix in which Waldo is in every row""" if len(collection) == 0: return False for col in range(len(collection[0])): col_true = 0 for row in range(len(collection)): if collection[row][col] == Waldo: col_true += 1 if col_true == len(collection): return True return False def exists_row_exists_waldo(collection): """There is some row in the matrix in which Waldo is in some column""" for row in collection: for col in row: if col == Waldo: return True return False def exists_col_exists_waldo(collection): """There is some column in the matrix in which Waldo is in some row""" if len(collection) == 0: return False for col in range(len(collection[0])): for row in range(len(collection)): if collection[row][col] == Waldo: return True return False
Markdown
UTF-8
12,929
2.609375
3
[]
no_license
--- layout: default title: "More alternatives to Google Analytics" permalink: /writings/more-google-analytics-alternatives/ description: "Some heavier replacements for Google Analytics, and a brief look at log-based analytics tools" canonical_url: https://lwn.net/Articles/824294/ --- <h1><a href="{{ page.permalink }}">{{ page.title }}</a></h1> <p class="subtitle">June 2020</p> > [Original article on LWN.net]({{ page.canonical_url }}) <style> DIV.BigQuote { font-style: normal; font-weight: normal; color: darkred; background-color: white; margin-left: 1cm; margin-right: 1cm; } pre { font-size: 90%; word-spacing: 0; } </style> <p>Last week, we <a href="https://lwn.net/Articles/822568/">introduced</a> the privacy concerns with using Google Analytics (GA) and presented two lightweight open-source options: GoatCounter and Plausible. Those tools are useful for site owners who need relatively basic metrics. In this second article, we present several heavier-weight GA replacements for those who need more detailed analytics. We also look at some tools that produce analytics data based on web-server-access logs, GoAccess, in particular.</p> <h4>Matomo</h4> <p>One of the most popular heavyweight offerings is the open core <a href="https://matomo.org/">Matomo</a>. It was formerly called "Piwik" and was created in 2007; LWN <a href="https://lwn.net/Articles/372594/">looked at</a> Piwik way back in 2010. It's a full-featured alternative to Google Analytics, so companies that need the power of GA can transition to it, but still get the privacy and transparency benefits that come from using an open-source and self-hosted option. As an example, web agency Isotropic recently <a href="https://isotropic.co/moving-to-matomo-google-analytics-biggest-competition/">switched</a> to Matomo:</p> <div class="BigQuote"> <p>We chose to do this as we wanted to respect our users privacy, and felt that hosting statistics on our own server was better for both us and them. [...] We needed something that rivaled the functionality of Google Analytics, or was even better than it. The solution needed to offer real-time analytics, geo-location, advertising campaign tracking, heat maps, and be open source.</p> </div> <p>Even though Matomo is the most popular open-source analytics tool and has been around the longest, it's still only used <a href="https://trends.builtwith.com/analytics/Matomo">on 1.4%</a> of the top one million web sites, roughly 2% of GA's market share &mdash; it's hard for even well-known open-source software to compete with the $600-billion gorilla.</p> <img class="photo" src="/images/lwn-matomo.png" alt="[Matomo UI from matomo.org]" title="Matomo UI"> <p>Like GA, Matomo provides a summary dashboard with a few basic numbers and charts, as well as many detailed reports, including location maps, referral information, and so on. Additionally, Matomo has a feature called "<a href="https://matomo.org/docs/content-tracking/">content tracking</a>" that allows automatically tracking users' interactions with the content (clicks and impressions) without writing code, unlike GA, which requires writing JavaScript or installing a third-party plugin. The self-hosted version of Matomo has all of these features, but site owners can also pay for and install various <a href="https://plugins.matomo.org/">plugins</a> such as <a href="https://en.wikipedia.org/wiki/Purchase_funnel">funnel</a> measurement, single-sign-on support, and even a rather invasive <a href="https://plugins.matomo.org/HeatmapSessionRecording">plugin</a> that records full user sessions including mouse movements. </p> <p>Matomo is written in PHP and uses MySQL as its data store; <a href="https://matomo.org/docs/installation/">installation</a> is straightforward by simply copying the files to a web server with PHP and MySQL installed. It's licensed under the GPLv3; it supports self-hosting for free (standalone or as a WordPress plugin), two relatively low-cost cloud options, and enterprise pricing. Matomo seems like a well-run project and has a fairly active <a href="https://forum.matomo.org/">community support forum</a>; it also provides business-level <a href="https://matomo.org/support-plans/">support plans</a> for companies using the self-hosted version.</p> <h4>Open Web Analytics</h4> <p>A similar but less popular tool is <a href="http://www.openwebanalytics.com/">Open Web Analytics (OWA)</a>, which is also written in PHP and licensed under the GPLv2. OWA uses a donation-based development model rather than having monthly pricing options for a hosted service. Of all the open-source tools, OWA is the one that feels most like a clone of Google Analytics; even <a href="http://demo.openwebanalytics.com/owa/index.php?owa_do=base.reportDashboard&owa_siteId=c9b7d12e322c7c360fb8f7c72ffe4c41">its dashboard</a> looks similar to GA's &mdash; so it may be a good option for users who are familiar with GA's interface.</p> <p>OWA is not as feature-rich as Matomo, but still has all the basics: an overview dashboard, web statistics, visitor locations on a map overlay, and referrer tracking. Like Matomo, it comes with a WordPress integration to analyze visitors on those type of sites. It also provides various ways to <a href="https://github.com/Open-Web-Analytics/Open-Web-Analytics/wiki#extending-owa">extend</a> the built-in functionality, including an API, the ability to add new "modules" (plugins), and the ability to hook into various tracking events (e.g. a visitor's first page view or a user's mouse clicks).</p> <p>OWA is maintained by a single developer, Peter Adams, and has had periods of significant inactivity. Recently, development seems to have picked up, with Adams shipping several <a href="https://github.com/Open-Web-Analytics/Open-Web-Analytics/releases">new releases</a> in early 2020. Some of the warnings on recent releases, such as <a href="https://github.com/Open-Web-Analytics/Open-Web-Analytics/releases/tag/1.6.9">those for the 1.6.9 release</a>, may be a bit worrisome, however ("<span>! IMPORTANT: The API endpoint has changed!</span>"). Installation is again straightforward, and just requires copying the PHP files to a web server and having a MySQL database available.</p> <h4>Countly</h4> <p>Another open-core option, <a href="https://count.ly/">Countly</a>, was founded in 2013; it is relatively feature-rich and has many dashboard types. Of the tools we are covering, though, it is the one that feels the most like a "web startup", complete with a polished video on its home page and sleek dashboards in its UI. Countly advertises that it is "<a href="https://count.ly/your-data-your-rules">committed to giving you control of your analytics data</a>".</p> <img class="photo" src="/images/lwn-countly.png" alt="[Countly UI from count.ly]" title="Countly UI"> <p>Countly has a <a href="https://count.ly/pricing">clear distinction</a> between its enterprise edition (relatively expensive, starting at $5000 annually) and its self-hosted community edition, with the latter limited to "basic Countly plugins" and "aggregated data". Countly's core source code is licensed under the GNU AGPL, with the server written using Node.js (JavaScript), and SDKs for Android and iOS written in Java and Objective&nbsp;C.</p> <p>Countly's basic plugins provide typical analytics metrics such as simple statistics and referrers for web and mobile devices, but also some more advanced features like scheduling email-based reports and recording JavaScript and mobile app crashes. However, its enterprise edition brings in a wide range of plugins (made either by Countly or by third-party developers) that provide advanced features such as HTTP performance monitoring, funnels with goals and completion rates, A/B testing, and so on. Overall, Countly's community edition is a reasonably rich offering for companies with mobile apps or that are selling products online, and it provides the option to upgrade to the enterprise version later if more is needed.</p> <h4>Snowplow</h4> <p>A more generalized event-analytics system is <a href="https://snowplowanalytics.com/">Snowplow Analytics</a>, founded in 2012 and marketed as "<span>the enterprise-grade event data collection platform</span>". Snowplow provides the data collection part of the equation, but it is up to the installer to determine how to model and display the data. It is useful for larger companies who want control over how they model sessions or that want to enrich the data with business-specific fields.</p> <p>Setting up an installation of Snowplow is definitely not for the faint of heart; it requires configuring the various components, along with significant Amazon Web Services (AWS) setup; it <a href="https://discourse.snowplowanalytics.com/t/selfhosting-of-snowplow/1109">may be possible</a>, but not easy, to install it outside of AWS. However, there is a comprehensive <a href="https://github.com/snowplow/snowplow/wiki/Setting-up-Snowplow">AWS setup guide</a> on the GitHub wiki (and the company does offer for-pay hosted options). Companies can set it up to insert events into PostgreSQL, AWS's columnar Redshift database, or leave the data in Amazon S3 for further processing. Typically a business-intelligence tool like <a href="https://looker.com/">Looker</a> or <a href="https://chartio.com/">ChartIO</a> is used to view the data, but Snowplow does not prescribe that aspect.</p> <p>Snowplow is a collection of tools written in a number of languages, notably Scala (via Spark) and Ruby. It is available under the Apache&nbsp;2.0 license. Snowplow is used by <a href="https://trends.builtwith.com/analytics/Snowplow">almost 3%</a> of the top 10,000 web sites, so it may be a reasonable option for larger companies that want full control over their data pipeline.</p> <h4>Analytics using web access logs</h4> <p>All of the systems described above use JavaScript-based tracking: the benefit of that approach is that it provides richer information (for example, screen resolution) and doesn't require access to web logs. However, if server-access logs are available, it may be preferable to feed those logs directly into analysis software. There are a number of open-source tools that do this: three tools that have all been around for over 20 years are <a href="https://awstats.sourceforge.io/">AWStats</a>, <a href="https://analog.readthedocs.io/en/latest/">Analog</a>, and <a href="http://www.webalizer.org/">Webalizer</a>. AWStats is written in Perl and is the most full-featured and actively maintained of the bunch; Analog is written in Python and Webalizer is written in C, but neither is actively maintained.</p> <p>A more recent contender is the MIT-licensed <a href="https://goaccess.io/">GoAccess</a>, which was designed first as a terminal-based log analyzer, but also has a nice looking HTML view. GoAccess is written in C with only an <a href="https://invisible-island.net/ncurses/">ncurses</a> dependency, and supports all of the common access-log formats, including those from cloud services such as Amazon S3 and Cloudfront.</p> <img class="photo" src="/images/lwn-goaccess-html.png" alt="[GoAccess UI]" title="GoAccess UI"> <p>GoAccess is definitely the most modern-looking and well-maintained access-log tool, and it generates all of the basic metrics: hit and visitor count by page URL, breakdowns by operating system and browser type, referring sites and URLs, and so on. It also has several metrics that aren't typically included in JavaScript-based tools, for example page-not-found URLs, HTTP status codes, and server response time.</p> <p>GoAccess's default mode outputs a static report, but it also has an option that updates the data in real time: it updates every 200 milliseconds in terminal mode, or every second in HTML mode (using its own little WebSocket server). GoAccess's design seems well thought-out, with options for incremental log parsing (using data structures stored to disk) and support for parsing large log files using fast parsing code and in-memory hash tables.</p> <p>The tool is easy to install on most systems, with pre-built packages for all the major Linux package managers, and a Homebrew version for macOS users. It even works on Windows using Cygwin or through the Linux Subsystem on Windows&nbsp;10.</p> <h4>Wrapping up</h4> <p>All in all, there are several good options for those who need more powerful analytics, or need a system similar to GA, but are open source. For those running e-commerce sites, or in need of features like funnel analysis, Matomo and Countly seem like good choices. Enterprises that need direct control over how their events are stored and modeled should perhaps consider a Snowplow installation. For those who have access to their web logs or just don't want to use JavaScript-based tracking, GoAccess seems like a good choice for web-log analysis in 2020.</p>
C
UTF-8
1,372
3.140625
3
[ "MIT" ]
permissive
#pragma once #include <gsl/gsl_sf_zeta.h> #include <cmath> double real_trigamma_cmplxarg(double x, double y, int m, int l){ //compute the real part of the trigamma function at z = x + iy using //my accelerated series formula //argument should have positive real part (x > 0) //m gives the number of zeta function terms to use //l gives the number of terms to use in the residual series double result = 0; //if x is small, the result will be large and thus, inaccurate. Use the //polygamma shift formula to give a larger value of x for the computation if(x < 1000){ return ((x*x - y*y)/(x*x + y*y)/(x*x + y*y)) + real_trigamma_cmplxarg(x + 1, y, m, l); } else{ double phase, ypow = 1.0, xpow, denom; //compute finite sum of Hurwitz zeta functions for (int i = 1; i < m; ++i){ phase = 2*(i/2) == i ? -1.0 : 1.0; result += phase*(2*i - 1)*ypow*gsl_sf_hzeta(2*i, x); ypow = ypow*y*y; } //compute the infinite sum of residuals phase = 2*(m/2) == m ? 1.0 : -1.0; for (int n = 0; n < l; ++n){ xpow = pow(x + n, 2*m); denom = ((x + n)*(x + n) + y*y)*((x + n)*(x + n) + y*y); result += phase*ypow*((2*m - 1)*y*y + (2*m + 1)*(x + n)*(x + n)) / xpow / denom; } return result; } }
Markdown
UTF-8
2,546
2.546875
3
[]
no_license
{{Station Infobox | Station Name = 行政中心站 | Engname = Xingzhengzhongxin station | Linecolor1 = red | Linecolor2 =#{{西安地铁线路标志色|4}} | Image = XINGZHENGZHONGXIN sta.JPG | Caption = | Location = [[西安市|西安市]][[未央区|未央区]] | Coord = | Type = 地下车站 | Line = 2号线<br>4號線 | Hall = 整体 | Open = 2011年9月16日 | Platform = [[岛式站台|岛式站台]] | Exit = 4(2未开通) | Time First = | Time Last = }} '''行政中心站'''位于[[西安市|西安市]][[未央区|未央区]],是[[西安地铁|西安地铁]][[西安地铁2号线|2号线]]的一个车站。 == 位置 == 这座车站位于[[未央广场|未央广场]]南端,[[凤城八路|凤城八路]]口。 ===结构=== {|cellspacing=0 cellpadding=3 |- |style="border-top:solid 1px gray;border-bottom:solid 1px gray;" valign=top width=70|'''-1F''' |style="border-top:solid 1px gray;border-bottom:solid 1px gray;" valign=top width=100| |style="border-top:solid 1px gray;border-bottom:solid 1px gray;" valign=top width=390|站厅、售票机、客服中心 |- |style="border-bottom:solid 1px gray;" rowspan=4 valign=top|'''-2F''' |←北 |[[西安地铁2号线|2号线]]列车往[[运动公园站|运动公园站]]<small>([[北客站站|北客站]]方向)</small> |- |style="border-right:solid 2px black;border-left:solid 2px black;border-top:solid 2px black;border-bottom:solid 2px black;font-size:smaller;" colspan=2 align=center|[[岛式站台|岛式站台]],开启左侧车门 |- |style="border-bottom:solid 1px gray;"|→南 |style="border-bottom:solid 1px gray;"|[[西安地铁2号线|2号线]]列车往[[凤城五路站|凤城五路站]]<small>([[会展中心站_(西安)|会展中心]]方向)</small> |} == 出口 == 这座车站一共有4个出口,其中B、D出口暂未开通。 == 邻近车站 == {{s-rail-start}} {{s-rail|title=西安地铁}} {{s-line new|system=XAM|line=2|previous=运动公园|next=凤城五路}} {{s-line new|system=XAM|line=4|previous=文景路|next=市中医医院}} {{s-end}} ==参考资料== <references/> {{西安地铁2号线}} {{西安地铁4号线}} [[Category:2011年启用的铁路车站|Category:2011年启用的铁路车站]] [[Category:西安地铁车站|Category:西安地铁车站]] [[Category:未央区|Category:未央区]] [[Category:西安地铁2号线车站|Category:西安地铁2号线车站]] [[Category:西安地铁4号线车站|Category:西安地铁4号线车站]]
Java
UTF-8
1,984
3.125
3
[]
no_license
package LuckyTickets; import java.io.*; /** * Created by chris on 1/13/2016. */ public class Main { public static void main(String[] args) throws IOException { // File file = new File(args[0]); // BufferedReader br = new BufferedReader(new FileReader(file)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; int length; int sum; while ((line = br.readLine()) != null) { length = Integer.parseInt(line); sum = 1; int[] num = new int[length]; for (int i = 0; i < num.length; i++) { if (i != (num.length / 2) - 1) num[i] = 0; else num[i] = 1; } int i = num.length - 1; boolean end = false; while (!end) { if (num[i] < 9) num[i]++; else { int j = i - 1; while (j >= 0) { if (j == 0 && num[j] == 9) { end = true; break; } if (num[j] == 9) num[j] = 0; else { num[j]++; break; } j--; } num[i] = 0; } // int lefthalf = 0; // int righthalf = 0; // for(int a = 0; a < num.length / 2;a++) // { // lefthalf += num[a]; // } // // for(int a = num.length / 2; a < num.length;a++) // { // righthalf += num[a]; // } // // if(righthalf == lefthalf) sum++; } System.out.println(sum); } } }
Markdown
UTF-8
1,032
2.953125
3
[ "MIT" ]
permissive
# Twittbot [![Gem Version](https://badge.fury.io/rb/twittbot.svg)](http://badge.fury.io/rb/twittbot) [![Inline docs](http://inch-ci.org/github/nilsding/twittbot.svg?branch=master)](http://inch-ci.org/github/nilsding/twittbot) Twittbot is the next generation of my old Twitter bot, `twittbot-nd`. ## Installation Installation is just as easy as installing the Rubygem: $ gem install twittbot ## Usage Create a new bot: $ twittbot new bot-name $ cd bot-name Authorize with Twitter: $ twittbot auth Add yourself as a botadmin: $ twittbot add-admin nilsding Add a template, such as for a simple reply bot: $ twittbot generate random-reply `random-reply` is a template that accepts a configuration. You can configure it by editing `./etc/random_reply.yml` with a text editor of your choice. And, if you want to, you can also change its behaviour by editing `./lib/random_reply.rb`. To list available templates, try this: $ twittbot list-templates Finally, run the bot: $ twittbot start
Swift
UTF-8
5,196
2.796875
3
[]
no_license
// // CardCollectionViewDataSource.swift // CardCollectionView // // Created by Kristofer Kline on 7/4/18. // Copyright © 2018 Kristofer Kline. All rights reserved. // import UIKit typealias Object = NSObject // TODO: Add addition state handling of images to retry for failed images. enum CellState: Hashable { case loading case loaded case failed } final class CardCollectionViewDataSource: Object, UICollectionViewDataSource { private let cellBufferCount = 10 private var imageCount = 0 private var loadedStates = [IndexPath: CellState]() private var loadedImages = [IndexPath: UIImage]() private var randomImageURL: URL private let serialQueue: DispatchQueue private let imageQueue: DispatchQueue private let networkQueue: DispatchQueue private var source = [IndexPath: UIImage]() private var cachedIndices = NSOrderedSet() private var indicesToReload = Set<IndexPath>() private var indicesToInsert = Set<IndexPath>() private lazy var session: URLSession = { let configuration = URLSessionConfiguration.default configuration.waitsForConnectivity = true return URLSession(configuration: configuration) }() init(qos: QualityOfService, imageSourceURL: URL) { randomImageURL = imageSourceURL serialQueue = DispatchQueue(label: "Data Source Queue", qos: .userInitiated, attributes: .concurrent) imageQueue = DispatchQueue(label: "Image Builder Queue", target: serialQueue) networkQueue = DispatchQueue(label: "Image Data Queue", target: serialQueue) super.init() } func loadFirstBatch(_ collectionView: UICollectionView) { for i in 0 ..< cellBufferCount { createImage(for: IndexPath(row: i, section: 0), collectionView: collectionView) } } private func preloadImages(_ collectionView: UICollectionView) { // Adding a guard to make sure we're not overloading the network with too many requests. let nextIndexPaths = (0 ..< cellBufferCount).map { IndexPath(row: loadedStates.count + $0, section: 0) } nextIndexPaths.forEach { self.createImage(for: $0, collectionView: collectionView) } collectionView.insertItems(at: nextIndexPaths) } private func createImage(for indexPath: IndexPath, collectionView: UICollectionView) { // Make sure the image hasn't already been loaded. guard !loadedStates.keys.contains(indexPath) else { return } loadedStates[indexPath] = .loading loadData(from: randomImageURL) { [weak self] (data, error) in guard let data = data, error == nil else { return print("Failed to get image data: \(error!.localizedDescription)") } self?.buildImage(from: data, indexPath: indexPath, collectionView: collectionView) } } private func loadData(from imageURL: URL, completion: @escaping (_ imageData: Data?, _ error: Error?) -> Void) { networkQueue.async { [weak self] in self?.session.dataTask(with: imageURL) { (data, response, error) in guard let data = data, error == nil else { return completion(nil, error) } completion(data, nil) }.resume() } } private func buildImage(from data: Data, indexPath: IndexPath, collectionView: UICollectionView) { imageQueue.async { [weak self] in guard let image = UIImage.createCachedThumbnail(with: data) else { return } self?.loadedImages[indexPath] = image self?.loadedStates[indexPath] = .loaded print("Did build image: \(indexPath.row): \(self!.loadedImages.count) images loaded") self?.loadIfVisible(indexPath, in: collectionView) } } private func loadIfVisible(_ indexPath: IndexPath, in collectionView: UICollectionView) { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } guard collectionView.indexPathsForVisibleItems.contains(indexPath) else { return } guard strongSelf.loadedImages.keys.contains(indexPath) else { return } let cell = collectionView.cellForItem(at: indexPath) as! CardCollectionViewCell cell.previewImageView.image = strongSelf.loadedImages[indexPath] } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Preload next batch of images. if (loadedStates.count - indexPath.row) < cellBufferCount { preloadImages(collectionView) } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionViewCell.identifier, for: indexPath) as! CardCollectionViewCell cell.previewImageView.image = loadedImages[indexPath] return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return loadedStates.count } }
Java
UTF-8
288
1.835938
2
[]
no_license
package com.iacsd.project.UserDao; import org.springframework.data.jpa.repository.JpaRepository; import com.iacsd.project.entity.Claim; public interface ClaimInterface extends JpaRepository<Claim, Integer> { Claim getByClaimId(int claimId); Claim getByPolicyNum(int policyNum); }
C#
UTF-8
2,234
2.734375
3
[ "MIT" ]
permissive
using System; namespace log4net.Util.TypeConverters { /// <summary> /// Supports conversion from string to <see cref="T:System.Type" /> type. /// </summary> /// <remarks> /// <para> /// Supports conversion from string to <see cref="T:System.Type" /> type. /// </para> /// </remarks> /// <seealso cref="T:log4net.Util.TypeConverters.ConverterRegistry" /> /// <seealso cref="T:log4net.Util.TypeConverters.IConvertFrom" /> /// <seealso cref="T:log4net.Util.TypeConverters.IConvertTo" /> /// <author>Nicko Cadell</author> internal class TypeConverter : IConvertFrom { /// <summary> /// Can the source type be converted to the type supported by this object /// </summary> /// <param name="sourceType">the type to convert</param> /// <returns>true if the conversion is possible</returns> /// <remarks> /// <para> /// Returns <c>true</c> if the <paramref name="sourceType" /> is /// the <see cref="T:System.String" /> type. /// </para> /// </remarks> public bool CanConvertFrom(Type sourceType) { return (object)sourceType == typeof(string); } /// <summary> /// Overrides the ConvertFrom method of IConvertFrom. /// </summary> /// <param name="source">the object to convert to a Type</param> /// <returns>the Type</returns> /// <remarks> /// <para> /// Uses the <see cref="M:System.Type.GetType(System.String,System.Boolean)" /> method to convert the /// <see cref="T:System.String" /> argument to a <see cref="T:System.Type" />. /// Additional effort is made to locate partially specified types /// by searching the loaded assemblies. /// </para> /// </remarks> /// <exception cref="T:log4net.Util.TypeConverters.ConversionNotSupportedException"> /// The <paramref name="source" /> object cannot be converted to the /// target type. To check for this condition use the <see cref="M:log4net.Util.TypeConverters.TypeConverter.CanConvertFrom(System.Type)" /> /// method. /// </exception> public object ConvertFrom(object source) { string text = source as string; if (text != null) { return SystemInfo.GetTypeFromString(text, throwOnError: true, ignoreCase: true); } throw ConversionNotSupportedException.Create(typeof(Type), source); } } }
C++
UTF-8
1,256
2.515625
3
[ "MIT" ]
permissive
#pragma once #include <cstdint> #include <stdexcept> #include <string> namespace lw { namespace error { class Exception : public std::runtime_error { public: Exception(const std::int64_t code, const std::string& message): std::runtime_error(message), m_error_code(code) {} // ---------------------------------------------------------------------- // std::int64_t error_code(void) const { return m_error_code; } // ---------------------------------------------------------------------- // private: std::int64_t m_error_code; }; // -------------------------------------------------------------------------- // #define LW_DEFINE_EXCEPTION_EX(_Type, _ParentNamespace, _Parent) \ class _Type : public _ParentNamespace::_Parent { \ public: \ using _ParentNamespace::_Parent::_Parent; \ }; #define LW_DEFINE_EXCEPTION(_Type) \ LW_DEFINE_EXCEPTION_EX( _Type, ::lw::error, Exception ) // -------------------------------------------------------------------------- // #define LW_UV_ERROR(_Type, _code) \ _Type(_code, (std::string)uv_err_name(_code) + ": " + uv_strerror(_code)) } }
Python
UTF-8
150
3.21875
3
[]
no_license
acres = float(input("informe o valor de area em acres : " ) ) metros = acres*4048.58 print("o valor de area em metros quadrados (m2) é : ", metros)
Java
UTF-8
500
2.171875
2
[]
no_license
package demo2; /** * @author : jiang * @time : 2018/3/20 18:06 */ public class PersonServiceImpl implements PersonService { @AopTest(desc = "xxxx") @Override public void save(String name) { System.out.println("do save"); } @Override public void update(String name, Integer id) { System.out.println("do update"); } @Override public String getPersonName(Integer id) { System.out.println("do get name"); return "jiang"; } }
C
UTF-8
631
2.984375
3
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <sys/file.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> int main(){ int flag=1; char op1; char op2; char space; int o1,o2,o3; printf("start \n"); while(1){ //prima la fase di read read(0,&op1,1); read(0,&space,1); read(0,&op2,1); fflush(0); if(op1 == '-' && space == '1') exit(2); o1= (op1)-48; o2= (op2)-48; o3=o1+o2; printf("\nprimo numero: %c", op1); printf("\nsecondo numero: %c", op2); printf("\nrusultato: %d \n",o3); read(0,&space,1); //non so ma mi saltavala prima read all'inizio dovevo inserirlo } return 0; }
PHP
UTF-8
2,728
3
3
[ "MIT" ]
permissive
<?php namespace luya\traits; use Yii; /** * Cacheable trait to specific cache for yii components. * * Concret implementation example: * * ``` * $cacheKey = 'foobar'; * * $cache = $this->getHasCache($cacheKey); * * if ($cache === false) { * * // execute code and save cache data into variable * * $this->setHasCache($cacheKey, $cache); // variable $cache has been changed from above * } * * return $cache; * ``` * * @author nadar * @since 1.0.0-beta4 */ trait CacheableTrait { /** * @var boolean If enabled and the cache component is available the menu language containers will be * cached for the time defined in $cacheExpiration. */ public $cacheEnabled = true; /** * @var integer Defined the duration of the caching lifetime in seconds. 3600 = 1 hour, 86400 = 24 hours. */ public $cacheExpiration = 86400; /** * @var null|bollean store the cacheable state */ private $_cachable = null; /** * Check if the current configuration of the application and the property allows a caching of the * language container data. * * @return boolean */ public function isCachable() { if ($this->_cachable === null) { $this->_cachable = ($this->cacheEnabled && Yii::$app->has('cache')) ? true : false; } return $this->_cachable; } /** * Set the cache value if caching is allowed. * * @param string $key The identifier key * @param mix $value The value to store in the cache component. * @return void */ public function setHasCache($key, $value) { if ($this->isCachable()) { Yii::$app->cache->set($key, $value, $this->cacheExpiration); } } /** * Remove a value from the cache if caching is enabled. * * @param string $key The cache identifier */ public function deleteHasCache($key) { if ($this->isCachable()) { Yii::$app->cache->delete($key); } } /** * Get the caching data if caching is allowed and there is any data stored for this key. * * @param string $key The identifiere key * @return mixed|boolean Returns the data, if not found returns false. */ public function getHasCache($key) { if ($this->isCachable()) { $data = Yii::$app->cache->get($key); if ($data) { Yii::info("Cacheable trait key '$key' loaded from cache.", __METHOD__); return $data; } Yii::info("Cacheable trait key '$key' NOT loaded.", __METHOD__); } return false; } }
Java
UTF-8
1,021
2.96875
3
[]
no_license
package batter; import member.member; public class batter extends member{ private int bat; //타수 private int hit; //안타수 private double batAvg; //타율 public batter() { } public batter(int number, String name, int age, double height, int bat, int hit, double batAvg) { super(number, name, age, height); this.bat = bat; this.hit = hit; this.batAvg = batAvg; } public int getBat() { return bat; } @Override public String toString() { return "batter / " + " 번호 : " + getNumber() + " / 이름 : " + getName() + " / 나이 : " + getAge() + " / 키 : " + getHeight() + " / 타수 : " +bat + " / 안타수 : " + hit + " / 타율 : " + batAvg; } public void setBat(int bat) { this.bat = bat; } public int getHit() { return hit; } public void setHit(int hit) { this.hit = hit; } public double getBatAvg() { return batAvg; } public void setBatAvg(double batAvg) { this.batAvg = batAvg; } }
C++
UTF-8
791
3.15625
3
[]
no_license
#include <iostream> #include <string> #include <cstring> using namespace std; int main(){ int a[6]; memset(a,0,sizeof(a)); string str; cin>>str; for(int i = 0; i < str.length(); i++){ if(str[i] == 'P'){ a[0]++; }else if(str[i] == 'A'){ a[1]++; }else if(str[i] == 'T'){ a[2]++; }else if(str[i] == 'e'){ a[3]++; }else if(str[i] == 's'){ a[4]++; }else if(str[i] == 't'){ a[5]++; } } while(a[0] > 0 || a[1] > 0 || a[2] > 0 || a[3] > 0 || a[4] > 0 || a[5] > 0 ){ if(a[0] > 0){ cout<<'P'; a[0]--; } if(a[1] > 0){ cout<<'A'; a[1]--; } if(a[2] > 0){ cout<<'T'; a[2]--; } if(a[3] > 0){ cout<<'e'; a[3]--; } if(a[4] > 0){ cout<<'s'; a[4]--; } if(a[5] > 0){ cout<<'t'; a[5]--; } } return 0; }
Python
UTF-8
1,137
2.984375
3
[]
no_license
#!/usr/bin/python3 import requests import sys import time def make_request(URL): r = requests.get(url = URL) data = r.json() if int(r.headers.get("X-Discogs-Ratelimit-Remaining")) <=0: time.sleep(60) r = requests.get(url = URL) data = r.json() return data if len(sys.argv) != 2: print("bad argument number") exit() URL = "https://api.discogs.com/artists/" data =make_request(URL+sys.argv[1]) bandMembers = data['members'] bands={} if len(bandMembers)>0: for member in bandMembers: data =make_request(member['resource_url']) for band in data['groups']: if not band['id'] in bands: bands.update({band['id']:{"name":band['name'],"members":[]}}) bands[band['id']]['members'].append(member['name']) del bands[int(sys.argv[1])] sortedBands=dict(sorted(bands.items(), key=lambda item: item[1]['name'])) for band in sortedBands.values(): if len(band['members']) > 1: print(band['name'],end=': ') for m in band['members']: print(m, end=" ") print("\n",end="")
Go
UTF-8
1,532
3.046875
3
[ "MIT" ]
permissive
package treemux import ( "context" "net/http" "strconv" ) type Request struct { ctx context.Context *http.Request route string Params Params } func NewRequest(req *http.Request) Request { return Request{ ctx: req.Context(), Request: req, } } func (req Request) Context() context.Context { return req.ctx } func (req Request) WithContext(ctx context.Context) Request { req.ctx = ctx return req } func (req Request) Route() string { return req.route } func (req Request) Param(key string) string { return req.Params.Text(key) } type Param struct { Name string Value string } type Params []Param func (ps Params) Get(name string) (string, bool) { for _, param := range ps { if param.Name == name { return param.Value, true } } return "", false } func (ps Params) Text(name string) string { s, _ := ps.Get(name) return s } func (ps Params) Uint32(name string) (uint32, error) { n, err := strconv.ParseUint(ps.Text(name), 10, 32) return uint32(n), err } func (ps Params) Uint64(name string) (uint64, error) { return strconv.ParseUint(ps.Text(name), 10, 64) } func (ps Params) Int32(name string) (int32, error) { n, err := strconv.ParseInt(ps.Text(name), 10, 32) return int32(n), err } func (ps Params) Int64(name string) (int64, error) { return strconv.ParseInt(ps.Text(name), 10, 64) } func (ps Params) Map() map[string]string { if len(ps) == 0 { return nil } m := make(map[string]string, len(ps)) for _, param := range ps { m[param.Name] = param.Value } return m }
Java
UTF-8
2,224
2.859375
3
[]
no_license
public class Kronometre { private int seconds,minutes,hours; private int days, months, years; public int getSeconds() { return seconds; } public int getMinutes() { return minutes; } public int getHours() { return hours; } public void setSeconds(int seconds) { this.seconds = seconds; } public void setMinutes(int minutes) { this.minutes = minutes; } public void setHours(int hours) { this.hours = hours; } public void daypass() { if(this.months == 1 && this.days == 31) {this.days = 1; this.months = 2; return;} if(this.months == 2 && (this.days == 29 && this.years % 4 == 0 || this.days == 28 && this.years % 4 != 0)) {this.days = 1; this.months = 3;return;} if(this.months == 3 && this.days == 31) {this.days = 1; this.months = 4;return;} if(this.months == 4 && this.days == 30) {this.days = 1; this.months = 5;return;} if(this.months == 5 && this.days == 31) {this.days = 1; this.months = 6;return;} if(this.months == 6 && this.days == 30) {this.days = 1; this.months = 7;return;} if(this.months == 7 && this.days == 31) {this.days = 1; this.months = 8;return;} if(this.months == 8 && this.days == 31) {this.days = 1; this.months = 9;return;} if(this.months == 9 && this.days == 30) {this.days = 1; this.months = 10;return;} if(this.months == 10 && this.days == 31) {this.days = 1; this.months = 11;return;} if(this.months == 11 && this.days == 30) {this.days = 1; this.months = 12;return;} if(this.months == 12 && this.days == 31) {this.days = 1; this.months = 1; this.years++;return;} days++; } public Kronometre() { seconds=0; minutes=0; hours=0; } public void arttir() { minutes++; seconds=0; if(minutes==60) { hours++; minutes=0; } if(hours == 24) { daypass(); hours = 0; } } public int getDays() { return days; } public void setDays(int days) { this.days = days; } public int getMonths() { return months; } public void setMonths(int months) { this.months = months; } public int getYears() { return years; } public void setYears(int years) { this.years = years; } }
C#
UTF-8
2,699
3.671875
4
[]
no_license
using System; using System.Collections; using System.Collections.Generic; namespace hw_2 { class Program { //Builder HW class QuotesBuilder { private string quote; public QuotesBuilder() { this.quote = ""; } public QuotesBuilder start() { this.quote += "“"; return this; } public QuotesBuilder content(string content) { this.quote += content; return this; } public QuotesBuilder end(string name) { this.quote += ".”\n - " + name; return this; } public string get() { return this.quote; } } //Matching HW: //using ({[ and )}] static bool checkOrderBraces(string src) { int flag = 0; foreach (var c in src) { if (c == '(' || c == '{' || c == '[') { flag++; } else if (c == ')' || c == '}' || c == ']') { flag--; } } return flag == 0; } //using numbers static bool checkOrder(string src) { string braces = "0123456789"; Stack<char> stack = new Stack<char>(); for (int i = 0; i < src.Length / 2; i++) { if (braces.Contains(src[i])) { stack.Push(src[i]); } } if (src.Length % 2 == 0) { for (int i = src.Length / 2; i < src.Length; i++) { if (stack.Peek() == src[i]) { stack.Pop(); } } } return stack.Count == 0; } static void Main(string[] args) { //Builder HW QuotesBuilder q = new QuotesBuilder(); Console.WriteLine(q.start() .content("Be yourself; everyone else is already taken") .end("Oscar Wilde") .get()); //Matched HW -> using braces Console.WriteLine(checkOrderBraces("(({{[]}}))")); //Matched HW -> using numbers but only if they mirrored each other Console.WriteLine(checkOrder("23700732")); } } }
Java
UTF-8
1,057
2.03125
2
[]
no_license
package com.zhaw.fit4jobs.payload.request.user; import com.zhaw.fit4jobs.models.user.ECivilStatus; import com.zhaw.fit4jobs.models.user.EGender; import lombok.Data; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.Date; @Data public class UpdateUserDetailsRequest { @NotBlank @Size(max = 10) private String name; @NotBlank @Size(max = 10) private String surname; @NotBlank @Size(max = 30) private String street; @NotBlank @Size(max = 10) private String number; @NotBlank @Size(max = 10) private String postCode; @NotBlank @Size(max = 20) private String city; @NotBlank @Size(max = 20) private String phone; @NotBlank @DateTimeFormat(pattern="dd/MM/yyyy") private Date birthDay; @NotBlank @Size(max = 20) private String mobile; @NotBlank @Size(max = 30) private String nationality; @Size(max = 20) private ECivilStatus civilStatus; @NotBlank @Size(max = 20) private EGender gender; }
Java
UTF-8
801
3.28125
3
[]
no_license
public class Solution_기지국설치 { public static int solution(int n, int[] stations, int w) { int scount = stations.length; int range = 2 * w + 1, half_range = w + 1; int answer = 0; int diff = stations[0] - half_range; if (diff > 0) answer += (diff - 1) / range + 1; for (int i = 1; i < scount; ++i) { diff = stations[i] - stations[i - 1] - range; if (diff > 0) answer += (diff - 1) / range + 1; } diff = (n + 1) - stations[scount - 1] - half_range; if (diff > 0) answer += (diff - 1) / range + 1; return answer; } public static void main(String[] args) { System.out.println(solution(11, new int[] { 4, 11 }, 1)); // 3 System.out.println(solution(16, new int[] { 9 }, 2)); // 3 System.out.println(solution(1, new int[] { 1 }, 1)); // 0 } }
C
UTF-8
605
2.8125
3
[]
no_license
/************************************************************************* > File Name: main.c > Author: chenhui > Mail: ********* > Created Time: 2016年02月22日 14:56:12 ************************************************************************/ #include <stdio.h> #include "stack/stack.h" //extern void push(char); //extern char pop(); //extern int is_empty(); //extern int top;//不是变量定义,不会分配内存空间 int a,b=1; int main() { push('a'); push('v'); push('i'); while(!is_empty()) { putchar(pop()); } putchar('\n'); // printf("%d\n",top); return 0; }