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
Python
UTF-8
839
3.171875
3
[]
no_license
import matplotlib.pyplot as plt import random import CentroidClassification as cc def run(): # filename = input("Enter filename: ") filename = "HandWrittenLetters.txt" class_ids = [1,2,3,4,5,6,7,8,9,10] # class_ids = random.sample(range(1, 27), 10) # class_ids = [x for x in range(11, 21)] print("For class:", class_ids) n = 38 i = 5 x_axis = [] y_axis = [] while i < n: test_instances = [i, n] print("\n############################") print("When train =", i, "and test =", n - i + 1) accuracy = cc.start(filename, class_ids, test_instances) x_axis.append(i) y_axis.append(accuracy) # plt.scatter(i, accuracy, s=80, c="b", marker="x") i += 5 plt.plot(x_axis, y_axis) plt.show() if __name__ == "__main__": run()
Markdown
UTF-8
7,492
2.515625
3
[]
no_license
一二九 “本人业已准备三上沉鱼岛手刃‘五魔’,成功之后我一定请白蕙来与诸位见面,安排各人的去处。” 八女侍虽然还不十分满意,但他们相信季灵芷必能成功,也相信白蕙必然作妥善的处理,于是依依不舍地看着季灵芷相辞而去。 十六只充满期待的明眸,目送对方英俊背影消失于视线之外。 茫茫沧海。 一叶孤帆,在四月的阳光中,蓝天似洗,白浪如银,分外使人心境开郎,油然而生‘乘长风破万里浪”的雄心壮志。 季灵芷凝立船首,怅望天云,心中充满了兴奋与惘然。 他不久就可以与海宫蛟女、白蕙,以及师叔“神通一指”相见,久别重逢自然是值得兴奋喜悦。 可是—— 这次他们将同返故乡“水云村”。 像师叔与母亲的会晤,可能使自己减少许多为难的地方,不过海宫蛟女、白蕙这一对异姓姊妹,与弃尘,黄琼那一对将会发生什么,却令人心烦意乱。 好在婚约方面尚未涉及“弃尘”,总算好一点,可是却另外有个失踪的青姬。 想到青姬,他心中更为杂乱。 自己亲口对“青灵姥姥”遗体所允的承诺,自然应该履行,而且青姬带去了一只“五龙环”,如今不仅想是恩师的纪念,而且是他报仇的主要关键。 他的心情愈想愈乱。 不要说这海阔天空,艳阳普照的环境,无法使他胸境泰然。 就连出现天际一大一小的‘海宫岛’也未曾引起他的注意。 沉思复沉思…… 季灵芷双目注视着船首所劈开的浪花。 水沫飞溅,一似无数颗继碎明珠,旋又落入海中消失得无影无踪。 这条轻快小舟,却似劲箭般破浪而来。 他却眼眸不瞬地凝望着浪花,似已进入催眠状态。 直到小舟距岸不过数里,才被船家一言唤醒:“客官,海宫岛快到啦。” 季灵芷猛然抬头,果见这座充满温馨回忆的岛屿耸立前方。 这时他的心情,突被往日旖旎柔情所充满,倒恨不得此舟能够离水飞逝。 一阵激动之下,季灵芷双臂如翼一振,奇奥的身形疾自船头凌空拔上,几个曼妙至极的回旋,已如飞絮轻烟般,点落数十丈外的波峰之上。 只骇得掌舵船家瞠目结舌,张口无言,他历次送人上岛虽曾见过来去如风的人物,但谁也赶不上这一位的奇妙卓绝。 再说季灵芷连连飞跃,藉着无上轻功,凌波踏浪而行。 转眼功夫便已踏上崖岸。 不由得长嘘了一口清气,以除胸头积愫。 然后,殷切的目光四处打量,却不见半点人影,不由心中颇感惊奇“蛟妹素以大海为生,时常望海上的船只,怎么今日不见她的踪影,难道这有其他的事情不成?” 脚下一飘,便向“双蛟窟”如电纵射。 当他行近这深通海眼的石潭时,更被眼前所见引得疑心大起。 那座曾经消磨一段旖旎风光的火山石窟已经封闭了。 骇然下,飞掠水面纵到窟前,只见山石砌塞洞门,苔痕微绿,显已久无人居。 季灵芷眼珠一转,悄然斜射飘刺,迳往海宫蛟女素日下海的沙滩,周围巡视一遍,不但独木小船不知藏到何处,连一片平坦沙渍上,更无人踪足迹。 禁不住心头一忒,奇快的转身向山下椰林中飘去,立见俊目中寒芒闪烁,穿林搜寻。 越过数十株参天椰林之后,目前展开了一片清幽广阔的空地,当中一栋椰树筑成的屋舍,雅洁非凡,四周的花圃草坪,种着许多不知名的奇花异草。 这座别致的房屋,显然是海宫蛟女等人的新居。 但也是悄无人踪,惟有椰林被海风吹拂得沙沙有声,益显得出奇的沉静。 季灵芷不由心中暗叫奇怪:“蛟妹等三人是武功不俗,师叔与白蕙更是饱有江湖经历机警过人,就算是住在这世外桃源的岛上,也不该没有一点防备。” 心念中,缓步走到门前,轻轻地将门一按。 只听得—— 叮,叮,叮,叮,一阵清脆的铃声响遍全屋,显然是个报警讯号。 季灵芷少年心性,不由得笑意浮起,暗忖道:“蛟妹她们见我突然出现门前,一定惊喜,我干脆躲一下,使她们更感意外。 马上奇快的斜侧身影,向门右一闪,就等对方开门。 哪料他的背脊刚一靠向右门边的墙侧,立感一枚冰冷冷的剑刃,轻点在他的“精足穴”上,部位准确之至。 季灵芷从对方剑尖上的力道已知来者功力不弱,而且既无足音,又没有衣襟带风之声,便即欺到身后,其本领可算绝顶高手。 因此身形不动,生似未曾发觉一般,仍然凝神屏息地注意大门,专等对方的下一个动作。 谁知对方并不受他的愚弄。 轻如落叶的足音一响,另一个人更从他身后捏住剑鞘,似有摘下他腰间长剑的意思。 季灵芷下意识的身躯轻微一动,对方剑尖立刻一紧,使他骇然停住。 他这时料定来敌身手高强,而且最少已有两人到了身后,于是泰然自若地问道:“两位是谁?报上姓名可好——” 话音未完,剑尖上立刻传来一阵轻微的颤震。 随听花圃中五丈开外的地方,有人发话道:“蛟儿、蕙儿,玩笑开得够了,你们怎么可以摘灵儿的宝剑。” 季灵芷又骇又喜,侧头向外一望。 只见师叔“神通一指”拈须微笑,端立花圃中央,然后转头一看背后,可不正是海宫蛟女提着宝剑,白蕙提着他的剑鞘。 二女见他这愕然的神气,忍不住齐声娇笑,拍手顿足地弯腰喘气。 白蕙首先忍住笑声,说道:“灵弟别恼,我们只是闹着玩的。” 他未来得及说话,海宫蛟女也抿嘴问道:“灵哥,你的功力虽是炉火纯青,可想不到我们来得这样快捷吧了” 季灵芷含笑地疑问道:“这倒是大出我的意外,难道-” 海宫蛟女道:“没有什么稀奇,我们自有制敌的妙诀。 可是这第一次却在你的身上试实,倒是意料不到的事情。” “哦,什么妙诀?” 白蕙连忙插嘴道:“天机不可泄漏,而且我们还有更好的在后面。” “这又是什么?”“这与我解剑的动作有关,现在还不能告诉你,但是你可以猜一猜。” 季灵芷心念如电一转,答道:“既与解剑有关,我就猜到了一点头绪。” “我才不信哩,你姑且说出来看对不对。” “想必是另有好剑,所以把旧的解下,另换新的。” 白蕙明眸一闪,讶然说道:“你怎么会猜到这一方面去-” “海宫蛟女却皓婉一摇,抢着说道:“别忙,让我来问问他。” 季灵芷不解地说道:“难道我猜的错了不成广“灵哥,你曾在这岛上很久,一切地方都很熟悉,你可曾在这岛上看到过宝剑,或者是有关的迹象没有?” “这倒没有,而且要是有的话,一定也先被你找出来了。” “那么你怎会猜到宝剑上去呢?” 季灵芷朗爽一笑,道:“这就叫做察言观色,举一反三!”
Shell
UTF-8
1,396
3.90625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash output=$(lpass ls SSH | tail -n +2) #echo "$output" pat='SSH\/(.*?) \[id: (.*?)\]' lpass_ssh_keys=() while read -r line; do [[ "$line" =~ $pat ]] #echo "$line" #echo "${BASH_REMATCH[0]}" # echo "${BASH_REMATCH[1]}" lpass_ssh_keys+=( $(echo "$line" | sed -E 's/^SSH\/(.*) \[.*/\1/') ) #echo "${BASH_REMATCH[2]}" done <<< $output echo -e "\nBelow are the SSH keys stored in Lastpass. Select which one to download \n (you can choose the name when prompted)?" select selected_lpass_key in "${lpass_ssh_keys[@]}"; do [ -n "${selected_lpass_key}" ] && break done echo "You selected: ${selected_lpass_key}...downloading from your lastpass account" keyname="$(lpass ls SSH | sed -n '2 p' | tr -s " " "\012" | head -n 1 | cut -d'/' -f2)" privateKey=$(lpass show "SSH/dxclaptop" --field="Private Key") publicKey=$(lpass show "SSH/dxclaptop" --field="Public Key") echo "Saving as ~/.ssh/${selected_lpass_key} and ~/.ssh/${selected_lpass_key}.pub: Type to override: " read override_keyname; if [[ $override_keyname = *[!\ ]* ]]; then selected_lpass_key=$override_keyname fi echo "Saving as ~/.ssh/${selected_lpass_key} and ~/.ssh/${selected_lpass_key}.pub" read -p "Press enter to continue" echo $privateKey > ~/.ssh/${selected_lpass_key} echo $publicKey > ~/.ssh/${selected_lpass_key}.pub echo "Here are the new keys listed\n" ls -al ~/.ssh/$selected_lpass_key*
Markdown
UTF-8
2,829
3.765625
4
[ "BSD-3-Clause", "CC-BY-3.0" ]
permissive
# PWM [PWM](https://en.wikipedia.org/wiki/Pulse-width_modulation) (Pulse-Width Modulation) is a programmable interface that allows you to, for example, control motor speed or change light brightness. Peripherals that support PWM are controlled by the current strength. To modulate the current, the voltage needs to be modulated. The voltage is proportional to the intensity of the current. To modulate the voltage, you must set the duty cycle and polarity: - The period is a constant interval at which the pulse repeats. - The duty cycle is the constant time within 1 period in which a signal is active. - A "polarity high" signal starts high for the duration of the duty cycle and goes low for the remainder of the period. Conversely, a "polarity low" signal starts low for the duration of the duty cycle and goes high for the remainder of the period. - The pulse repeats if repetition has been enabled. **Figure: Duty cycle** ![Duty cycle](media/peri_api_duty_cycle.png) For example, if the period is 10,000,000 nanoseconds and the polarity high duty cycle is 7,000,000 nanoseconds, the average voltage is at 70%. **Figure: Average voltage per duty cycle** ![Average voltage per duty cycle](media/peri_api_duty_cycle_voltage.png) ## Opening and Closing a Handle To open and close a handle: 1. To open a PWM handle, use the `peripheral_pwm_open()` function: ``` int chip = 0; int pin = 2; peripheral_pwm_h pwm_h; peripheral_pwm_open(chip, pin, &pwm_h); ``` > **Note** > > For more information on the pin names and locations, see [Supported Protocols](peripheral-io-api.md#protocol). 2. To close a PWM handle that is no longer used, use the `peripheral_pwm_close()` function: ``` peripheral_pwm_close(pwm_h); ``` ## Setting the Period To set the period, use the `peripheral_pwm_set_period()` function. The following example sets the period to 20 milliseconds. The unit is nanoseconds. ``` Uint32_t period = 20000000; peripheral_pwm_set_period(pwm_h, period); ``` ## Setting the Duty Cycle To set the duty cycle, use the `peripheral_pwm_set_duty_cycle()` function. The following example sets the duty cycle to 2 milliseconds. The unit is nanoseconds. ``` uint32_t duty_cycle = 2000000; peripheral_pwm_set_duty_cycle(pwm_h, duty_cycle); ``` ## Setting the Polarity To set the polarity, use the `peripheral_gpio_set_polarity()` function with 1 of the following polarity types: - `PERIPHERAL_PWM_POLARITY_ACTIVE_HIGH`: Polarity is high. - `PERIPHERAL_PWM_POLARITY_ACTIVE_LOW`: Polarity is low. ``` peripheral_pwm_set_polarity(pwm_h, PERIPHERAL_PWM_POLARITY_ACTIVE_HIGH); ``` ## Enabling Repetition To enable repetition, use the `peripheral_pwm_set_enabled()` function: ``` bool enable = true; peripheral_pwm_set_enabled(pwm_h, enable); ```
Java
UTF-8
230
1.78125
2
[]
no_license
import com.FrameController; public final class Main { FrameController controller; public Main(){ this.controller = new FrameController(); } public static void main(String[] args) { new Main(); } }
Java
UTF-8
414
3.46875
3
[]
no_license
public class Buble { public static void exch(int[]a, int i, int j) { int temp=a[i]; a[i]=a[j]; a[j]=temp; } public static void sort(int[] a, int size) { for(int i=0; i<size; i++) { for(int j=0; j<size-1-i; j++) { if(a[j]>a[j+1]) exch(a,j,j+1); } } } }
Java
UTF-8
2,179
1.96875
2
[]
no_license
import core.AllureUtils; import core.BrowserFactory; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; import ru.yandex.qatools.allure.Allure; import ru.yandex.qatools.allure.events.TestCaseEvent; import ru.yandex.qatools.allure.model.TestCaseResult; import java.util.List; import java.util.logging.Logger; /** * Created by Dell-SSD on 30.07.2017. */ public class ImaxHW extends BrowserFactory { @Test public void iMax(){ get("https://planetakino.ua/showtimes/"); driver().findElement(By.cssSelector(".filters-block__technology [href*='4dx']")).click(); driver().findElement(By.cssSelector(".filters-block__technology [href*='relux']")).click(); driver().findElement(By.cssSelector(".filters-block__technology [href*='cinetech']")).click(); List<WebElement> times = driver().findElements(By.cssSelector(".p-one-day .t-imax .time ")); WebElement element = times.get(times.size()-1); element.click(); WebDriverWait wait = new WebDriverWait(driver(), 10); WebElement zal = driver().findElement(By.cssSelector(".g-element.hs-image-0000000001")); wait.until(ExpectedConditions.elementToBeClickable(zal)); List<WebElement>freeSeat = driver().findElements(By.cssSelector(".g-element.hs-image-0000000001")); List<WebElement>soldSeat = driver().findElements(By.cssSelector(".g-element.hs-image-0000000005")); double allPlaces = freeSeat.size() + soldSeat.size(); System.out.println(allPlaces); double soldOut = soldSeat.size(); System.out.println(soldSeat.size()); double percentOfSold = (soldSeat.size()/allPlaces)*100; System.out.println(percentOfSold); AllureUtils.fireAllureParameter("AllSeats", String.valueOf((int)allPlaces)); AllureUtils.fireAllureParameter("PercentOfSold",String.valueOf((int)percentOfSold)); Assert.assertTrue(percentOfSold<50,"SOLD OUT BIATCH"); } }
Java
UTF-8
3,595
2.390625
2
[]
no_license
package Client.com.nasri.restjersy.Service; import javax.persistence.EntityManager; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import org.json.JSONException; import org.json.JSONObject; import com.nasri.restjersey.EM; import Client.com.nasri.restjersy.Controller.ClubController; import Client.com.nasri.restjersy.model.Club; import Server.com.nasri.restjersey.controller.BadgeController; import Server.com.nasri.restjersey.model.Badge; @Path("/club") public class ClubService { @GET @Produces("application/json") @Path("/getAll/{id}") public Response getTout(@PathParam("id") int id) throws JSONException { JSONObject jsonObject = new JSONObject(); ClubController cc = new ClubController(); Club[] clubs = cc.getAllClubs(); jsonObject.put("nb", clubs.length); jsonObject.put("users", clubs); String result = "" + jsonObject; return Response.status(200).entity(result).build(); } @POST @Path("/add") public Response addClub(@FormParam("description") String description, @FormParam("image") String image, @FormParam("nom") String nom, @FormParam("slogan") String slogan) { ClubController uc = new ClubController(); Club club = new Club(description, image, nom, slogan); Boolean r = uc.addClub(club); JSONObject jsonObject = new JSONObject(); jsonObject.put("result", r); String result = "" + jsonObject; return getNoCacheResponseBuilder(Response.Status.OK).entity(result).build(); } @POST @Path("/update") @Produces("application/json") public Response updateClub(@FormParam("id") int id, @FormParam("description") String description, @FormParam("image") String image, @FormParam("nom") String nom, @FormParam("slogan") String slogan) { ClubController uc = new ClubController(); EntityManager em = EM.getEntityManager(); Club club=(Club) em.find(Club.class, id); club.setDescription(description); club.setImage(image); club.setNom(nom); club.setSlogan(slogan); Boolean r = uc.updateClub(club); JSONObject jsonObject = new JSONObject(); jsonObject.put("result", r); String result = "" + jsonObject; return getNoCacheResponseBuilder(Response.Status.OK).entity(result).build(); } protected ResponseBuilder getNoCacheResponseBuilder(Response.Status status) { CacheControl cc = new CacheControl(); cc.setNoCache(true); cc.setMaxAge(-1); cc.setMustRevalidate(true); return Response.status(status).cacheControl(cc); } @DELETE @Path("{id}") public Response deleteClub(@PathParam("id") int id) { JSONObject jsonObject = new JSONObject(); ClubController uc = new ClubController(); Boolean r = uc.deleteClub(id); jsonObject.put("result", r); String result = "" + jsonObject; return Response.status(200).entity(result).build(); } @GET @Path("{id}") public Response findClub(@PathParam("id") int id) { JSONObject jsonObject = new JSONObject(); JSONObject json = new JSONObject(); ClubController uc = new ClubController(); Club r = uc.getClub(id); json.put("id", r.getId()); json.put("description", r.getDescription()); json.put("image", r.getImage()); json.put("nom", r.getNom()); json.put("slogan", r.getSlogan()); jsonObject.put("result", json); String result = "" + jsonObject; return Response.status(200).entity(result).build(); } }
C
UTF-8
3,084
2.9375
3
[]
no_license
#include <stdio.h> #include "voice.h" #include "mainfunction.h" static int attitude; static int scndattitude; static int relance; //Presentation : Determine l'attitude de l'user. void presentation(void){ printf("Bienvenue dans le premier logiciel de tchatbot realise par slargo\n"); printf("C'est un honneur pour nous de vous presenter ce premier logiciel, d'une complexite semi importante pour un noob.\n"); printf("Tout d'abord, permettez moi de vous demander comment allez vous ?\n\nBien = 1 Normal = 2 Mal = 3 Osef = 4 ?\n\nVeuillez entrer votre reponse : \n\n"); scanf("%d", &attitude); printf("\nVous avez choisi la reponse : %d\n", attitude); } // Premier brief : Classe l'user dans une categorie void premierbrief(void){ if(attitude == 1){ printf("\nEt bien, ca fait plaisir !\n"); } else if (attitude == 2) printf("\nPas de nouvelle, bonne nouvelle.\n"); else if (attitude == 3) printf("\nMince alors.. que passa amigo ?\n"); else printf("\nSen bas les couilleeees sen bas les couilles senba senba senba les couilles!\n"); } void secondpresentation(void){ if(attitude == 1){ printf("\n Apprenons a nous connaitre. Vous sentez vous a l'aise de continuer ?\n Oui = 1 Non = 2 : "); scanf("%d", &scndattitude); if (scndattitude == 1){ printf("\nC'est parti pour le show.\n"); secondclassement(); } else presentation(); } else if(attitude == 2){ printf("\n Hey bro, peut etre qu'on peut s'amuser. Te sens tu a l'aise pour continuer ?\n Oui = 1 Non = 2 : "); scanf("%d", &scndattitude); if (scndattitude == 1){ printf("\nC'est parti pour le show.\n"); secondclassement(); } else presentation(); } else if(attitude == 3){ printf("\n Bon, je sens que t'as besoin de parler. Est-ce qu'il y a un sujet particulier qui te pose probleme ?\n Oui = 1 Non = 2 : "); scanf("%d", &scndattitude); if (scndattitude == 1){ printf("\nOn va resoudre tout ca \n"); interractions(); } else presentation(); } else{ printf("\n Les c. vont mieux ? Envie de voir un truc marrant ?\n Oui = 1 Non = 2 : "); scanf("%d", &scndattitude); if (scndattitude == 1){ printf("\nC'est parti pour le show... HARDCORE STYLEEEE \n"); troll(); } else presentation(); } } void secondclassement(void){ printf("-------------------Show FINAL-----------."); } void interractions(void){ printf("Soins divins"); } void troll(void){ printf(" VOUS SEREZ CONDAMNE TOUT VOTRE VIE A ECRIRE EN JAVA MOHHAHAHA"); } void findujeu(void){ printf("Envie de rejouer ? Oui = 1 Non = 2 : "); scanf("%d", &relance); if(relance == 1){ presentation(); } else if(relance == 2){ printf("Au revoir ! "); } else{ printf("Well, something go wrong."); } }
Python
UTF-8
3,808
2.640625
3
[]
no_license
# # file and data management methods import ROOT as rt import numpy as np import datetime import calendar import sys import os from array import array class FileSaver(): ''' ''' def __init__(self, filename, treepath, *args): # args: # 0: text plotted # 1: self.filename = filename # self.treepath = treepath # e.g. 'HtBins' def save(self, obj, name): name = self.treepath+'/'+name if isinstance(obj, rt.TCanvas): obj.Update() f = rt.TFile(self.filename, "update") f.cd() def GiveTimestamp(strIn): ''' returns the timestamp of a given string, if the structure of the string is of the form: "... _xyz_timestamp.root" ''' return True def GiveOutputString(strIn): ''' takes the timestamp from the given string to create a string for the matching plot output file. an additional timestamp 144XXXXXX is added. input string hast to be of the form: ../selector_rootFiles/my_selector_results_DY_v1_1447935068.root return: ../plot_rootFiles/2015_48/my_plot_results_v1_1447935068_144XXXXXX.root ''' ss = "../plot_rootFiles/" foldername = GiveYearWeekFoldername() strTemp = strIn.split("_") strPath = ss + foldername + "my_plot_results_" dd = datetime.datetime.utcnow() strTimestamp = str(calendar.timegm(dd.timetuple())) strFormerTitle = strTemp[len(strTemp)-2] strEnd = strTemp[len(strTemp)-1] # 14XXXXXXXXXXX.root strFormerTimestamp = strEnd.split(".")[0] strFile = strFormerTitle + "_" + strFormerTimestamp + "_" + strTimestamp + ".root" if ensure_Dir(ss+foldername): #print "dir ensured" return strPath + strFile else: #print "dir not ensured" return False def inputFileNumberOfLines(): f = "outputfiles.txt" k = 0 with open(f,"r") as s: for line in s: k += 1 return k def inputFile(n=""): ''' returns the last line (default) or given line of the file outputfiles.txt, cleaned by the \n newline sign ''' f = "outputfiles.txt" k = 0 l = False if(n!=""): l = True with open(f,"r") as s: for line in s: k += 1 if(l and k == n): return line.replace("\n","") return line.replace("\n","") def FilelistDatetime(): ''' reads the file outputfiles.txt used by plot_tool.py and writes a list with the filenames and the datetime given from the timestamp, also the file size in byte output: files_date.txt ''' fi = "outputfiles.txt" fo = "files_date.txt" lines = [] with open(fi,"r") as s: for line in s: path = line.replace("\n","") try: fsize = str(os.path.getsize(path)) except os.error: fsize = " n/a " ss = line.split("_") d = int(ss[len(ss)-1].split(".")[0]) #date from filename ds = str(datetime.datetime.fromtimestamp(d)) #datestring lines.append(ds + "\t" + fsize + "\t" + line) with open(fo,"w") as s: for l in lines: s.write(l) return True def GivePlotfolder(): ''' returns the path of the current plot folder (year and week number) example: "../plots/2015_48/" (including the last / ) ''' ss = "../plots/" foldername = GiveYearWeekFoldername() if ensure_Dir(ss+foldername): #print "dir ensured" return ss+foldername else: #print "dir not ensured" return False def GiveYearWeekFoldername(): ''' returns a string constructed by year and week, e.g.: "2015_48/" ''' today = datetime.date.today() y,w,d = today.isocalendar() return str(y)+"_"+str(w)+"/" def GivePlotFilePath(strFile): ''' returns the file ''' path = GivePlotfolder() return path+strFile def Folder(): ''' ''' pass def ensure_Dir(path): ''' checks if a path exists, otherwise create it ''' d = os.path.dirname(path) if not os.path.exists(d): # print "path doesnt exist" os.mkdir(d) return True elif os.path.exists(d): # print "path exists" return True def someTest(): return 0
Shell
UTF-8
8,943
3.328125
3
[]
no_license
#!/bin/bash n=0 function get_disk_num { printf -v num "%03d" $n n=$((n+1)) } function roundup_disk_num { x=$1 n=$((((n+$x-1)/$x)*$x)) } function add_ssd { ssd=$1 title=$2 if [ -z "$title" ] then tmp1=${ssd%.*} title=${tmp1##*/} fi echo " Adding SSD ${ssd} with title ${title}" echo ${ssd} get_disk_num cp ${ssd} ${tmp} beeb title ${tmp} "${title}" beeb dput_ssd -f ${mmb} ${num} ${tmp} rm -f ${tmp} } function get_add_ssd { title=$1 url=$2 file=${url##*/} wget -N -P downloads ${url} add_ssd downloads/${file} ${title} } function get_add_dsd { title=$1 url=$2 file=${url##*/} wget -N -P downloads ${url} beeb split_dsd downloads/${file} ${tmp1} ${tmp2} add_ssd ${tmp1} ${title} add_ssd ${tmp2} ${title} rm -f ${tmp1} rm -f ${tmp2} } function title_ssd { beeb blank_ssd ${tmp} beeb title ${tmp} "$1" get_disk_num beeb dput_ssd -f ${mmb} ${num} ${tmp} rm -f ${tmp} } function add_directory { dir=$1 echo "Adding directory ${dir}" pwd ls for ssd in $(find ${dir} -name '*.ssd' | sort -f) do add_ssd ${ssd} done } function get_git_repo { url=$1 dir=downloads/${url##*/} echo "-------------------------------------" echo $dir echo "-------------------------------------" if [ ! -d ${dir} ] then git clone ${url}.git ${dir} else pushd ${dir} git pull --rebase popd fi } mkdir -p build/downloads cd build # Create a fresh blank MMB file mmb=../TEST.MMB rm -f ${mmb} beeb dblank_mmb -f ${mmb} tmp=tmp.ssd tmp1=tmp1.ssd tmp2=tmp2.ssd # ########################################################################## # Bitshifters # ########################################################################## title_ssd "BITSHIFTERS" # 2015 get_add_ssd NastyEffects https://bitshifters.github.io/content/crtc-somenastyeffects.ssd # 2016 get_add_ssd BeebTracker1 https://bitshifters.github.io/content/bs-beebtrk.ssd get_add_ssd BeebTracker2 https://bitshifters.github.io/content/bs-beebtrk2.ssd get_add_ssd BeebTracker3 https://bitshifters.github.io/content/bs-beebtrk3.ssd # 2017 get_add_dsd TelTxtBadApp https://bitshifters.github.io/content/bs-badappl.dsd get_add_ssd TeleTextR https://bitshifters.github.io/content/bs-teletextr.ssd get_add_ssd NuLAGalVol1 https://bitshifters.github.io/content/bs-bbcnula1.ssd get_add_ssd NuLAGalVol2 https://bitshifters.github.io/content/bs-bbcnula2.ssd # 2018 get_add_ssd PriceOfPersi https://bitshifters.github.io/content/pop-beeb.ssd get_add_ssd TwistedBrain https://bitshifters.github.io/content/bs-twisted.ssd # 2019 get_add_ssd BeebStep https://bitshifters.github.io/content/bs-beebstep.ssd get_add_ssd StuntCarRacr https://bitshifters.github.io/content/bs-scr-beeb.ssd get_add_ssd Patarty https://bitshifters.github.io/content/bs-patarty.ssd get_add_ssd WaveRunner https://bitshifters.github.io/content/bs-wave-runner-v1-1.ssd get_add_ssd XMAS-19 https://bitshifters.github.io/content/bs-xmas-19.ssd # 2020 get_add_dsd BeebNICCC https://bitshifters.github.io/content/bs-beeb-niccc.dsd get_add_ssd NovaInvite https://bitshifters.github.io/content/bs-nova-invite.ssd get_add_ssd EvilInfluenc https://bitshifters.github.io/content/EvilIn11.ssd # 2021 get_add_ssd WobbleColour https://bitshifters.github.io/content/bs-wobble-colours.ssd get_add_ssd BarBeeb https://bitshifters.github.io/content/bs-bar-beeb.ssd # 2022 get_add_ssd MasterMode7 https://bitshifters.github.io/content/mmode7.ssd get_add_ssd AlienDayDre https://bitshifters.github.io/content/alien-daydream.ssd # ########################################################################## # Trickysoft (Richard Broadhurst) # ########################################################################## roundup_disk_num 50 title_ssd "TRICKYSOFT" get_add_ssd Asteroids http://bbcmicro.co.uk/gameimg/discs/3525/Disc156-Asteroids.ssd get_add_ssd AstroBlaster http://bbcmicro.co.uk/gameimg/discs/1964/Disc110-AstroblasterRx2CB.ssd get_add_ssd CanyonBomber http://bbcmicro.co.uk/gameimg/discs/3530/Disc158-CanyonBomber.ssd get_add_ssd Carnival http://bbcmicro.co.uk/gameimg/discs/1912/Disc107-CarnivalSTD.ssd get_add_ssd Centipede http://bbcmicro.co.uk/gameimg/discs/2850/Disc125-CentipedeCBSTD.ssd get_add_ssd Circus http://bbcmicro.co.uk/gameimg/discs/2629/Disc116-CircusJ.ssd get_add_ssd Frogger http://bbcmicro.co.uk/gameimg/discs/1934/Disc108-FroggerRSCB.ssd get_add_ssd MissileCmd https://stardot.org.uk/forums/download/file.php?id=82056 get_add_ssd Pacman http://bbcmicro.co.uk/gameimg/discs/3523/Disc156-TrickysoftPacManCB.ssd get_add_ssd Phoenix http://bbcmicro.co.uk/gameimg/discs/2719/Disc121-Phoenix.ssd get_add_ssd RallyX http://bbcmicro.co.uk/gameimg/discs/3583/Disc159-TrickysoftRallyXCB.ssd get_add_ssd RipCord http://bbcmicro.co.uk/gameimg/discs/2649/Disc117-RipCordJ.ssd get_add_ssd Scramble http://bbcmicro.co.uk/gameimg/discs/2904/Disc128-ScrambleCB.ssd get_add_ssd SpaceInvader http://bbcmicro.co.uk/gameimg/discs/2571/Disc115-SpaceInvaders.ssd get_add_ssd Sprint1 http://bbcmicro.co.uk/gameimg/discs/3027/Disc133-Sprint1J.ssd get_add_ssd SuperBreakou http://bbcmicro.co.uk/gameimg/discs/3535/Disc158-SuperBreakoutJ.ssd # ########################################################################## # Games # ########################################################################## roundup_disk_num 50 title_ssd "GAMES" get_add_ssd Alien8 http://bbcmicro.co.uk/gameimg/discs/217/Disc013-Alien8.ssd get_add_ssd Boffin http://bbcmicro.co.uk/gameimg/discs/274/Disc016-Boffin.ssd get_add_ssd DevilsIsland http://bbcmicro.co.uk/gameimg/discs/2631/Disc116-DevilsIslandSTD.ssd get_add_ssd DrWho1stAdv http://bbcmicro.co.uk/gameimg/discs/980/Disc055-DoctorWhoTheFirstAdventure.ssd get_add_ssd Elite\(86\) http://bbcmicro.co.uk/gameimg/discs/2088/Disc999-EliteMasterAndTubeEnhanced.ssd get_add_ssd Exile http://bbcmicro.co.uk/gameimg/discs/709/Disc040-ExileR.ssd get_add_ssd FireTrack http://bbcmicro.co.uk/gameimg/discs/2468/DiscA06-FireTrackSAM7.ssd get_add_ssd LunarJetman http://bbcmicro.co.uk/gameimg/discs/406/Disc023-LunarJetmanCosmicBattlezones.ssd get_add_ssd PharaohCurse http://bbcmicro.co.uk/gameimg/discs/484/Disc027-PharaohsCurse.ssd get_add_ssd PriceOfPersi https://bitshifters.github.io/content/pop-beeb.ssd get_add_ssd Revs http://bbcmicro.co.uk/gameimg/discs/267/Disc015-Revs.ssd get_add_ssd SnapperV1 http://bbcmicro.co.uk/gameimg/discs/2345/DiscA01-SnapperV1.ssd get_add_ssd StuntCarRacr https://bitshifters.github.io/content/bs-scr-beeb.ssd get_add_dsd Time\&Magic http://bbcmicro.co.uk/gameimg/discs/2343/Disc999-TimeAndMagikTrilogySTD.dsd get_add_ssd Uridium http://bbcmicro.co.uk/gameimg/discs/557/Disc031-UridiumCB.ssd get_add_ssd WhiteLight http://bbcmicro.co.uk/gameimg/discs/2712/Disc999-WhiteLight10DFS.ssd # ########################################################################## # Chris Evan's Test Collection # ########################################################################## get_git_repo https://github.com/scarybeasts/beebjit roundup_disk_num 50 title_ssd "CHRIS EVANS" add_directory downloads/beebjit/test/display # ########################################################################## # Tom Seddon's Test Collection # ########################################################################## get_git_repo https://github.com/tom-seddon/6845-tests roundup_disk_num 50 title_ssd "TOM SEDDON" for ssd in $(find downloads/6845-tests/ssds -name '*.ssd' | sort -f) do title=$(echo ${ssd} | cut -c37- | cut -d. -f1) add_ssd ${ssd} ${title} done beeb dcat -f ${mmb} # ########################################################################## # VideoNula # ########################################################################## dir=downloads/VideoNuLA_pack_Feb2018 if [ ! -d ${dir} ] then wget -N -P downloads "https://www.dropbox.com/s/g3i5fe5napf8rwt/VideoNuLA_pack_Feb2018.zip" mkdir -p ${dir} unzip -d ${dir} downloads/VideoNuLA_pack_Feb2018.zip beeb split_dsd ${dir}/cpc.dsd ${dir}/cpc0.ssd ${dir}/cpc2.ssd fi roundup_disk_num 50 title_ssd "VIDEO NULA" for ssd in $(find ${dir} -name '*.ssd' | sort -f) do title=$(echo ${ssd} | cut -c34- | cut -d. -f1) add_ssd ${ssd} ${title} done add_ssd ../local/nulatest.ssd # ########################################################################## # 6502 Tests # ########################################################################## get_git_repo https://github.com/dp111/6502Timing get_git_repo https://github.com/hoglet67/6502_65C02_functional_tests roundup_disk_num 50 title_ssd "6502 TESTS" add_ssd downloads/6502_65C02_functional_tests/beeb/dormann.ssd add_ssd ../local/BCDTEST.ssd add_directory downloads/6502Timing
Markdown
UTF-8
310
2.515625
3
[ "MIT" ]
permissive
--- title: Goods type position_number: 1 content_markdown: |- List of goods type | Code | Description | | --- | --- | | ABNORMAL | Abnormal | | CONTAINER | Container | | LIQUID_BULK | Liquid bulk cargo | | GENERAL_MERCHANDISE | General Merchandise | | SOLID_BULK | Solid bulk cargo | ---
Python
UTF-8
554
3.90625
4
[]
no_license
print("Hello World") print('O----') print(' |||') print('*' * 10) # variables price = 10 rating = 4.9 my_name = "Nirjhor" is_published = False print(price, rating) # Exercise name = "John Smith" age = 20 is_new = True print(name, age, is_new) # 3rd class y_name = input('what is your name? ') print('Hi '+y_name) # Exercise name_3 = input('What is your name? ') favorite_color = input('What is your favorite color? ') print(name_3 + ' likes ' + favorite_color) # 4th Class birthday_tear = input('Birth Year: ') age = 2019 - birthday_tear print(age)
Markdown
UTF-8
14,257
2.5625
3
[]
no_license
--- layout: default title: "3644.工人阶级必须领导一切" weight: 3644 --- 姚文元1968-8-25 工人阶级必须领导一切 姚文元 1968.08.25 一个伟大的斗、批、改的高潮正在到来。毛主席最新指示的发表,浩浩荡荡的产业工人大军有领导、有步骤地开进学校和其他一切还没有搞好斗、批、改的单位,是这个高潮到来的信号。这个高潮,是经过成立各省、市、自治区革命委员会、大批判、清理阶级队伍等等一系列工作之后出现的,它将在各个领域中引起深刻的变革,猛烈地冲击一切不适应社会主义经济基础的上层建筑,教育广大人民,粉碎暗藏的反动派,引向无产阶级文化大革命的全面胜利,大大促进社会生产力的发展。 放在各级革命委员会当前的重大任务,就是不失时机地认真搞好斗、批、改。完成这个任务,必须坚持工人阶级领导,“充分发挥工人阶级在文化大革命中和一切工作中的领导作用。” 自从十九世纪中期马克思主义开始形成的时候起,就提出用无产阶级专政代替资产阶级专政的口号,到今天已经一百二十年了。只有帝国主义、地主阶级、资产阶级及其代理人新老修正主义者才反对这个彻底革命的口号。中国共产党是以这个口号为其基本纲领的。而要实现这个口号,就要联合工人以外的广大群众,这主要是农民群众、城市小资产阶级群众以及有可能改造的知识分子,并领导他们前进。 无产阶级文化大革命的整个过程,仅仅是在工人阶级这个唯一的阶级领导下进行的。我们的党是无产阶级的先锋队。以毛主席为首、林副主席为副的无产阶级司令部,是工人阶级、贫下中农和广大劳动群众的利益的集中代表者,是全党、全军、全国和广大革命人民唯一的领导中心。毛主席的无产阶级革命路线,毛主席的各项指示,都反映了工人阶级和亿万革命人民的迫切要求,体现了无产阶级对整个无产阶级文化大革命的坚强领导。正是在以毛主席为首的无产阶级司令部领导下,才能发动这样一场亿万革命群众参加的无产阶级文化大革命。坚持工人阶级的领导,首先要保证工人阶级的伟大领袖毛主席的每一个指示,工人阶级的最高战斗指挥部的每一个号令,都能迅速地畅通地贯彻执行。必须反对“多中心即无中心论”、山头主义、宗派主义等种种破坏工人阶级领导的资产阶级反动倾向。各地革命委员会是无产阶级专政的权力机构,各单位都应当接受革命委员会的领导。我们国家中,不允许存在与毛主席的无产阶级司令部相对抗的任何大的或小的“独立王国”。旧北京市委那种抗拒毛主席指示、针插不进、水泼不进的“独立王国”,是中国赫鲁晓夫等一伙大阴谋家对抗工人阶级领导、进行资本主义复辟的手段。这个“独立王国”已被革命的风暴彻底摧毁了。它的阶级斗争的历史教训,应为一切革命者所记取。全国各地那些被资产阶级分子所把持的大大小小的独立王国里的公民们,也应当研究这个教训。 工人宣传队进入教育阵地,这是一件惊天动地的大事。自古以来,学校这个地方,就是为剥削阶级及其子女所垄断。解放以后,好了一些,但基本上还是被资产阶级知识分子所垄断。从这些学校出来的学生,有些人由于各种原因(这些原因大概是:或本人比较好,或教师比较好,或受了家庭、亲戚、朋友的影响,而主要的是受社会的影响)能同工农兵结合,为工农兵服务,有一些人则不能。在无产阶级专政的国家内,存在着资产阶级与无产阶级争夺领导权的严重现象。在这场无产阶级文化大革命中,红卫兵小将奋起造党内一小撮走资派的反,学校中的资产阶级反动势力暂时地遭到了一次沉重的打击。但随后不久,有些人又暗地活动起来,挑动群众斗群众,破坏文化大革命,破坏斗、批、改,破坏大联合和革命的三结合,破坏清理阶级队伍的工作和整党的工作。这种情况引起了广大群众的不满。现实的状况告诉我们:在这种情况下,单靠学生、知识分子不能完成教育战线的斗、批、改、及其他一系列任务,必须有工人、解放军参加,必须有工人阶级的坚强领导。 毛主席最近指出:“实现无产阶级教育革命,必须有工人阶级领导,必须有工人群众参加,配合解放军战士,同学校的学生、教员、工人中决心把无产阶级教育革命进行到底的积极分子实行革命的三结合。工人宣传队要在学校中长期留下去,参加学校中全部斗、批、改任务,并且永远领导学校。在农村,则应由工人阶级的最可靠的同盟者──贫下中农管理学校。” 毛主席这个指示,指出了学校教育革命的方向和道路,是彻底摧毁资产阶级教育制度的锐利的武器。广大青年学生,要热烈欢迎工人阶级占领学校阵地,参加斗、批、改,并且永远领导学校。 工人阶级有阶级斗争、生产斗争、科学实验三大革命运动的丰富的实践经验,工人阶级最仇恨一切反社会主义、反毛泽东思想的反革命言行,最痛恨为剥削阶级服务的旧教育制度,最反对某些知识分子破坏国家财产、阻碍斗、批、改的“打内战”行动,最讨厌言行不一的空谈习气和两面派作风。所以,工人阶级群众同无产阶级专政的主要支柱──中国人民解放军的战士相结合,能够最有力地制止一切违反毛主席革命路线的错误倾向,最有效地解决种种所谓“老大难”的问题。知识分子纠缠不休不能解决的矛盾,工人们一到,很快就解决了。隐藏在幕后挑动群众斗群众的一小撮坏人,只有在工人、解放军的参预下,才能把他们的反革命面貌彻底揭发出来。 “工人只要管工厂就够了。”这是反马克思主义的观点。工人阶级懂得:只有解放全人类,才能最后解放自己。不把学校中的无产阶级教育革命搞彻底,不挖掉修正主义根子,工人阶级就不能最后得到解放,就有资本主义复辟的危险,就有重新被剥削被压迫的危险。积极参加各个领域的文化大革命,用毛泽东思想占领一切文化教育阵地,是有觉悟的工人阶级应当肩负的责任。 “我们要自己解放自己,不需要校外的工人参加。”《十六条》说的是“群众自己解放自己”。难道工人不算“群众”?难道工人阶级不算“自己”?一切真正的而非口头说说骗人的无产阶级革命派都把工人阶级当作“自己”人,当作人民群众中最先进、最有觉悟的一部分人。工人、战士、学校中革命的积极分子“三结合”,就是群众自己解放自己最可靠的保证。那种把工人当作“自己”以外的异己力量的人,如果不是糊涂,他自己就是工人阶级的阶级异己分子,工人阶级就有理由专他的政。有些自己宣布自己为“无产阶级革命派”的知识分子,一遇到工人阶级触动他那个小小的“独立王国”的利益的时候,就反对起工人来了。这种叶公好龙式的人物,在中国还是不少的。这种人就是所谓轻视工农、爱摆架子、自以为了不起的人物,而其实不过是现代的一批叶公而已。凡是知识分子成堆的地方,不论是学校,还是别的单位,都应有工人、解放军开进去,打破知识分子独霸的一统天下,占领那些大大小小的“独立王国”,占领那些“多中心即无中心”论者盘踞的地方。这样,成堆的知识分子中间的不健康的空气、作风和想法就可以改变,他们也就有可能得到改造和解放。 “工人不懂教育。”某些所谓“高级知识分子”这样说。还是收起你那一套资产阶级知识分子臭架子吧!有两种教育:资产阶级教育和无产阶级教育。你们“懂”的是资产阶级那一套假“学问”,教理工科的不会开机器和修机器,教文学的不会写文章,教农业化学的不懂得施肥料,这样的笑话不是到处都有吗?理论与实践一致的无产阶级的教育制度,只能在无产阶级的直接参加下才能逐步创造出来,你们于此是一窍不通的。 “工人不了解学校情况,不了解两条路线斗争的历史。”同志,不要着急,工人是会了解的。工人阶级比那些目光短浅、只看到自己一个小山头的知识分子,水平不知道高出多少。他们不是住三、五天,而要长期工作下去,要永远占领学校和领导学校。一切客观存在的事物都是可以被认识的,工人阶级将会通过自己的革命实践更深刻地认识世界,并按照工人阶级的面貌改造世界。 工人宣传队要有步骤、有计划地到大、中、小学去,到上层建筑各个领域中去,到一切还没有搞好斗、批、改的单位去,以毛泽东思想为指针,团结、帮助那里决心把无产阶级教育革命进行到底的积极分子,联合大多数群众,包括有可能改造的知识分子,用无产阶级的彻底革命精神,促进那里的斗、批、改。这是中国工人阶级当前一项伟大的历史使命。在这个过程中,工人阶级本身会受到深刻的阶级斗争锻炼,涌现出一批优秀的工人干部,充实到国家机关的各个方面以及各级革委会里去,不但管理学校而已。 为了完成这个历史任务,工人阶级必须认真学好毛泽东思想,学习毛主席历来教导的群众路线和调查研究的作风,不断提高自己的政治觉悟,加强革命的纪律性,不断批判工人阶级内部各种资产阶级腐朽作风的侵蚀及影响。在文化教育单位,资产阶级有它的传统势力。在工人阶级要用无产阶级世界观即毛泽东思想改造世界时,资产阶级总是力图用他们的资产阶级世界观来腐蚀工人队伍包括其领导干部中的薄弱部分。对此必须有高度的警惕。必须保持坚定的无产阶级立场。必须警惕糖衣炮弹或其它形式的手段对工人队伍的袭击。还要认真地做好清理阶级队伍工作,抓革命、促生产,搞好工厂企业的斗、批、改。 毛主席最近指出:“建立三结合的革命委员会,大批判,清理阶级队伍,整党,精简机构、改革不合理的规章制度、下放科室人员,工厂里的斗、批、改,大体经历这么几个阶段。” 毛主席的这段话,是对斗、批、改阶段群众运动发展的总结,为我们完成工厂企业斗、批、改的任务指出了明确的道路。(⑴⑵) 首先的任务是建立三结合的革命委员会,使工厂企业的领导权真正掌握在无产阶级手里。这往往是同大批判和大体上清理阶级队伍两项任务结合起来做的。 革命的群众性的大批判,使人们清除了中国赫鲁晓夫及其在各地代理人的反革命修正主义路线的毒害,提高了两条路线斗争觉悟,从政治上、思想上为清理阶级队伍开路,并且在清理阶级队伍的过程中,起着发动群众、巩固斗争成果的作用。清理阶级队伍,稳、准、狠地打击一小撮特务、叛徒、死不悔改的走资派和没有改造好的地、富、反、坏、右分子,是工人阶级向资产阶级和一切剥削阶级进行无产阶级专政、纯洁自己队伍、清除钻到内部来的阶级敌人的一件十分重要的工作,它为大批判提供了生动的活材料。两者相互促进、相互推动。大批判和清理阶级队伍,为整党创造了最好的条件。经过政治上、思想上、组织上阶级斗争的严格考验,广大党员的政治觉悟有了很大提高,同群众的关系有了很大的改进,党内的极少数坏人清除出去了,党员的政治状况、组织状况基本上弄清楚了,并且吸收一批在运动中涌现出来的积极分子参加党组织,使党增加新鲜血液,逐步形成一个坚决执行毛主席无产阶级革命路线的领导核心,这样,我们就能整顿好党的组织,我们就能实现毛主席指出的伟大整党目标:“党组织应是无产阶级先进分子所组成,应能领导无产阶级和革命群众对于阶级敌人进行战斗的朝气蓬勃的先锋队组织。” 在工矿企业中的运动是如此,在文化教育事业中,在党、政机关中的运动,也大体是如此。 革命的高潮推动着生产的高潮。由于几万万贫下中农努力,我国农业生产多年获得丰收。有了一个巩固的农村的社会主义阵地,才能使城市中的无产阶级文化大革命节节胜利。我们向工人阶级的巩固的同盟军贫下中农致敬。随着斗、批、改的深入开展,工业战线上也在涌现出许多新事物,不少地方已在改的过程中出现了蓬蓬勃勃的技术革命。形势大好,振奋人心,一小撮妄想复辟的阶级敌人彻底完蛋了。现在美帝、苏修和世界上一切反动派的日子很不好过,他们焦头烂额,分崩离析,走投无路。在毛泽东同志领导下的经过无产阶级文化大革命锻炼的我们伟大的社会主义祖国,则是光辉灿烂,前途无量。我们一定要努力跟上发展着的形势,充分发动群众,及时总结经验,做好调查研究,抓好典型,全面规划,加强领导,认真打好斗、批、改这一仗。这是我们夺取无产阶级文化大革命全面胜利中的一仗,让我们紧跟毛主席的伟大战略部署乘胜前进! (载《红旗》杂志一九六八年八月二十五日,第二期;转载《人民日报》一九六八年八月二十六日) CCRADB
JavaScript
UTF-8
258
2.671875
3
[]
no_license
var rolls_royce = "Okoro Ikechi"; var genesis = "HNG-03711"; var bently = "ofoikechi@gmail.com"; var tesla = "JavaScript"; console.log("Hello World, this is " + rolls_royce + " with HNGi7 ID " + genesis + " and email " + bently + " using " + tesla + " for stage 2 task.");
SQL
UTF-8
2,544
3.40625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Anamakine: 127.0.0.1 -- Üretim Zamanı: 10 Eyl 2021, 17:34:40 -- Sunucu sürümü: 10.4.13-MariaDB -- PHP Sürümü: 7.2.31 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 */; -- -- Veritabanı: `logtutma` -- -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `loglar` -- CREATE TABLE `loglar` ( `id` int(11) NOT NULL, `uyeid` int(11) NOT NULL, `ip` varchar(200) NOT NULL, `tarih` varchar(200) NOT NULL, `aciklama` text DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `loglar` -- INSERT INTO `loglar` (`id`, `uyeid`, `ip`, `tarih`, `aciklama`) VALUES (1, 1, '::1', '2021-09-10 16:50:52', NULL), (2, 1, '::1', '2021-09-10 16:51:42', 'Sisteme giriş yaptı'), (3, 1, '::1', '2021-09-10 16:53:04', 'Sisteme giriş yaptı'), (4, 1, '::1', '2021-09-10 16:54:21', 'Sisteme giriş yaptı'), (5, 1, '::1', '2021-09-10 16:54:26', 'Sistemden çıkış yaptı'), (6, 1, '::1', '2021-09-10 16:56:17', 'Sisteme giriş yaptı'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `uyeler` -- CREATE TABLE `uyeler` ( `id` int(11) NOT NULL, `kadi` varchar(200) NOT NULL, `sifre` varchar(200) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Tablo döküm verisi `uyeler` -- INSERT INTO `uyeler` (`id`, `kadi`, `sifre`) VALUES (1, 'yavuz', 'adcd7048512e64b48da55b027577886ee5a36350'); -- -- Dökümü yapılmış tablolar için indeksler -- -- -- Tablo için indeksler `loglar` -- ALTER TABLE `loglar` ADD PRIMARY KEY (`id`); -- -- Tablo için indeksler `uyeler` -- ALTER TABLE `uyeler` ADD PRIMARY KEY (`id`); -- -- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri -- -- -- Tablo için AUTO_INCREMENT değeri `loglar` -- ALTER TABLE `loglar` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- Tablo için AUTO_INCREMENT değeri `uyeler` -- ALTER TABLE `uyeler` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; 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 */;
Python
UTF-8
297
3
3
[]
no_license
def outPutTree(DtreeObj,vertexidSet): vertexid=DtreeObj.getVertexId() vertexidSet.append(vertexid) # print("I am :",vertexid ,"I am following children:") child=DtreeObj.getChild() for childId in child: outPutTree(childId,vertexidSet) return vertexidSet
C++
UTF-8
429
2.90625
3
[]
no_license
/******************* * ts_split.cpp * ****************/ #include <iostream> #include <fstream> #include <string> #include <string.h> #include <vector> int main() { char* str; strcpy(str, "abc|efg;ic; q"); // char str[] = "abc|efg;ic; q"; const char* delim = "|"; char* tmp = strtok(str, delim); while(tmp != NULL) { printf("%s\n", tmp); tmp = strtok(NULL, " "); } return 0; }
C++
UTF-8
761
2.5625
3
[]
no_license
#pragma once #include "Transform.h" namespace CameraSwitchMethod { enum Enum : uint8_t { JumpCut, Ease, Fade, Count }; } class Camera { public: Camera(); ~Camera(); Vector3 GetPosition() const; Vector3 GetRotation() const; Vector3 GetZoom() const; void SetPosition(const Vector3& cameraPosition); void LookAt(const Vector3& lookAtPosition); void SetForward(const Vector3& forward); void SetAxes(const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis); void Roll(float amt); void Pitch(float amt); void Yaw(float amt); bool IsDirty() const; void ClearDirty(); Matrix4 GetMatrix() const; private: Vector3 m_Position; Vector3 m_XAxis; Vector3 m_YAxis; Vector3 m_ZAxis; bool m_IsDirty; };
Java
UTF-8
1,683
3.078125
3
[]
no_license
public class MyFileName { private String input; public MyFileName(){ } public MyFileName(String input) { this.input = input; } public String getPath(){ if (input == null || "".equals(input)) { return ""; } int lastIndex = input.lastIndexOf('\\'); return input.substring(0, lastIndex); } public String getFileName(){ if (input == null || "".equals(input)) { return ""; } int index=input.lastIndexOf("\\"); int indexOfDot=input.indexOf('.'); if (index != -1 && indexOfDot != -1) { return input.substring(index + 1, indexOfDot); } return ""; } public String getExtension(){ if (input == null || "".equals(input)) { return ""; } int indexOfDot = input.lastIndexOf("."); if (indexOfDot != -1) { return input.substring(indexOfDot + 1,input.length()); } return ""; } public String getDisk(){ if (input == null || "".equals(input)) { return ""; } int index = input.indexOf('\\'); if(index !=-1){ return input.substring(0,index); } return ""; } public String[] getFolders(){ if (input == null || "".equals(input)) { return null; } int star =input.indexOf("\\"); int end =input.lastIndexOf("\\"); if (star!=-1 && end!= -1){ String folders = input.substring(star+1,end); return folders.split("\\\\"); // System.out.println(folders); } return null; } }
Java
UTF-8
3,531
2.515625
3
[]
no_license
package com.example.report4; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch(requestCode){ case 0: { int result = data.getIntExtra("sum", -1); TextView t1 = findViewById(R.id.text); t1.setText("더한 결과 = " + result); break; } case 1:{ int result = data.getIntExtra("sum",-1); TextView t1 = findViewById(R.id.text); t1.setText("뺀 결과 = " + result); break; } case 2:{ int result = data.getIntExtra("sum",-1); TextView t1 = findViewById(R.id.text); t1.setText("곱한 결과 = " + result); break; } case 3:{ double result = data.getDoubleExtra("sum",-1); TextView t1 = findViewById(R.id.text); t1.setText("나눈 결과 = " + result); break; } } super.onActivityResult(requestCode, resultCode, data); } public void plus(View v){ EditText e1 = findViewById(R.id.res1); EditText e2 = findViewById(R.id.res2); String s1 = e1.getText()+""; String s2 = e2.getText()+""; int val1 = Integer.parseInt(s1); int val2 = Integer.parseInt(s2); Intent Intent = new Intent(this,SubActivity_1.class); Intent.putExtra("num1",val1); Intent.putExtra("num2",val2); startActivityForResult(Intent,0); } public void minus(View v){ EditText e1 = findViewById(R.id.res1); EditText e2 = findViewById(R.id.res2); String s1 = e1.getText()+""; String s2 = e2.getText().toString(); int val1 = Integer.parseInt(s1); int val2 = Integer.parseInt(s2); Intent Intent = new Intent(this,SubActivity_2.class); Intent.putExtra("num1",val1); Intent.putExtra("num2",val2); startActivityForResult(Intent,1); } public void mul(View v){ EditText e1 = findViewById(R.id.res1); EditText e2 = findViewById(R.id.res2); String s1 = e1.getText()+""; String s2 = e2.getText().toString(); int val1 = Integer.parseInt(s1); int val2 = Integer.parseInt(s2); Intent Intent = new Intent(this,SubActivity_3.class); Intent.putExtra("num1",val1); Intent.putExtra("num2",val2); startActivityForResult(Intent,2); } public void div(View v){ EditText e1 = findViewById(R.id.res1); EditText e2 = findViewById(R.id.res2); String s1 = e1.getText()+""; String s2 = e2.getText().toString(); double val1 = Double.parseDouble(s1); double val2 = Double.parseDouble(s2); Intent Intent = new Intent(this,SubActivity_4.class); Intent.putExtra("num1",val1); Intent.putExtra("num2",val2); startActivityForResult(Intent,3); } }
Ruby
UTF-8
78
3
3
[]
no_license
(1..gets.to_i).each {|| puts gets.chomp.split().map{|i|i.reverse}.join(" ") }
Java
UTF-8
241
1.570313
2
[]
no_license
package com.danilo.diplomski.repositories; import org.springframework.data.repository.CrudRepository; import com.danilo.diplomski.models.Obligation; public interface ObligationRepository extends CrudRepository<Obligation, Integer> { }
Java
UTF-8
3,208
2.109375
2
[]
no_license
package com.denghb.zuiyou.crawler.client; import com.denghb.zuiyou.common.Constants; import com.denghb.zuiyou.business.data.UserRuleVoData; import org.springframework.messaging.converter.StringMessageConverter; import org.springframework.messaging.simp.stomp.*; import org.springframework.stereotype.Component; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import org.springframework.web.socket.messaging.WebSocketStompClient; import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport; import org.springframework.web.socket.sockjs.client.SockJsClient; import org.springframework.web.socket.sockjs.client.Transport; import org.springframework.web.socket.sockjs.client.WebSocketTransport; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; /** * Created by denghb on 2017/4/29. */ @Component public class Client { private static final String url = String.format("ws://%s/socket", Constants.Server.GATEWAY_HOST); private WebSocketStompClient stompClient; public Client() { List<Transport> transports = new ArrayList<Transport>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestTemplateXhrTransport()); SockJsClient sockJsClient = new SockJsClient(transports); // sockJsClient.doHandshake(new MyWebSocketHandler(), url);// 握手 stompClient = new WebSocketStompClient(sockJsClient); stompClient.setMessageConverter(new StringMessageConverter()); stompClient.setDefaultHeartbeat(new long[]{0, 0}); // stompClient.setTaskScheduler(taskScheduler); // for heartbeats connection(); } private void connection() { stompClient.connect(url, new StompSessionHandlerAdapter() { @Override public void afterConnected(StompSession session, StompHeaders connectedHeaders) { super.afterConnected(session, connectedHeaders); session.subscribe("/topic/notice", new StompFrameHandler() { @Override public Type getPayloadType(StompHeaders headers) { return String.class; } @Override public void handleFrame(StompHeaders headers, Object payload) { // ... System.out.println(payload); if (Constants.Command.SYSTEM_EXIT.equals(payload)){ System.exit(9); } if(Constants.Command.UPDATE_RULE.equals(payload)){ UserRuleVoData.pull(); } } }); session.send("/app/message", "com/denghb/zuiyou/crawler"); } @Override public void handleTransportError(StompSession session, Throwable exception) { super.handleTransportError(session, exception); System.out.println("handleTransportError"); // 链接失败 connection(); } }); } }
TypeScript
UTF-8
6,720
2.5625
3
[ "MIT" ]
permissive
// Type definitions for non-npm package Wechat Mini Program - wechat-miniprogram 3.4 // Project: https://developers.weixin.qq.com/miniprogram/dev/api/ // Definitions by: Wechat Miniprogram <https://github.com/wechat-miniprogram>, // SgLy <https://github.com/SgLy>, // TtTRz <https://github.com/TtTRz> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Minimum TypeScript Version: 3.5 /// <reference path="./lib.wx.app.d.ts" /> /// <reference path="./lib.wx.page.d.ts" /> /// <reference path="./lib.wx.api.d.ts" /> /// <reference path="./lib.wx.cloud.d.ts" /> /// <reference path="./lib.wx.component.d.ts" /> /// <reference path="./lib.wx.behavior.d.ts" /> /// <reference path="./lib.wx.event.d.ts" /> declare namespace WechatMiniprogram { type IAnyObject = Record<string, any> type Optional<F> = F extends (arg: infer P) => infer R ? (arg?: P) => R : F type OptionalInterface<T> = { [K in keyof T]: Optional<T[K]> } interface AsyncMethodOptionLike { success?: ((...args: any[]) => void) | undefined } type PromisifySuccessResult< P, T extends AsyncMethodOptionLike > = P extends { success: any } ? void : P extends { fail: any } ? void : P extends { complete: any } ? void : Promise<Parameters<Exclude<T['success'], undefined>>[0]> interface Console { /** [console.debug()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.debug.html) * * 向调试面板中打印 debug 日志 */ debug( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void /** [console.error()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.error.html) * * 向调试面板中打印 error 日志 */ error( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void /** [console.group(string label)](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.group.html) * * 在调试面板中创建一个新的分组。随后输出的内容都会被添加一个缩进,表示该内容属于当前分组。调用 [console.groupEnd](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.groupEnd.html)之后分组结束。 * * **注意** * * * 仅在工具中有效,在 vConsole 中为空函数实现。 */ group( /** 分组标记,可选。 */ label?: string ): void /** [console.groupEnd()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.groupEnd.html) * * 结束由 [console.group](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.group.html) 创建的分组 * * **注意** * * * 仅在工具中有效,在 vConsole 中为空函数实现。 */ groupEnd(): void /** [console.info()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.info.html) * * 向调试面板中打印 info 日志 */ info( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void /** [console.log()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.log.html) * * 向调试面板中打印 log 日志 */ log( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void /** [console.warn()](https://developers.weixin.qq.com/miniprogram/dev/api/base/debug/console.warn.html) * * 向调试面板中打印 warn 日志 */ warn( /** 日志内容,可以有任意多个。 */ ...args: any[] ): void } } declare let console: WechatMiniprogram.Console declare let wx: WechatMiniprogram.Wx /** 引入模块。返回模块通过 `module.exports` 或 `exports` 暴露的接口。 */ declare function require( /** 需要引入模块文件相对于当前文件的相对路径,或 npm 模块名,或 npm 模块路径。不支持绝对路径 */ module: string ): any /** 引入插件。返回插件通过 `main` 暴露的接口。 */ declare function requirePlugin( /** 需要引入的插件的 alias */ module: string ): any /** 插件引入当前使用者小程序。返回使用者小程序通过 [插件配置中 `export` 暴露的接口](https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/using.html#%E5%AF%BC%E5%87%BA%E5%88%B0%E6%8F%92%E4%BB%B6)。 * * 该接口只在插件中存在 * * 最低基础库: `2.11.1` */ declare function requireMiniProgram(): any /** 当前模块对象 */ declare let module: { /** 模块向外暴露的对象,使用 `require` 引用该模块时可以获取 */ exports: any } /** `module.exports` 的引用 */ declare let exports: any /** [clearInterval(number intervalID)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/clearInterval.html) * * 取消由 setInterval 设置的定时器。 */ declare function clearInterval( /** 要取消的定时器的 ID */ intervalID: number ): void /** [clearTimeout(number timeoutID)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/clearTimeout.html) * * 取消由 setTimeout 设置的定时器。 */ declare function clearTimeout( /** 要取消的定时器的 ID */ timeoutID: number ): void /** [number setInterval(function callback, number delay, any rest)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/setInterval.html) * * 设定一个定时器。按照指定的周期(以毫秒计)来执行注册的回调函数 */ declare function setInterval( /** 回调函数 */ callback: (...args: any[]) => any, /** 执行回调函数之间的时间间隔,单位 ms。 */ delay?: number, /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ rest?: any ): number /** [number setTimeout(function callback, number delay, any rest)](https://developers.weixin.qq.com/miniprogram/dev/api/base/timer/setTimeout.html) * * 设定一个定时器。在定时到期以后执行注册的回调函数 */ declare function setTimeout( /** 回调函数 */ callback: (...args: any[]) => any, /** 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。 */ delay?: number, /** param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。 */ rest?: any ): number
Java
UTF-8
2,071
2.125
2
[]
no_license
package com.kabum.adapter.http; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.kabum.adapter.web.KabumDto; import com.kabum.application.KabumServicePort; @Component public class KabumServiceAdapter implements KabumServicePort { @Override public List<KabumResources> listaDeProdutos(KabumDto dto) { String url = "https://www.kabum.com.br/cgi-local/site/listagem/listagem.cgi?string=" + dto.getChave() + "&btnG=&pagina=1&ordem=3&limite=100&prime=false&marcas=[]&tipo_produto=[]&filtro=[]"; Document document = null; try { document = Jsoup.connect(url).get(); } catch (IOException e1) { throw new RuntimeException(e1.getMessage()); } String json = document.html(); json = json.substring(json.indexOf("listagemDados = ") + "listagemDados = ".length(), json.indexOf("const listagemErro")).trim(); JsonNode readTree = null; try { readTree = new ObjectMapper().readTree(json); } catch (JsonMappingException e) { throw new RuntimeException(e.getMessage()); } catch (JsonProcessingException e) { throw new RuntimeException(e.getMessage()); } List<KabumResources> produtos = new ArrayList<>(); Iterator<JsonNode> iterator = readTree.iterator(); while (iterator.hasNext()) { JsonNode next = iterator.next(); if (next.findValue("disponibilidade").asBoolean()) { produtos.add(new KabumResources( next.get("nome").asText(), next.findValue("disponibilidade").asBoolean(), new BigDecimal(next.findValue("preco_desconto").asText()), new String("https://www.kabum.com.br").concat(next.findValue("link_descricao").asText()))); } } return produtos; } }
C#
UTF-8
1,803
2.71875
3
[]
no_license
using Pendvlo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Pendvlo.DAL; namespace Pendvlo.Repository { public class SucursalesRepository : Repository { public SucursalesRepository(DBContext dBContext) : base(dBContext) { } /* Get all */ public List<Sucursal> getAll() { List<Sucursal> list_ = DBContext.Sucursales.OrderBy(s => s.Name).ToList(); return list_; } /* Get by id */ public Sucursal getByID(int id) { Sucursal Sucursal_ = DBContext.Sucursales.Where(m => m.ID == id).FirstOrDefault(); return Sucursal_; } /* Create libertad sucursal */ public void createLibertadSucursal() { var result = DBContext.Sucursales.Add(new Sucursal { Name = "LIBERTAD" }); DBContext.SaveChanges(); } /* Create miguel blanco */ public void createMiguelBlanco() { var result = DBContext.Sucursales.Add(new Sucursal { Name = "MIGUEL BLANCO" }); DBContext.SaveChanges(); } /* Get libertad */ public Sucursal getLibertadSucursal() { Sucursal Sucursal = DBContext.Sucursales.Where(m => m.Name == "LIBERTAD").FirstOrDefault(); return Sucursal; } /* Get corte completo */ public Sucursal getMiguelBlancoSucursal() { Sucursal Sucursal = DBContext.Sucursales.Where(m => m.Name == "MIGUEL BLANCO").FirstOrDefault(); return Sucursal; } } }
PHP
UTF-8
5,585
2.578125
3
[]
no_license
<?php /** * Autor: Luis Albizures * fecha: 06/07/2015 * Hora: 10:00 AM * server CRUD para la tabla de opciones de menu. * Entidades de DB que se utilizan: * fn_tipo() pg_tipo seg_opcion` pg_estado sp_sel_seg_opcion( ) fn_ins_seg_opcion( ? , ? ...) sp_upd_seg_opcion(?,?,?,?,?,?,?) sp_del_seg_opcion(?) sp_sel_tipo_opcion() sp_sel_seg_opcion_hijos( padre ) **/ // Obtiene la lista de tipos de opción, ej: Menu, Sub-Menu $app->get('/opLista','sessionAlive', function() use ($app) { $db = new DbHandler(); $response = array(); $datos = $db->getAllRecord("call sp_sel_tipo_opcion()"); if ($datos != NULL) { $response = $datos; }else{ $response['status'] = "info"; $response['message'] = 'No hay datos'; } echoResponse(200, $response); }); $app->get('/estadoListaUser','sessionAlive', function() use ($app) { $db = new DbHandler(); $response = array(); $datos = $db->getAllRecord("call sp_sel_pg_estado_usuario()"); if ($datos != NULL) { $response = $datos; }else{ $response['status'] = "info"; $response['message'] = 'No hay datos'; } echoResponse(200, $response); }); // Obtiene la lista de opciones hijas de un padre específico solicitado por $id $app->get('/opListaH/:id','sessionAlive', function($id) use ($app) { $db = new DbHandler(); $response = array(); $datos = $db->getAllRecord("call sp_sel_seg_opcion_hijos($id)"); if ($datos != NULL) { $response = $datos; }else{ $response['status'] = "info"; $response['message'] = 'No hay datos'; } echoResponse(200, $response); }); // Opcion para obtener la totalidad de registros de la tabla opcion $app->get('/opDatos','sessionAlive', function() use ($app){ $response = array(); // $db = new DbHandler(); $datos = $db->getAllRecord("call sp_sel_seg_opcion( )"); //var_dump($datos); // call sp_sel_seg_usuario( ? ) pusuario if ($datos != NULL) { $response = $datos; }else{ $response['status'] = "info"; $response['message'] = 'No hay datos'; } echoResponse(200, $response); }); // Opción para ingresar un registro de la tabla opcion $app->post('/opDatos','sessionAlive',function() use ($app){ // Recupera los datos de la forma // $r = json_decode($app->request->getBody()); verifyRequiredParams(array('nombre', 'descripcion', 'titulo', 'idPadre','idTipo','orden'),$r->opcion); // $nombre = $r->opcion->nombre; $descripcion = $r->opcion->descripcion; $titulo = $r->opcion->titulo; $idPadre = $r->opcion->idPadre; $idTipo = $r->opcion->idTipo; $orden = $r->opcion->orden; $response = array(); // // // Ejemplo de uso de un insert: // // select fn_ins_seg_opcion('Ingresa opciones', 'ingreso de opciones', 'Opciones' , 0, 1, 1) // $db = new DbHandler(); // $column_names = array('nombre', 'descripcion', 'titulo', 'idPadre','idTipo','orden'); // $db->insertIntoTable($r->opcion, $column_names, 'seg_usuario' ); $id = $db->get1Record("select fn_ins_seg_opcion( '$nombre','$descripcion','$titulo', $idPadre, $idTipo , $orden ) as id"); if ($id != NULL) { $response['data'] = $id; $response['status'] = "success"; $response['message'] = 'Se agrego correctamente'; }else{ $response['status'] = "info"; $response['message'] = 'No hay datos'; } echoResponse(200, $response); }); // Actualiza los datos de un registro de opción especificado en el parámetro $id $app->post('/opDatosU','sessionAlive',function() use ($app){ // Recupera los datos de la forma // $r = json_decode($app->request->getBody()); verifyRequiredParams(array('id','nombre', 'descripcion', 'titulo', 'idPadre','idTipo','orden'),$r->opcion); // $nombre = $r->opcion->nombre; $descripcion = $r->opcion->descripcion; $titulo = $r->opcion->titulo; $idPadre = $r->opcion->idPadre; $idTipo = $r->opcion->idTipo; $orden = $r->opcion->orden; $response = array(); // // // Ejemplo de uso de un insert: // // select fn_ins_seg_opcion('Ingresa opciones', 'ingreso de opciones', 'Opciones' , 0, 1, 1) // $db = new DbHandler(); $column_names = array('id','nombre', 'descripcion', 'titulo', 'idPadre','idTipo','orden'); // $db->insertIntoTable($r->opcion, $column_names, 'seg_usuario' ); $resId = $db->updateRecord("call sp_upd_seg_opcion(?,?,?,?,?,?,?)", $r->opcion, $column_names,'isss'); if ($resId == 0) { $response['status'] = "info"; $response['message'] = 'Datos actualizados'; }else{ if ($resId < 0) { $response['status'] = "error " . $resId; $response['message'] = 'No pudo actualizar los Datos'; } } echoResponse(200, $response); }); // Elimina un registro de opción especificado por $id $app->get('/opDatosD/:id','sessionAlive',function($id) use ($app){ // Recupera los datos de la forma // // $r = json_decode($app->request->getBody()); $response = array(); // // // Ejemplo de uso de un insert: // // select fn_ins_seg_opcion('Ingresa opciones', 'ingreso de opciones', 'Opciones' , 0, 1, 1) // $db = new DbHandler(); //$resId = $db->deleteRecord("call sp_del_seg_opcion(?)", $r->id); $resId = $db->deleteRecord("call sp_del_seg_opcion(?)", $id); if ($resId == 0) { $response['status'] = "info"; $response['message'] = 'Datos eliminados'; }else{ if ($resId < 0) { $response['status'] = "error " . $resId; $response['message'] = 'No pudo eliminar los Datos'; } } echoResponse(200, $response); }); ?>
Markdown
UTF-8
4,144
2.890625
3
[]
no_license
# ShareCuttly Application réductrice de liens avec l'API cutt.ly, permettant d'obtenir un lien raccourci redirigeant vers le lien voulu tout en permettant d'en retirer les statistiques de trafics au travers du lien raccourci. Fonctionnalités: * Raccourcir des liens en utilisant l'API cutt.ly * Permettre la requête de nom de lien spécifique à l'API pour les liens raccourcis * Enregistrer les requêtes, afin de garder un historique des liens raccourcis * Permettre l'affichage et la gestion de l'historique de requête (Affichage, suppression, copie d'éléments) * Récupérer et afficher les détails de trafics sur un lien raccourci présent dans l'historique Fonctionnalités prévues mais non implémenté: * Réglages quant à l'enregistrement des requêtes **|** Permettre de désactiver l'enregistrement des requêtes faites depuis l'application ou depuis la fonction **partage** d'Android * Implémenté dans l'enregistrement des requêtes, mais modification des paramètres non implémentées * Option de raccourcissement de lien puis de repartage immédiat **|** Dans les options de partage, avoir la possibilités de raccourcir un lien avec ShareCuttly puis réexécuter la fonction de partage Android pour partager le lien raccourci sur d'autre application ## Écran d'accueil Une fois l'application ouverte, le premier écran est l'écran où il est possible de raccourcir un lien. Il est possible de naviguer entre les écrans avec le menu en haut à gauche. ![Écran d'accueil de l'application](https://i.imgur.com/DNNOJNO.png) ## Raccourcir un lien Pour raccourcir un lien il suffit, au choix, d'écrire une URL ou de la copier dans l'emplacement juste au dessus des boutons, ou d'utiliser le bouton "Paste & Short" pour utiliser l'élément du presse papier comme lien à raccourcir. Il est possible de faire la demande d'un nom d'URL spéciale avec l'emplacement de texte juste au dessus, si le nom est disponible il sera associé au lien. Une fois un des boutons cliqué le lien raccourci sera affiché, en cas de succès, à la place sur lien qui vient d'être raccourci et copié dans le presse papier, en plus d'être enregistré dans l'historique. ![Raccourcir un lien](https://i.imgur.com/CMZ5k4j.png "Raccourcir un lien") ![Lien raccourci avec succès](https://i.imgur.com/m4ym9Oz.png) ## Navigation Voici le menu pour naviguer entre les deux principales vues de l'application: ![Menu de navigation](https://i.imgur.com/0lbMqW3.png) ## Historique des liens raccourcis L'application garde un historique des liens raccourcis afin de pouvoir en récupérer les statistiques d'utilisations, en plus de permettre de les retrouver. Il est possible de copier un lien raccourcis en maintenant une pression sur l'élément souhaité. Chaque élément affiche le nom donné par l'API au lien raccourcis, la date à droite, puis l'URL long, celui raccourci, et l'url raccourci qui redirige vers l'url long. ![Historique des liens](https://i.imgur.com/4fGjJ8K.png) ## Détails des éléments d'historique En cliquant sur un des éléments dans l'historique on affiche les détails de ce dernier. Sur cette page on peut voir en plus clair tous les éléments précédemment affiché sur les éléments de l'historique. On peut également faire une requête de statistique pour le lien. La vue permet soit de retourner à l'écran précédent grâce au bouton en haut à gauche, ou de supprimer l'élément affiché, cela avec une demande de confirmation pour éviter les appuis accidentels. ![Détails d'un élément d'historique](https://i.imgur.com/mHqB5Eq.png) ![Statistique de l'élément d'historique](https://i.imgur.com/9HLfwA2.png) ## Partage de lien depuis d'autres applis ShareCuttly permet également de raccourcir des liens depuis les options de partage qu'on peut par exemple retrouver sur les navigateurs web. Utiliser l'option de partage de ShareCuttly raccourcira le lien à partager et copiera le lien raccourci dans le presse-papier. Ici l'option de partage de l'application a été mise en valeur par un carré jaune. !![Option de partage de ShareCuttly](https://i.imgur.com/PGTxKoO.png)
PHP
UTF-8
339
2.578125
3
[]
no_license
<?php require_once "../autoload/autoload-psr4.php"; $prod = new App\Classes\Produto("Refrigerante"); $prod->detalhes(); $geladeira = new App\Classes\Eletrodomestico("Geladeira", 110); $geladeira->detalhes(); $microonda = new App\Classes\Microondas("Micro", 110, 600); $microonda->detalhes(); var_dump($prod, $geladeira, $microonda);
Java
UTF-8
2,468
3.21875
3
[]
no_license
package greedy; import org.junit.jupiter.api.Test; import supplementary.structures.graph.Graph; import supplementary.structures.graph.Vertex; import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; public class DijkstraTest { Dijkstra dijk = new Dijkstra(); @Test void linearSimpleTest() { Graph graph = new Graph(true); Vertex<String> first = new Vertex<String>("1"); Vertex<String> second = new Vertex<String>("2"); Vertex<String> third = new Vertex<String>("3"); Vertex<String> fourth = new Vertex<String>("4"); graph.addEdge(first, second, 5); graph.addEdge(second, third, 10); graph.addEdge(second, fourth, 5); double actual = dijk.distance(graph, first, third); double expected = 15; assertEquals(expected, actual); } @Test void singleNode() { Graph graph = new Graph(true); Vertex<String> first = new Vertex<String>("1"); graph.addVertex(first); double[] actual = dijk.distance(graph, first); double[] expected = {0}; assertArrayEquals(expected, actual, .1); } @Test void multiVertexGraph() { Graph graph = new Graph(true); Vertex<String> first = new Vertex<String>("0"); Vertex<String> second = new Vertex<String>("1"); Vertex<String> third = new Vertex<String>("2"); Vertex<String> fourth = new Vertex<String>("3"); graph.addEdge(first, third, 5); graph.addEdge(third, second, 2); graph.addEdge(second, third, 3); graph.addEdge(second, fourth, 8); double[] actual = dijk.distance(graph, first); double[] expected = {0, 5, 7, 15}; assertArrayEquals(expected, actual, 0.1); } @Test void cycle() { Graph graph = new Graph(true); Vertex<String> first = new Vertex<String>("0"); Vertex<String> second = new Vertex<String>("1"); Vertex<String> third = new Vertex<String>("2"); Vertex<String> fourth = new Vertex<String>("3"); graph.addEdge(first, second, 5); graph.addEdge(second, first, 12); graph.addEdge(second, third, 8); graph.addEdge(third, fourth, 6); graph.addEdge(fourth, first, 2); double actual = dijk.distance(graph, second, fourth); double expected = 14; assertEquals(expected, actual); } }
Markdown
UTF-8
436
2.578125
3
[]
no_license
# Virtual piano online A free virtual piano that you can find on this website is a wonderful opportunity for you to try your compositional skills. You can play it on your computer keyboard, or using your mouse. Each keyboard button corresponds to one key on the piano and plays the respective sound. Sounds are the samples of the highest quality recorded with a real live piano. See live: [Virtual piano online](http://real-royal.com/)
C++
GB18030
1,125
3.5625
4
[]
no_license
/*** 1002. д (20) ʱ 400 ms ڴ 65536 kB 볤 8000 B Standard CHEN, Yue һȻnλ֮ͣúƴд͵ÿһλ֡ ʽÿ1Ȼnֵﱣ֤nС10100 ʽһnĸλ֮͵ÿһλƴּ1 ո񣬵һһƴֺûпո 1234567890987654321123456789 yi san wu ***/ #include<cstdio> #include<string> #include<iostream> using namespace std; int main() { char k; string pinyin[10]={"ling","yi","er","san","si","wu","liu","qi","ba","jiu"}; int n, sum=0, a[5], i=0, j; while ( (k=cin.get()) != '\n') { n=k-'0'; sum+=n; } while (sum!=0) { a[i]=sum%10; sum/=10; i++; } cout<<pinyin[a[i-1]]; i--; while (i>=1) { cout<<" "<<pinyin[a[i-1]]; i--; } return 0; }
Markdown
UTF-8
4,987
3.109375
3
[ "BSL-1.0" ]
permissive
# Utilities SOCI provides a portable abstraction for selection of database queries. ## DDL SOCI supports some basic methods to construct portable DDL queries. That is, instead of writing explicit SQL statement for creating or modifying tables, it is possible to use dedicated SOCI functions, which prepare appropriate DDL statements behind the scenes, thus enabling the user application to create basic database structures in a way that is portable across different database servers. Note that the actual support for these functions depends on the actual backend implementation. It is possible to create a new table in a single statement: ```cpp sql.create_table("t1").column("i", soci::dt_integer).column("j", soci::dt_integer); ``` Above, table "t1" will be created with two columns ("i", "j") of type integer. It is also possible to build similar statements piece by piece, which is useful if the table structure is computed dynamically: ```cpp { soci::ddl_type ddl = sql.create_table("t2"); ddl.column("i", soci::dt_integer); ddl.column("j", soci::dt_integer); ddl.column("k", soci::dt_integer)("not null"); ddl.primary_key("t2_pk", "j"); } ``` The actual statement is executed at the end of above block, when the ddl object goes out of scope. The "not null" constraint was added to the definition of column "k" explicitly and in fact any piece of SQL can be inserted this way - with the obvious caveat of having limited portability (the "not null" piece seems to be universaly portable). Columns can be added to and dropped from already existing tables as well: ```cpp sql.add_column("t1", "k", soci::dt_integer); // or with constraint: //sql.add_column("t1", "k", soci::dt_integer)("not null"); sql.drop_column("t1", "i"); ``` If needed, precision and scale can be defined with additional integer arguments to functions that create columns: ```cpp sql.add_column("t1", "s", soci::dt_string, precision); sql.add_column("t1", "d", soci::dt_double, precision, scale); ``` Tables with foreign keys to each other can be also created: ```cpp { soci::ddl_type ddl = sql.create_table("t3"); ddl.column("x", soci::dt_integer); ddl.column("y", soci::dt_integer); ddl.foreign_key("t3_fk", "x", "t2", "j"); } ``` Tables can be dropped, too: ```cpp sql.drop_table("t1"); sql.drop_table("t3"); sql.drop_table("t2"); ``` Note that due to the differences in the set of types that are actually supported on the target database server, the type mappings, as well as precision and scales, might be different, even in the way that makes them impossible to portably recover with metadata queries. In the category of portability utilities, the following functions are also available: ```cpp sql.empty_blob() ``` the above call returns the string containing expression that represents an empty BLOB value in the given target backend. This expression can be used as part of a bigger SQL statement, for example: ```cpp sql << "insert into my_table (x) values (" + sql.empty_blob() + ")"; ``` and: ```cpp sql.nvl() ``` the above call returns the string containing the name of the SQL function that implements the NVL or COALESCE operation in the given target backend, for example: ```cpp sql << "select name, " + sql.nvl() + "(phone, \'UNKNOWN\') from phone_book"; ``` Note: `empty_blob` and `nvl` are implemented in Oracle, PostgreSQL and SQLite3 backends; for other backends their behaviour is as for PostgreSQL. ## DML Only two related functions are currently available in this category: `get_dummy_from_clause()` can be used to construct select statements that don't operate on any table in a portable way, as while some databases allow simply omitting the from clause in this case, others -- e.g. Oracle -- still require providing some syntactically valid from clause even if it is not used. To use this function, simply append the result of this function to the statement: ```cpp double databasePi; session << ("select 4*atan(1)" + session.get_dummy_from_clause()), into(databasePi); ``` If just the name of the dummy table is needed, and not the full clause, you can use `get_dummy_from_table()` to obtain it. Notice that both functions require the session to be connected as their result depends on the database it is connected to. ## Database Metadata It is possible to portably query the database server to obtain basic metadata information. In order to get the list of table names in the current schema: ```cpp std::vector<std::string> names(100); sql.get_table_names(), into(names); ``` alternatively: ```cpp std::string name; soci::statement st = (sql.prepare_table_names(), into(name)); st.execute(); while (st.fetch()) { // ... } ``` Similarly, to get the description of all columns in the given table: ```cpp soci::column_info ci; soci::statement st = (sql.prepare_column_descriptions(table_name), into(ci)); st.execute(); while (st.fetch()) { // ci fields describe each column in turn } ```
Python
UTF-8
475
2.609375
3
[]
no_license
def dfs(i, p, seq): global N, M ret = 0 if i == N: ret = check(seq) else: for x in range(p, M + 1): ret = max(ret, dfs(i + 1, x, tuple(list(seq) + [x]))) return ret def check(seq): cnt = 0 for a, b, c, d in query: if seq[b - 1] - seq[a - 1] == c: cnt += d return cnt N, M, Q = map(int, input().split()) query = [tuple(map(int, input().split())) for _ in range(Q)] print(dfs(0, 1, tuple()))
Java
UTF-8
431
1.882813
2
[]
no_license
package org.livinggoods.myapp.data.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class AttendanceFields { @SerializedName("CHP details") @Expose private CHPDetails cHPDetails; public CHPDetails getCHPDetails() { return cHPDetails; } public void setCHPDetails(CHPDetails cHPDetails) { this.cHPDetails = cHPDetails; } }
Python
UTF-8
622
3.890625
4
[]
no_license
# -*- coding: utf-8 -*- # 给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。 class Solution: def KthNode(self, pRoot, k): # 遍历顺序为左根右 global result result = [] self.midnode(pRoot) if k <= 0 or len(result) < k: return None else: return result[k - 1] def midnode(self, root): if not root: return None self.midnode(root.left) result.append(root) self.midnode(root.right)
JavaScript
UTF-8
3,613
3.21875
3
[]
no_license
// https://pokeapi.co/api/v2/pokemon/?limit=949 'use strict'; var searchForm = $('#searchForm'); start(); function start(){ fetch(`https://pokeapi.co/api/v2/pokemon/?limit=718`) .then(function(response) { //Turns the the JSON into a JS object return response.json(); }) .then(function(data) { data.results.forEach(poke => { let pokeUrl = poke.url; let lastSlash = poke.url.lastIndexOf('/', pokeUrl.length - 1); let penultimateSlash = poke.url.lastIndexOf('/', lastSlash - 1); let pokeId = pokeUrl.slice(penultimateSlash, lastSlash) let container = $('<div class="square">').addClass('pokemon'); let image = $('<img>').attr('src', `https://pokeapi.co/media/img/${pokeId}.png`); let title = $('<h2>').text(poke.name); container.append(image, title); $('#poke-container').append(container); }) console.log(data.results); }); }; $('.logo').on('click', function() { start(); }); searchForm.on('click', function(element) { element.preventDefault(); var inputSearch = $('#inputSearch').val(); let container = $('<div>').addClass('col-xs-12 col-md-4 col-md-offset-4 pokemon'); fetch(`https://pokeapi.co/api/v2/pokemon/${inputSearch}/`) .then(function(response) { // Turns the the JSON into a JS object return response.json(); }) .then(function(data) { // console.log(data); // Saco el ID según el pokemon elegido // let pokeUrl = data.forms[0].url; // let lastSlash = pokeUrl.lastIndexOf('/', pokeUrl.length - 1); // let penultimateSlash = pokeUrl.lastIndexOf('/', lastSlash - 1); // let pokeId = pokeUrl.slice(penultimateSlash, lastSlash) // Creo un container para mi pokemon let image = $('<img class = "imgPoke">').attr('src', `https://pokeapi.co/media/img/${data.id}.png`); let title = $('<h2 class="name">').text(data.name); let height = $('<div class="col-md-5 caract"><p>').text('Altura: ' + data.height / 10 + ' m'); let weight = $('<div class="col-md-5 caract"><p>').text('Peso: ' + data.weight / 10 + ' kg'); container.append(title, image, height, weight); // obtener la habilidad data.abilities.forEach(function(element) { if (element.is_hidden === true) { container.append('<div class="col-md-5 caract"><p>Habilidad: ' + element.ability.name + '</p></div>'); } }); $('#poke-container').html(container); // para obtener la descripción return fetch(`https://pokeapi.co/api/v2/pokemon-species/${data.id}/`); }) .then(function(response) { return response.json(); }) .then(function(data) { // para obtener el tipo de pokemon data.genera.forEach(function(element) { if (element.language.name === 'es') { let category = $('<div class="caractGenus col-md-6"><p>').text('Categoría: ' + element.genus); container.append(category); } }); data.flavor_text_entries.forEach(function(element) { if (element.language.name === 'es' && element.version.name === 'omega-ruby') { $('.imgPoke').after('<p class ="description">' + element.flavor_text + '</p>'); } }); }).catch(function(error) { }); }); /* function description(pokeData) { fetch(`https://pokeapi.co/api/v2/pokemon-species/${pokeData}/`) .then(function(response) { //Turns the the JSON into a JS object return response.json(); }) .then(function(data) { console.log(data); let description = data.flavor_text_entries[21].flavor_text; console.log(description); }); };*/
Rust
UTF-8
1,235
3.78125
4
[]
no_license
use crate::containers::shape::EntityShape; use std::f64::consts::PI; #[derive(Copy, Clone, Debug, PartialEq)] pub struct Circle { pub entity_type: EntityShape, radius: f64, } impl Circle { pub fn new(radius: f64) -> Circle { Circle { entity_type: EntityShape::Circle, radius, } } pub fn get_radius(&self) -> f64 { self.radius } pub fn set_radius(&mut self, radius: f64) { self.radius = radius; } pub fn get_area(&self) -> f64 { let base = self.radius; PI * base.powi(2) } } #[cfg(test)] mod tests { use super::Circle; use std::f64::consts::PI; #[test] fn it_gets_radius_and_area() { let radius: f64 = 5.9; let my_circle = Circle::new(radius); assert_eq!(my_circle.get_radius(), radius); assert_eq!(my_circle.get_area(), PI * radius.powi(2)); } #[test] fn it_sets_radius() { let radius: f64 = 5.9; let mut my_circle = Circle::new(radius); let new_radius: f64 = 10.0; my_circle.set_radius(10.0); assert_eq!(my_circle.get_radius(), new_radius); assert_eq!(my_circle.get_area(), PI * new_radius.powi(2)); } }
Markdown
UTF-8
2,649
2.8125
3
[]
no_license
#### chess.py chess.py is small, text-based chess game implementing all known rules of chess (including the oft-forgotten "[en passant](https://en.wikipedia.org/wiki/En_passant)" special capture rule :-) ![Unicode characters are pretty cool](docs/images/chesspyTerminalScreenshot.png "chess.py screenshot") ### Requirements Currently, [python3](http://www.python.org/getit/) is the only dependency, so the game *should* also run on Windows and MacOS X. Chess pieces are represented with the standard [unicode characters](http://en.wikipedia.org/wiki/Chess_symbols_in_Unicode) In the future I will add a graphical user interface (likely using the 'pygame' library) (The game is currently completely terminal/command-line based. At the moment, the player selects pieces by typing the coordinates (eg. 'e2' followed by 'e4' to play the famous "[King's Pawn](https://en.wikipedia.org/wiki/King%27s_Pawn_Game)" opening move).) #### Completed Features Core gameplay is complete, with all known chess mechanics implemented: - [x] Pawn - [x] Promotion - [x] [En passant](https://en.wikipedia.org/wiki/En_passant) special capture - [x] Knight - [x] Bishop - [x] King - [x] King/Rook Castling - [x] Rook - [x] Queen - [x] Main game logic: Turn-based basic playable game mechanics - [x] Check/checkmate detection - Draw detection - [x] [Stalemate](https://en.wikipedia.org/wiki/Stalemate) - [x] Impossibility of checkmate ("insufficient mating material rule") - [x] [3-fold repetition](https://en.wikipedia.org/wiki/Threefold_repetition) - [x] [50-move rule](https://en.wikipedia.org/wiki/Fifty-move_rule) #### History chess.py was written during freetime between December 2013 and January 2014, but was abandoned near-completion of terminal-based gameplay. After a 4 year hiatus, development was resumed with the left-over gameplay mechanics (described above) being quickly implemented. #### Roadmap With the terminal-based chess game fully completed, it serves as a building block for future projects: - [x] Refactor terminal application into client/server architecture - [x] Communication of each player via JSON messages send over TCP sockets - [] Provide opponent connection status etc - [] Confirm validity of JSON messages - [] Create a [TypeScript 'chess.ts' client](https://github.com/shasheene/chess.ts) - [] Host chess.py on a persistent cloud server, with chess.ts as the frontend - [] Host multiple sessions - [] Computer player AI bot - [] Graphical user interface (in python) with move selection through mouse clicks - [] Create Android client (with the Flutter UI framework) and publish on app store
Markdown
UTF-8
6,243
2.953125
3
[ "MIT" ]
permissive
# Git Pull Dirigent Git Pull Dirigent is a bash script which aims to automate the whole process of updating a Git repository in an advanced manner and one shot. #### Main Features - Updates a Git repository - Installs or Updates php dependencies **if composer.json is affected** after pull - Installs or Updates node dependencies **if package.json was updated** after pull - Compiles Assets using Laravel Mix, **if any compileable file is affected** after pull - Offers **control over the processes** which can be executed You can: - Specify what should be run and when should be run ### Usage #### Requirments Depending on what you want to do with this script, it has different requirements. ##### php dependencies - To supervise php dependency management [Composer](https://getcomposer.org/download/) is required. - Your repository should contain composer.json file. ##### node dependencies - To manage node dependency management [NPM](https://getcomposer.org/download/) or [YARN](https://classic.yarnpkg.com/en/docs) is required. - Your repository should contain package.json file. ##### compiling assets - To conduct the complie process of your files requires [laravel-mix](https://laravel.com/docs/7.x/mix) must be included in node dependencies and to be configured properly. - Your repository should contain webpack.mix.js file. - To run mix you have to install [NPM](https://getcomposer.org/download/) or [YARN](https://classic.yarnpkg.com/en/docs). ### Choosing what to run Git Pull Dirigent's work is based on the digit combination **gpd_cmd** which can be found at the begining of the script. Every index in this command is reserved for a specific functionality. By default Git Pull Dirigent will run a digit combination like **11110** which will update your repository and subsequently it will check whether the **composer.json** was updated, if it does it will run **'composer install'** command, if not will do nothing. Similarly, it will run **'npm install'** command if **package.json** was updated. Finally, using **'npm run production'** it will run all mix tasks by minifying output for production **if and only if** any of files which are set to be compiled **was changed**. What's good here is that we can have a control over this process and we can modify it by changing only a few variables. Let's assume that instead of **npm** we want to use **yarn** to update our node dependencies, the only thing we should do is to **change the digit** in the second position (the index which is reserved for the type of PM) in the combination from **1** to **2**. In the same way, if we want to run **'composer update'** we can change only the first digit from **1** to **2**. Below is provided a table which helps to create combinations. If you don't want to run any of aforementioned tasks simply change its digit to **0**. ### Controlling when to execute Git Pull Dirigent by default will run tasks asssigned to it only if their respective files get affected during update. For example, if package.json is changed, then gpd will update node dependencies, if not, gpd will not it will skip this process. We can have a control **when to run** jobs we specified to be done. This can be done by changing the last digit of combination. If this digit is set to **1** it will run always the commands which are specified, if it is **0** it will run them only if their files are changed. ### Creating combinations Git Pull Dirigent can do diffent things by assigning different combinations to **gpd_cmd**. Instructions on how to use these commands are provided in the table below. | ------ | -- COMPOSER --| ----- JS PM ---- | - JS PM CMD - | - FILE COMPILE - | ---- -- WHEN-- ------- | | ------ | - install | update | install | update | install | update | - prod | dev | watch | always |- on update - | | ------ | --- 1 --- | --- 2 --- | ---- 1 --- | --- 2 --- | --- 1 --- | --- 2 ---- | -- 1 -- | - 2 - | -- 3 -- | --- 1 --- | --- -- 0 ------ | | ------ | ---- ---- 1 ---- ---- | ----- --- 1 ---- ---- | --- --- 1 -------- | --- -- --- -- 1 -- --- ---- | --- --- - 0 --- --- ------- | | ------ | composer install | --- ------ ----- npm install --- --- --- | ---- run prod ------- | -- on updates only - | | ------ | composer.json | --- --- --- --- package.json -- --- ---- --- | -- files to compile --- | ---------------------- | In this table was described how **gpd_cmd=11110**, and what selected commands will do. ##### gpd_cmd examples: - gpd_cmd=00000 -> will pull the changes and run nothing - gpd_cmd=10000 -> will update php dependencies only if composer.json was changed - gpd_cmd=10001 -> will update php dependencies always - gpd_cmd=01101 -> will install node dependencies always - gpd_cmd=01001 -> will do nothing, since script exits because in position 2 and 3 there is no job specified for npm - gpd_cmd=30000 -> will do nothing, script exists because there is a wrong command for composer ### Setting up the executable command #### Linux(Ubuntu) You can either set it to run as a global command or simply put in a project repository. To use it **as a global command** follow ensuing steps: Open cmd and go to bin: ```sh $ cd /bin ``` create an file using your text editor, in my case nano: ```sh $ nano gitpulldirigent ``` add the content of this script and save it. After this make the file **executable**: ```sh $ chmod +x gitpulldirigent ``` your file is ready to run globaly. To **test** it, go to the root directory of your project ```sh $ gitpulldirigent ``` #### Windows Clone this script and make sure it is placed in the projects root directory, makes sure you give the **read & execute permission** to it. Right click in the main directory of your project and select **'Run Bash Here'** from the menu and run: ```sh $ sh gitpulldirigent.sh ``` ### Known issues - If files which are defined to be compiled by webpack mix contain modules (files) which are being included (imported) inside those files, changes in these imported module (files) will not trigger the necessary command. ### Todos - Testing more - Send gpd_cmd as parameter - Extending functionality - Fix known issues License ---- MIT
Python
UTF-8
11,028
2.65625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Mar 06 13:25:56 2018 @author: Pablo """ from __future__ import division import numpy as np import cv2 import os from matplotlib.patches import Wedge import matplotlib.pyplot as plt import utils def compute_minimum_distances(num_fishers): """ num_fishers: number of Principal Components (which, for the FisherFaces recognizer, is equal to the number of classes minus one) num_fishers type: Compute a leaving one (of each class) out 61 times and calculate distance to closest neighbour and distance to closest neighbour of second closest class """ vector_eucl = np.zeros((len(class_numbers), 4, 61)) vector_mahal = np.zeros((len(class_numbers), 4, 61)) for k in range(61): print(str(k)) # Load test samples test_samples = [] for i in np.arange(k, 61*len(class_numbers), 61): test_samples.append(images[i]) images_train = np.delete(images, np.arange(k, 61*len(class_numbers), 61), axis=0) labels_train = np.delete(labels, np.arange(k, 61*len(class_numbers), 61), axis=0) # Train eigenimages model model = cv2.face.createFisherFaceRecognizer() model.train(images_train, labels_train) fisher_imgs = model.getEigenVectors() #map(lambda x: model.setLabelInfo(int(x[0]), x[4:]), class_names) # define each class's name mean_vector = model.getMean() projections = model.getProjections() projections = np.array(projections).reshape(len(projections), num_fishers) # Standard deviation of each variable, for mahalanobis metric std_dev = np.std(projections, axis=0) # Project test samples to subspace (PCA) test_samples = np.array(map(lambda x: np.dot(fisher_imgs.T, (x.reshape(1,14400)-mean_vector).T).reshape(1,num_fishers), test_samples)) for i in range(len(class_numbers)): dist_eucl = np.array(map(lambda x: np.linalg.norm(test_samples[i]-x), projections)) dist_mahal = np.array(map(lambda x: np.linalg.norm((test_samples[i]-x)/std_dev), projections)) min_dists_eucl = [] min_dists_mahal = [] for j in range(len(class_numbers)): min_dists_eucl.append(min(dist_eucl[60*j:(60*j+60)])) min_dists_mahal.append(min(dist_mahal[60*j:(60*j+60)])) # Compute closest neighbour distance and second closest class's distance min_dist_eucl = min(min_dists_eucl) first_idx_eucl = min_dists_eucl.index(min_dist_eucl) min_dists_eucl[first_idx_eucl] = max(min_dists_eucl) min_dist_eucl2 = min(min_dists_eucl) second_idx_eucl = min_dists_eucl.index(min_dist_eucl2) min_dist_mahal = min(min_dists_mahal) first_idx_mahal = min_dists_mahal.index(min_dist_mahal) min_dists_mahal[first_idx_mahal] = max(min_dists_mahal) min_dist_mahal2 = min(min_dists_mahal) second_idx_mahal = min_dists_mahal.index(min_dist_mahal2) vector_eucl[i,0,k] = min_dist_eucl vector_eucl[i,1,k] = first_idx_eucl vector_eucl[i,2,k] = min_dist_eucl2 vector_eucl[i,3,k] = second_idx_eucl vector_mahal[i,0,k] = min_dist_mahal vector_mahal[i,1,k] = first_idx_mahal vector_mahal[i,2,k] = min_dist_mahal2 vector_mahal[i,3,k] = second_idx_mahal return vector_eucl, vector_mahal def add_letter(idx, val): """ idx: index of the current ytick idx type: int val: value of the current ytick val type: float or int This function is used to edit the labels of the y axis (yticks) """ if idx==0: return 'r =\n'+str(int(round(val))) else: return 'R =\n'+str(int(round(val))) def add_letter_float(idx, val): """ idx: index of the current ytick idx type: int val: value of the current ytick val type: float This function is used to edit the labels of the y axis (yticks) """ if idx==0: return 'r =\n'+str(round(val*100)/100) else: return 'R =\n'+str(round(val*100)/100) # ============================================================================= # LOAD IMAGES AND LABELS # ============================================================================= path = 'C:/Users/Pablo/Google Drive/TFM/Modified Images/' class_names = os.listdir(path) class_numbers = list(map(lambda x: int(x[0]), class_names)) images, labels = utils.load_images_and_labels(path) height = images.shape[1] # ============================================================================= # FISHERIMAGES: STATIC TRAINING LEAVING ONE (OF EACH CLASS) OUT # ============================================================================= vector_eucl, vector_mahal = compute_minimum_distances(len(class_numbers)-1) # ============================================================================= # SCATTER EUCLIDEAN DISTANCES # ============================================================================= plt.figure() colors = ['b','m','r','k','y','c','g'] plt.suptitle('Minimum euclidean distances\n(r: average distance to closest neighbour; R: average distance to closest neighbour of second closest class)') plot_handles = [] for i in range(len(class_numbers)): ax = plt.subplot('24'+str(i+1)) ax.set_title(class_names[i][4:], fontdict={'color':colors[i]}) plt.xticks([]) # hide x-axis values # Create random angles for a two-dimensional scattering plot rand_angles = np.random.rand(61) * 2 * np.pi x_vals = vector_eucl[i,0,:] * np.cos(rand_angles) y_vals = vector_eucl[i,0,:] * np.sin(rand_angles) rand_angles = np.random.rand(61) * 2 * np.pi x_vals2 = vector_eucl[i,2,:] * np.cos(rand_angles) y_vals2 = vector_eucl[i,2,:] * np.sin(rand_angles) save_handle = True for j in range(61): if save_handle and int(vector_eucl[i,1,j]) == i: plot_handles.append(plt.plot(x_vals[j], y_vals[j], color=colors[int(vector_eucl[i,1,j])], marker='.', markerSize=2.3, label=class_names[i])[0]) save_handle = False else: plt.plot(x_vals[j], y_vals[j], color=colors[int(vector_eucl[i,1,j])], marker='.', markerSize=2.3) plt.plot(x_vals2[j], y_vals2[j], color=colors[int(vector_eucl[i,3,j])], marker='.', markerSize=2.3) # Plot circles with average distances r1 = np.mean(vector_eucl[i,0,:]) r2 = np.mean(vector_eucl[i,2,:]) col1 = colors[np.argmax(np.bincount(vector_eucl[i,1].astype(np.int)))] col2 = colors[np.argmax(np.bincount(vector_eucl[i,3].astype(np.int)))] utils.draw_circumference(ax, [0,0], r1, col1) utils.draw_circumference(ax, [0,0], r2, col2) # Draw circle and toroid w = Wedge((0, 0), vector_eucl[i,0].max(), 0, 360, fc=col1, ec=None, alpha=0.2) ax.add_artist(w) limit_val = vector_eucl[i,2].max() w = Wedge((0, 0), limit_val, 0, 360, width=limit_val-vector_eucl[i,2].min(), fc=col2, ec=None, alpha=0.2) ax.add_artist(w) # Set and colour the yticks plt.plot([-limit_val, 0], [r1, r1], color=col1, lineWidth=0.4, alpha=0.3) plt.plot([-limit_val, 0], [r2, r2], color=col2, lineWidth=0.4, alpha=0.3) ax.set_yticks([r1, r2]) ax.set_yticklabels([add_letter(idx, x) for idx, x in enumerate(ax.get_yticks())]) [t.set_color(i) for (i,t) in zip([col1, col2], ax.yaxis.get_ticklabels())] # # ax.axis('equal') # ax.set_autoscale_on(False) ax.axis([-limit_val, limit_val, -limit_val, limit_val]) # Add legend plt.legend(handles=plot_handles, loc=2, bbox_to_anchor=(1.4,.9)) # Show maximized window plt.get_current_fig_manager().window.showMaximized() # ============================================================================= # SCATTER MAHALANOBIS DISTANCES # ============================================================================= # Plot predicted class of test samples plt.figure() colors = ['b','m','r','k','y','c','g'] plt.suptitle('Minimum mahalanobis distances\n(r: average distance to closest neighbour; R: average distance to closest neighbour of second closest class)') plot_handles = [] for i in range(len(class_numbers)): ax = plt.subplot('24'+str(i+1)) ax.set_title(class_names[i][4:], fontdict={'color':colors[i]}) plt.xticks([]) # hide x-axis values # Create random angles for a two-dimensional scattering plot rand_angles = np.random.rand(61) * 2 * np.pi x_vals = vector_mahal[i,0,:] * np.cos(rand_angles) y_vals = vector_mahal[i,0,:] * np.sin(rand_angles) rand_angles = np.random.rand(61) * 2 * np.pi x_vals2 = vector_mahal[i,2,:] * np.cos(rand_angles) y_vals2 = vector_mahal[i,2,:] * np.sin(rand_angles) save_handle = True for j in range(61): if save_handle and int(vector_mahal[i,1,j]) == i: plot_handles.append(plt.plot(x_vals[j], y_vals[j], color=colors[int(vector_mahal[i,1,j])], marker='.', markerSize=2.3, label=class_names[i])[0]) save_handle = False else: plt.plot(x_vals[j], y_vals[j], color=colors[int(vector_mahal[i,1,j])], marker='.', markerSize=2.3) plt.plot(x_vals2[j], y_vals2[j], color=colors[int(vector_mahal[i,3,j])], marker='.', markerSize=2.3) # Plot circumferences with average distances r1 = np.mean(vector_mahal[i,0,:]) r2 = np.mean(vector_mahal[i,2,:]) col1 = colors[np.argmax(np.bincount(vector_mahal[i,1].astype(np.int)))] col2 = colors[np.argmax(np.bincount(vector_mahal[i,3].astype(np.int)))] utils.draw_circumference(ax, [0,0], r1, col1) utils.draw_circumference(ax, [0,0], r2, col2) # Draw circle and toroid w = Wedge((0, 0), vector_mahal[i,0].max(), 0, 360, fc=col1, ec=None, alpha=0.2) ax.add_artist(w) limit_val = vector_mahal[i,2].max() w = Wedge((0, 0), limit_val, 0, 360, width=limit_val-vector_mahal[i,2].min(), fc=col2, ec=None, alpha=0.2) ax.add_artist(w) # Set and colour the yticks plt.plot([-limit_val, 0], [r1, r1], color=col1, lineWidth=0.4, alpha=0.3) plt.plot([-limit_val, 0], [r2, r2], color=col2, lineWidth=0.4, alpha=0.3) ax.set_yticks([r1, r2]) ax.set_yticklabels([add_letter_float(idx, x) for idx, x in enumerate(ax.get_yticks())]) [t.set_color(i) for (i,t) in zip([col1, col2], ax.yaxis.get_ticklabels())] ax.axis([-limit_val, limit_val, -limit_val, limit_val]) # Add legend plt.legend(handles=plot_handles, loc=2, bbox_to_anchor=(1.4,.9)) # Show maximized window plt.get_current_fig_manager().window.showMaximized() plt.show()
C++
UTF-8
422
2.796875
3
[]
no_license
#include "http.h" void HTTP::parser(string url){ string::size_type idx = url.find(':'); if( idx != string::npos){ url = url.substr(idx+3); } idx = url.find('/'); m_host = url.substr(0,idx); m_url = url.substr(idx+1); } void HTTP::connect(){ } #ifdef DEBUG void HTTP::show() const{ std::cout << "HOST: " << m_host << "\nURL: " << m_url << std::endl; } #endif
Python
UTF-8
9,120
2.734375
3
[ "MIT" ]
permissive
import cv2 import os import imageio import numpy as np DIR_PATH = os.path.dirname(os.path.realpath(__file__)) def resize_frame(frame, new_side_len): # min_height_chamber2 = 506 # min_width_chamber2 = 416 # # max_height_chamber2 = 708 # max_width_chamber2 = 1036 # # min_height_chamber4 = 514 # min_width_chamber4 = 446 # # max_height_chamber4 = 718 # max_width_chamber4 = 1104 height = frame.shape[0] width = frame.shape[1] max_side_len = max(height, width) # padding with np.nan values in order to get a square input. if max_side_len == height: frame_pad = np.empty((height, height)) frame_pad[:] = np.nan padding = max_side_len - width if (padding % 2) == 0: frame_pad[:, range((padding // 2), (max_side_len - padding // 2))] = frame else: frame_pad[:, range(((padding + 1) // 2), (max_side_len - (padding - 1) // 2))] = frame else: frame_pad = np.empty((width, width)) frame_pad[:] = np.nan padding = max_side_len - height if (padding % 2) == 0: frame_pad[range((padding // 2), (max_side_len - padding // 2)), :] = frame else: frame_pad[range(((padding + 1) // 2), (max_side_len - (padding - 1) // 2)), :] = frame # resizing frame_res = cv2.resize(frame_pad, (new_side_len, new_side_len), interpolation=cv2.INTER_AREA) return frame_res def crop_outer_part(img, info): """ remove parts around the ECHO """ lower = int(info["height"] / 10) # remove lower part because of changing time in the bar upper = int(info["height"] / 8) # 5.8) # remove upper part because of the moving ECG right = int(info["width"] / 7.7) # remove right part because of changing pulse (ppm) display img[0:lower:, :] = 0 img[-upper:, :] = 0 img[:, -right:] = 0 return img def get_slope(x1, y1, x2, y2): # returns the slope of a line going between the two points try: return (float(y2) - y1) / (float(x2) - x1) except ZeroDivisionError: # line is vertical return None def yintercept(x, y, slope): """Get the y intercept of a line segment""" if slope is not None: return y - slope * x else: return None def get_corner_point(mask, corner_specification): """ calculates the corner points of the mask """ height = mask.shape[0] width = mask.shape[1] if corner_specification == "lowest": # start at the top left for x in range(0, height): for y in range(0, width): if mask[x, y] == 1: return x, y if corner_specification == "highest": # start from the bottom left for x in range(height - 1, 0, -1): for y in range(0, width): if mask[x, y] == 1: return x, y if corner_specification == "right": # start from the bottom right for y in range(width - 1, 0, -1): for x in range(height - 1, 0, -1): if mask[x, y] == 1: return x, y if corner_specification == "left": # start from the bottom left for y in range(0, width): for x in range(height - 1, 0, -1): if mask[x, y] == 1: return x, y def remove_colored_pixel(frame_bgr): """removes colored pixels and returns a grey scale image """ frame_hsv = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2HSV) # set all colored pixels to black frame_hsv[frame_hsv[:, :, 1] > 80] = 0 # convert from HSV to BRG to GREY frame = cv2.cvtColor(frame_hsv, cv2.COLOR_HSV2BGR) frame_grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) return frame_grey def morphological_transformation_foreground(foreground): kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (80, 80)) foreground = cv2.morphologyEx(foreground, cv2.MORPH_CLOSE, kernel) vertical = int(foreground.shape[0] / 5) horizontal = int(foreground.shape[1] / 5) foreground[0:vertical, 0:horizontal] = 0 foreground[0:vertical, -horizontal:] = 0 return foreground def morphological_transformation_mask(mask): kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) return mask def standardize_ndarray(ndarray): # takes a n-dim array and standardizes it to zero mean and std 1 ignoring 'nan' values. # takes an ECHO and standardizes the video to zero mean and std. of one. # the result can optionally be rescaled to greyscale (values from 0 to 255) mean = np.nanmean(ndarray, keepdims=True) std = np.nanstd(ndarray, keepdims=True) z = np.divide((ndarray - mean), std) return z def rgb_2_gray(frame): return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) def calculate_gradients(array_2d): laplacian = cv2.Laplacian(array_2d, cv2.CV_64F) sobelx = cv2.Sobel(array_2d, cv2.CV_64F, 1, 0, ksize=5) sobely = cv2.Sobel(array_2d, cv2.CV_64F, 0, 1, ksize=5) return laplacian def opt_triangular_points(mask,foreground,validate_cropping,out_file_dir,file_path,file_name): height = foreground.shape[0] width = foreground.shape[1] x_low, y_low = get_corner_point(foreground, "lowest") x_high, y_high = get_corner_point(foreground, "highest") x_right, y_right = get_corner_point(foreground, "right") x_left, y_left = get_corner_point(foreground, "left") if np.sum(mask) > mask.shape[0] * mask.shape[1] * 0.9: print("Broken (all white) overlay!") else: # correct lowest point down to triangle peak y_1 = y_low while mask[x_low, y_1] > 0: # do not go further left when in the "writing" bar if np.sum(mask[x_low, :]) > width / 2: break y_1 -= 1 y_2 = y_low while mask[x_low, y_2] > 0: # do not go further right when in the "writing" bar if np.sum(mask[x_low, :]) > width / 2: break y_2 += 1 # take middle point and go down y_low_opt = int((y_1 + y_2) / 2) x_low_opt = x_low while x_low_opt > 0 and mask[x_low_opt, y_low_opt] > 0: # do not go further down when the "writing" bar is reached if np.sum(mask[x_low_opt, :]) > width / 2: x_low_opt += 5 # correct for some pixel break x_low_opt -= 1 # correct left and right points y_left_opt = y_left while y_left_opt > 0 and mask[x_left, y_left_opt] > 0: y_left_opt -= 1 y_right_opt = y_right while y_right_opt < width and mask[x_right, y_right_opt] > 0: y_right_opt += 1 # use optimized points x_low = x_low_opt y_low = y_low_opt y_left = y_left_opt y_right = y_right_opt # first line m1 = get_slope(x_low, y_low, x_left, y_left) b1 = yintercept(x_low, y_low, m1) # second line m2 = get_slope(x_low, y_low, x_right, y_right) b2 = yintercept(x_low, y_low, m2) # optimize (second step) x_middle = int((x_low + x_high) / 2) y_middle_left = np.math.ceil((m1 * x_middle + b1)) y_middle_right = int(m2 * x_middle + b2) # correct left and right points y_middle_left_opt = y_middle_left while y_middle_left_opt > 0 and mask[x_middle, y_middle_left_opt] > 0: y_middle_left_opt -= 1 y_middle_right_opt = y_middle_right while y_middle_right_opt < width and mask[x_middle, y_middle_right_opt] > 0: y_middle_right_opt += 1 if y_middle_right_opt >= width: y_middle_right_opt = width - 1 # right opt. line m2 = get_slope(x_low, y_low, x_high, y_middle_right_opt) b2 = yintercept(x_low, y_low, m2) else: # right opt. line m2 = get_slope(x_low, y_low, x_middle, y_middle_right_opt) b2 = yintercept(x_low, y_low, m2) # left opt. line m1 = get_slope(x_low, y_low, x_middle, y_middle_left_opt) b1 = yintercept(x_low, y_low, m1) # correct left/right (y-coord) corner points if y_right < y_middle_right_opt: y_right = y_middle_right_opt x_right = x_middle if y_left > y_middle_left_opt: y_left = y_middle_left_opt x_left = x_middle for x in range(0, height): for y in range(0, width): # select all points inside the triangle if m1 * x + b1 <= y <= m2 * x + b2 and x < x_high: foreground[x, y] = 1 else: foreground[x, y] = np.nan return foreground, (x_low, y_left), (x_high, y_right) def save_picture(out_file_dir, file_path, pic): out_file_path = os.path.join(out_file_dir, os.path.splitext(os.path.basename(file_path))[0] + '.jpg') os.makedirs(out_file_dir, exist_ok=True) imageio.imwrite(out_file_path, pic)
Swift
UTF-8
3,509
3.015625
3
[]
no_license
// // PlanningCalculator.swift // BabyGenderPlanning // // Created by Dmitriy Petrov on 01.07.2020. // Copyright © 2020 BytePace. All rights reserved. // import Foundation class PlanningCalculator { let bloodCalculator: BloodCalculator let freymanDobrotinCalculator: FreymanDobrotinCalculator let conceptionDateCalculator: ConceptionDateCalculator init(bloodCalculator: BloodCalculator = .init(), freymanDobrotinCalculator: FreymanDobrotinCalculator = .init(), conceptionDateCalculator: ConceptionDateCalculator = .init()) { self.bloodCalculator = bloodCalculator self.freymanDobrotinCalculator = freymanDobrotinCalculator self.conceptionDateCalculator = conceptionDateCalculator } func calculateByBlood(father: ParentInfo, mother: ParentInfo, periodInMonth: Int, desiredGender: Gender) -> CalculationInfo? { let conceptionDates = conceptionDateCalculator.getDatesOfConception(from: periodInMonth) let dates = bloodCalculator.calculateResultForPlanning(father: father, mother: mother, conceptionDates: conceptionDates, desiredGender: desiredGender) guard let planningResults = parseDates(dates) else { return nil } return CalculationInfo(id: randomUUID, method: .bloodRenewal, gender: desiredGender, calculationDate: Date(), father: father, mother: mother, planningResults: planningResults) } func calculateByFreymanDobrotin(father: ParentInfo, mother: ParentInfo, periodInMonth: Int, desiredGender: Gender) -> CalculationInfo? { let conceptionDates = conceptionDateCalculator.getDatesOfConception(from: periodInMonth) let dates = freymanDobrotinCalculator .calculateResultForPlanning(father: father, mother: mother, conceptionDates: conceptionDates, desiredGender: desiredGender) guard let planningResults = parseDates(dates) else { return nil } return CalculationInfo(id: randomUUID, method: .freymanDobroting, gender: desiredGender, calculationDate: Date(), father: father, mother: mother, planningResults: planningResults) } } // MARK: - Helper methods extension PlanningCalculator { func parseDates(_ dates: [Date]) -> [PlanningResultInfo]? { guard !dates.isEmpty else { return nil } let datesDictionary = Dictionary(grouping: dates, by: { $0.month }) let planningResults = datesDictionary .compactMap { dict -> PlanningResultInfo? in guard let month = Month(rawValue: dict.key - 1), let year = dict.value.first?.year else { return nil } let days = dict.value.map { $0.day } return PlanningResultInfo(id: randomUUID, month: month, year: year, days: days) } .sorted(by: { lhs, rhs in guard lhs.year == rhs.year else { return lhs.year < rhs.year } return lhs.month.rawValue < rhs.month.rawValue }) return planningResults } }
Python
UTF-8
823
3
3
[]
no_license
def kmp(pat, txt): plen = len(pat) tlen = len(txt) lps = [0] * plen ti = 0 pindex = 0 lps1(pat, plen, lps) for i in range(tlen): if pat[pindex] == txt[ti]: pindex += 1 ti += 1 if pindex == plen: print("pattern found at" + str(ti - pindex)) pindex = lps[pindex - 1] elif ti < tlen and pat[pindex] != txt[ti]: if pindex: pindex = lps[pindex - 1] else: ti += 1 def lps1(pat, plen, lps): i = 1 len = 0 while i < plen: if pat[i] == pat[len]: len += 1 i += 1 lps[i] = len else: if len: len = lps[len - 1] else: i += 1 kmp("ritu", "ritupraritu")
C#
UTF-8
2,132
3.78125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pattern.Decorator { #region Create an interface. public interface Shape { void Draw(); } #endregion #region Create concrete classes implementing the same interface. public class Rectangle : Shape { public void Draw() { Console.WriteLine("Shape: Rectangle"); } } public class Circle : Shape { public void Draw() { Console.WriteLine("Shape: Circle"); } } #endregion #region Create abstract decorator class implementing the Shape interface. public abstract class ShapeDecorator : Shape { protected Shape decoratedShape; public ShapeDecorator(Shape decoratedShape) { this.decoratedShape = decoratedShape; } public virtual void Draw() { decoratedShape.Draw(); } } #endregion #region Create concrete decorator class extending the ShapeDecorator class. public class RedShapeDecorator : ShapeDecorator { public RedShapeDecorator(Shape decoratedShape) : base(decoratedShape) { } public override void Draw() { decoratedShape.Draw(); setRedBorder(decoratedShape); } private void setRedBorder(Shape decoratedShape){ Console.WriteLine("Border Color: Red"); } } #endregion class Program { static void Main(string[] args) { Shape circle = new Circle(); Shape redCircle = new RedShapeDecorator(new Circle()); Shape redRectangle = new RedShapeDecorator(new Rectangle()); Console.WriteLine("-----Circle with normal border-----"); circle.Draw(); Console.WriteLine("-----Circle of red border-----"); redCircle.Draw(); Console.WriteLine("-----Rectangle of red border-----"); redRectangle.Draw(); Console.ReadKey(); } } }
JavaScript
UTF-8
11,774
2.6875
3
[]
no_license
$(document).ready(function() { var moveForce = 30; // max popup movement in pixels var rotateForce = 20; // max popup rotation in deg var watson_word_count_message; var userName; $(document).mousemove(function(e) { var docX = $(document).width(); var docY = $(document).height(); var moveX = (e.pageX - docX / 2) / (docX / 2) * -moveForce; var moveY = (e.pageY - docY / 2) / (docY / 2) * -moveForce; var rotateY = (e.pageX / docX * rotateForce * 2) - rotateForce; var rotateX = -((e.pageY / docY * rotateForce * 2) - rotateForce); $('.popup') .css('left', moveX + 'px') .css('top', moveY + 'px') .css('transform', 'rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)'); }); // Initialize Firebase -- this is a link to Eric's scratch Database var config = { apiKey: "AIzaSyDTbzUdtRlYpfkOZNwwWHXOg0iRmVgrEL4", authDomain: "who-is-scratch.firebaseapp.com", databaseURL: "https://who-is-scratch.firebaseio.com", projectId: "who-is-scratch", storageBucket: "who-is-scratch.appspot.com", messagingSenderId: "1079782059107" }; firebase.initializeApp(config); // Get a reference to the database service var database = firebase.database(); //initialize all modals $(".modal").modal(); //This sextion grabs all of the input from the input page. Note that in our production version, //only the NAME will come from the input page, the rest of the content will come from Watson $("#submit").on("click", function(event) { event.preventDefault(); var inputName = $("#user_name").val(); var duplicateName = 0; var nameArray = []; var commentArray = []; var accuracy = 0; //these items will come from Watson, but for now, they are grabed from the input page var inputOpen = $("#openness").val(); var inputCons = $("#conscientiousness").val(); var inputExt = $("#extraversion").val(); var inputAgree = $("#agreeableness").val(); var inputEmot = $("#emotional_range").val(); //get a snapshot of the database and create an Array with all of the names currently stored database.ref().on("child_added", function(childSnapshot) { var name = childSnapshot.val().Name; nameArray.push(name); }); duplicateName = nameArray.indexOf(inputName); if (duplicateName != "-1") { // call a modal to alert to a duplicate name $('#dupName').modal('open'); } else { var url = "https://www.reddit.com/user/" + inputName + "/comments.json"; $.getJSON(url, function(response) { //Add this variable to determine how many comments are returned in the Object //_____________________________________________________________________________________ var numComments = Object.keys(response.data.children).length; // change the middle criteria to use the numComments obtainted above for (i = 0; i < numComments; i++) { commentArray[i] = response.data.children[i].data.body; } var commentString = commentArray.toString(); var cleanString = cleaner(commentString); var computedStringLength = countString(cleanString); //check the string length to determine if we have at least 100 words to send to Watson //_____________________________________________________________________________________ if (computedStringLength < 100) { $('#shortString').modal('open'); } else { if (computedStringLength < 500) { accuracy = 0; watson(cleanString, inputName, accuracy); } else { accuracy = 1; watson(cleanString, inputName, accuracy); } } //function to trigger no username found Modal. }, function(data, status){ var check = data; }).fail(function(error){ $('#noName').modal('open'); }); } // This clears the input form $("#user_name").val(""); return; }); //whenever the database changes, pull the database contents and update the chart database.ref().on("child_added", function(childSnapshot) { var key = childSnapshot.key; var name = childSnapshot.val().Name; var openness = childSnapshot.val().Openness; var conscientiousness = childSnapshot.val().Conscientiousness; var extraversion = childSnapshot.val().Extraversion; var agreeableness = childSnapshot.val().Agreeableness; var emotional_range = childSnapshot.val().Emotional_Range; // build table var row = $("<tr align='center'>"); var cell_1 = $("<td>"); var cell_2 = $("<td>"); var cell_3 = $("<td>"); var cell_4 = $("<td>"); var cell_5 = $("<td>"); var cell_6 = $("<td>"); var cell_7 = $("<td>"); var delete_button = $("<span>"); row.attr("id", "row" + key); row.attr("class", key); delete_button.attr("id", key); delete_button.addClass("btn glyphicon glyphicon-trash"); cell_1.append(delete_button); // ToDo: I need to append an href to Cell2 so that we can link to it's chart.... cell_2.append(name); cell_3.append(openness); cell_4.append(conscientiousness); cell_5.append(extraversion); cell_6.append(agreeableness); cell_7.append(emotional_range); row.append(cell_1); row.append(cell_2); row.append(cell_3); row.append(cell_4); row.append(cell_5); row.append(cell_6); row.append(cell_7); $("tbody").append(row); }); $(document).on("click", ".btn", function(event) { event.preventDefault(); var button_index = $(this).attr("id"); $("#row" + button_index).remove(); database.ref(button_index + "/").remove(); }); // This event handler changes the mouse type to a clickable hand when over a name $(document).on("mouseover", "#header tr:has(td)", function(e) { $(this).css("cursor", "pointer"); }); // This event handler highlights the name when clicked and also renders the chart $(document).on("click", "#header tr:has(td)", function(e) { $('#warning').empty(); $('#warning').removeClass(); userName = $(this).attr('class'); $("#header td").removeClass("highlight"); var clickedCell = $(e.target).closest("td"); clickedCell.addClass("highlight"); $('#' + clickedCell.parent().attr('id')).each(function(index, tr) { var rowData = $('td', tr).map(function(index, td) { return $(td).text(); }); var chartData = [parseFloat(rowData[2]), parseFloat(rowData[3]), parseFloat(rowData[4]), parseFloat(rowData[5]), parseFloat(rowData[6])]; renderChart(chartData); getMessageByName(rowData[1]); }); }); function renderChart(chartData) { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', axisX: { title: "Axis Title in Tahoma Font", titleFontFamily: "tahoma" }, data: { labels: ["Openness", "Conscientiousness", "Extraversion", "Agreeableness", "Emotional Range"], datasets: [{ label: "Personality Chart", backgroundColor: ["blue", "orange", "teal", "red", "purple"], data: chartData, fontSize: 30, }] }, // Configuration options go here options: { legend: { display: false }, title: { display: true, text: 'Personality Profile For ' + userName, fontSize: 30, fontColor: "black" }, scales: { yAxes: [{ ticks: { beginAtZero: true, fontSize: 20 } }], xAxes: [{ ticks: { fontSize: 20 } }] } } }); }; function watson(arg1, arg2, arg3) { $.ajax({ beforeSend: function(xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa('b70d03c0-98b6-4779-a114-492044d84740' + ":" + 'kxEYfXWtvODD')); }, url: "https://cors-anywhere.herokuapp.com/https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13", headers: { 'Content-Type': 'text/plain;charset=utf-8' }, method: "POST", data: arg1 }).then(function(response) { firebase.database().ref(arg2).set({ Name: arg2, Accuracy: arg3, Openness: response.personality[0].percentile.toFixed(3), Conscientiousness: response.personality[1].percentile.toFixed(3), Extraversion: response.personality[2].percentile.toFixed(3), Agreeableness: response.personality[3].percentile.toFixed(3), Emotional_Range: response.personality[4].percentile.toFixed(3), watson_word_count_message: response.word_count_message || null }); window.location = "table_proto.html"; }); }; function cleaner(string) { var stringArray = string.split(" "); for (x = 0; x < stringArray.length; x++) { if (stringArray[x].search("http") != "-1") { stringArray[x] = ""; } else { if (stringArray[x].search("www") != "-1") { stringArray[x] = ""; } } } return stringArray.join(" "); } //this function counts the number of spaces in the string function countString(string) { var rawStringLength = string.length; var spaceCount = 0; for (i = 0; i < rawStringLength; i++) { if (string[i] == " ") { spaceCount++ } } var actualStringLength = rawStringLength - spaceCount; return actualStringLength; } function getMessageByName(name) { var database = firebase.database(); database.ref(name).on('value', function(snapshot) { if (snapshot.val().Accuracy === 0) { $('#warning').addClass("warning glyphicon glyphicon-warning-sign"); $('#warning').html(" " + "There were less than 500 words in the input. For better result we need more words."); } }); } }); //------------------------------------------------
Markdown
UTF-8
1,246
2.71875
3
[]
no_license
# PackGen Go based Packet Generator # Help bash# ./PackGen --help Usage of ./PackGen: -c int Number of connections to be generated with auto-generated MAC and IP (default 10) -di string destination ip (default "127.0.0.1") -dm string destination MAC address (default "FF:FF:FF:FF:FF:FF") -i string device name (default "lo") -r int Rate of packet generation needed in seconds (default 30) -si string source ip (default "20.0.0.1") -sm string Src MAC address (default "00:01:02:00:00:00") # Example Usage bash# ./PackGen -c 1000 -di 40.40.40.1 -dm 00:0c:29:f2:cf:73 -i ens224 -r 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 CurrentRate is 40 Done generating packets. Good Bye!!! bash#
Markdown
UTF-8
11,964
2.765625
3
[ "MIT" ]
permissive
# 0x16. C - Simple Shell ![Build Status](https://travis-ci.org/joemccann/dillinger.svg?branch=master) ## Resources **Read or watch**: * [Unix shell](https://intranet.hbtn.io/rltoken/RsZhUQ_26du3YUYKXO3gXA "Unix shell") * [Thompson shell](https://intranet.hbtn.io/rltoken/CNhUqQ5TFpdvFGsd1Meyig "Thompson shell") * [Ken Thompson](https://intranet.hbtn.io/rltoken/G_kMmrcR7rm3uXsiVk1F0w "Ken Thompson") * [Everything you need to know to start coding your own shell](https:///rltoken/NLmjz6DsgyNjdD7GwL6VRA) **man or help**: * `sh` (_Run `sh` as well_) ## General Requirements * All files will be compiled on **Ubuntu** 14.04 LTS * C programs and functions will be compiled with `**gcc**` using the flags `-Wall` `-Werror``-Wextra` `and -pedantic` * Files should end with a new line * Use the `Betty` style. * The shell should not have any memory leaks * No more than 5 functions per file * All header files should be include guarded * Use system calls only when if needed to ([why?](https://intranet.hbtn.io/rltoken/StgX3y26fwPNV_DqlZLErw "why?")) ### List of allowed functions and system calls - `access` (man 2 access) - `chdir` (man 2 chdir) - `close` (man 2 close) - `closedir` (man 3 closedir) - `execve` (man 2 execve) - `exit` (man 3 exit) - `_exit` (man 2 _exit) - `fflush` (man 3 fflush) - `fork` (man 2 fork) - `free` (man 3 free) - `getcwd` (man 3 getcwd) - `getline` (man 3 getline) - `isatty` (man 3 isatty) - `kill` (man 2 kill) - `malloc` (man 3 malloc) - `open` (man 2 open) - `opendir` (man 3 opendir) - `perror` (man 3 perror) - `read` (man 2 read) - `readdir` (man 3 readdir) - `signal` (man 2 signal) - `stat` (__xstat) (man 2 stat) - `lstat` (__lxstat) (man 2 lstat) - `fstat` (__fxstat) (man 2 fstat) - `strtok` (man 3 strtok) - `wait` (man 2 wait) - `waitpid` (man 2 waitpid) - `wait3` (man 2 wait3) - `wait4` (man 2 wait4) - `write` (man 2 write) ### General Learning Objectives - Who designed and implemented the original Unix operating system - Who wrote the first version of the UNIX shell - Who invented the B programming language (the direct predecessor to the C programming language) - Who is Ken Thompson - How does a shell work - What is a pid and a ppid - How to manipulate the environment of the current process - What is the difference between a function and a system call - How to create processes - What are the three prototypes of `main` - How does the shell use the `PATH` to find the programs - How to execute another program with the `execve` system call - How to suspend the execution of a process until one of its children terminates - What is `EOF` / “end-of-file”? ![Shell](https://i.ibb.co/LN4TNFb/Shell.png) ### Who designed and Implemented original Unix operation system? [Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson), [Dennis Ritchie](https://en.wikipedia.org/wiki/Dennis_Ritchie), [Brian Kernighan](https://en.wikiquote.org/wiki/Brian_Kernighan) and [Douglas McIlroy](https://en.wikiquote.org/wiki/Doug_McIlroy) at Bell Labs The development began in 1969 and published internally in November 1971 and then announced to the world in October 1973 by Bell Labs. ### Who wrote the first version of the UNIX shell The first Unix shell was the sh, written by Ken Thompson computer programmer at [Bell Labs](https://en.wikipedia.org/wiki/Bell_Labs) and distributed with Versions 1 through 6 of Unix, from 1971 to 1975. Tough rudimentary by modern standards, it introduced many of the basic features common to all later Unix shells, including piping, simple control structures using `if` and `goto`, and filename wildcarding. Though not in current use, it is still available as part of some [Ancient UNIX Systems] ("Ancient UNIX Systems"). ### Who invented the B programming language (the direct predecessor to the C programming language) Kenneth Lane Thompson is an American pioneer of computer science. He worked at Bell Labs where he designed and implemented the original Unix operating system. He also invented the B programming language, the direct predecessor to the C programming language, and was one of the creators and early developers of the Plan 9 operating systems. Since 2006, Thompson works at Google, where he co-invented the Go programming language. ### What is a pid and a ppid ![PID-PPID](https://delightlylinux.files.wordpress.com/2012/06/pid.png) ### How to manipulate the environment of the current process` The shell uses an environment list that is used to store eviroment variables. This list is an array of strings, with the following format: `var=value`, where `var` is the name of the variable and `value`its value. As a reminder, you can list the environment with the command `printenv`. Actually, every process comes with an environment. When a new process is created, it inherits a copy of its parent’s environment. To access the entire environment within a process. Find the options below: * via the `main` function * via the global variable `environ` (man environ) An [_environment variable_](https://en.wikipedia.org/wiki/Environment_variable) is a variable whose value is set outside the program, typically through functionality built into the operating system or microservice. An environment variable is made up of a name/value pair, and any number may be created and available for reference at a point in time. - At runtime, the reference to the environment variable name is replaced with its current value. ### What is the Difference Between System Call and Function Call The main difference between system call and function call is that a **system call is a request for the kernel to access a resource while a function call is a request made by a program to perform a specific task.** ![SYSTEM-FUNCTION-CALL](https://pediaa.com/wp-content/uploads/2019/05/Difference-Between-System-Call-and-Function-Call-Comparison-Summary_1.jpg) ### How to create processes ![CHILD-PROCESS](https://i.ibb.co/0tktK2X/child-process.png) The system call `fork` creates a new child process, almost identical to the parent (the process that calls `fork`). Once `fork` successfully returns, two processes continue to run the same program, but with different stacks, datas and heaps. Using the return value of `fork`, it is possible to know if the current process is the father or the child: `fork` will return `0` to the child, and the PID of the child to the father. ![PIPELINE](https://i.ibb.co/n68HQdm/pipeline.png) Shell commands have a very specific purpose. More complicated commands can be constructed by combining simpler commands in a pipeline (|), so the output of one command becomes the input to another command. The standard shell syntax for pipelines(|) is to list multiple commands. When the shell runs commands forks new processes using **exec**, so the new process executes the program. ### What are the three prototypes of `main` `* int main(void) * int main(int ac, char **av)` * int main(int ac, char **av, char **env) ### How does the shell use the `PATH` to find the programs There are two types of files those that just contain information and those that are executable (files that are used to run functions and operations in the machine). The PATH variable is basically a list of directories that the computer search in to find an executable that has been requested. Any command name that is not built-in, is assumed to be the name of an executable program file, and the shell attempts to find an executable file with that name and runs it. (Shells find and run commands.) If the command name contains no slashes (like most command names, e.g. `date`), the shell looks for the executable file with that exact name in the list of directories kept in the `PATH` environment variable. Because `PATH` is a shell environment variable, you can change the list, and the list is usually exported and inherited by child processes of the shell. Directories in `PATH` are separated by colons, e.g. the following `PATH` variable contains three directories separated by colons: ``` $ echo "$PATH" /usr/local/bin:/bin:/usr/bin ``` When typing a file with no slashes, shell goes looking for the `executable file in the list of directories kept in the `PATH` environment variable, looking for an executable file named to execute. The shell tries each directory in the `PATH`, left-to-right, and runs the first executable program with the matching command name that it finds. The shell next tries the second directory name in the `PATH` variable (`/bin`) and looks for an executable file named `/bin/ls`, and this is the usual location of the ls. Since this file exists, the shell runs this executable program and ls appears The **slashes** in the pathname prevent the shell from using `PATH` to look up the command name, so the shell executes it directly. ### How to execute another program with the `execve` system call The system call `execve` allows a process to execute another program. This system call loads the new program into the current process’ memory in place of the “previous” program: on success `execve` does not return to continue the rest of the “previous” program. The program invoked inherits the calling process’s PID, and any open file descriptors that are not set to close-on-exec. Signals pending on the calling process are cleared. Any signals set to be caught by the calling process are reset to their default behaviour. ### How to suspend the execution of a process until one of its children terminates A call to wait() blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, the parent continues its execution after wait system call instruction. Child process may terminate due to any of these: - It calls exit(); - It returns (an int) from main - It receives a signal (from the OS or another process) whose default action is to terminate. ### What is `EOF` / “end-of-file”? It is an acronym for ‘End Of File’. It refers to a state that may occur while reading a file, or anything that can be read using the semantics of file IO, such as reading from devices or streams in Linux. The state can be represented in some cases by a value which equates to that state. There is a C function, `feof()`, whihc can be used to test whether reading from a stream has caused the EOF state to be reached. In certain cases, it is possible to generate an EOF state, such as by typing Ctrl-D to terminate standard input to a process, such as a shell. Here is an example of our shell: <img src="/Images/Test-result.gif?raw=true"> ## FlowCharts <img src="/Images/Shell flow chart-main.c.jpg?raw=true"> main.c flowchart (main logic to capture user information) <img src="/Images/Shell flow chart-new_proc.jpg?raw=true"> create_proc flowchart (main logic to decide if an input is a valid command) <img src="/Images/Shell flow chart-process_selector.jpg?raw=true"> process_selector flowchart (main logic to call another executable file from c code) ## Installation Execute the following commmand in your terminal: ``` sudo apt install cowsay && git clone https://github.com/daorejuela1/simple_shell.git && gcc -Wall -Werror -Wextra -pedantic simple_shell/*.c -o simple_shell/hsh ``` ## Execute the simple shell Afters installing the shell you can run it in interactive mode or non-interactive mode ``` cd simple_shell/ ./hsh $ls $exit ``` ``` cd simple_shell/ echo "ls" | ./hsh ``` ## Run example file To run the example file use: ``` cd simple_shell/ Example/./test ``` ## To Do - [ ] Read files instead of standar input - [ ] Manage pipelines ## Social networks Follow us on Twitter Karen Campo [![Karen Campo](http://i.imgur.com/tXSoThF.png)](https://twitter.com/KarenCa96752258) David Orejuela [![David Orejuela](http://i.imgur.com/tXSoThF.png)](https://twitter.com/daorejuela14)
C++
UHC
1,838
3.109375
3
[]
no_license
#include<iostream> using namespace std; int length, visit[102][102], visit1[102][102], dirX[4] = { 0,1,0,-1 }, dirY[4] = { 1,0,-1,0 }; char arr[102][102], arr1[102][102]; void input(); void init(); void dfs(int x, int y, int color); int main() { int count = 0, count1 = 0; input(); /* ƴҶ*/ for (int i = 0; i < length; i++) { for(int j = 0; j < length; j++){ if (arr[i][j] == 'R') { dfs(j, i, 1); count++; } if (arr[i][j] == 'G') { dfs(j, i, 2); count++; } if(arr[i][j] == 'B'){ dfs(j, i, 3); count++; } } } init(); /* ϶*/ for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (arr[i][j] == 'G') { dfs(j, i, 2); count1++; } if (arr[i][j] == 'B') { dfs(j, i, 3); count1++; } } } cout << count << " " << count1 << endl; return 0; } void input() { cin >> length; for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { cin >> arr[i][j]; arr1[i][j] = arr[i][j]; } } } void init() { for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { visit[i][j] = 0; if (arr1[i][j] == 'R') arr[i][j] = 'G'; else arr[i][j] = arr1[i][j]; } } } void dfs(int x, int y, int color) { if (x < 0 || y < 0 || x >= length || y >= length) return; arr[y][x] = 'A'; visit[y][x] = 1; for (int i = 0; i < 4; i++) { int tmpx = x + dirX[i]; int tmpy = y + dirY[i]; if (color == 1 && !visit[tmpy][tmpx] && arr[tmpy][tmpx] == 'R') { dfs(tmpx, tmpy, color); } if (color == 2 && !visit[tmpy][tmpx] && arr[tmpy][tmpx] == 'G') { dfs(tmpx, tmpy, color); } if (color == 3 && !visit[tmpy][tmpx] && arr[tmpy][tmpx] == 'B') { dfs(tmpx, tmpy, color); } } }
Java
UTF-8
3,261
2.328125
2
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.program.database.module; import java.io.IOException; import db.*; import ghidra.util.exception.AssertException; import ghidra.util.exception.VersionException; class FragmentDBAdapterV0 extends FragmentDBAdapter { static final int V0_VERSION = 0; static final int V0_FRAGMENT_NAME_COL = 0; static final int V0_FRAGMENT_COMMENTS_COL = 1; static final Schema V0_FRAGMENT_SCHEMA = new Schema(V0_VERSION, "Key", new Field[] { StringField.INSTANCE, StringField.INSTANCE }, new String[] { "Name", "Comments" }); private Table fragmentTable; /** * Gets a version 0 adapter for the program tree fragment database table. * @param handle handle to the database containing the table. * @param create true if this constructor should create the table. * @param treeID associated program tree ID * @throws VersionException if the the table's version does not match the expected version * for this adapter. * @throws IOException if database IO error occurs */ public FragmentDBAdapterV0(DBHandle handle, boolean create, long treeID) throws VersionException, IOException { String tableName = getTableName(treeID); if (create) { fragmentTable = handle.createTable(tableName, V0_FRAGMENT_SCHEMA, new int[] { V0_FRAGMENT_NAME_COL }); } else { fragmentTable = handle.getTable(tableName); if (fragmentTable == null) { throw new VersionException("Missing Table: " + tableName); } int version = fragmentTable.getSchema().getVersion(); if (version != V0_VERSION) { throw new VersionException(VersionException.NEWER_VERSION, false); } } } @Override public DBRecord createFragmentRecord(long parentFragmentID, String name) throws IOException { long key = fragmentTable.getKey(); if (key == 0) { key = 1; } DBRecord record = V0_FRAGMENT_SCHEMA.createRecord(key); record.setString(V0_FRAGMENT_NAME_COL, name); fragmentTable.putRecord(record); return record; } @Override DBRecord getFragmentRecord(long key) throws IOException { return fragmentTable.getRecord(key); } @Override DBRecord getFragmentRecord(String name) throws IOException { Field[] keys = fragmentTable.findRecords(new StringField(name), V0_FRAGMENT_NAME_COL); if (keys.length == 0) { return null; } if (keys.length > 1) { throw new AssertException("Found " + keys.length + " fragments named " + name); } return fragmentTable.getRecord(keys[0]); } @Override void updateFragmentRecord(DBRecord record) throws IOException { fragmentTable.putRecord(record); } @Override boolean removeFragmentRecord(long childID) throws IOException { return fragmentTable.deleteRecord(childID); } }
C
UTF-8
7,036
2.671875
3
[]
no_license
// Translation table for common custom characters. #define CUSTOM_CHAR_MAP_LEN 38 const uint16_t customCharMapChars[CUSTOM_CHAR_MAP_LEN] = { 0x120, // 0 - all blank (match). 0x1F8, // 1 - all filled (match). 0x1F0, // 2 - one pixel bar, left (match). 0x1F1, // 3 - two pixel bar, left (match). 0x1F2, // 4 - three pixel bar, left (match). 0x1F3, // 5 - 4 pixel bar, left (match). 0x1F4, // 6 - 1 pixel bar, right (match). 0x1F5, // 7 - 2 pixel bar, right (match). 0x1F6, // 8 - 3 pixel bar, right (match). 0x1F7, // 9 - 4 pixel bar, right (match). 0x25F, // 10 - 1 pixel bar, bottom (match). 0x25F, // 11 - 2 pixel bar, bottom. 0x2DC, // 12 - 3 pixel bar, bottom. 0x2DC, // 13 - 4 pixel bar, bottom (match). 0x2DC, // 14 - 5 pixel bar, bottom. 0x2DB, // 15 - 6 pixel bar, bottom. 0x0AF, // 16 - 1 pixel bar, top (match). 0x0AF, // 17 - 2 pixel bar, top. 0x2DF, // 18 - 3 pixel bar, top (match). 0x2DF, // 19 - 4 pixel bar, top. 0x2DB, // 20 - 5 pixel bar, top. 0x2DB, // 21 - 6 pixel bar, top. 0x1F0, // 22 - 1 pixel bar, left + full low horizontal bar. 0x1F1, // 23 - 2 pixel bar, left + full low horizontal bar. 0x1F2, // 24 - 3 pixel bar, left + full low horizontal bar. 0x1F3, // 25 - 4 pixel bar, left + full low horizontal bar. 0x1F4, // 26 - 1 pixel bar, right + full low horizontal bar. 0x1F5, // 27 - 2 pixel bar, right + full low horizontal bar. 0x1F6, // 28 - 3 pixel bar, right + full low horizontal bar. 0x1F7, // 29 - 4 pixel bar, right + full low horizontal bar. 0x1FC, // 30 - Filled upward arrow -> unfilled arrow. 0x1EC, // 31 - Filled heart -> filled circle. 0x1ED, // 32 - Unfilled heart -> unfilled circle. 0x1DB, // 33 - Open checkbox -> box. 0x1E0, // 34 - Checked checkbox -> box with horz line across. 0x09F, // 35 - Grayed checkbox -> 100% dither. 0x19B, // 36 - Left filled triangle. 0x199, // 37 - Right filled triangle. }; const uint8_t customCharMapPixels[CUSTOM_CHAR_MAP_LEN * 7] = { // 0 - all blank. 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, // 1 - all filled. 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, // 2 - one pixel bar, left. 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, // 3 - two pixel bar, left. 0b11000, 0b11000, 0b11000, 0b11000, 0b11000, 0b11000, 0b11000, // 4 - three pixel bar, left. 0b11100, 0b11100, 0b11100, 0b11100, 0b11100, 0b11100, 0b11100, // 5 - 4 pixel bar, left. 0b11110, 0b11110, 0b11110, 0b11110, 0b11110, 0b11110, 0b11110, // 6 - 1 pixel bar, right. 0b00001, 0b00001, 0b00001, 0b00001, 0b00001, 0b00001, 0b00001, // 7 - 2 pixel bar, right. 0b00011, 0b00011, 0b00011, 0b00011, 0b00011, 0b00011, 0b00011, // 8 - 3 pixel bar, right. 0b00111, 0b00111, 0b00111, 0b00111, 0b00111, 0b00111, 0b00111, // 9 - 4 pixel bar, right. 0b01111, 0b01111, 0b01111, 0b01111, 0b01111, 0b01111, 0b01111, // 10 - 1 pixel bar, bottom. 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, // 11 - 2 pixel bar, bottom. 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, // 12 - 3 pixel bar, bottom. 0b00000, 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, // 13 - 4 pixel bar, bottom. 0b00000, 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, // 14 - 5 pixel bar, bottom. 0b00000, 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, // 15 - 6 pixel bar, bottom. 0b00000, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, // 16 - 1 pixel bar, top. 0b11111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, // 17 - 2 pixel bar, top. 0b11111, 0b11111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, // 18 - 3 pixel bar, top. 0b11111, 0b11111, 0b11111, 0b00000, 0b00000, 0b00000, 0b00000, // 19 - 4 pixel bar, top. 0b11111, 0b11111, 0b11111, 0b11111, 0b00000, 0b00000, 0b00000, // 20 - 5 pixel bar, top. 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b00000, 0b00000, // 21 - 6 pixel bar, top. 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b00000, // 22 - one pixel bar, left + full low horizontal bar. 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111, // 23 - two pixel bar, left + full low horizontal bar. 0b11000, 0b11000, 0b11000, 0b11000, 0b11000, 0b11000, 0b11111, // 24 - three pixel bar, left + full low horizontal bar. 0b11100, 0b11100, 0b11100, 0b11100, 0b11100, 0b11100, 0b11111, // 25 - 4 pixel bar, left + full low horizontal bar. 0b11110, 0b11110, 0b11110, 0b11110, 0b11110, 0b11110, 0b11111, // 26 - 1 pixel bar, right + full low horizontal bar. 0b00001, 0b00001, 0b00001, 0b00001, 0b00001, 0b00001, 0b11111, // 27 - 2 pixel bar, right + full low horizontal bar. 0b00011, 0b00011, 0b00011, 0b00011, 0b00011, 0b00011, 0b11111, // 28 - 3 pixel bar, right + full low horizontal bar. 0b00111, 0b00111, 0b00111, 0b00111, 0b00111, 0b00111, 0b11111, // 29 - 4 pixel bar, right + full low horizontal bar. 0b01111, 0b01111, 0b01111, 0b01111, 0b01111, 0b01111, 0b11111, // 30 - Filled upward arrow. 0b00100, 0b00100, 0b01110, 0b01110, 0b11111, 0b11111, 0b00100, // 31 - Filled heart. 0b11111, 0b10101, 0b00000, 0b00000, 0b00000, 0b10001, 0b11011, // 32 - Unfilled heart. 0b11111, 0b10101, 0b01010, 0b01110, 0b01110, 0b10101, 0b11011, // 33 - Open checkbox. 0b00000, 0b00000, 0b11111, 0b10001, 0b10001, 0b10001, 0b11111, // 34 - Checked checkbox. 0b00100, 0b00100, 0b11101, 0b10110, 0b10101, 0b10001, 0b11111, // 35 - Grayed checkbox. 0b00000, 0b00000, 0b11111, 0b10101, 0b11011, 0b10101, 0b11111, // 36 - Left filled triangle. 0b01000, 0b01100, 0b01110, 0b01111, 0b01110, 0b01100, 0b01000, // 37 - Left filled triangle. 0b01000, 0b01100, 0b01110, 0b01111, 0b01110, 0b01100, 0b01000, };
Python
UTF-8
1,449
3.15625
3
[]
no_license
import csv import datetime, time import random import calendar import holidays rows = [] csvfile = '../original_data/test.csv' training_data = list() holidays = holidays.UnitedStates() with open(csvfile, 'r') as original: reader = csv.reader(original) cnt = 1 for row in reader: if cnt == 1: row.append("YEAR") row.append("MONTH") row.append("DAY") row.append("DAY_OF_WEEK") row.append("HOUR") row.append("MINUTE") row.append("IS_HOLIDAY") else: year = random.randint(2010, 2011) month = random.randint(1, 12) date_range = calendar.monthrange(year, month)[1] day = random.randint(1, date_range) is_weekday = datetime.date(year, month, day).weekday() is_holiday = datetime.date(year, month, day) in holidays hour = random.randint(0, 24) if is_holiday == True: is_holiday = 1 else: is_holiday = 0 row.append(year) row.append(month) row.append(day) row.append(is_weekday) row.append(hour) row.append(random.randint(0, 59)) row.append(is_holiday) rows.append(row) cnt += 1; output = csv.writer(open('../generated_data/testing_with_dates.csv', 'w'), delimiter=',') output.writerows(rows)
C
UTF-8
6,120
2.71875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> #include "stack.h" #define EPSILON 1e-3 #define F(arg) cosh(arg)*cosh(arg)*cosh(arg)*cosh(arg) #define A 0.0 #define B 5.0 #define SLEEPTIME 1 int *tasks_per_process; double farmer(int); void worker(int); int main(int argc, char **argv ) { int i, myid, numprocs; double area, a, b; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); if(numprocs < 2) { fprintf(stderr, "ERROR: Must have at least 2 processes to run\n"); MPI_Finalize(); exit(1); } if (myid == 0) { // Farmer // init counters tasks_per_process = (int *) malloc(sizeof(int)*(numprocs)); for (i=0; i<numprocs; i++) { tasks_per_process[i]=0; } } if (myid == 0) { // Farmer area = farmer(numprocs); } else { //Workers worker(myid); } if(myid == 0) { fprintf(stdout, "Area=%lf\n", area); fprintf(stdout, "\nTasks Per Process\n"); for (i=0; i<numprocs; i++) { fprintf(stdout, "%d\t", i); } fprintf(stdout, "\n"); for (i=0; i<numprocs; i++) { fprintf(stdout, "%d\t", tasks_per_process[i]); } fprintf(stdout, "\n"); free(tasks_per_process); } MPI_Finalize(); return 0; } double farmer(int numprocs) { // Stack to store tasks stack *bag = new_stack(); double points[2]; double *data; double newdata[4]; // Populate stack with initial task points[0]=A; points[1]=B; push(points, bag); // States for whether workers are in use int worker1, worker2, worker3, worker4; worker4 = 0; worker3 = 0; worker2 = 0; worker1 = 0; // Double for the total double total = 0; // Other stuff... MPI_Status status; int tag; int source; // Loop goes here int i = 0; while(1){ i++; //printf("%d\n", i); if (worker1 == 0 && is_empty(bag) == 0){ // if worker1 is idle then assign task to worker 1 data = pop(bag); worker1 = 1; tasks_per_process[1] += 1; MPI_Send(data, 2, MPI_DOUBLE, 1, 1, MPI_COMM_WORLD); } if (worker2 == 0 && is_empty(bag) == 0){ // if worker1 is idle then assign task to worker 1 data = pop(bag); worker2 = 1; tasks_per_process[2] += 1; MPI_Send(data, 2, MPI_DOUBLE, 2, 1, MPI_COMM_WORLD); } if (worker3 == 0 && is_empty(bag) == 0){ // if worker1 is idle then assign task to worker 1 data = pop(bag); worker3 = 1; tasks_per_process[3] += 1; MPI_Send(data, 2, MPI_DOUBLE, 3, 1, MPI_COMM_WORLD); } if (worker4 == 0 && is_empty(bag) == 0){ // if worker1 is idle then assign task to worker 1 data = pop(bag); worker4 = 1; tasks_per_process[4] += 1; MPI_Send(data, 2, MPI_DOUBLE, 4, 1, MPI_COMM_WORLD); } MPI_Recv(newdata, 3, MPI_DOUBLE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); source = status.MPI_SOURCE; tag = status.MPI_TAG; if (tag == 1){ //if the tag is 1 then the values returned need to be pushed to the stack points[0]=newdata[0]; points[1]=newdata[1]; printf("%lf %lf\n", points[0], points[1] ); push(points, bag); points[0]=newdata[1]; points[1]=newdata[2]; printf("%lf %lf\n", points[0], points[1] ); push(points, bag); int c = is_empty(bag); } else { //if the tag is not 1 then the value needs to be added to the total total = total + newdata[0]; } switch(source){ case 1: worker1 = 0; break; case 2: worker2 = 0; break; case 3: worker3 = 0; break; case 4: worker4 = 0; break; } if (worker1 == 0 && worker2 == 0 && worker3 == 0 && worker4 == 0 && is_empty(bag) == 1) { break; } } MPI_Send(data, 2, MPI_DOUBLE, 1, 9, MPI_COMM_WORLD); MPI_Send(data, 2, MPI_DOUBLE, 2, 9, MPI_COMM_WORLD); MPI_Send(data, 2, MPI_DOUBLE, 3, 9, MPI_COMM_WORLD); MPI_Send(data, 2, MPI_DOUBLE, 4, 9, MPI_COMM_WORLD); return total; } void worker(int mypid) { //initiaise variables int i = 0; int tag; double left, right, fleft, fright, lrarea, mid, fmid, larea, rarea; double data[2]; double newdata[3]; MPI_Status status; while(1){ i++; MPI_Recv(data, 2, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); tag = status.MPI_TAG; if (tag == 9){ //if message has been sent with tag 9, this is the signal to stop and we should break the loop break; } else{ left = data[0]; right = data[1]; fleft = F(left); fright = F(right); lrarea = (fleft + fright) / 2 * (left - right); mid = (left + right) / 2; fmid = F(mid); larea = (fleft + fmid) * (mid - left) / 2; rarea = (fmid + fright) * (right - mid) / 2; if( fabs((larea + rarea) - lrarea) > EPSILON ) { newdata[0] = left; newdata[1] = mid; newdata[2] = right; MPI_Send(newdata, 3, MPI_DOUBLE, 0, 1, MPI_COMM_WORLD); }else{ newdata[0] = larea + rarea; newdata[1] = 0; newdata[2] = 0; MPI_Send(newdata, 3, MPI_DOUBLE, 0, 2, MPI_COMM_WORLD); } } } } /* # ----------------------------------------------------------------------------------------------- # # **************************** ___________ ___ _____ ____ ____ *************************** # # **************************** / ___/ | / _] |/ | \ *************************** # # **************************** ( \_| |/ [_| __| o | _ | *************************** # # **************************** \__ |_| |_| _] |_ | | | | *************************** # # **************************** / \ | | | | [_| _]| _ | | | *************************** # # **************************** \ | | | | | | | | | | | *************************** # # **************************** \___| |__| |_____|__| |__|__|__|__| *************************** # # ----------------------------------------------------------------------------------------------- # */
Python
UTF-8
411
4.3125
4
[]
no_license
# The usage of function "range()" for i in range(5): print(f'{i:<3}*') print() # create a list with range from 3 to 7 (8 not included) nums_1 = list(range(3,8)) print(nums_1) print() # create a list with range from 1 to 9 with a gap of 2 nums_2 = list(range(1,10,2)) print(nums_2) print() # create a list with range from 10 to 2 with a gap of -2 nums_3 = list(range(10,1,-2)) print(nums_3) print()
Python
UTF-8
4,830
2.65625
3
[]
no_license
import numpy as np import pandas as pd import scipy.stats as stats import matplotlib as plt import sklearn import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB #Create your df here: cupid = pd.read_csv("profiles.csv") #print(cupid.keys()) #print(cupid.job.value_counts()) #Mapping for new columns kids = { 'doesn&rsquo;t have kids': int(0), 'doesn&rsquo;t have kids, but might want them': int(0), 'doesn&rsquo;t have kids, and doesn&rsquo;t want any': int(0), 'doesn&rsquo;t have kids, but wants them': int(0), 'doesn&rsquo;t want kids': int(0), 'wants kids': int(0), 'might want kids': int(0), 'has kids' : int(1), 'has a kid': int(1), 'has kids, but doesn&rsquo;t want more': int(1), 'has a kid, but doesn&rsquo;t want more': int(1), 'has a kid, and might want more': int(1), 'has kids, and might want more': int(1), 'has a kid, and wants more': int(1), 'has kids, and wants more': int(1), } statuses = { 'single': 1, 'seeing someone': 2, 'available': 1, 'married': 2 } gender = { 'f': 1, 'm': 2 } orietation = { 'straight': 1, 'gay': 2, 'bisexual': 3 } drink = { 'not at all': 1, 'rarely': 2, 'socially': 3, 'very often': 4, 'desperately': 5 } drugged = { 'never':1, 'somtimes':2, 'often':3 } body_types = { 'used up':1, 'skinny':2, 'thin' :3, 'fit':4, 'athletic':5, 'jacked':6, 'average':7, 'a little extra':8, 'full figured':9, 'curvy':10, 'overweight':11, 'rather not say':12 } jobs = { 'other': 1, 'student': 2, 'science / tech / engineering': 3, 'computer / hardware / software': 4, 'artistic / musical / writer': 5, 'sales / marketing / biz dev': 6, 'medicine / health': 7, 'education / academia': 8, 'executive / management': 9, 'banking / financial / real estate': 10, 'entertainment / media': 11, 'law / legal services': 12, 'hospitality / travel': 13, 'construction / craftsmanship': 14, 'clerical / administrative': 15, 'political / government': 16, 'rather not say': 17, 'transportation': 18, 'unemployed': 19, 'retired': 20, 'military': 21, } #Creating new columns cupid['kids'] = cupid.offspring.map(kids) cupid['statuses'] = cupid.status.map(statuses) cupid['gender'] = cupid.sex.map(gender) cupid['orietation'] = cupid.orientation.map(orietation) cupid['drink'] = cupid.drinks.map(drink) cupid['body_types'] = cupid.body_type.map(body_types) cupid['drugged'] = cupid.drugs.map(drugged) cupid['jobs'] = cupid.job.map(jobs) #Grouping the Data and dropping NaNs data = cupid[[ 'age', 'kids', 'statuses', 'gender', 'orietation', 'drink', 'body_types', 'drugged', 'jobs' ]].dropna() #Normalizing the Data e = data.values scaler = preprocessing.MinMaxScaler() np_scaled = scaler.fit_transform(e) data = pd.DataFrame(np_scaled, columns=data.columns) print(data) #Training and Testing Data x = data[['age', 'body_types', 'statuses', 'orietation', 'jobs']] y = data[['kids']] #Splitting Train/Test Data x_train, x_test, y_train, y_test = train_test_split(x, y, train_size = 0.8, test_size = 0.2, random_state = 100) lr = LinearRegression() #Fitting the Data and predicting Y for LinearRegression lr_y_predicted = lr.fit(x_train, y_train).predict(x_test) print("The score of your Linear Regression model is %f" % (lr.score(x_test, y_test))) print("Here are the weightings of your Linear Regression model: \n%a" % (lr.coef_)) #Fitting the data for NaiveBayes gnb = GaussianNB() gnb_y_predicted = gnb.fit(x_train, y_train.values.ravel()).predict(x_test) print("The score of your Naive Bayes model is %f" % (gnb.score(x_test, y_test))) ##Plotting people who have kids vs people who don't ##Unsurprisingly most people looking for a relationship do not have children ##Can I predict whether someone on OKCupid has kids or not? cupid.kids.value_counts().plot(kind='bar', title='Users with Offspring') plt.xticks(ticks=[0,1], labels=[ "Don't Have Offspring", "Have Offspring" ], rotation='horizontal') plt.yticks(ticks=[4919, 19466]) plt.show() #Labels for Body Type Pie Chart labels = ([ 'Used up', 'Skinny', 'Thin' , 'Fit', 'Athletic', 'Jacked', 'Average', 'A Little Extra', 'Full Figured', 'Curvy', 'Overweight', 'Rather Not Say']) explode=[0, 0, 0, 0, 0, 0, 0, 0, 0.1, 0.2, 0.3, 0.4] #Body Type Pie Chart cupid.body_types.value_counts().plot(kind='pie', title="Body Types", labels=labels, wedgeprops={'linewidth':100}, explode=explode, rotatelabels=False) plt.ylabel('') plt.show()
Go
UTF-8
1,961
3.09375
3
[]
no_license
package main import ( "bufio" "os" "strconv" "strings" ) func main() { part1() part2() } func part1() { file, _ := os.Open("input/day13.txt") defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() departureTime64, _ := strconv.ParseInt(scanner.Text(), 10, 64) scanner.Scan() departureTime := int(departureTime64) schedulesStr := strings.Split(scanner.Text(), ",") schedules := make([]int, 0) for i := 0; i < len(schedulesStr); i += 1 { scheduleInt, err := strconv.ParseInt(schedulesStr[i], 10, 64) if err == nil { schedules = append(schedules, int(scheduleInt)) } } closestTime := make(map[int]int, 0) for i := 0; i < len(schedules); i += 1 { for j := 1; j*schedules[i] < departureTime; j += 1 { closestTime[schedules[i]] = (j + 1) * schedules[i] } } min := 1_000_000_000 schedule := -1 for k, v := range closestTime { if v < min { min = v schedule = k } } println((min - departureTime) * schedule) } func part2() { file, _ := os.Open("input/day13.txt") defer file.Close() scanner := bufio.NewScanner(file) scanner.Scan() scanner.Text() scanner.Scan() schedulesStr := strings.Split(scanner.Text(), ",") pairs := make([][2]int, 0) for i := 0; i < len(schedulesStr); i += 1 { id64, err := strconv.ParseInt(schedulesStr[i], 10, 64) if err == nil { id := int(id64) pairs = append(pairs, [2]int{id, i % id}) } } max := max(pairs) j := 1 for true { i := j*max[0] + max[1] if i < 0 { println("overflow") break } if fitsAll(i, pairs) { println(i) break } j += 1 } } func fitsAll(num int, pairs [][2]int) bool { for i := 0; i < len(pairs); i++ { if !fits(num, pairs[i]) { return false } } return true } func fits(num int, pair [2]int) bool { return num%pair[0]-pair[1] == 0 } func max(pairs [][2]int) [2]int { max := [2]int{-1, -1} for i := 0; i < len(pairs); i++ { if pairs[i][0] > max[0] { max = pairs[i] } } return max }
Java
UTF-8
2,384
2.46875
2
[]
no_license
package com.wochstudios.InfiniteSoundboards.adapters; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import com.wochstudios.InfiniteSoundboards.database.SoundboardContract; import com.wochstudios.InfiniteSoundboards.models.Sound; import com.wochstudios.InfiniteSoundboards.R; /** * Created by dave on 9/7/2015. */ public class SoundCursorAdapter extends CursorAdapter { public SoundCursorAdapter(Context con,Cursor cursor, int flags){ super(con,cursor,flags); } @Override public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { View view = LayoutInflater.from(context).inflate(R.layout.list_item, viewGroup, false); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView soundText = (TextView)view; soundText.setText(cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_TITLE))); } public Sound getSound(int postion){ Cursor cursor = getCursor(); Sound sound = new Sound(); if(cursor.moveToPosition(postion)){ sound.setTitle(cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_TITLE))); sound.setID(cursor.getInt(cursor.getColumnIndex(SoundboardContract.SoundsTable._ID))); sound.setSoundboardId(cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_SOUNDBOARD_ID))); sound.setUri(Uri.parse(cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_URI)))); } return sound; } /* private Sound convertRowToSound(Cursor cursor){ int id = cursor.getInt(cursor.getColumnIndex(SoundboardContract.SoundsTable._ID)); String title = cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_TITLE)); String soundboard_id = cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_SOUNDBOARD_ID)); String file_uri = cursor.getString(cursor.getColumnIndex(SoundboardContract.SoundsTable.COLUMN_URI)); return new Sound(id,title, Uri.parse(file_uri), soundboard_id); }*/ }
C++
UTF-8
2,016
3.3125
3
[]
no_license
#include <iostream> using namespace std; #include "queue.h" template <class T> queue<T>::queue() { front=NULL; rear=NULL; } template <class T> int queue<T>::isempty() { if(front==NULL) return 1; else return 0; } template <class T> void queue<T>::enqueue(T t,int priority) { node *temp=new node(); temp->next=NULL; temp->p=t; temp->priority=priority; if(!isempty()) { rear->next=temp; rear=temp; } else { front=temp; rear=temp; } } template <class T> int queue<T>::display(T a[]) { node *temp=new node(); temp=front; T b; int i=0; if(!isempty()) { while(temp!=NULL) { b=temp->p; a[i]=b; i++; temp=temp->next; } } else cout<<"\n\nQueue empty!!\nPLease enter records!!\n"; return i; } template <class T> T queue<T>::dequeue(int *flag) { T pt; if(!isempty()) { *flag=1; int high=0; node *temp1=new node(); node *prev=new node(); node *temp=new node(); temp=front; if(front==rear) { pt=front->p; front=NULL; rear=NULL; } else { while(temp!=NULL) { if(temp->priority>high) { high=temp->priority; temp1=temp; } temp=temp->next; } pt=temp1->p; prev=front; if(temp1==front) { front=front->next; delete temp1; } else { while(prev->next!=temp1) { prev=prev->next; } if(temp1==rear) { rear=prev; prev->next=NULL; delete temp1; } else { temp=temp1->next; delete temp1; prev->next=temp; } } } } else { cout<<"\n\nQueue empty!!\nPLease enter records!!\n"; *flag=0; } return pt; } template <class T> queue<T>::~queue() { node *temp=new node(); while(front!=NULL) { temp=front; front=front->next; delete(temp); } }
Go
UTF-8
2,688
2.640625
3
[]
no_license
package databaseOperator import ( "fmt" _ "github.com/Go-SQL-Driver/MySQL" "github.com/go-xorm/xorm" "log" "math/rand" "os" "tidb_yace/common" "time" ) func StartDabaseOperation(tomlConfig *common.TomlConfigStruct, logger *log.Logger) { // 初始化dbConfig dbParamet := initDbConfig(tomlConfig) // 初始化压测参数 yaceParam := initYace(tomlConfig) // 获取engine engine := getEngine(dbParamet, logger) // 创建数据表 //createTab(engine, logger) // 根据压测参数在测试表中造数据 fmt.Println("根据压测参数在测试表中造数据") for thread_id := 1; thread_id <= yaceParam.thread; thread_id++ { engine_thread_id := getEngine(dbParamet, logger) go makeData(engine_thread_id, logger, yaceParam) } // 从这个地方开始进入压测阶段,压测操作在insert、update、select中随机选择 for times := 1; times <= yaceParam.times; times++ { for thread_id := 1; thread_id <= yaceParam.thread; thread_id++ { var operation = []func(engine *xorm.Engine, logger *log.Logger,thread_id int){insertOperat, updateOperat, selectOperat} index := rand.Intn(3) startTime := time.Now() operation[index](engine, logger, thread_id) runTime := time.Since(startTime).Nanoseconds() logger.Println("thread is",thread_id, "runTime is",runTime) } } } // 创建数据表 func createTab(engine *xorm.Engine, logger *log.Logger){ err := engine.Sync2(new(user)) if err != nil { logger.Println("create table user is bad") os.Exit(1) } log.Println("create table user is ok") } // 初始化dbConfig func initDbConfig(tomlConfig *common.TomlConfigStruct) (DB *dbConfig) { //获取数据库连接参数 db := new(dbConfig) db.address = tomlConfig.Database.Address db.port = tomlConfig.Database.Port db.user = tomlConfig.Database.User db.passwd = tomlConfig.Database.Passwd db.schema = tomlConfig.Database.Schema db.charset = tomlConfig.Database.Charset return db } func initYace(tomlConfig *common.TomlConfigStruct) (yaceParam *yace) { yaceP := new(yace) yaceP.thread = tomlConfig.System.Thread yaceP.times = tomlConfig.System.Times yaceP.rows = tomlConfig.System.Rows return yaceP } func getEngine(dbParamet *dbConfig, logger *log.Logger) (dbEngine *xorm.Engine) { dbEndpoint := fmt.Sprintf("%s:%d", dbParamet.address, dbParamet.port) params := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=true", dbParamet.user, dbParamet.passwd, dbEndpoint, dbParamet.schema, dbParamet.charset) engine, err := xorm.NewEngine("mysql", params) if err != nil { logger.Println("connect db is bad",err) os.Exit(1) } fmt.Println("connect db is ok") return engine }
PHP
UTF-8
1,463
2.625
3
[]
no_license
<?php session_start(); include '../../MyDb.php'; date_default_timezone_set('PRC'); $name = $_POST['name']; $invite = $_POST['invite']; $code = $_POST['code']; $passWord = $_POST['password']; $phone = $_POST['phone']; $registTime = $loginTime = date("Y-m-d H:i:s"); //先判断验证码是否相等 if(isset($_SESSION['sms_code'])){ if ($code != $_SESSION['sms_code']){ echo "验证码错误!"; exit(); } }else{ echo '没有验证码信息,请尝试重新发送验证码'; } //邀请码 $invite = isset($invite)?$invite:0; $db = MyDb::getDb(); //先判断是否有相同名 $sql_check_name = "select * from user where name = ?"; $state = $db->prepare($sql_check_name); $result = $state->execute(array($name)); if($state->rowCount()>0){ echo '该用户名已注册,请换一个尝试!'; exit(); } //判断手机号是否已经注册过 $sql_check_phone = "select * from user where phone = ?"; $state = $db->prepare($sql_check_phone); $result = $state->execute(array($phone)); if($state->rowCount()>0){ echo '该手机号已注册,请登录,如忘记密码请重置密码!'; exit(); } //插入数据库 $sql_add_user = "insert into user (name,phone,password,registtime,logintime) values (?,?,?,?,?)"; $state = $db->prepare($sql_add_user); if ($state->execute(array($name,$phone,$passWord,$registTime,$loginTime))){ echo 'success'; }else{ echo '出了一点小问题,稍后再试。'; }
Java
UTF-8
5,291
2.125
2
[]
no_license
package de.sfgmbh.comlayer.organisation.views; import java.awt.Dimension; import java.awt.Font; import java.awt.SystemColor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import net.miginfocom.swing.MigLayout; import de.sfgmbh.comlayer.core.controller.ViewManager; import de.sfgmbh.comlayer.core.views.BaseTab; import de.sfgmbh.comlayer.organisation.controller.ChairTabBtnsControl; import de.sfgmbh.comlayer.organisation.controller.ChairTabCmbboxFilter; /** * The tab for the chair organization * * @author anna * */ public class ChairTab extends JPanel { private static final long serialVersionUID = 1L; private JTextField textFieldChairname_; private JTable chairOrgaTable_; private JLabel lblChairname_; private JScrollPane organisationTableScrollPane_; private JPanel buttonPanel_; private JButton btnAdd_; private JButton btnDelete_; private JLabel lblUniIcon_; private TableRowSorter<TableModel> rowSorter_; /** * Create the frame. */ public ChairTab() { initialize(); } private void initialize() { setMinimumSize(new Dimension(100, 10)); setMaximumSize(new Dimension(100, 50)); setLayout(new MigLayout( "", "[140px:140px:140px][10px:10px:10px][grow][grow][grow][grow][100px:100px:100px]", "[][][grow][bottom]")); JLabel lblChairorganisation = new JLabel("Lehrstuhlverwaltung"); lblChairorganisation.setFont(new Font("SansSerif", Font.BOLD, 13)); add(lblChairorganisation, "cell 0 0,alignx center,aligny bottom"); lblChairname_ = new JLabel("Lehrstuhlname:"); add(lblChairname_, "cell 2 0,aligny bottom"); textFieldChairname_ = new JTextField(); textFieldChairname_ .setToolTipText("<html>Sie können die Liste der <br> Lehrstühle über diesen<br>Filter begrenzen</html>"); textFieldChairname_.addActionListener(new ChairTabCmbboxFilter()); lblUniIcon_ = new JLabel(); lblUniIcon_ .setIcon(new ImageIcon( BaseTab.class .getResource("/de/sfgmbh/comlayer/core/images/UniBA_logo.png"))); lblUniIcon_.setMaximumSize(new Dimension(50, 50)); add(lblUniIcon_, "cell 6 0,alignx right,aligny top"); textFieldChairname_.setColumns(10); add(textFieldChairname_, "cell 2 1,growx"); add(ViewManager.getInstance().getCoreLiveTickerPanel(), "cell 0 2,grow, aligny top"); organisationTableScrollPane_ = new JScrollPane(); organisationTableScrollPane_.setMinimumSize(new Dimension(600, 500)); organisationTableScrollPane_.setPreferredSize(new Dimension(600, 500)); add(organisationTableScrollPane_, "flowx,cell 2 2 4 1,grow"); chairOrgaTable_ = new JTable(); chairOrgaTable_.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); chairOrgaTable_.setModel(ViewManager.getInstance() .getOrgaChairTableModel()); chairOrgaTable_.setShowVerticalLines(false); chairOrgaTable_.getColumnModel().removeColumn( chairOrgaTable_.getColumn("Hidden")); chairOrgaTable_.setBackground(SystemColor.activeCaption); organisationTableScrollPane_.setViewportView(chairOrgaTable_); // Enable table sorting for the model rowSorter_ = new TableRowSorter<TableModel>(); chairOrgaTable_.setRowSorter(rowSorter_); rowSorter_.setModel(ViewManager.getInstance().getOrgaChairTableModel()); rowSorter_.sort(); buttonPanel_ = new JPanel(); buttonPanel_.setLayout(null); buttonPanel_.setMinimumSize(new Dimension(80, 10)); buttonPanel_.setMaximumSize(new Dimension(100, 32767)); add(buttonPanel_, "cell 6 2,grow"); btnAdd_ = new JButton("hinzufügen"); btnAdd_.setToolTipText("<html>Klicken Sie hier <br>um einen neuen Lehrstuhl anzulegen</html>"); btnAdd_.addActionListener(new ChairTabBtnsControl("add")); btnAdd_.setBounds(6, 11, 88, 23); buttonPanel_.add(btnAdd_); JButton btnBearbeiten = new JButton("bearbeiten"); btnBearbeiten .setToolTipText("<html>Selektieren Sie einen Lehrstuhl <br> und klicken Sie hier um dessen Eigenschaften zu ändern</html>"); btnBearbeiten.addActionListener(new ChairTabBtnsControl("edit")); btnBearbeiten.setBounds(6, 45, 88, 23); buttonPanel_.add(btnBearbeiten); btnDelete_ = new JButton("l\u00F6schen"); btnDelete_ .setToolTipText("<html>Selektieren Sie einen Lehrstuhl<br> um ihn zu löschen</html>"); btnDelete_.addActionListener(new ChairTabBtnsControl("delete")); btnDelete_.setBounds(6, 79, 88, 23); buttonPanel_.add(btnDelete_); } /** * @return the textFieldChairname */ public JTextField getTextFieldChairname() { return textFieldChairname_; } /** * @return the chairOrgaTable */ public JTable getChairOrgaTable() { return chairOrgaTable_; } /** * @return the rowSorter */ public TableRowSorter<TableModel> getRowSorter() { return rowSorter_; } /** * @param rowSorter * the rowSorter to set */ public void setRowSorter(TableRowSorter<TableModel> rowSorter) { this.rowSorter_ = rowSorter; } }
Markdown
UTF-8
242
2.78125
3
[]
no_license
--- title: 将char转化为整数 date: 2019-08-11 23:31:53 tags: [charToInt] --- - b-a的值+10 结果11(注意等于12就会返回-1) `Character.digit('b',12)` - 如char[] 里面存的是数字则,结果是2 `Character.digit('2',10)`
Markdown
UTF-8
7,627
3.265625
3
[]
no_license
四十 司马青笑道:“那你又何必去理会他们呢,你应相信我能胜过铁钵和尚的,只要我不死,他们就没有指望了。” 上官红这才现出了忧急道:“青哥!你对这一战究竟有多少把握?” 司马青笑笑道:“我说有十分的把握你会不会相信?我说毫无把握你又会不会相信?” “我不知道,这一战本来已经可以取消了,但是你又把它给挑起来,大概是有几分把握,因为你并不是那种拿性命当儿戏的人,可是………我看周围的人,似乎没有一个人看好你的。” 司马青微笑道:“所以你又担心起来了。” “难道我不该担心吗,你是我的丈夫,对于你的生死安危,我比任何一个人都关心。” “原先你不是对我很有信心的吗?” “是的,可是这些人都认为你死定了似的。” “红红,两个人在未战之前就预测其胜负存亡,多少总该有点根据是不是?” “所以我才担心,每一个人都持有你必败的看法,总不会毫无根据的。” “测定胜负的根据是对双方武功深浅的了解,他们之认为我必败,是因为他们有的人在铁钵和尚手下吃过亏,有人则根据铁钵和尚以往的事迹与凶名而作的直觉,却并没有多大的根据的,因为这些人没有一个跟我交过手,对我的武功都一无所知。正如有人说一个人单独走在山野间,突然跳出一头大虫,听的人都会为之一惊,开始为那个遇虎的人担心了,没有人会替老虎担心的,但实际的情形并不如此,徒手搏虎的勇士多得很。” 上官红却道:“青哥,我不管有多少徒手搏虎的勇士,我只关心你,别人都认为你必败是根据什么我不知道,但即便每个人都认为你必胜,我仍然是为你担虑。” 司马青笑了起来:“红红,你那里像个江湖的侠女。” “江湖侠女该是什么样子的,我不相信别的江湖女子在丈夫与人决斗时能无动于衷。” “至少人家不会像你这样,既然身为江湖人,就当有提得起放得开的心胸,随时准备接受凶险的来临。” 上官红笑了起来:“青哥,我是问你有几分把握,却没有要求你不去赴约。” 司马青道:“如果我的回答是毫无把握呢?” 上官红道:“如果这一战是无可避免,有把握要去,没把握也耍去,我就不会问了,因为我认为这一战并非必要,才要问问清楚!” “怎见得这一战是并非必要呢?” “铁钵和尚在别人心目中是凶僧,但你我知道他并非如此,他只是受了卫天风的逼迫而已………” “是的,大丈夫有所必为,也有所不为,他就是这一点没有弄清楚,我要他把这一点想明白!” “这个理由你已经说过了,但是我觉得不够充份,铁钵和尚既是本人尚有是非之心,再坏也坏不到那儿去,为了点化他这个人,你不值得冒这个险,因为你此刻一身所寄,还承担着天下的安危。” 司马青道:“红红,你把我看得太重了,正如铁钵和尚把他自己看得太重一样。” “不!青哥,卫天风阴谋夺霸武林,掀起一天血雨腥风,很多人都屈于其威势,敢于站出来跟他公然作对的只有你一个,这不是我看重你,别的人都是如此看。” “我倒不如此想,事情总是会有人做的,如果杀死我就没人敢反抗卫天风了,我就活不到今天,以卫天风现有的实方,集中对付我并非难事,他没有这么做,是因为看准了你我的力量还威胁不了他的霸业,而且,在情理上你我有正大光明对付他的理由,所以他才容忍一二;但他真正顾忌的不是你我,而是一些真正握有实力的人。” “他既然不重视我们,为什么又耍弄出个铁钵和尚来杀你呢?” “因为铁钵和尚并不是他的党羽,只是受了他的挟制—而已,而且他知道铁钵和尚并不想杀我,也杀不了我,所以才来上这一手,主要是想铁钵和尚死在我手里,好利用十大天魔出而为助。” “那你为什么还要上他的当呢?” 司马青笑道:“有一个很特殊的理由,我现在无法告诉你,等我斗过铁钵和尚后,你就知道了,你放心好了,这一战是无可避免的,而且卫天风会后悔他安排下的这个圈套,最后套进去的一定是他自己。” 上官红望着司马青道:“青哥,你好像身上带着很多秘密,我们虽已结为夫妇,但是我一点都不了解你。” 可马青淡然地道:“那是难怪的,我们虽然很早就被人们配成一对了,可是我们真正在一起的时间还是太短,不可能一下子就完全了解的,不过我的一切并不想瞒你,只是希望你一步步地从事实上去了解,才容易接受一点。” 上官红叹了口气,看看东方如玉与哈元甲的桌上,那两个人仍是望着她,充满了火热的眼光,心中忽地一动,含笑向司马青道:“青哥,我去向他们两边打个招呼,你不会反对吧。” 司马青道:“那当然不会,可是我希望你稍微克制一下自己的性子,不要给人太难堪,那两方面都是一方之雄,无故地开罪他们,把他们逼向卫天风那儿去,实在是得不偿失。” 上官红笑道:“不会的,我现在是司马青的妻子,不是武林盟主的女儿了,行事也不会像以前那么暴躁了,你的朋友能摸清他们的底子,卫天风的人也一定知道他们的身份,故意不加揭穿,目的也是想在设法拉拢他们,我去拉拢他们一下,使他们的立场表明,也好杜绝卫天风对他们的笼络之途。” “你假如以司马青的妻子身份前去拉拢他们,恐怕效果会适得其反,你看他们的眼中对你充满了思慕之情………” 上官红笑了一笑:“那倒不尽然,情势之运用,存乎一心,不管他们心里存着什么邪念头,但我会叫他们明白地站出来的。” 说着移步走向左边的桌上,那正是飞云少岛主东方如玉的座位,他看见上官红过来,似乎颇为不安,低下了头,但是上官红却不肯放过他,浅浅一躬笑道:“东方兄,别来无恙。” 东方如玉很尴尬,讷讷地道:“姑………姑娘,你认错人了。” 上官红笑道:“飞云岛的东方如玉少岛主,小妹怎么会认错呢,我知道东方兄故掩形迹,是为了怕引起一些人的误会,但是我觉得这大可不必,天风堡的势力虽大,未必就能优过飞云岛去,东方兄如此谨慎,不是太长卫天风的气势了吗?” 东方如玉更为窘迫,不知道说什么好了。 上官红一敛笑容道:“东方兄!前蒙错爱,小妹因为先父已与外子司马青缔婚了,乃憾以婉却,但小妹对飞云岛的盛情以及东方兄的人品才华,仍是十分钦敬的,现在看起来,倒是令小妹十分失望了,如果东方兄是真的怕卫天凤不敢承认,小妹也就承认看错了人好了。” 语毕转身走向哈元甲的桌上道:“哈大哥!你我同属北方武林一脉,再加上先人两代的交情,小妹有难,我知道你不会坐视的?你果然来了,小妹深感庆幸,北地武林毕竟不是藏头缩尾之辈。”
Python
UTF-8
373
4.4375
4
[]
no_license
""" 5- Receba um número inteiro e mostre se ele á par ou ímpar. """ number = int(input('Digite um número inteiro: ')) if number == 0: print('Você digitou o número zero.' '\nEle não é par nem ímpar,' '\napesar de possuir propriedades de par.') elif number % 2 == 0: print(f'{number} é par.') else: print(f'{number} é ímpar.')
Java
UTF-8
613
3.453125
3
[]
no_license
package com.study02; import java.util.Scanner; public class Lotto { public static void main(String[] args) { // 1에서 20 사이의 숫자 중 5개를 뽑는 로또 게임 만들어보자. Scanner sc = new Scanner(System.in); System.out.println("1에서 20사이 숫자 5개를 입력하세요."); int i = sc.nextInt(); System.out.println("당첨 번호는 바로....!"); randomNumber(); randomNumber(); randomNumber(); randomNumber(); randomNumber(); } public static void randomNumber() { int i = (int) (Math.random() * (20 - 1 + 1)) + 1; System.out.print(i+ "\t"); } }
PHP
UTF-8
921
2.6875
3
[ "MIT" ]
permissive
<?php namespace FrontendBridge\Lib; use Cake\Network\Response; use Cake\Utility\Hash; /** * Custom CakeResponse for Service calls * * @package default */ class ServiceResponse extends Response { /** * Constructor * * @param string|array $code One of Types::CODE_*, or an array containing 'code' and 'data' keys * @param array $data data to return */ public function __construct($code, array $data = array ()) { if (is_array($code)) { $body = Hash::merge(array ( 'code' => 'success', 'data' => array () ), $code); } else { $body = array ( 'code' => $code, 'data' => $data ); } $options = array ( 'type' => 'json', 'body' => json_encode($body) ); parent::__construct($options); } }
SQL
UTF-8
3,396
3.59375
4
[]
no_license
DROP DATABASE IF EXISTS `doozy`; CREATE DATABASE `doozy`; USE `doozy`; CREATE TABLE `users` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `email` varchar(50) NOT NULL, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `interests` ( `interest_id` tinyint(4) NOT NULL AUTO_INCREMENT, `interest_name` varchar(50) NOT NULL, PRIMARY KEY (`interest_id`) ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; INSERT INTO `interests` VALUES (1, 'sports'); INSERT INTO `interests` VALUES (2, 'hacking'); INSERT INTO `interests` VALUES (3, 'exercise'); INSERT INTO `interests` VALUES (4, 'dining'); INSERT INTO `interests` VALUES (5, 'museums'); INSERT INTO `interests` VALUES (6, 'art'); INSERT INTO `interests` VALUES (7, 'hiking'); INSERT INTO `interests` VALUES (8, 'gaming'); INSERT INTO `interests` VALUES (9, 'clubbing'); INSERT INTO `interests` VALUES (10, 'dancing'); INSERT INTO `interests` VALUES (11, 'reading'); INSERT INTO `interests` VALUES (12, 'tv'); INSERT INTO `interests` VALUES (13, 'theater'); INSERT INTO `interests` VALUES (14, 'movies'); INSERT INTO `interests` VALUES (15, 'concerts'); INSERT INTO `interests` VALUES (16, 'music'); INSERT INTO `interests` VALUES (17, 'shopping'); INSERT INTO `interests` VALUES (18, 'yoga'); CREATE TABLE `users_interests` ( `user_id` int(11) NOT NULL, `interest_1` tinyint(4) DEFAULT NULL, `interest_2` tinyint(4) DEFAULT NULL, `interest_3` tinyint(4) DEFAULT NULL, `interest_4` tinyint(4) DEFAULT NULL, `interest_5` tinyint(4) DEFAULT NULL, `interest_6` tinyint(4) DEFAULT NULL, KEY `FK_user_id_interests` (`user_id`), CONSTRAINT `FK_user_id_interests` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE RESTRICT ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `users_issues` ( `user_id` int(11) NOT NULL, `issue_1` tinyint(4) NOT NULL, `issue_2` tinyint(4) NOT NULL, `issue_3` tinyint(4) NOT NULL, KEY `FK_user_id_issues` (`user_id`), CONSTRAINT `FK_user_id_issues` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE RESTRICT ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `open_users` ( `user_id` int(11) NOT NULL, `open` tinyint(1) NOT NULL, KEY `FK_user_id_open` (`user_id`), CONSTRAINT `FK_user_id_open` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE RESTRICT ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE matches ( user_id_1 int(11) NOT NULL, user_id_2 int(11) NOT NULL, interest_1 tinyint(4) DEFAULT NULL, interest_2 tinyint(4) DEFAULT NULL, interest_3 tinyint(4) DEFAULT NULL, interest_4 tinyint(4) DEFAULT NULL, interest_5 tinyint(4) DEFAULT NULL, interest_6 tinyint(4) DEFAULT NULL, KEY FK_user_id_1 (user_id_1), KEY FK_user_id_2 (user_id_2), CONSTRAINT FK_user_id_1 FOREIGN KEY (user_id_1) REFERENCES users (user_id) ON DELETE RESTRICT ON UPDATE CASCADE, CONSTRAINT FK_user_id_2 FOREIGN KEY (user_id_2) REFERENCES users (user_id) ON DELETE RESTRICT ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
C
UTF-8
1,848
2.8125
3
[ "Apache-2.0" ]
permissive
/* * Test D-Bus Message Abstraction */ #undef NDEBUG #include <c-stdaux.h> #include <stdlib.h> #include "dbus/message.h" static void test_setup(void) { _c_cleanup_(message_unrefp) Message *m1 = NULL, *m2, *m3; MessageHeader hdr = { .endian = 'l' }; int r; /* verify constructors / destructors */ r = message_new_incoming(&m2, hdr); c_assert(r == 0); r = message_new_incoming(&m3, hdr); c_assert(r == 0); m3 = message_unref(m3); m1 = message_unref(m1); } static void test_size(void) { MessageHeader hdr = { .endian = 'l' }; Message *m; int r; /* verify total message size cannot exceed 128MB */ hdr.n_body = htole32(0); r = message_new_incoming(&m, hdr); c_assert(r == 0); message_unref(m); hdr.n_body = htole32(128); r = message_new_incoming(&m, hdr); c_assert(r == 0); message_unref(m); hdr.n_body = htole32(128UL * 1024UL * 1024UL - sizeof(MessageHeader)); r = message_new_incoming(&m, hdr); c_assert(r == 0); message_unref(m); hdr.n_body = htole32(128UL * 1024UL * 1024UL - sizeof(MessageHeader) + 1UL); r = message_new_incoming(&m, hdr); c_assert(r == MESSAGE_E_TOO_LARGE); hdr.n_fields = htole32(8); hdr.n_body = htole32(128UL * 1024UL * 1024UL - sizeof(MessageHeader) - 8); r = message_new_incoming(&m, hdr); c_assert(r == 0); message_unref(m); hdr.n_fields = htole32(8 + 1); hdr.n_body = htole32(128UL * 1024UL * 1024UL - sizeof(MessageHeader) - 8); r = message_new_incoming(&m, hdr); c_assert(r == MESSAGE_E_TOO_LARGE); } int main(int argc, char **argv) { test_setup(); test_size(); return 0; }
Java
UTF-8
1,295
2.359375
2
[]
no_license
package it.uniroma3.commands; import it.uniroma3.OrderState; import it.uniroma3.domain.OrderLineItem; import java.util.List; public class NewOrderCommand extends BaseCommand1<String> { private String consumerId; private String restaurantId; private List<OrderLineItem> lineItems; private OrderState state; public NewOrderCommand(String id, String consumerId, String restaurantId, List<OrderLineItem> lineItems) { super(id); this.consumerId = consumerId; this.restaurantId = restaurantId; this.lineItems = lineItems; this.state = OrderState.PENDING; } public String getConsumerId() { return consumerId; } public void setConsumerId(String consumerId) { this.consumerId = consumerId; } public String getRestaurantId() { return restaurantId; } public void setRestaurantId(String restaurantId) { this.restaurantId = restaurantId; } public List<OrderLineItem> getLineItems() { return lineItems; } public void setLineItems(List<OrderLineItem> lineItems) { this.lineItems = lineItems; } public OrderState getState() { return state; } public void setState(OrderState state) { this.state = state; } }
Java
UTF-8
963
2.5
2
[]
no_license
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; public class MemSubFrame extends JFrame { boolean close = false; JPanel vdp = new JPanel(); JLabel lb = new JLabel("VIDEO TITLE"); JScrollPane sp = new JScrollPane(); DefaultListModel model = new DefaultListModel(); JList vdl = new JList(model); public MemSubFrame(ArrayList<String> vtitlelist){ ArrayList<String> vtlist = vtitlelist; for(String vtitle:vtlist){ model.addElement(vtitle); } sp.getViewport().setView(vdl); sp.setPreferredSize(new Dimension(200, 80)); vdp.add(lb); vdp.add(sp); getContentPane().add(vdp); } }
C++
UTF-8
914
3.1875
3
[]
no_license
/* You can use the preprocessor to control what code is even compiled, allowing you easily switch between different builds. This way you can change from a debug build to a release build without manually removing every instance of a printout. */ #include <stdio.h> // this macro doesn't replace DEBUGGING with anything, // it just exists, and that's enough for what we're doing #define DEBUGGING int main(int argc, char** argv) { // use this code if DEBUGGING is defined #ifdef DEBUGGING printf("We're in debug mode\n"); // else... #else printf("We're in release mode\n"); // end the 'ifdef' #endif printf("...doing some work...\n"); // use this code if DEBUGGING is not defined #ifndef DEBUGGING printf("We're not debugging\n"); #endif } // try this yourself, comment out the line '#define DEBUGGING' // and see what happens
C#
UTF-8
336
2.78125
3
[]
no_license
namespace _07_InfernoInfinity.Models.Weapons { public class Axe : Weapon { private const int MIN_DAMAGE = 5; private const int MAX_DAMAGE = 10; public Axe(string name, string weaponType, string rarity) : base(name, weaponType, MAX_DAMAGE, MIN_DAMAGE, rarity) { } } }
Python
UTF-8
1,418
2.515625
3
[]
no_license
# -*- coding: utf-8 -*- import datetime from django.contrib.contenttypes.models import ContentType from django.utils import timezone from .models import Action def create_action(user, verb, target=None): """ 一个用户给某张图片打上书签 一个用户喜欢或不喜欢某张图片 一个用户创建一个账户 一个用户关注或不关注某个用户 上述事物都会调用该方法来创建一条feed流 """ now = timezone.now() # 获得当前的时间 last = datetime.timedelta(seconds=60) # 在当前时间上减少1分钟 last_minute = now - last # 最后一次时间,在当前时间减少一分钟是最后一次时间 print(now, last, last_minute) similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute) # 取出所有创建时间 >= 最后时间的数据(1分钟前) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct, target_id=target.id) # 如果创建时间>= 最后时间 的数据为空,那就直接保存 if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False
C#
UTF-8
751
2.671875
3
[ "MIT" ]
permissive
using System; using System.Text; using CsRex; using CsRex.Parsing; using CsRex.Parsing.Nodes; namespace CsRex.Parsing.Nodes { internal class Word : Node { private string _word; internal Word (string word) { if (word.Length > 255) { throw new ArgumentException("Length of word must be at most 255.", nameof(word)); } _word = word; _compiledLength = 1; _minLength = word.Length; } internal string Value { get { return _word; } } internal override void CompileNode (Span<Instruction> buffer, StringBuilder words) { buffer[0] = new Instruction(Opcode.Word, parameter: (ushort) words.Length, length: (byte) _word.Length); words.Append(_word); } } }
C++
UTF-8
527
2.78125
3
[]
no_license
#include <boost/asio.hpp> #include <string> #include <thread> #include <atomic> namespace mdv { class MessageHandler; class Uart { public: Uart(std::string port, unsigned int baud_rate, MessageHandler &msg_handler); void writeString(std::string msg); std::string readLine(); void receiveThread(); private: boost::asio::io_context m_ioc; boost::asio::serial_port m_serial; std::atomic<bool> m_done; MessageHandler &m_message_handler; std::thread m_receive_thread; }; } // namespace mdv
Java
UTF-8
23,537
1.625
2
[]
no_license
package app.mycity.mycity.views.fragments; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import app.mycity.mycity.App; import app.mycity.mycity.util.Constants; import app.mycity.mycity.R; import app.mycity.mycity.api.ApiFactory; import app.mycity.mycity.api.model.Comment; import app.mycity.mycity.api.model.Likes; import app.mycity.mycity.api.model.Profile; import app.mycity.mycity.api.model.ResponseAddComment; import app.mycity.mycity.api.model.ResponseComments; import app.mycity.mycity.api.model.ResponseContainer; import app.mycity.mycity.api.model.ResponseLike; import app.mycity.mycity.api.model.SubComment; import app.mycity.mycity.api.model.SubCommentContainer; import app.mycity.mycity.api.model.Success; import app.mycity.mycity.util.EventBusMessages; import app.mycity.mycity.util.SharedManager; import app.mycity.mycity.views.activities.Storage; import app.mycity.mycity.views.adapters.CommentsRecyclerAdapter; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; import fr.arnaudguyon.tabstacker.TabStacker; import hani.momanii.supernova_emoji_library.Actions.EmojIconActions; import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CommentsFragment extends android.support.v4.app.Fragment implements TabStacker.TabStackInterface { @BindView(R.id.commentsFragmentRecyclerView) RecyclerView recyclerView; @BindView(R.id.commentPhoto) CircleImageView photo; @BindView(R.id.addCommentEditText) EmojiconEditText editText; CommentsRecyclerAdapter adapter; List<Comment> commentList; Map profiles = new HashMap<Long, Profile>(); @BindView(R.id.rootView) ConstraintLayout rootView; @BindView(R.id.commentsPlaceHolder) ConstraintLayout placeHolder; @BindView(R.id.addCommentProgress) ProgressBar progressBar; @BindView(R.id.change) ImageView changeButton; @BindView(R.id.replyText) TextView replyText; EmojIconActions emojIcon; boolean isLoading; int totalCount; String postId = "46"; String ownerId = "45"; private String commentText; boolean emojyShoven; Type type = Type.COMMENT; private String replyCommentId; private int replyCommentPosition; private Storage storage; enum Type { COMMENT, REPLY } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.comment_fragment, container, false); postId = getArguments().getString("postId"); ownerId = getArguments().getString("ownerId"); ButterKnife.bind(this, view); return view; } @OnClick(R.id.change) public void clickChange(View v){ if(!emojyShoven){ emojIcon.setUseSystemEmoji(true); changeButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_keyboard_outline)); } else { changeButton.setImageDrawable(getResources().getDrawable(R.drawable.smiley)); emojIcon.closeEmojIcon(); } emojyShoven = !emojyShoven; } public static CommentsFragment createInstance(String fragmentId, String postId, String ownerId, String type) { CommentsFragment fragment = new CommentsFragment(); Bundle bundle = new Bundle(); bundle.putString("name", fragmentId); bundle.putString("postId", postId); bundle.putString("ownerId", ownerId); bundle.putString("type", type); fragment.setArguments(bundle); return fragment; } @OnClick(R.id.profileFragBackButtonContainer) public void backButton(View v){ getActivity().onBackPressed(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); emojIcon=new EmojIconActions(getContext(), rootView, editText, new ImageView(getContext())); emojIcon.ShowEmojIcon(); commentList = new ArrayList<>(); adapter = new CommentsRecyclerAdapter(commentList, profiles); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int totalItemCount = layoutManager.getItemCount(); int lastVisibleItems = layoutManager.findLastVisibleItemPosition(); if (!isLoading) { if ( lastVisibleItems >= totalItemCount -10 ) { isLoading = true; if(totalCount >= commentList.size()){ loadComments(commentList.size()); } } } } }; if(SharedManager.getProperty(Constants.KEY_PHOTO_130)!=null){ Picasso.get().load(SharedManager.getProperty(Constants.KEY_PHOTO_130)).into(photo); } recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); recyclerView.addOnScrollListener(scrollListener); loadComments(commentList.size()); replyText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { replyText.setVisibility(View.GONE); type = Type.COMMENT; } }); } private void loadComments(final int offset) { Callback callback = new Callback<ResponseContainer<ResponseComments>>() { @Override public void onResponse(Call<ResponseContainer<ResponseComments>> call, Response<ResponseContainer<ResponseComments>> response) { if(response!=null&&response.body().getResponse()!=null){ isLoading = false; totalCount = response.body().getResponse().getCount(); commentList.addAll(response.body().getResponse().getItems()); if(response.body().getResponse().getProfiles()!=null){ for (Profile p: response.body().getResponse().getProfiles() ) { profiles.put(p.getId(), p); } } adapter.update(commentList, profiles); if(commentList.size()==0){ placeHolder.setVisibility(View.VISIBLE); } else { placeHolder.setVisibility(View.GONE); } if(offset==0){ recyclerView.scrollToPosition(0); } } } @Override public void onFailure(Call<ResponseContainer<ResponseComments>> call, Throwable t) { } }; switch (getArguments().getString("type")){ case "post": ApiFactory.getApi().getCommentsPost( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "1", postId, ownerId, offset, "1", 20, 2, "photo_130").enqueue(callback); break; case "photo": ApiFactory.getApi().getCommentsPhoto( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "1", postId, ownerId, offset, "1", 2, 20, "photo_130").enqueue(callback); break; case "event": ApiFactory.getApi().getCommentsEvent( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "1", postId, ownerId, offset, "1", 2, 20, "photo_130").enqueue(callback); break; } } @Subscribe(threadMode = ThreadMode.MAIN) public void reply(EventBusMessages.ReplyToComment event){ if(profiles.containsKey(event.getUserId())){ Profile profile = (Profile) profiles.get(event.getUserId()); replyText.setText("Ответ для " + profile.getFirstName()); } type = Type.REPLY; replyText.setVisibility(View.VISIBLE); App.showKeyboard(getContext()); editText.requestFocus(); replyCommentId = event.getCommentId(); replyCommentPosition = event.getPosition(); } @OnClick(R.id.addComment) public void addComment(View v){ progressBar.setVisibility(View.VISIBLE); commentText = editText.getText().toString(); editText.setText(""); Callback commentCallback = new Callback<ResponseContainer<ResponseAddComment>>() { @Override public void onResponse(Call<ResponseContainer<ResponseAddComment>> call, Response<ResponseContainer<ResponseAddComment>> response) { if(response!=null&&response.body().getResponse()!=null){ Comment comment = new Comment(); comment.setText(commentText); comment.setOwnerId(SharedManager.getProperty(Constants.KEY_MY_ID)); comment.setDate((int) (Calendar.getInstance().getTimeInMillis()/1000)); comment.setId(response.body().getResponse().getCommentId()); comment.setFromId(SharedManager.getProperty(Constants.KEY_MY_ID)); comment.setPostId(postId); Likes likes = new Likes(); likes.setUserLikes(0); likes.setCount(0); comment.setLikes(likes); SubCommentContainer subCommentContainer = new SubCommentContainer(); List<SubComment> subCommentList = new ArrayList<>(); subCommentContainer.setItems(subCommentList); comment.setSubComments(subCommentContainer); progressBar.setVisibility(View.GONE); commentList.add(0, comment); adapter.update(commentList, profiles); adapter.notifyItemChanged(replyCommentPosition); placeHolder.setVisibility(View.GONE); replyText.setVisibility(View.GONE); type = Type.COMMENT; } } @Override public void onFailure(Call<ResponseContainer<ResponseAddComment>> call, Throwable t) { } }; Callback replyCallback = new Callback<ResponseContainer<ResponseAddComment>>() { @Override public void onResponse(Call<ResponseContainer<ResponseAddComment>> call, Response<ResponseContainer<ResponseAddComment>> response) { if(response!=null&&response.body().getResponse()!=null){ SubComment comment = new SubComment(); comment.setText(commentText); comment.setOwnerId(SharedManager.getProperty(Constants.KEY_MY_ID)); comment.setDate((int) (Calendar.getInstance().getTimeInMillis()/1000)); comment.setId(response.body().getResponse().getCommentId()); comment.setFromId(SharedManager.getProperty(Constants.KEY_MY_ID)); comment.setPostId(postId); Likes likes = new Likes(); likes.setUserLikes(0); likes.setCount(0); comment.setLikes(likes); progressBar.setVisibility(View.GONE); commentList.get(replyCommentPosition).getSubComments().getItems().add(0, comment); commentList.get(replyCommentPosition).getSubComments().setCount(commentList.get(replyCommentPosition).getSubComments().getItems().size()); adapter.notifyDataSetChanged(); placeHolder.setVisibility(View.GONE); } } @Override public void onFailure(Call<ResponseContainer<ResponseAddComment>> call, Throwable t) { } }; if(type == Type.REPLY){ switch (getArguments().getString("type")){ case "post": ApiFactory.getApi().addReplyToPostComment(App.accessToken(), postId, ownerId, commentText, replyCommentId).enqueue(replyCallback); break; case "photo": ApiFactory.getApi().addReplyToPhotoComment(App.accessToken(), postId, ownerId, commentText, replyCommentId).enqueue(replyCallback); break; case "event": ApiFactory.getApi().addReplyToEventComment(App.accessToken(), postId, ownerId, commentText, replyCommentId).enqueue(replyCallback); break; } } if(type == Type.COMMENT){ switch (getArguments().getString("type")){ case "post": ApiFactory.getApi().addPostComment(SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), postId, ownerId, commentText).enqueue(commentCallback); break; case "photo": ApiFactory.getApi().addPhotoComment(SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), postId, ownerId, commentText).enqueue(commentCallback); break; case "event": ApiFactory.getApi().addEventComment(SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), postId, ownerId, commentText).enqueue(commentCallback); break; } } } @Subscribe(threadMode = ThreadMode.MAIN) public void like(final EventBusMessages.LikeComment event) { Comment comment = commentList.get(event.getAdapterPosition()); if (comment.getLikes().getUserLikes() == 1) { comment.getLikes().setCount(comment.getLikes().getCount()-1); comment.getLikes().setUserLikes(0); adapter.notifyItemChanged(event.getAdapterPosition()); ApiFactory.getApi().unlike( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "comment", comment.getId(), comment.getOwnerId() ).enqueue(new retrofit2.Callback<ResponseContainer<ResponseLike>>() { @Override public void onResponse(retrofit2.Call<ResponseContainer<ResponseLike>> call, retrofit2.Response<ResponseContainer<ResponseLike>> response) { if (response != null && response.body() != null) { } } @Override public void onFailure(retrofit2.Call<ResponseContainer<ResponseLike>> call, Throwable t) { } }); } else if (comment.getLikes().getUserLikes() == 0) { comment.getLikes().setCount(comment.getLikes().getCount()+1); comment.getLikes().setUserLikes(1); adapter.notifyItemChanged(event.getAdapterPosition()); ApiFactory.getApi().like( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "comment", comment.getId(), comment.getOwnerId() ).enqueue(new retrofit2.Callback<ResponseContainer<ResponseLike>>() { @Override public void onResponse(retrofit2.Call<ResponseContainer<ResponseLike>> call, retrofit2.Response<ResponseContainer<ResponseLike>> response) { if (response != null && response.body() != null) { } } @Override public void onFailure(retrofit2.Call<ResponseContainer<ResponseLike>> call, Throwable t) { } }); } } @Subscribe(threadMode = ThreadMode.MAIN) public void like(final EventBusMessages.LikeSubcomment event) { Comment comment = commentList.get(event.getAdapterPosition()); SubComment subComment = comment.getSubComments().getItems().get(event.getCommentPosition()); if (comment.getLikes().getUserLikes() == 1) { subComment.getLikes().setCount(subComment.getLikes().getCount()-1); subComment.getLikes().setUserLikes(0); adapter.notifyItemChanged(event.getAdapterPosition()); ApiFactory.getApi().unlike( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "comment", subComment.getId(), subComment.getOwnerId() ).enqueue(new retrofit2.Callback<ResponseContainer<ResponseLike>>() { @Override public void onResponse(retrofit2.Call<ResponseContainer<ResponseLike>> call, retrofit2.Response<ResponseContainer<ResponseLike>> response) { } @Override public void onFailure(retrofit2.Call<ResponseContainer<ResponseLike>> call, Throwable t) { } }); } else if (comment.getLikes().getUserLikes() == 0) { subComment.getLikes().setCount(subComment.getLikes().getCount()+1); subComment.getLikes().setUserLikes(1); adapter.notifyItemChanged(event.getAdapterPosition()); ApiFactory.getApi().like( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), "comment", subComment.getId(), subComment.getOwnerId() ).enqueue(new retrofit2.Callback<ResponseContainer<ResponseLike>>() { @Override public void onResponse(retrofit2.Call<ResponseContainer<ResponseLike>> call, retrofit2.Response<ResponseContainer<ResponseLike>> response) { } @Override public void onFailure(retrofit2.Call<ResponseContainer<ResponseLike>> call, Throwable t) { } }); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(final EventBusMessages.DeleteComment event) { AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create(); alertDialog.setTitle("Удалить комментарий?"); alertDialog.setMessage(commentList.get(event.getPosition()).getText()); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Отмена", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { final int position = event.getPosition(); Callback callback = new Callback<ResponseContainer<Success>>() { @Override public void onResponse(Call<ResponseContainer<Success>> call, Response<ResponseContainer<Success>> response) { if(response!=null&&response.body().getResponse() != null && response.body().getResponse().getSuccess()==1) commentList.remove(position); adapter.notifyItemRemoved(position); } @Override public void onFailure(Call<ResponseContainer<Success>> call, Throwable t) { } }; switch (getArguments().getString("type")){ case "post": ApiFactory.getApi().deleteComment( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), commentList.get(position).getId(), ownerId).enqueue(callback); break; case "photo": ApiFactory.getApi().deleteCommentPhoto( SharedManager.getProperty(Constants.KEY_ACCESS_TOKEN), commentList.get(position).getId(), ownerId).enqueue(callback); break; } dialog.dismiss(); } }); alertDialog.show(); } @Subscribe(threadMode = ThreadMode.MAIN) public void storeComment(EventBusMessages.StoreComment event){ storage.setDate("tempComment" + commentList.get(event.getPosition()).getId(), commentList.get(event.getPosition())); if(profiles.containsKey(commentList.get(event.getPosition()).getOwnerId())){ storage.setDate("tempCommentProfile" + commentList.get(event.getPosition()).getId(), profiles.get(commentList.get(event.getPosition()).getOwnerId())); } } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); } @Override public void onAttach(Context context) { super.onAttach(context); storage = (Storage) context; } @Override public void onTabFragmentPresented(TabStacker.PresentReason presentReason) { } @Override public void onTabFragmentDismissed(TabStacker.DismissReason dismissReason) { } @Override public View onSaveTabFragmentInstance(Bundle bundle) { return null; } @Override public void onRestoreTabFragmentInstance(Bundle bundle) { } }
TypeScript
UTF-8
520
2.78125
3
[]
no_license
import { Movie } from './movie'; describe('Movie', () => { it('should create an instance of Movie',() => { expect(new Movie()).toBeTruthy(); }); it('should accept values', () => { let movie = new Movie(); movie = { id: "111", title: "Rangasthalam", director: "Rajamouli", cast: 'print "Hello"', genre: " ", } expect(movie.id).toEqual("111"); expect(movie.title).toEqual("Rangasthalam"); expect(movie.director).toEqual("Rajamouli"); }); })
C
UTF-8
2,015
2.53125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ifpercentage.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: egallego <egallego@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/18 17:26:26 by egallego #+# #+# */ /* Updated: 2021/03/18 17:26:28 by egallego ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void print_per_prec(t_struct *f) { if (f->precisionft > 0) print_zero(f->precisionft, f); } int per_prec(int j, t_struct *f) { int k; f->zero = 0; f->precisionft = f->precisionft - f->len; k = j - f->precisionft; return (k); } void print_per(t_struct *f) { int j; char c; j = f->width; c = '%'; if (f->width != 0) j = f->width; if (j != 0) j = j - 1; if (f->precision == 1) j = per_prec(j, f); if (f->zero != 0 && j > 0) print_zero(j, f); if (f->zero == 0 && j > 0) print_space(j, f); if (f->precision == 1) print_per_prec(f); write(1, &c, 1); f->nprinted++; } void print_per_minus(t_struct *f) { int j; char c; j = f->width; c = '%'; f->len = 1; if (f->width != 0) j = f->width; if (j != 0) j = j - f->len; if (f->precision == 1) j = per_prec(j, f); if (f->precision == 1) print_per_prec(f); write(1, &c, 1); if (j > 0) print_space(j, f); f->nprinted++; } void ifpercentage(const char *str, t_struct *f, va_list ap) { f->saida = 1; while (str[f->i] != '%') ft_flags(str, f, ap); if (f->minus == 1) print_per_minus(f); else print_per(f); }
Python
UTF-8
2,215
3.296875
3
[ "MIT" ]
permissive
from typing import List, Dict import torch def calculate_batch_statistics( original_tokens: torch.Tensor, predicted_tokens: torch.Tensor, skipping_tokens: List ) -> Dict: """Calculate The TP, FP, and FN for given tensors with original and predicted tokens. Each tensor is a 2d matrix, where each row contain information about corresponding subtokens. :param skipping_tokens: list of tokens, which will be skipped :param original_tokens: tensor with original subtokens :param predicted_tokens: tensor with predicted subtokens :return: statistic for given tensors """ true_positive = 0 false_positive = 0 false_negative = 0 for original_token, predicted_token in zip(original_tokens, predicted_tokens): for subtoken in predicted_token: if subtoken in skipping_tokens: continue if subtoken in original_token: true_positive += 1 else: false_positive += 1 for subtoken in original_token: if subtoken in skipping_tokens: continue if subtoken not in predicted_token: false_negative += 1 return { 'true_positive': true_positive, 'false_positive': false_positive, 'false_negative': false_negative } def calculate_metrics(statistics: Dict) -> Dict: """Calculate precision, recall, and f1 based on a TP, FP, FN :param statistics: dict with statistics :return: metrics for given statistics """ true_positive = statistics['true_positive'] false_positive = statistics['false_positive'] false_negative = statistics['false_negative'] if true_positive + false_positive > 0: precision = true_positive / (true_positive + false_positive) else: precision = 0.0 if true_positive + false_negative > 0: recall = true_positive / (true_positive + false_negative) else: recall = 0.0 if precision + recall > 0: f1_score = 2 * precision * recall / (precision + recall) else: f1_score = 0.0 return { 'precision': precision, 'recall': recall, 'f1_score': f1_score }
PHP
UTF-8
3,691
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Redirect; use App\Http\Requests; use App\Http\Requests\CategoryCreateRequest; use App\Http\Controllers\Controller; use App\Category;//Se agrega para no tener que estar escribiendo \App\Category cada vez que se utilice class CategoriesController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return Response */ public function index() { //$categories = Category::orderBy('name')->get();; $categories = Category::paginate(5); return view('admin.categories.index', compact('categories'));//Regresar la variable categories a la vista con todos los datos // return \View::make('categories.index') // ->with('categories', Category::all()); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { } /** * Store a newly created resource in storage. * * @return Response */ public function store(CategoryCreateRequest $request) { Category::create([ 'name' => $request['name'] ]); flash()->success('Nueva categoria creada: "'. $request['name'].'"'); return redirect('admin/categories'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $category = Category::find($id); return view('admin/categories/edit',['category'=>$category]); //return view('admin/categories', compact('categories')); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id,CategoryUpdateRequest $request) { $category = Category::find($id); $category->fill($request->all()); $category->save(); flash()->warning('La categoria fue editada correctamente'); return Redirect::to('admin/categories'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { Category::destroy($id); flash()->warning('La categoria fue eliminada correctamente'); return redirect('admin/categories'); } /*public function getIndex(){ return View::make('categories.index') ->with('categories',Category::all()); } public function postCreate(){ $validator = Validator::make(Input::all(), Category::$rules); if($validator->passes()){ $category = new Category; $category->name = Input::get('name'); $category->save(); return Redirect::to('admin/categories/index') ->with('message','Category Created') ->withErrors($validator) ->withInput(); } } public function postDestroy(){ $category = Category::find(Input::get('id')); if($category){ $category->delete(); return Redirect::to('admin/categories/index') ->with('message','Category Deleted'); } return Redirect::to('admin/categories/index') ->with('message','Something went wrong, please try again'); }*/ }
Python
UTF-8
866
4.4375
4
[]
no_license
//Square Every Digit //Welcome. In this kata, you are asked to square every digit of a number. //For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. //Note: The function accepts an integer and returns an integer function squareDigits(num){ return parseInt(num.toString().split('').map((eachNum)=>Math.pow(eachNum,2)).join('')); } console.log(squareDigits(9119)); //Square Every Digit python Version import math def square_digits(num): newArray=[] split=list(str(num)) for i in split: newArray.append(str(int(math.pow(int(i),2)))) return int("".join(newArray)) print square_digits(9119) //Ruby Square Every Digit def square_digits(num) splitted=num.to_s.split('') mathPow= Proc.new{ |x| x.to_i**2 } (splitted.collect(&mathPow).join('')).to_i end print(square_digits(3212))
PHP
UTF-8
2,066
2.59375
3
[]
no_license
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class InitialMigration extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function($table) { $table->increments('id'); $table->string('email')->unique(); $table->string('firstname'); $table->string('lastname'); $table->string('password'); $table->string('username'); $table->string('phone'); $table->string('address'); $table->timestamps(); }); Schema::create('ads', function($table) { $table->increments('id'); $table->string('title'); $table->string('description'); $table->integer('category_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->timestamps(); }); Schema::create('categories', function($table) { $table->increments('id'); $table->string('name'); $table->string('description'); $table->string('image_path'); $table->integer('parent_id')->unsigned()->nullable(); $table->timestamps(); }); Schema::create('shares', function($table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('category_id')->unsigned(); $table->timestamps(); }); Schema::create('images', function($table) { $table->increments('id'); $table->string('title'); $table->string('path'); $table->integer('ad_id')->unsigned(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); Schema::drop('ads'); Schema::drop('categories'); Schema::drop('images'); Schema::drop('shares'); } }
Java
UTF-8
7,088
2.296875
2
[]
no_license
/* Copyright 2012 - iSencia Belgium N Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.isencia.passerelle.process.actor.flow; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import ptolemy.data.expr.StringParameter; import ptolemy.kernel.CompositeEntity; import ptolemy.kernel.util.IllegalActionException; import ptolemy.kernel.util.NameDuplicationException; import com.isencia.passerelle.actor.ProcessingException; import com.isencia.passerelle.actor.ValidationException; import com.isencia.passerelle.core.ErrorCode; import com.isencia.passerelle.core.Port; import com.isencia.passerelle.core.PortFactory; import com.isencia.passerelle.message.ManagedMessage; import com.isencia.passerelle.process.actor.Actor; import com.isencia.passerelle.process.actor.ProcessRequest; import com.isencia.passerelle.process.actor.ProcessResponse; import com.isencia.passerelle.process.model.Context; import com.isencia.passerelle.process.service.ProcessManager; /** * A transformer actor that allows to manipulate Context entries. * <p> * An entry is identified by a <code>scope</code>, a <code>name</code> and a <code>value</code>. The scope acts as a * parent "namespace", within which each specific entry has a unique name. <br/> * Technically this is implemented in a basic way by maintaining a separate <code>Map<String,String></code> for each * scope and storing each entry as a simple entry in such a map. <br/> * An empty scope identifies the "main" level, i.e. directly into the received <code>Context</code>'s entries map. * </p> * <p> * <ul> * <li>Set : set a new entry or overwrite an existing with same scope&name</li> * <li>Remove : remove an existing entry; do nothing if it is not found. <br/> * A remove with only a scope and no entry name will remove the complete scope in one shot.</li> * </ul> * </p> */ @SuppressWarnings("serial") @Deprecated public class ContextEntryModifier extends Actor { private enum Mode { Set, Remove; } public Port input; public Port output; public StringParameter entryScopeParameter; public StringParameter entryNameParameter; public StringParameter entryValueParameter; public StringParameter modeParameter; /** * @param container * @param name * @throws IllegalActionException * @throws NameDuplicationException */ public ContextEntryModifier(CompositeEntity container, String name) throws IllegalActionException, NameDuplicationException { super(container, name); input = PortFactory.getInstance().createInputPort(this, null); output = PortFactory.getInstance().createOutputPort(this); entryScopeParameter = new StringParameter(this, "Entry scope"); entryNameParameter = new StringParameter(this, "Entry name"); entryValueParameter = new StringParameter(this, "Entry value"); modeParameter = new StringParameter(this, "Mode"); modeParameter.addChoice(Mode.Set.name()); modeParameter.addChoice(Mode.Remove.name()); modeParameter.setExpression(Mode.Set.name()); } /** * An illustration of validating the parameter settings. E.g. for the mode parameter, we expect either Add, Modify or * Remove, but this constraint can not be enforced with 100% certainty in model files. So we can check it again here. */ @Override protected void validateInitialization() throws ValidationException { super.validateInitialization(); String mode = modeParameter.getExpression(); try { Mode.valueOf(mode); } catch (IllegalArgumentException e) { throw new ValidationException(ErrorCode.ACTOR_INITIALISATION_ERROR, "Invalid mode " + mode, this, null); } } @Override public void process(ProcessManager processManager, ProcessRequest request, ProcessResponse response) throws ProcessingException { ManagedMessage message = request.getMessage(input); if (message != null) { try { Context diagnosisContext = ProcessRequest.getContextForMessage(processManager, message); String entryName = entryNameParameter.getExpression(); String entryValue = entryValueParameter.getExpression(); String scopeStr = entryScopeParameter.getExpression(); String modeStr = modeParameter.getExpression(); if (scopeStr == null || scopeStr.trim().length() == 0) { doItOnMainContext(diagnosisContext, modeStr, entryName, entryValue); } else { doItOnScope(diagnosisContext, modeStr, scopeStr, entryName, entryValue); } response.addOutputMessage(output, message); } catch (Exception e) { throw new ProcessingException(ErrorCode.ACTOR_EXECUTION_ERROR, "Failed to modify Context entries", this, message, e); } } } /** * * @param diagnosisContext * @param modeStr * @param scopeStr * @param entryName * @param entryValue * @throws IllegalStateException * e.g. when the Context has a conflicting entry for e.g. scope * @throws IllegalArgumentException * e.g. when an invalid mode is passed */ @SuppressWarnings("unchecked") private void doItOnScope(Context diagnosisContext, String modeStr, String scopeStr, String entryName, String entryValue) throws IllegalStateException, IllegalArgumentException { Object scopeObj = diagnosisContext.getEntryValue(scopeStr); HashMap<String, String> scopeMap = null; if (scopeObj != null) { try { scopeMap = (HashMap<String, String>) scopeObj; } catch (ClassCastException e) { throw new IllegalStateException("Context entry scope not a Map for " + scopeStr); } } Mode mode = Mode.valueOf(modeStr); switch (mode) { case Set: if (scopeMap == null) { scopeMap = new HashMap<String, String>(); diagnosisContext.putEntry(scopeStr, scopeMap); } scopeMap.put(entryName, entryValue); break; case Remove: if (scopeMap != null) { if (StringUtils.isEmpty(entryName)) { // it's a remove for the complete scope diagnosisContext.removeEntry(scopeStr); } else { // it's a remove for one specific entry scopeMap.remove(entryName); } } break; } } private void doItOnMainContext(Context diagnosisContext, String modeStr, String entryName, String entryValue) { Mode mode = Mode.valueOf(modeStr); switch (mode) { case Set: diagnosisContext.putEntry(entryName, entryValue); break; case Remove: diagnosisContext.removeEntry(entryName); break; } } }
Markdown
UTF-8
552
3
3
[]
no_license
--- layout: post title: mysqlでGROUP BYした際に同じカラム名の値も表示したい date: 2018-02-08 03:19:25 categories: mysql sql --- <p>下記のようなテーブルとレコードがあります。</p> <p>id | user_id | amount | type<br> 1 | 1 | 100 | a<br> 2 | 1 | 200 | b<br> 3 | 1 | 300 | c<br> 4 | 2 | 1000 | a<br> 5 | 2 | 1500 | b<br> 6 | 2 | 2000 | c</p> <p>これを下記のように取得したいのですがmysqlで可能でしょうか?</p> <p>user_id | a | b | c<br> 1 | 100 | 200 | 300<br> 2 | 1000 | 1500 | 2000</p>
JavaScript
UTF-8
1,170
3.53125
4
[]
no_license
var convertNumberToHex = function( num ) { var hexDigits = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']; var current = ['0','0']; var hexCounter = 1; var placeValue = 1; for ( var i = 1; i <= num; i++ ) { // if number is not at F if( hexCounter !== 16 ) { // replace it with the next highest current.pop(); current.push( hexDigits[hexCounter] ); hexCounter++; // if number is maxed out at F } else { // if it's not time to increase place values if( current[placeValue - 1] !== 'F' ) { hexCounter = 0; // increase the value of the digit previous to the PV we're changing current[placeValue - 1] = hexDigits[ hexDigits.indexOf( current[placeValue - 1] ) + 1 ]; current.pop(); current.push( hexDigits[hexCounter] ); hexCounter++; } else { // Highest colors go is FF return 'FF'; } } }; return current.join(''); }; var rgb = function(n1, n2, n3) { var output = []; for (var i = 0; i < arguments.length; i++) { output.push( convertNumberToHex(arguments[i]) ); }; return output.join(''); };
JavaScript
UTF-8
2,475
2.53125
3
[]
no_license
import React, { Component } from "react"; import "./UserSettings.scss"; import {getToken} from "../../../Utils/Common"; import { NavLink } from 'react-router-dom'; class UserSettings extends Component { constructor() { super(); this.state = { email: "", password: "", oldPassword: "", confirmPassword: "", }; } handleUserInput = (e) => { const name = e.target.name; const value = e.target.value; this.setState({ [name]: value}); }; handleClick = () => { console.log(this.state.email); console.log(this.state.oldPassword); console.log(this.state.password); console.log(this.state.confirmPassword); fetch("http://localhost:5295/Profile/ChangePassword", { method: "post", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}`, }, body: JSON.stringify(this.state), }) // .then((res) => res.json()) .then((result) => { this.setState({ data: result, }); }); }; render() { return ( <div className="setting"> <h2 htmlFor="email"> поменять пароль</h2> <label htmlFor="email">E-mail</label> <input type="email" name="email" placeholder="Email" value={this.state.email} onChange={this.handleUserInput} /> <label htmlFor="password">Введите старый пароль</label> <input type="password" name="oldPassword" placeholder="Введите старый пароль" value={this.state.oldPassword} onChange={this.handleUserInput} /> <label htmlFor="password">Введите новый пароль</label> <input type="password" name="password" placeholder="Введите новый пароль" value={this.state.password} onChange={this.handleUserInput} /> <label htmlFor="password">Повторите пароль</label> <input type="password" name="confirmPassword" placeholder="Повторите пароль" value={this.state.confirmPassword} onChange={this.handleUserInput} /> <input type="button" value="Change" onClick={this.handleClick} /> <NavLink to='/'>Вернуться</NavLink> </div> ); } } export default UserSettings;
Java
UTF-8
4,631
3.40625
3
[]
no_license
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; import java.awt.Font; /** * @author Vasilis Bilbilis * @version 1.0 Version */ public class Clock extends Actor { private int startingTime; private int seconds; private int clockType = 0; private long lastCurrentSecond; private long timeSaved = 0; public boolean timeUp = false; private boolean count = false; private boolean displayTime; private boolean countDown; private String text; private int min; private int sec; /** * Create a new Clock with your own text or other values. * * @param countDown * Set the kind of the clock. If true the clock will cound down from the given starting time. Otherwise it'll count up from 0. * * @param displayTime * Set the clock's visibility. If true the clock is visible. * * @param startingTime * The starting time for countdown clocks. If you restart the clock it'll start from this value. * * @param text * The text above the clock. If text is null the clock will be centered and there is no text. */ public Clock(boolean countDown, boolean displayTime, int startingTime, String text) { this.countDown = countDown; this.displayTime = displayTime; this.startingTime = startingTime; this.text = text; seconds = startingTime; getImage().clear(); if (!countDown) { seconds = 0; } if (displayTime) { getImage().scale(130, 70); } this.startClock(); } /** * The act method of the class Clock. * Let the clock count the time. If the act method is not executed the clock will count on but not change it's image. To pause the clock use the method stopClock(). * The Clock is irrespective of the acting speed of the scenario so that it doesn't mater how fast the other act methods are executed. */ public void act() { if (countDown) { if (count && !timeUp) { if (System.currentTimeMillis() - lastCurrentSecond >= 1000) { lastCurrentSecond += 1000; seconds--; if (displayTime) { drawTime(); } } if (seconds == 0) { timeUp = true; } } } } /** * The drawing method of the clock. * This method draws the current value of your clock onto the clock object. */ private void drawTime() { min = (int) (seconds / 60); sec = seconds % 60; String remainingTime; if (sec < 10) { remainingTime = min + ":0" + sec; } else { remainingTime = min + ":" + sec; } //getImage().setColor(Color.black); //getImage().fill(); getImage().clear(); GreenfootImage text = new GreenfootImage((this.text == null ? "" : this.text), 30, Color.white, new Color(0, 0, 0, 0)); GreenfootImage time = new GreenfootImage(remainingTime, 40, Color.white, new Color(0, 0, 0, 0)); /**if (text.getWidth() > getImage().getWidth()) { getImage().clear(); getImage().scale(text.getWidth() + 10, 70); getImage().setColor(Color.gray); getImage().fill(); }*/ getImage().drawImage(text, (getImage().getWidth()/2)-(text.getWidth()/2), 5); getImage().drawImage(time, (getImage().getWidth()/2)-(time.getWidth()/2), (this.text == null ? (getImage().getHeight()/2)-(time.getHeight()/2) : 30)); } /** * Check whether the time is up. * * @return * Returns true if the time is up. If the clock is no countdown clock the method will return false. */ public boolean timeUp() { return timeUp; } /** * Start the clock. */ public void startClock() { lastCurrentSecond = System.currentTimeMillis() - timeSaved; count = true; } /** * Pause the clock. */ public void stopClock() { timeSaved = System.currentTimeMillis() - lastCurrentSecond; count = false; } /** * Reset the clock. */ public void resetClock() { seconds = startingTime; timeUp = false; } }
C++
UTF-8
1,152
2.890625
3
[]
no_license
#include<iostream> #include<queue> #include<numeric> using namespace std; const int n = 5; double avg_waiting_time(int at[], int bt[]) { int rem_bt[n], wt[n] = {0}; copy(bt, bt+n, rem_bt); queue<int> processes; int curr_t = 0, time_quantum = 2, i = 0; while(at[i]<=curr_t) processes.push(i++); int total_t = 0; total_t = accumulate(bt,bt+n,total_t); while(curr_t < total_t) { int curr_p = processes.front(); processes.pop(); if(rem_bt[curr_p] > time_quantum) { curr_t+=time_quantum; rem_bt[curr_p]-=time_quantum; } else { curr_t+=rem_bt[curr_p]; rem_bt[curr_p] = 0; wt[curr_p] = curr_t - at[curr_p] - bt[curr_p]; }while(at[i]<=curr_t && i<n) processes.push(i++); if(rem_bt[curr_p] > 0) processes.push(curr_p); } double avg_wt = 0; avg_wt = accumulate(wt, wt+n, avg_wt)/n; return avg_wt; } int main() { int arrival_t[n] = {0,2,3,5,6}; int burst_t[n] = {4,3,2,3,1}; cout<<"Average waiting time : "<<avg_waiting_time(arrival_t, burst_t); return 0; }
Java
UTF-8
719
2.0625
2
[]
no_license
package com.am.trendo.repo; import android.arch.lifecycle.LiveData; import android.content.Context; import android.location.Location; import com.am.trendo.model.Sale; import java.util.List; import io.reactivex.Completable; import io.reactivex.Single; public interface DataRepo { Single<List<Sale>> getTopSales(); Single<List<Sale>> getNearbySales(Location location); LiveData<List<Sale>> getFavorites(Context context); Single<Sale> getSaleById(String saleId); Completable addToFavorite(Sale sale, Context context); Completable removeFavorite(Sale sale, Context context); Single<Boolean> isFavorite(Context context, String saleId); void addSaleAlarm(Context context, Sale sale); }
C#
UTF-8
7,037
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dominio; using System.Data.SqlClient; using AccesoDatos; namespace Negocio { public class ArticuloNegocio { public List<Articulo> listarArticulos() { SqlConnection conexion = new SqlConnection(); SqlCommand comando = new SqlCommand(); SqlDataReader lector; List<Articulo> listado = new List<Articulo>(); Articulo articulo; //PoderSecundarioNegocio poderSecundarioNegocio = new PoderSecundarioNegocio(); try { conexion.ConnectionString = AccesoDatosManager.cadenaConexion; comando.CommandType = System.Data.CommandType.Text; //MSF-20190420: agregué todos los datos del heroe. Incluso su universo, que lo traigo con join. comando.CommandText = "select A.Id, A.Codigo, A.Nombre, A.Descripcion, A.IdMarca, M.Descripcion as Marca, A.IdCategoria, C.Descripcion as Categoria, A.Imagen, A.Precio " + "From ARTICULOS A, MARCAS M, CATEGORIAS C where A.IdMarca = M.Id AND A.IdCategoria = C.Id"; comando.Connection = conexion; conexion.Open(); lector = comando.ExecuteReader(); while (lector.Read()) { articulo = new Articulo(); articulo.Id = (int)lector["Id"]; if (!Convert.IsDBNull(lector["Codigo"])) articulo.Codigo = (string)lector["Codigo"]; if (!Convert.IsDBNull(lector["Nombre"])) articulo.Nombre = (string)lector["Nombre"]; if (!Convert.IsDBNull(lector["Descripcion"])) articulo.Descripcion = (string)lector["Descripcion"]; if (!Convert.IsDBNull(lector["IdMarca"])) articulo.Marca = new CodigoDescripcion(); articulo.Marca.Id = (int)lector["IdMarca"]; articulo.Marca.Descripcion = (string)lector["Marca"]; if (!Convert.IsDBNull(lector["IdCategoria"])) articulo.Categoria = new CodigoDescripcion(); articulo.Categoria.Id = (int)lector["IdCategoria"]; articulo.Categoria.Descripcion = (string)lector["Categoria"]; if (!Convert.IsDBNull(lector["Precio"])) { articulo.Precio = decimal.Round((decimal)lector["Precio"],2); } listado.Add(articulo); } return listado; } catch (Exception ex) { throw ex; } finally { conexion.Close(); } } public void agregarArticulo(Articulo nuevo) { AccesoDatosManager accesoDatos = new AccesoDatosManager(); SqlConnection conexion = new SqlConnection(); SqlCommand comando = new SqlCommand(); try { //conexion.ConnectionString = AccesoDatosManager.cadenaConexion; //comando.CommandType = System.Data.CommandType.Text; ////MSF-20190420: le agregué todas las columnas. Teniendo en cuenta inclusive lo que elegimos en el combo de selección.. //comando.CommandText = "insert into ARTICULOS (Codigo, Nombre, Descripcion, IdMarca, IdCategoria, Precio) values"; //comando.CommandText += "('" + nuevo.Codigo + "', '" + nuevo.Nombre + "', '" + nuevo.Descripcion + "', " + // nuevo.Marca.Id + "," + nuevo.Categoria.Id + ", @Precio)"; //comando.Parameters.AddWithValue("@Precio", nuevo.Precio); //comando.Connection = conexion; //conexion.Open(); accesoDatos.setearConsulta("insert into ARTICULOS (Codigo, Nombre, Descripcion, IdMarca, IdCategoria, Precio, Imagen) values (@Codigo, @Nombre, @Descripcion, @IdMarca, @IdCategoria, @Precio, @Imagen)"); accesoDatos.Comando.Parameters.Clear(); accesoDatos.Comando.Parameters.AddWithValue("@Codigo", nuevo.Codigo); accesoDatos.Comando.Parameters.AddWithValue("@Nombre", nuevo.Nombre); accesoDatos.Comando.Parameters.AddWithValue("@Descripcion", nuevo.Descripcion); accesoDatos.Comando.Parameters.AddWithValue("@IdMarca", nuevo.Marca.Id); accesoDatos.Comando.Parameters.AddWithValue("@IdCategoria", nuevo.Categoria.Id); accesoDatos.Comando.Parameters.AddWithValue("@Precio", nuevo.Precio); accesoDatos.Comando.Parameters.AddWithValue("@Imagen", nuevo.Imagen); accesoDatos.abrirConexion(); accesoDatos.ejecutarAccion(); } catch (Exception ex) { throw ex; } finally { accesoDatos.cerrarConexion(); } } public void modificarArticulo(Articulo articulo) { AccesoDatosManager accesoDatos = new AccesoDatosManager(); try { accesoDatos.setearConsulta("update ARTICULOS Set Codigo=@Codigo, Nombre=@Nombre, Descripcion=@Descripcion, IdMarca=@IdMarca, IdCategoria=@IdCategoria, Precio=@Precio Where Id=" + articulo.Id.ToString()); accesoDatos.Comando.Parameters.Clear(); accesoDatos.Comando.Parameters.AddWithValue("@Codigo", articulo.Codigo); accesoDatos.Comando.Parameters.AddWithValue("@Nombre", articulo.Nombre); accesoDatos.Comando.Parameters.AddWithValue("@Descripcion", articulo.Descripcion); accesoDatos.Comando.Parameters.AddWithValue("@IdMarca", articulo.Marca.Id); accesoDatos.Comando.Parameters.AddWithValue("@IdCategoria", articulo.Categoria.Id); accesoDatos.Comando.Parameters.AddWithValue("@Precio", articulo.Precio); accesoDatos.abrirConexion(); accesoDatos.ejecutarAccion(); } catch (Exception ex) { throw ex; } finally { accesoDatos.cerrarConexion(); } } public void eliminarArticulo (int id) { AccesoDatosManager datos = new AccesoDatosManager(); try { datos.abrirConexion(); datos.setearConsulta("delete from ARTICULOS where id =" + id); datos.ejecutarAccion(); datos.cerrarConexion(); } catch (Exception ex) { throw ex; } } } }
C++
UTF-8
4,534
2.796875
3
[]
no_license
#include "Game\Public\Factory.h" Factory* Singleton<Factory>::mSingleton = nullptr; int Factory::mMissiliesAvailable = 25; std::hash<std::string> s_hash; GameObject* Factory::CreateCity(Hash hash, exEngineInterface* pEngine, exVector2 startPosition) { const float CITY_WIDTH = 50.0f; const float CITY_HEIGHT = 10.0f; exColor cityColor; cityColor.SetColor(64, 22, 153, 255); GameObject* city = new GameObject(hash); COGTransform* pTransform = new COGTransform(city, startPosition); city->AddComponent(pTransform); COGBoxShape* pBoxShape = new COGBoxShape(pEngine, city, CITY_WIDTH, CITY_HEIGHT, cityColor); city->AddComponent(pBoxShape); COGPhysics* pPhysics = new COGPhysics(city, true, GameObjectType::City); city->AddComponent(pPhysics); city->Initialize(); return city; } GameObject* Factory::CreateMissile(Hash hash, exEngineInterface* pEngine, exVector2 startPosition, exVector2 finalPosition, exColor color, bool collisionActive, GameObjectType type) { exColor missileColor = color; GameObject* missile = new GameObject(hash); COGTransform* pTransform = new COGTransform(missile, startPosition); missile->AddComponent(pTransform); COGMissileController* pMissileController = new COGMissileController(missile, pTransform, pEngine); pMissileController->SetVectorToMissile(finalPosition); missile->AddComponent(pMissileController); COGLineShape* pLineShape = new COGLineShape(pEngine, missile, startPosition, missileColor); missile->AddComponent(pLineShape); COGPhysics* pPhysics = new COGPhysics(missile, collisionActive, type); missile->AddComponent(pPhysics); missile->Initialize(); return missile; } GameObject* Factory::CreateGameObject(exEngineInterface* pEngine, exVector2 startPosition, GameObjectType gameType) { GameObject* newGameObject; ++mIdentify; switch (gameType) { case GameObjectType::City: { ++mCities; return newGameObject = CreateCity(s_hash("City" + std::to_string(mIdentify)), pEngine, startPosition); } case GameObjectType::Explosion: return newGameObject = CreateExplosion(s_hash("Explosion" + std::to_string(mIdentify)), pEngine, startPosition); default: std::cout << "Wrong type" << std::endl; return nullptr; } } GameObject* Factory::CreateMissiles(exEngineInterface* pEngine, exVector2 startPosition, exVector2 finalPosition, GameObjectType gameType) { GameObject* newGameObject; ++mIdentify; switch (gameType) { case GameObjectType::MissileFriend: { --Factory::mMissiliesAvailable; exColor friendColor; friendColor.SetColor(255, 255, 255, 255); return newGameObject = CreateMissile(s_hash("Missile" + std::to_string(mIdentify)), pEngine, startPosition, finalPosition, friendColor, false, GameObjectType::MissileFriend); } case GameObjectType::MissileEnemy: { exColor enemyColor; enemyColor.SetColor(200, 0, 20, 255); return newGameObject = CreateMissile(s_hash("MissileEnemy" + std::to_string(mIdentify)), pEngine, startPosition, finalPosition, enemyColor, true, GameObjectType::MissileEnemy); } default: std::cout << "Wrong type" << std::endl; return nullptr; } } GameObject* Factory::CreateExplosion(Hash hash, exEngineInterface* pEngine, exVector2 startPosition) { exColor explosionColor; explosionColor.mColor[0] = 255; explosionColor.mColor[1] = 255; explosionColor.mColor[2] = 196; explosionColor.mColor[3] = 255; float Radius = 40.0f; GameObject* explosion = new GameObject(hash); COGTransform* pTransform = new COGTransform(explosion, startPosition); explosion->AddComponent(pTransform); COGExplosion* pExplosion = new COGExplosion(pEngine, explosion, pTransform, startPosition, explosionColor); explosion->AddComponent(pExplosion); COGExplosionController* pExplosionController = new COGExplosionController(explosion, pTransform, Radius); explosion->AddComponent(pExplosionController); COGPhysics* pPhysics = new COGPhysics(explosion, true, GameObjectType::Explosion); explosion->AddComponent(pPhysics); explosion->Initialize(); return explosion; } void Factory::addToStaleList(GameObject* gameObject) { if (gameObject->GetHandle().IsValid()) { if (gameObject->FindComponent<COGBoxShape>(ComponentType::BoxShape) != nullptr) { --mCities; } mStaleGameObjects.push_back(gameObject); } } void Factory::cleanStaleList() { if (mStaleGameObjects.size() > 0) { for (int i = 0; i < (int)mStaleGameObjects.size(); ++i) { GameObjectInventory::Instance()->Unregister(mStaleGameObjects[i]); mStaleGameObjects.erase(mStaleGameObjects.begin() + i); } } }
C#
UTF-8
6,500
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using StapeleyDigital.AthleticsData.Data; using StapeleyDigital.AthleticsData.Dto; namespace StapeleyDigital.AthleticsData.Api.Controllers { [Route("api/athletes")] [Produces("application/json")] public class AthletesController : Controller { private readonly IAthleteRepository _athleteRepository; private readonly IDeviceRepository _deviceRepository; private readonly IPerformanceRepository _performanceRepository; private readonly IEventRepository _eventRepository; private readonly ILogger<AthletesController> _logger; private readonly IMapper _mapper; public AthletesController(IAthleteRepository athleteRepository, IDeviceRepository deviceRepository, IPerformanceRepository performanceRepository, IEventRepository eventRepository, ILogger<AthletesController> logger, IMapper mapper) { _athleteRepository = athleteRepository; _deviceRepository = deviceRepository; _performanceRepository = performanceRepository; _eventRepository = eventRepository; _logger = logger; _mapper = mapper; } /// <summary> /// Gets athletes /// </summary> /// <remarks> /// <![CDATA[ /// Sample Request: /// /// GET /athletes?uniqueDeviceId=abc123 /// /// ]]> /// /// </remarks> /// <returns>A collection of athletes</returns> /// <response code="200">Returns the collection of athletes</response> /// <response code="400">If the device id supplied was not found</response> [HttpGet()] [ProducesResponseType(typeof(IEnumerable<AthleteDto>), 200)] [ProducesResponseType(400)] public IActionResult GetAthletes(string uniqueDeviceId = null) { try { if (uniqueDeviceId != null) { // Validate the device exists if (!_deviceRepository.DeviceExists(uniqueDeviceId)) { return NotFound(); } var athleteEntities = _athleteRepository.GetAthletesByDevice(uniqueDeviceId); var results = _mapper.Map<IEnumerable<AthleteDto>>(athleteEntities); return Ok(results); } else { var athleteEntities = _athleteRepository.GetAthletes(); var results = _mapper.Map<IEnumerable<AthleteDto>>(athleteEntities); return Ok(results); } } catch (Exception ex) { _logger.LogCritical($"Exception while getting athletes", ex); return StatusCode(500, "A problem happened while handling your request"); } } /// <summary> /// Gets an athlete using the id. /// </summary> /// <remarks> /// <![CDATA[ /// Sample Request: /// /// GET /athletes/1 /// /// ]]> /// /// </remarks> /// <param name="id">The identifier for the athlete</param> /// <returns></returns> /// <response code="200">Returns the athlete</response> /// <response code="404">If the athlete is not found</response> [HttpGet("{id}")] [ProducesResponseType(typeof(AthleteDto), 200)] [ProducesResponseType(404)] public IActionResult GetAthlete(int id) { try { var athleteEntity = _athleteRepository.GetAthlete(id); if (athleteEntity == null) { return NotFound(); } var athleteResult = _mapper.Map<AthleteDto>(athleteEntity); return Ok(athleteResult); } catch (Exception ex) { _logger.LogCritical($"Exception while getting athlete with identifier {id}", ex); return StatusCode(500, "A problem happened while handling your request"); } } /// <summary> /// Gets performances for an athlete /// </summary> /// <remarks> /// <![CDATA[ /// Sample Request: /// /// GET /athletes/1/performances /// /// ]]> /// /// </remarks> /// <param name="id">The Identifier for the athlete</param> /// <param name="eventId">Optional Event Filter</param> /// <returns>A collection of performances</returns> /// <response code="200">Returns the collection of performances</response> /// <response code="404">The athlete could not be found</response> [HttpGet("{id:int}/performances")] [ProducesResponseType(typeof(IEnumerable<PerformanceDto>), 200)] [ProducesResponseType(404)] public IActionResult GetPerformancesByAthlete(int id, int? eventId = null) { try { var athleteEntity = _athleteRepository.GetAthlete(id); if (athleteEntity == null) { return NotFound(); } var performanceEntities = _performanceRepository.GetPerformancesByAthlete(id); if (eventId.HasValue) { var eventEntity = _eventRepository.GetEvent(eventId.Value); if (eventEntity==null) { return NotFound($"Event {eventId} does not exist"); } performanceEntities = performanceEntities.Where(x => x.EventId == eventId.Value); } var results = _mapper.Map<IEnumerable<PerformanceDto>>(performanceEntities); return Ok(results); } catch (Exception ex) { _logger.LogCritical($"Exception while getting performances for athlete {id}", ex); return StatusCode(500, "A problem happened while handling your request"); } } } }
Java
UTF-8
742
2.796875
3
[]
no_license
package br.com.thegabrielfalcao.designpatterns.chainofresponsability.alura.calculadora.desconto.impl; import br.com.thegabrielfalcao.designpatterns.chainofresponsability.alura.calculadora.model.Orcamento; import br.com.thegabrielfalcao.designpatterns.chainofresponsability.alura.calculadora.desconto.Desconto; public class DescontoPorCincoItens implements Desconto { private Desconto desconto; @Override public void proximoDesconto(Desconto desconto) { this.desconto = desconto; } @Override public double calcular(Orcamento orcamento) { if (orcamento.getItens().size() > 4) { return orcamento.getValorFinal() * 0.05; } return desconto.calcular(orcamento); } }
Java
UTF-8
2,992
2.140625
2
[]
no_license
package com.lvsint.abp.server.managers; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import uk.co.abp.SessionException; import uk.co.abp.Workspace; import com.lvsint.abp.promotion.beans.CampaignPromotionReward; import com.lvsint.abp.server.stores.CampaignPromotionRewardStore; public interface CampaignPromotionRewardManager { public void setCampaignPromotionRewardStore(CampaignPromotionRewardStore campaignPromotionRewardStore); public CampaignPromotionReward insert(Workspace workspace, CampaignPromotionReward campaignPromotionReward) throws SessionException; /** * * Promotional money that has been manually adjusted to an account must in some way shape or form be linked to an * actual rewarded promotion that rewarded 'PROMO_MONEY'. This tightly couples together then all the logic re. * Campaign Promotion Reward, referencing the special bucket Promotion Reward (id -1) that all ex gratia payments to * expiring promotional cash, using promotional cash to fund bets etc. This method will create and insert the go * into. * * @param workspace * @param accountId the id of the account that we are adjusting * @param transactionId the transaction id of the adjustment that uses the PROMO colour of money. This will be * stored in both the triggering and rewarding transaction id in the created CampaignPromotionReward * @param credit the amount to be adjusted. * @return * @throws SessionException */ public CampaignPromotionReward insertAdhocReward(Workspace workspace, long accountId, long transactionId, BigDecimal credit) throws SessionException; public CampaignPromotionReward get(Workspace workspace, Long campaignPromotionRewardId) throws SessionException; public void delete(Workspace workspace, Long campaignPromotionRewardId) throws SessionException; public List<CampaignPromotionReward> getAllByAccountId(Workspace workspace, long accountId) throws SessionException; public List<CampaignPromotionReward> get(Workspace workspace, long transactionId, long campaignPromoId) throws SessionException; public List<CampaignPromotionReward> getByAccountIdAndCampaignPromoId(Workspace workspace, long accountId, long campaignPromoId) throws SessionException; public List<CampaignPromotionReward> getByAccountIdCampaignPromoIdAndPromotionRewardReference(Workspace workspace, long accountId, long campaignPromoId, long promotionRewardReference) throws SessionException; HashMap<Long, BigDecimal> findAvailablePromotionRewardCreditsForAccount(Workspace workspace, long accountId) throws SessionException; void insert(Workspace workspace, long transactionId, Map<Long, BigDecimal> campaignPromotionRewardDebits) throws SessionException; }
Markdown
UTF-8
3,749
3.140625
3
[]
no_license
--- layout: post title: "Migrate blog from Wordpress to Orchard CMS" description: How to migrate the content of a Wordpress blog to an Orchard CMS website using XML and XSL. tags: Orchard, Wordpress, CMS, xml, xsd, import, export date: 2011-05-28 14:15:39 assets: assets/posts/2011-05-28-migrate-blog-from-wordpress-to-orchard-cms image: author: name: Mikael Lundin email: hello@mikaellundin.name web: http://mikaellundin.name twitter: mikaellundin github: miklund linkedin: miklund --- As I mentioned before, I'm working on a replacement for this blog. I'm going to migrate to Orchard CMS, mostly to learn that content management system. This has been a pleasant experience so far. Before I can release my new blog I need to move all my content from Wordpress to Orchard CMS. Someone (not me) should really think about writing a module to make this a pleasant journey. I did this manually, because I only expect to do it once. ## Export from Wordpress ![Wordpress export XML](/assets/posts/2011-05-28-migrate-blog-from-wordpress-to-orchard-cms/wpexport.png) Wordpress has an export function. You find it in Tools menu. This is cool, except that the format is some weird kind of RSS, that is extended with Wordpress' own xml elements. Fine. Let's see what we can do about this. {% gist miklund/77c6361c66a119661d5c wordpressexport.xml %} This is your whole Wordpress exported in one file. You will have draft messages, spam comments and even pages in there. All you're probably interested in is published pages and accepted comments. If you want to make some bulk action to your blog data, you should do it now. I'm thinking, changing all the absolute paths from old blog address to the new blog address with a quick, search and replace. I forgot to do that, and now have to go through 180 blog posts manually. Not that I mind very much. I had planned to do that anyway. ## Import into Orchard CMS ![Orchard export XML](/assets/posts/2011-05-28-migrate-blog-from-wordpress-to-orchard-cms/orchardimport.png) Go to the modules gallery, find and install the Orchard Team Install Export module. As the name of the module surely reveal, it let's you import and export data into Orchard. To find out what kind of XML Schema Orchard uses, try writing a couple of blog posts, comments and export it. It should look something like this {% gist miklund/77c6361c66a119661d5c orchardexport.xml %} Now we have our data in Wordpress xml format, and we would like to transform it into Orchard xml format to import it into our new blog. For that we will use my favorite tool. ## Transforming the export data into import data We use XSLT to transform from one xml format into another. We could use ordinary scripting, but xslt makes it so easy. Here's the script that I used. Excuse me for the VBScript part, but I got lazy and took the simple way out when I had to transform date formats. {% gist miklund/77c6361c66a119661d5c stylesheet.xsl %} Now you add the following line on the top of the Wordpress xml file, on line 2, under the xml declaration. ```xml <?xml-stylesheet type="text/xsl" href="import.xslt" ?> ``` At this point it would be pretty simple to create an import from wordpress Orchard module, but I just want to solve my problem and move on. That is why I open my Wordpress xml-file in Internet Explorer and let that transform it for me. Press F12 and you will have the ability to save the whole transformed file to disc. ![internet explorer dev tool](/assets/posts/2011-05-28-migrate-blog-from-wordpress-to-orchard-cms/iedevtool.png) Now you can use that file to import your goodies into Orchard. Don't forget to move wp-content into your media library also and change all the media links accordingly. Not very hard, was it?
Swift
UTF-8
789
2.65625
3
[]
no_license
// // newRecipeTableViewCell.swift // SimpleTable // // Created by Fang Liu Frank on 5/3/17. // Copyright © 2017 Fang Liu Frank. All rights reserved. // import UIKit class newRecipeTableViewCell: UITableViewCell { @IBOutlet weak var recipeTitle: UILabel! func configureCell(task:NewRecipe){ if let name = task.name { recipeTitle.text = name if let newIng = task.ingredients{ print(newIng) } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
PHP
UTF-8
971
2.796875
3
[]
no_license
<?php function dbconnect($host,$id,$pass,$db){ // 데이터베이스 연결 $connect = mysqli_connect($host,$id,$pass,$db); if($connect == false){ die('Database Not Connected :'.mysqli_error()); } return $connect; } function msg($msg){ // 경고 메세지 출력 후 이전 페이지로 이동 echo " <meta http-equiv=\"Content-Type\"content=\"text/html; charset=euc-kr\"/> <script> window.alert('$msg'); history.go(-1); </script> "; } function s_msg($msg){ // 일반 메세지 출력 echo " <meta http-equiv=\"Content-Type\"content=\"text/html; charset=euc-kr\"/> <script> window.alert('$msg'); </script> "; } function check_injection($input){ $input = preg_replace("/[\r\n\s\t\'\;\"\=\-\-\#\/*]+/","", $input); if(preg_match('/(union|select|from|where)/i', $input)){ msg("No SQL-Injection"); } return $input; }
Java
UTF-8
83
2.0625
2
[]
no_license
package oop; public abstract class Controller { public abstract void update(); }