language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
279
1.914063
2
[]
no_license
package com.example.codegym.service; import com.example.codegym.model.PersonalCode; public interface PersonalCodeService { void save(PersonalCode personalCode); PersonalCode findById(Integer id); void delete(Integer id); PersonalCode findByCode(String code); }
JavaScript
UTF-8
1,267
2.703125
3
[]
no_license
var NewPlane = React.createClass({ handleClick() { var model_id = this.refs.model_id.value; var description = this.refs.description.value; var latitude = this.refs.latitude.value; var longitude = this.refs.longitude.value; var elevation = this.refs.elevation.value; $.ajax({ url: '/api/v1/planes', type: 'POST', data: { plane: { model_id: model_id, description: description, datetime: new Date(), latitude: latitude, longitude: longitude, elevation: elevation }}, success: (plane) => { console.log(plane[model_id]) this.props.handleSubmit(plane); } }) }, render() { return ( <div> <h3>New Plane</h3> <input ref='model_id' placeholder='Enter a model number' /> {/* <input ref='datetime' placeholder='Enter a date and time (format: YYYY-MM-DD HH:MM:SS timezone)' /> */} <input ref='description' placeholder='Enter a description' /> <input ref='latitude' placeholder='Latitude' /> <input ref='longitude' placeholder='Logitude' /> <input ref='elevation' placeholder='Elevation' /> <button onClick={this.handleClick}>Submit</button> </div> ) } });
Java
UTF-8
3,994
2.21875
2
[]
no_license
package mobi.uta.campussynergy.Fragment; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Button; import java.util.ArrayList; import mobi.uta.campussynergy.Activity.MainActivity; import mobi.uta.campussynergy.R; /** * Created by Jstaud on 2/7/15. */ public class LoginLikesFragment extends Fragment { ArrayList<Boolean> picked; Button buttonGreekLife, buttonTech, buttonAcademics, buttonReligion, buttonStudyGroups, buttonMusic; View mOverlay; private Context context; public View.OnClickListener clicky = new View.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { /*case R.id.button1: toggle(buttonGreekLife); break;*/ /*case R.id.button2: toggle(1); break; case R.id.button3: toggle(2); break; case R.id.button4: toggle(3); break; case R.id.button5: toggle(4); break; case R.id.button6: toggle(5); break;*/ case R.id.button_back: getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.container, new LoginInfoFragment()) .commit(); break; case R.id.button_next: if(isInfoValidated()) { Intent i = new Intent(context, MainActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); getActivity().finish(); } break; } } }; public LoginLikesFragment() { } public static LoginLikesFragment newInstance() { return new LoginLikesFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_login_likes, container, false); context = root.getContext(); Button bNext = (Button) root.findViewById(R.id.button_next); Button bBack = (Button) root.findViewById(R.id.button_back); bNext.setOnClickListener(clicky); bBack.setOnClickListener(clicky); buttonGreekLife = (Button) root.findViewById(R.id.button1); buttonGreekLife.setEnabled(false); buttonTech = (Button) root.findViewById(R.id.button2); buttonAcademics = (Button) root.findViewById(R.id.button3); buttonReligion = (Button) root.findViewById(R.id.button4); buttonStudyGroups = (Button) root.findViewById(R.id.button5); buttonMusic = (Button) root.findViewById(R.id.button6); buttonGreekLife.setOnClickListener(clicky); buttonTech.setOnClickListener(clicky); buttonAcademics.setOnClickListener(clicky); buttonReligion.setOnClickListener(clicky); buttonStudyGroups.setOnClickListener(clicky); buttonMusic.setOnClickListener(clicky); return root; } public View getOverlay() { return mOverlay; } public void toggle(Button check){ } public ArrayList<Boolean> getPicked(){ return picked; } private boolean isInfoValidated() { //Fix dis shit return true; } }
JavaScript
UTF-8
2,050
3.109375
3
[]
no_license
// work on send/retrieve line 45 var price = 0; $(document).ready(function(){ var baseFile = "https://my.api.mockaroo.com/jerseys.json?key=0a8afae0"; // setup links $.getJSON(baseFile, function(data){ $("#product-list").empty(); // remove any old links // data is an array of product objects $.each(data, function(i, e){ var $price = $("<h5></h5>"); var $mascot = $("<p></p>"); var $city = $("<p></p>"); var $number = $("<p></p>"); var $a = $("<a href='#order-button'><b></b></a>"); var $li =$("<li></li>"); $a.text(e.name); $city.text(e.city); $mascot.text(e.mascot); $number.text(e.number); $price.text(e.price); price = $(e.price).value; $a.append($price); $city.append($city); $mascot.append($mascot); $number.append($number); $li.append($a, $number, $city, $mascot, $price); $("#product-list").append($li); $a.click(createClickHandler(e)); }); }); function createClickHandler(e) { return function onClick() { let details = "" details = e.description $("#product-details").text("Great choice! How many would you like?"); $("#order-button").show(); $("#label").show(); $("#quantity").show(); } } var orderButton = document.getElementById("order-button"); orderButton.onclick = function() { // MODAL var modal = document.getElementById("myModal"); var span = document.getElementsByClassName("close")[0]; //******************* Send quantity and retrieve total price here */ var total = 0; var quantity = $("#quantity").value; console.log(price); total = quantity*price; //******************* Display total price in $("#total-price") here */ $("#total-price").text( "Total: $" + total.toFixed(2) ); modal.style.display = "block"; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } } });
Swift
UTF-8
1,070
2.71875
3
[]
no_license
// // MovieCell.swift // PremierSwift // // Created by Gabriela Pittari on 13/10/2017. // import UIKit import RxSwift class MovieTableViewCell: UITableViewCell { private var disposeBag = DisposeBag() @IBOutlet var nameLabel: UILabel! @IBOutlet var posterImageView: UIImageView! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var averageLabel: UILabel! var movieViewModel: MovieTableViewModelType? { willSet { disposeBag = DisposeBag() } didSet { setupBindings() } } // asigning the value of the view model to the view func setupBindings() { guard let viewModel = movieViewModel else { return } viewModel.name.bind(to: nameLabel.rx.text).disposed(by: disposeBag) viewModel.overview.bind(to: descriptionLabel.rx.text).disposed(by: disposeBag) viewModel.voteAverage.bind(to: averageLabel.rx.text).disposed(by: disposeBag) viewModel.posterImage.bind(to: posterImageView.rx.image).disposed(by: disposeBag) } }
PHP
UTF-8
283
2.703125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Eag\Banger\Validator; use Eag\Banger\Exception\InvalidBankAccountNumber; interface BankAccountValidator { /** * @throws InvalidBankAccountNumber */ public function validate(string $bankAccount, string $country): void; }
C#
UTF-8
4,025
2.53125
3
[]
no_license
using Diploma.Files; using Diploma.Models; using Diploma.Utils; using Diploma.Wrappers; using GemBox.Document; using Moq; using System; using System.Collections.Generic; using System.Text; using Xunit; namespace Diploma.Tests { public class FileWriterTests { private StudentModel GetSampleStudentModel() { var sampleStudentModel = new StudentModel { FirstName = "Vasily", LastName = "Pascal", Grades = new List<Subject> { new Subject { SubjectName = "Math", Grade = 7 }, new Subject { SubjectName = "Chemistry", Grade = 9 } } }; return sampleStudentModel; } [Fact] public void CreateDiplomas_GetFirstParargaphCalledOnce() { Mock<IDocWrapper> pdfWrapper = new Mock<IDocWrapper>(); Mock<IStringCreator> stringCreator = new Mock<IStringCreator>(); FileWriter sut = new FileWriter(pdfWrapper.Object, stringCreator.Object); var student = GetSampleStudentModel(); sut.CreateDiplomas(student); stringCreator.Verify(s => s.GetFirstParagraph(student.LastName, student.FirstName), Times.Once); } [Fact] public void CreateDiplomas_GetSecondParargaphTextCalledOnce() { Mock<IDocWrapper> pdfWrapper = new Mock<IDocWrapper>(); Mock<IStringCreator> stringCreator = new Mock<IStringCreator>(); FileWriter sut = new FileWriter(pdfWrapper.Object, stringCreator.Object); var student = GetSampleStudentModel(); sut.CreateDiplomas(student); stringCreator.Verify(t => t.GetSecondParagraphText(student.Grades), Times.Once); } //[Fact] //public void CreateDiplomas_ReturnsDocumentModel() //{ // ComponentInfo.SetLicense("FREE-LIMITED-KEY"); // Mock<IDocWrapper> pdfWrapper = new Mock<IDocWrapper>(); // Mock<IStringCreator> stringCreator = new Mock<IStringCreator>(); // FileWriter sut = new FileWriter(pdfWrapper.Object, stringCreator.Object); // var student = GetSampleStudentModel(); // var expectedDocument = new DocumentModel(); // string firstParagraphText = "Hello"; // var secondParagraphText = "World"; // stringCreator.Setup(s => s.GetFirstParagraph(It.IsAny<string>(), It.IsAny<string>())).Returns(firstParagraphText); // stringCreator.Setup(s => s.GetSecondParagraphText(It.IsAny<IEnumerable<Subject>>())).Returns(secondParagraphText); // expectedDocument.Sections.Add(new Section(expectedDocument, // new List<Paragraph>() { new Paragraph(expectedDocument, firstParagraphText), new Paragraph(expectedDocument, secondParagraphText) })); // var actual = sut.CreateDiplomas(student); // Assert.Equal(expectedDocument, actual); //} [Fact] public void SaveDiploma_CreathPath_CallOnce() { Mock<IDocWrapper> pdfWrapper = new Mock<IDocWrapper>(); Mock<IStringCreator> stringCreator = new Mock<IStringCreator>(); FileWriter sut = new FileWriter(pdfWrapper.Object, stringCreator.Object); sut.SaveDiploma(It.IsAny<DocumentModel>(), It.IsAny<string>(), It.IsAny<string>()); stringCreator.Verify(s => s.CreatePath(It.IsAny<string>(), It.IsAny<string>()), Times.Once); } [Fact] public void SaveDiploma_SaveDocument_CallOnce() { Mock<IDocWrapper> pdfWrapper = new Mock<IDocWrapper>(); Mock<IStringCreator> stringCreator = new Mock<IStringCreator>(); FileWriter sut = new FileWriter(pdfWrapper.Object, stringCreator.Object); sut.SaveDiploma(It.IsAny<DocumentModel>(), It.IsAny<string>(), It.IsAny<string>()); pdfWrapper.Verify(d => d.SaveDocument(It.IsAny<DocumentModel>(), It.IsAny<string>()), Times.Once()); } } }
JavaScript
UTF-8
4,358
3.421875
3
[ "MIT" ]
permissive
var cardValues = function() { var cardValues = new Map(); cardValues.set("A", 11); cardValues.set(2, 2); cardValues.set(3, 3); cardValues.set(4, 4); cardValues.set(5, 5); cardValues.set(6, 6); cardValues.set(7, 7); cardValues.set(8, 8); cardValues.set(9, 9); cardValues.set(10, 10); cardValues.set("J", 10); cardValues.set("Q", 10); cardValues.set("K", 10); return cardValues; } var createSuits = function() { var suits = ["clubs", "diamonds", "hearts", "spades"]; return suits; } var createValues = function() { var values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]; return values; } var createDeck = function() { var suits = createSuits(); var values = createValues(); var deck = []; for (var suit in suits) { for (var value in values) { deck.push([values[value], suits[suit]]); } } return deck; } var drawCard = function(deck) { var randomIndex = Math.floor((Math.random() * deck.length)); var drawnCard = deck[randomIndex]; deck.splice(randomIndex, 1); return drawnCard; } var createHand = function(deck) { var firstCard = drawCard(deck); var secondCard = drawCard(deck); return [firstCard, secondCard]; } var hitMe = function(hand, deck) { var newCard = drawCard(deck); hand.push(newCard); return newCard; } var containsAce = function(hand) { var aces = 0; for (var index in hand) { var card = hand[index]; if (card[0] === "A") { aces++; } } return aces; } var getScore = function(hand) { var score = 0; for (var index in hand) { var card = hand[index]; var value = cardValues().get(card[0]); score += value; } for (var i = 0; i < containsAce(hand); i++) { if (score > 21) { score -= 10; } } return score; } var bust = function(hand) { var score = getScore(hand); return score > 21; } var dealerTurn = function(hand, deck) { while (getScore(hand) < 17) { hitMe(hand, deck); } return hand; } var getWinner = function(dealerHand, playerHand) { if (bust(playerHand)) { return "Dealer"; } else if (bust(dealerHand) || getScore(playerHand) > getScore(dealerHand)) { return "Player"; } else if (getScore(dealerHand) > getScore(playerHand)) { return "Dealer"; } else { return null; } } $(document).ready(function() { var deck; var player; var dealer; $("form#play").submit(function(event) { $("#dealer").empty(); $("#player").empty(); deck = createDeck(); player = createHand(deck); dealer = createHand(deck); $("#dealer").append("<div class=\"card\" id=\"hidden-card\"><p>?</p></div>"); for(var index = 1; index < dealer.length; index++) { var suit = dealer[index][1]; var value = dealer[index][0]; $("#dealer").append("<div class=\"card suit"+suit+"\"><p>"+value+"</p></div>"); } for(var index in player) { var suit = player[index][1]; var value = player[index][0]; $("#player").append("<div class=\"card suit"+suit+"\"><p>"+value+"</p></div>"); } $(".new-game").show(); $("#play").hide(); event.preventDefault(); }); $("form#hit").submit(function(event) { debugger; var newCard = hitMe(player, deck); var suit = newCard[1]; var value = newCard[0]; $("#player").append("<div class=\"card suit"+suit+"\"><p>"+value+"</p></div>"); if (bust(player)) { $("#message").text("Bust! Dealer wins!") $('#myModal').modal('show'); } event.preventDefault(); }); $("form#stay").submit(function(event) { var revealedCard = dealer[0]; var revealedSuit = revealedCard[1]; var revealedValue = revealedCard[0]; $("#hidden-card").replaceWith("<div class=\"card suit"+revealedSuit+"\"><p>"+revealedValue+"</p></div>"); while (getScore(dealer) < 17) { var newCard = hitMe(dealer, deck); var suit = newCard[1]; var value = newCard[0]; $("#dealer").append("<div class=\"card suit"+suit+"\"><p>"+value+"</p></div>"); } if (bust(dealer)) { $("#message").text("Bust! Player wins!"); } else { var winner = getWinner(dealer, player); if (winner !== null) { $("#message").text(winner+" wins!"); } else { $("#message").text("It's a tie!"); } } $('#myModal').modal('show'); event.preventDefault(); }); });
Markdown
UTF-8
2,544
3.328125
3
[]
no_license
## The challenge Your challenge is to build out this GitHub user search app using the [GitHub users API](https://docs.github.com/en/rest/reference/users#get-a-user) and get it looking as close to the design as possible. Your users should be able to: - View the optimal layout for the app depending on their device's screen size - See hover states for all interactive elements on the page - Search for GitHub users by their username - See relevant user information based on their search - Switch between light and dark themes - **Bonus**: Have the correct color scheme chosen for them based on their computer preferences. _Hint_: Research `prefers-color-scheme` in CSS. The GitHub users API endpoint is `https://api.github.com/users/:username`. So, if you wanted to search for the Octocat profile, you'd be able to make a request to `https://api.github.com/users/octocat`. ### Expected behaviour - On first load, show the profile information for Octocat. - Display an error message (as shown in the design) if no user is found when a new search is made. - If a GitHub user hasn't added their name, show their username where the name would be without the `@` symbol and again below with the `@` symbol. - If a GitHub user's bio is empty, show the text "This profile has no bio" with transparency added (as shown in the design). The lorem ipsum text in the designs shows how the bio should look when it is present. - If any of the location, website, twitter, or company properties are empty, show the text "Not Available" with transparency added (as shown in the design). - Website, twitter, and company information should all be links to those resources. For the company link, it should remove the `@` symbol and link to the company page on GitHub. For Octocat, with `@github` being returned for the company, this would lead to a URL of `https://github.com/github`. ## Deploying your project - Production URL: [http://valentina-milicevic-prod-github-user-search-app.vercel.app](http://valentina-milicevic-prod-github-user-search-app.vercel.app) - Development URL: [http://valentina-milicevic-dev-github-user-search-app.vercel.app](http://valentina-milicevic-dev-github-user-search-app.vercel.app) ## Screenshots Desktop version (dark): ![Desktop version (dark)](./assets/screenshots/desktop-dark.png) Desktop version (light): ![Desktop version (light)](./assets/screenshots/desktop-light.png) Tablet version: ![Tablet version](./assets/screenshots/tablet.png) Mobile version: ![Mobile version](./assets/screenshots/mobile.png)
Java
UTF-8
2,200
1.914063
2
[]
no_license
package com.junyou.bus.chenghao.configure.export; import java.util.Map; import com.kernel.data.dao.AbsVersion; public class ChengHaoPeiZhiConfig extends AbsVersion { /** * 称号id */ private int id; /** * 称号所属类型 1:平台称号 2:成就称号 */ private int type1; /** * 头衔名称 */ private String name; /** * 资源 */ private String res; /** * 属性加成 */ private Map<String, Long> attrs; /** * 需求等级 */ private int needlevel; /** * 需求道具id */ private String needitem; /** * 关联成就id */ private int id1; /** * 称号拥有时间(分) */ private int time; /** * 是否初始激活 */ private int init; /** * 平台id */ private String pingtaiid; private Map<String, Long> extraAttrs; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getType1() { return type1; } public void setType1(int type1) { this.type1 = type1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRes() { return res; } public void setRes(String res) { this.res = res; } public Map<String, Long> getAttrs() { return attrs; } public void setAttrs(Map<String, Long> attrs) { this.attrs = attrs; } public int getNeedlevel() { return needlevel; } public void setNeedlevel(int needlevel) { this.needlevel = needlevel; } public String getNeeditem() { return needitem; } public void setNeeditem(String needitem) { this.needitem = needitem; } public int getId1() { return id1; } public void setId1(int id1) { this.id1 = id1; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getPingtaiid() { return pingtaiid; } public void setPingtaiid(String pingtaiid) { this.pingtaiid = pingtaiid; } public Map<String, Long> getExtraAttrs() { return extraAttrs; } public void setExtraAttrs(Map<String, Long> extraAttrs) { this.extraAttrs = extraAttrs; } public int getInit() { return init; } public void setInit(int init) { this.init = init; } }
Swift
UTF-8
9,371
2.890625
3
[]
no_license
// // IMMessage.swift // IMDemo // // Created by 小白 on 2017/2/20. // Copyright © 2017年 LinJian. All rights reserved. // import UIKit struct IMImageObject { /** * 文件展示名 */ var displayName: String? /** * 图片本地路径 * @discussion 目前 SDK 没有提供下载大图的方法,但推荐使用这个地址作为图片下载地址,APP 可以使用自己的下载类或者 SDWebImage 做图片的下载和管理 */ var path: String? /** * 缩略图本地路径 */ var thumbPath: String? /** * 图片远程路径 */ var url: String? /** * 缩略图远程路径 * @discussion 仅适用于使用云信上传服务进行上传的资源,否则无效。 */ var thumbUrl: String? /** * 图片尺寸 */ var size: CGSize? /** * 文件大小 */ var fileLength: CLongLong? } struct IMAudioObject { /** * 语音的本地路径 */ var path: String? /** * 语音的远程路径 */ var url: String? /** * 语音时长,毫秒为单位 * @discussion SDK会根据传入文件信息自动解析出duration,但上层也可以自己设置这个值 */ var duration: NSInteger? } struct IMCustomObject { var content: String? } /** * 消息体协议 */ protocol IMMessageObject: NSObjectProtocol { /** * 消息体所在的消息对象 */ var message: IMMessage { get } /** * 消息内容类型 * * @return 消息内容类型 */ func type() -> (IMMessage.MessageType) } class IMMessage: NSObject { /** * 消息送达状态枚举 */ enum MessageDeliveryState: NSInteger { /** * 消息发送失败 */ case MessageDeliveryStateFailed /** * 消息发送中 */ case MessageDeliveryStateDelivering /** * 消息发送成功 */ case MessageDeliveryStateDeliveried } /** * 消息附件下载状态 */ enum MessageAttachmentDownloadState: NSInteger { /** * 附件需要进行下载 (有附件但并没有下载过) */ case MessageAttachmentDownloadStateNeedDownload /** * 附件收取失败 (尝试下载过一次并失败) */ case MessageAttachmentDownloadStateFailed /** * 附件下载中 */ case MessageAttachmentDownloadStateDownloading /** * 附件下载成功/无附件 */ case MessageAttachmentDownloadStateDownloaded } /** * 消息内容类型枚举 */ enum MessageType: NSInteger { /** * 文本类型消息 */ case MessageTypeText = 0 /** * 图片类型消息 */ case MessageTypeImage = 1 /** * 声音类型消息 */ case MessageTypeAudio = 2 /** * 视频类型消息 */ case MessageTypeVideo = 3 /** * 位置类型消息 */ case MessageTypeLocation = 4 /** * 通知类型消息 */ case MessageTypeNotification = 5 /** * 文件类型消息 */ case MessageTypeFile = 6 /** * 提醒类型消息 */ case MessageTypeTip = 10 /** * 自定义类型消息 */ case MessageTypeCustom = 100 } /** * 消息类型(默认为文本消息) */ var messageType: MessageType = IMMessage.MessageType(rawValue: 0)! /** * 消息来源 */ var from: String? /** * 消息所属会话 */ var session: String? /** * 消息ID,唯一标识 */ var messageID: String? /** * 消息文本 * @discussion 聊天室消息中除 NIMMessageTypeText 和 NIMMessageTypeTip 外,其他消息 text 字段都为 nil */ var text: String? /** * 消息附件内容 */ var messageObject: Any? /** * 图片消息附件内容 */ var imageObject: IMImageObject = IMImageObject() /** * 语音消息附件内容 */ var audioObject: IMAudioObject = IMAudioObject() /** * 自定义消息附件内容 */ var customObject: IMCustomObject = IMCustomObject() /** * 消息附件种类 */ var messageObjectType: String? /** * 消息发送时间 * @discussion 本地存储消息可以通过修改时间戳来调整其在会话列表中的位置,发完服务器的消息时间戳将被服务器自动修正 */ var timestamp: TimeInterval? /** * 消息投递状态 仅针对发送的消息 */ var deliveryState: MessageDeliveryState = MessageDeliveryState.MessageDeliveryStateFailed /** * 消息附件下载状态 仅针对收到的消息 */ var attachmentDownloadState: MessageAttachmentDownloadState? /** * 消息是否标记为已删除 * @discussion 已删除的消息在获取本地消息列表时会被过滤掉,只有根据messageId获取消息的接口可能会返回已删除消息。 */ var isDeleted: Bool? } // ------------------------- 其它暂时未用到的接口 ----------------------------- // /** // * 消息设置 // * @discussion 可以通过这个字段制定当前消息的各种设置,如是否需要计入未读,是否需要多端同步等 // */ // @property (nullable,nonatomic,strong) NIMMessageSetting *setting; // // /** // * 消息反垃圾配置 // * @discussion 目前仅支持易盾,只有接入了易盾才可以设置这个配置 // */ // @property (nullable,nonatomic,strong) NIMAntiSpamOption *antiSpamOption; // // // /** // * 消息推送文案,长度限制200字节 // */ // @property (nullable,nonatomic,copy) NSString *apnsContent; // // /** // * 消息推送Payload // * @discussion 可以通过这个字段定义消息推送Payload,支持字段参考苹果技术文档,长度限制 2K // */ // @property (nullable,nonatomic,copy) NSDictionary *apnsPayload; // // /** // * 指定成员推送选项 // * @discussion 通过这个选项进行一些更复杂的推送设定,目前只能在群会话中使用 // */ // @property (nullable,nonatomic,strong) NIMMessageApnsMemberOption *apnsMemberOption; // // // /** // * 服务器扩展 // * @discussion 客户端可以设置这个字段,这个字段将在本地存储且发送至对端,上层需要保证 NSDictionary 可以转换为 JSON,长度限制 4K // */ // @property (nullable,nonatomic,copy) NSDictionary *remoteExt; // // /** // * 客户端本地扩展 // * @discussion 客户端可以设置这个字段,这个字段只在本地存储,不会发送至对端,上层需要保证 NSDictionary 可以转换为 JSON // */ // @property (nullable,nonatomic,copy) NSDictionary *localExt; // // /** // * 消息拓展字段 // * @discussion 服务器下发的消息拓展字段,并不在本地做持久化,目前只有聊天室中的消息才有该字段(NIMMessageChatroomExtension) // */ // @property (nullable,nonatomic,strong) id messageExt; // // /** // * 是否是收到的消息 // * @discussion 由于有漫游消息的概念,所以自己发出的消息漫游下来后仍旧是"收到的消息",这个字段用于消息出错是时判断需要重发还是重收 // */ // @property (nonatomic,assign,readonly) BOOL isReceivedMsg; // // /** // * 是否是往外发的消息 // * @discussion 由于能对自己发消息,所以并不是所有来源是自己的消息都是往外发的消息,这个字段用于判断头像排版位置(是左还是右)。 // */ // @property (nonatomic,assign,readonly) BOOL isOutgoingMsg; // // /** // * 消息是否被播放过 // * @discussion 修改这个属性,后台会自动更新db中对应的数据 // */ // @property (nonatomic,assign) BOOL isPlayed; // // /** // * 对端是否已读 // * @discussion 只有当当前消息为 P2P 消息且 isOutgoingMsg 为 YES 时这个字段才有效,需要对端调用过发送已读回执的接口 // */ // @property (nonatomic,assign,readonly) BOOL isRemoteRead; // // /** // * 消息发送者名字 // * @discussion 当发送者是自己时,这个值可能为空,这个值表示的是发送者当前的昵称,而不是发送消息时的昵称。聊天室消息里,此字段无效。 // */ // @property (nullable,nonatomic,copy,readonly) NSString *senderName; // // // /** // * 发送者客户端类型 // */ // @property (nonatomic,assign,readonly) NIMLoginClientType senderClientType; // @end
JavaScript
UTF-8
3,262
3.1875
3
[]
no_license
'use strict'; /////////////////////////////////////// // Modal window const modal = document.querySelector('.modal'); const overlay = document.querySelector('.overlay'); const btnCloseModal = document.querySelector('.btn--close-modal'); const btnsOpenModal = document.querySelectorAll('.btn--show-modal'); const openModal = function (e) { e.preventDefault(); modal.classList.remove('hidden'); overlay.classList.remove('hidden'); }; const closeModal = function () { modal.classList.add('hidden'); overlay.classList.add('hidden'); }; // for (let i = 0; i < btnsOpenModal.length; i++) // btnsOpenModal[i].addEventListener('click', openModal); btnsOpenModal.forEach(btn => btn.addEventListener('click', openModal)); btnCloseModal.addEventListener('click', closeModal); overlay.addEventListener('click', closeModal); document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !modal.classList.contains('hidden')) { closeModal(); } }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////Lecture//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Selecting the entire page////////////////////////////////////////////////////////////////////////////////////////// console.log(document.documentElement); //..documentElement //Selecting the Head console.log(document.head); //Selecting the body console.log(document.body); const header = document.querySelector('.header'); const allSections = document.querySelectorAll('.section'); console.log(allSections); document.getElementById('section--1'); const allButtons = document.getElementsByTagName('button'); console.log(allButtons); console.log(document.getElementsByClassName('btn')); //////////////////////////////////////////Creating and inserting elements/////////////////////////////////////////////// const message = document.createElement('div'); //created a div message.classList.add('cookie-message'); //added cookie-meesgae style to it message.innerHTML = 'We use cookied for improved functionality and analytics. <button class="btn btn--close-cookie">Got it!</button>'; //Now inserting it into our DOM //prepand and append are use to move the HTML element start or to end . And it should not in two places like humanbeings header.prepend(message); //prepend added the element to the start of the selection header.append(message); //prepend added the element to the end of the selection //if you want to put in 2 places you can use header.prepend(message.cloneNode(true)); //it will create a copy of message at the start //BEFORE AND AFTER header.before(message); //put the message before the header element as a siblings header.after(message); //put the message after the header element as a siblings //DeLETING ELEMENT document .querySelector('.btn--close-cookie') .addEventListener('click', function () { console.log('Button is clicked'); // message.remove(); message.parentElement.removeChild(message); }); message.style.backgroundColor = '#37383d'; message.style.width = '120%';
Markdown
UTF-8
1,704
2.6875
3
[]
no_license
# Factory Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/factory`. To experiment with that code, run `bin/console` for an interactive prompt. TODO: Delete this and the text above, and describe your gem ## Installation Add this line to your application's Gemfile: ```ruby gem 'factory' ``` And then execute: $ bundle Or install it yourself as: $ gem install factory ## Usage ```ruby Customer = Factory.new(:name, :address, :zip) => Customer joe = Customer.new("John Smith", "123 Maple, Anytown NC", 12345) => #<struct Customer name="Joe Smith", address="123 Maple, Anytown NC", zip="12345"> joe.name joe["name"] joe[:name] joe[0] => "John Smith" Customer = Factory.new(:name, :age) do def greeting "Hello #{name}!" end end Customer.new("Dave", 23).greeting => "Hello Dave!" ``` ## Development After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). ## Contributing 1. Fork it ( https://github.com/[my-github-username]/factory/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
Java
UTF-8
975
1.945313
2
[]
no_license
package bnym.casestudy.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import bnym.casestudy.entity.Authorities; import bnym.casestudy.entity.User; import bnym.casestudy.service.UserDetailsDao; @Controller public class IndexController { @Autowired UserDetailsDao userService; @RequestMapping(value = { "/", "/home", "/index" }) public ModelAndView home() { System.out.println("Hello There!"); ModelAndView mav = new ModelAndView("index"); userService.addAdmin(); return mav; } @RequestMapping(value = { "/login" }) public ModelAndView loginpage() { ModelAndView mav = new ModelAndView("login"); return mav; } }
C++
UTF-8
261
3.28125
3
[]
no_license
#include <iostream> using namespace std; void prime(int a) { int i; for (i=2;i<a;i++) { if (a%i==0) break; } if (i==a) cout<<"prime"<<endl; else cout<<"not prime"<<endl; } int main() { int a; cin>>a; prime(a); return 0; }
JavaScript
UTF-8
1,046
2.75
3
[]
no_license
const PubSub = require('../helpers/pub_sub.js') const GameLogic = function() { this.tally = 0; this.cards = []; this.level = 0; } GameLogic.prototype.bindEvents = function () { PubSub.subscribe('SquareView:card-clicked', (event) => { const card = event.detail; this.verifyMatch(card); }) PubSub.subscribe('MasterView:set-level', (event) => { this.level = event.detail; }) PubSub.subscribe('DataLoad:set-difficulty', (event) => { this.level = event.detail; }) }; GameLogic.prototype.verifyMatch = function (card) { if (this.cards.length == 1) { if (this.cards[0].value == card.value) { this.tally += 1; this.cards = []; if (this.level == this.tally) { this.gameWon = "won"; const finish = Date.now(); PubSub.publish('GameLogic:game-complete', finish) } } else { this.cards.push(card) PubSub.publish('GameLogic:clear-cards', this.cards) this.cards = []; } } else { this.cards.push(card) } } module.exports = GameLogic;
C++
GB18030
544
3.609375
4
[]
no_license
//дһһά˳ʱת90 #include<iostream> using namespace std; double func(double a[][3]); int main() { double a[3][3]={{1,2,3},{4,5,6},{7,8,9}}; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) cout<<a[i][j]; cout<<endl; } func(a); cin.get(); return 0; } double func(double a[][3]) { double b[3][3]; for(int i=0;i<3;i++) for(int j=0;j<3;j++) b[i][j]=a[j][i]; cout<<endl; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) cout<<b[i][j]; cout<<endl; } return b[3][3]; }
PHP
UTF-8
1,581
2.59375
3
[]
no_license
<?php /** * @todo: write description */ namespace common\spec_parsers; class FocalLengthSpecParser extends NumericSpecParser { // These two attributes defines key of base_spec table and category id's the parser class is applicable to. static public $keys = array('Фокусное расстояние'); static public $categories = array(); protected $knownMeasures = array('мм'); protected $measures = array( 'мм' => array('мм'), ); protected function patterns() { $measures = $this->measures; $measures_list = implode('|', $this->getMeasureAliases($measures)); $patterns = $this->generateSimplePatterns($this->current_key, $measures); $patterns['/^(\d+\.?\d*)\s-\s(\d+\.?\d*)\s?('.$measures_list.')$/mi'] = function ($matches) use ($measures) { $return = []; $return[] = array( 'key' => 'Фокусное расстояние (мин.)', 'value' => $matches[1], 'measure' => \common\spec_parsers\NumericSpecParser::getMeasureByAlias($matches[3], $measures), ); $return[] = array( 'key' => 'Фокусное расстояние (макс.)', 'value' => $matches[2], 'measure' => \common\spec_parsers\NumericSpecParser::getMeasureByAlias($matches[3], $measures), ); return $return; }; return $patterns; } protected function convertMeasureSingleValue($to_measure, $row) { return $row; } }
Go
UTF-8
957
3.109375
3
[]
no_license
//This example uses multifile approach to emulate numpy example in the book //https://go.dev/play/p/TdmXQvaD2iN package main import ( "fmt" "play.ground/foo" ) func main() { inputs := []float64{1, 2, 3, 2.5} weights := [][]float64{ {0.2, 0.8, -0.5, 1}, {0.5, -0.91, 0.26, -0.5}, {-0.26, -0.27, 0.17, 0.87}, } biases := []float64{2, 3, 0.5} results := foo.DotProd_Fn(inputs, weights, biases) fmt.Println(results) } -- go.mod -- module play.ground -- foo/foo.go -- package foo func DotProd_Fn(inputs []float64, weights [][]float64, biases []float64) []float64 { layers_output := make([]float64, 3) for i := range weights { neuron_weights := weights[i] neuron_bias := biases[i] var neuron_output float64 = 0 for j := range inputs { neuron_output = inputs[j] * neuron_weights[j] } neuron_output += neuron_bias layers_output[i] = neuron_output } return (layers_output) } /* Results [4.5 1.75 2.675] Program exited. */
Java
UTF-8
496
2.46875
2
[]
no_license
package org.otw.archive; import java.net.URL; public class Creator { private String name; private String username; private URL url; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } }
JavaScript
UTF-8
2,329
2.703125
3
[]
no_license
function loadClient(){ apiAdapter.handleClientLoad(); } var apiAdapter = {}; apiAdapter.apiKey = "AIzaSyCeKGMtbJLsVrdJX9gJ3fs3_c6GEn_1Gdk"; apiAdapter.clientId = "736158154921-0kh3ksre0i2s8banbektai9vkqo99oql.apps.googleusercontent.com"; apiAdapter.scopes = "https://www.googleapis.com/auth/calendar"; apiAdapter.printError = function(reason){ console.log("Error: " + reason.result.error.message); } // only add courses after gapi loads apiAdapter.addAllCourses = function(){ scraper.scrape(); apiAdapter.gapi.client.calendar.calendars.insert({ "resource" : {"summary": "Classes", "timeZone": "America/New_York", "description": "Auto-generated class schedule from Schedule Loader" } }).then( function(resp){ apiAdapter.calendarId = resp.result.id; for (var i = 0; i < scraper.courses.length; i++){ apiAdapter.insertClassEvent(courseDataParser, scraper.courses[i]); } alert('Your classes have been added to your calendar!'); }, apiAdapter.printError); } //called when JS client library loads --> need to load this script beforehand apiAdapter.handleClientLoad = function(){ this.gapi = gapi; this.gapi.client.setApiKey(this.apiKey); window.setTimeout(apiAdapter.checkAuth, 1); } //callback of handleClientLoad apiAdapter.checkAuth = function(){ apiAdapter.gapi.auth.authorize( {client_id: apiAdapter.clientId, scope: apiAdapter.scopes, immediate: false}, apiAdapter.handleAuthResult); } //callback of checkAuth apiAdapter.handleAuthResult = function(authResult){ if (authResult && !authResult.error){ //if authResult is valid, load the api then addAllCourses apiAdapter.gapi.client.load('calendar', 'v3') .then(apiAdapter.addAllCourses, apiAdapter.printError); } } apiAdapter.insertClassEvent = function(courseDataParser, course){ var calEvent; for (var i = 0; i < course.date_range.length; i++){ calEvent = courseDataParser.createCalEvent(course, i); // calEvent.calendarId = "primary"; calEvent.calendarId = apiAdapter.calendarId; var requestInsertEvent = apiAdapter.gapi.client.calendar.events.insert(calEvent); requestInsertEvent.then( function(resp){ console.log('successfully added ' + course.courseName + ' to calendar owned by ' + resp.result.creator.email); // console.log(JSON.stringify(resp)); console.log(); }, apiAdapter.printError); } }
PHP
UTF-8
778
2.578125
3
[]
no_license
<?php // Name: Artruo Martinez // Due: May 4, 2016 // Senior Project // Purpose: This file will select all inofrmation from the JobsAssigned table, execpt for the ID. This information // to the iOS app so that the foreman can whart jobs are assgined. include("connect.php"); mysql_select_db("beachelectric"); $sql = "select * from JobsAssigned"; $query = mysql_query($sql); $array = array(); if(mysql_num_rows($query) == 0) { array_push($array,"no job"); echo json_encode($array); exit; } else { while($values = mysql_fetch_assoc($query)) { if(!empty($values['JobType'])) { array_push($array, $values['JobType'] . ", " . $values['WorkerAssigned'] . ", " . $values['Location']); } } echo json_encode($array); } ?>
Java
UTF-8
743
2.015625
2
[]
no_license
package services.allRussianUniversities; import dao.topRussianUniversities.TopRussianUniversitiesDao; import entities.RussianUniversitiesInQS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class TopRussianUniversitiesServiceImpl implements TopRussianUniversitiesService { @Autowired private TopRussianUniversitiesDao russianUniversititesDAOImplementation; @Override @Transactional public List<RussianUniversitiesInQS> getAllRussianTopUniversities() { return russianUniversititesDAOImplementation.getAllTopRussianUniversititesInQS(); } }
Python
UTF-8
2,995
4.5
4
[]
no_license
#Q.1-Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class. class Circle(): def __init__(self, r): self.radius = r def getarea(self): return self.radius**2*3.14 def getcircumference(self): return 2*self.radius*3.14 NewCircle = Circle(8) print(NewCircle.getarea()) print(NewCircle.getcircumference()) #Q.2- Create a Student class and initialize it with name and roll number. Make methods to : #1. Display - It should display all informations of the student. class student: def __init__ (self,name,roll): self.name=name self.roll=roll def display(self): print(self.name,self.roll) s1=student(226,"bharti") s1.display() #Q.3- Create a Temprature class. Make two methods : #1. convertFahrenheit - It will take celsius and will print it into Fahrenheit. #2. convertCelsius - It will take Fahrenheit and will convert it into Celsius. class temperature: def __init__(self,celsius,fahrenheit): self.fahrenheit=fahrenheit self.celsius=celsius def getfahrenheit(self): print("fahrenheit",(1.8* self.celsius)+32 def getcelsius(self): print("celsius",(self.fahrenheit-32)*05.5) fahrenheit=float(input("enter fahrenheit")) celsius=float(input("enter celsius")) t=temperature(celsius,fahrenheit) t.getfahrenheit() t.getcelsius() #**Q.4- Create a class MovieDetails and initialize it with Movie name, artistname,Year of release and ratings . #Make methods to #1. Display-Display the details. #2. Update- Update the movie details. class MovieDetails(): def __init__ (self,movie_name,artist_name,releasing_date,ratings): self.movie_name=movie_name self.artist_name=artist_name self.releasing_date=releasing_date self.ratings=ratings def update(self, movie_name, artist_name, releasing_date, ratings): self.movie_name = movie_name self.artist_name = artist_name self.releasing_date = releasing_date self.ratings = ratings def show(self): print(self.movie_name,self.artist_name,self.ratings,self.releasing_date) movie_name=input("enter movie name: ") artist_name=input("enter artist name: ") ratings=int(input("enter the ratings out of 5: ")) releasing_date=input("enter releasing date: ") s1=MovieDetails(movie_name,artist_name,ratings,releasing_date) s1.show() s1.update("abcd","dance","5","1999") s1.show() #Q.5- Create a class Expenditure and initialize it with expenditure,savings.Make the following methods. #1. Display expenditure and savings #2. Calculate total salary #3. Display salary class expenditure: def __init__ (self,expenditure,saving): self.expenditure = expenditure self.saving = saving def getdisplay(self): print("expend is",self.expenditure,"saving is",self.saving) def getcalculation(self): print("total salary=",self.expenditure+self.saving) c=expenditure(50000,70000) c.getdisplay() c.getcalculation()
PHP
UTF-8
447
3.125
3
[]
no_license
<?php namespace Core; class Objectify { private $__toString = ''; public function __construct($objects = null) { if ($objects instanceof \Closure) { $this->__toString = $objects; return; } if ($objects) { foreach ($objects as $key => $value) { if (!property_exists($this, $key)) { continue; } $this->$key = $value; } } } public function __toString() { return call_user_func($this->__toString); } }
Ruby
UTF-8
717
4.53125
5
[]
no_license
# In the previous two exercises, you developed methods that convert # simple numeric strings to signed Integers. In this exercise and the next, # you're going to reverse those methods. # Write a method that takes a positive integer or zero, and converts # it to a string representation. # You may not use any of the standard conversion methods available in Ruby, # such as Integer#to_s, String(), Kernel#format, etc. Your method should do # this the old-fashioned way and construct the string by analyzing and # manipulating the number. def integer_to_string(integer) integer.digits.reverse.join end puts integer_to_string(4321) == '4321' puts integer_to_string(0) == '0' puts integer_to_string(5000) == '5000'
Java
UTF-8
3,007
2.5
2
[]
no_license
/* * Created on Oct 9, 2006 */ package orbe.model.style; import java.awt.Color; import java.net.URL; import net.sf.doolin.util.ValueHandler; import net.sf.doolin.util.xml.DigesterUtils; import orbe.model.ColorUtils; import org.apache.commons.digester.Digester; public class DefaultRepositoryHexTerrain { /** * Unique instance */ private static RepositoryHexTerrain defaultRepository = null; /** * Get the instance */ public static RepositoryHexTerrain getDefaultRepository() { if (defaultRepository != null) { return defaultRepository; } else { return createDefaultRepository(); } } /** * Creates the instance */ private static synchronized RepositoryHexTerrain createDefaultRepository() { if (defaultRepository != null) { return defaultRepository; } else { RepositoryHexTerrain temp = new RepositoryHexTerrain(); DigesterUtils digesterUtils = DigesterUtils.createNonValidatingDigester(); digesterUtils.ruleObject("terrain", HexTerrainHelper.class, "setValue"); digesterUtils.ruleProperty("nom", "setName"); digesterUtils.ruleProperty("couleur", "setColor"); Digester digester = digesterUtils.getDigester(); digester.addCallMethod("terrains/terrain/ref-symbole", "setSymbol", 1, new Class[] { Integer.class }); digester.addCallParam("terrains/terrain/ref-symbole", 0, "id"); URL resource = DefaultRepositoryHexTerrain.class.getResource("/orbe/resources/terrain/Terrains.xml"); digesterUtils.parse(resource, new TerrainHandler(temp)); defaultRepository = temp; return defaultRepository; } } public static class TerrainHandler extends ValueHandler<HexTerrainHelper> { private RepositoryHexTerrain repository; public TerrainHandler(RepositoryHexTerrain repository) { this.repository = repository; } @Override public void setValue(HexTerrainHelper value) { DefaultHexTerrain terrain = value.getTerrain(); repository.addTerrain(terrain); } } public static class HexTerrainHelper { private int id; private String name; private Color color; private HexSymbol symbol; public void setColor(String value) { color = ColorUtils.fromHEX(value); } public DefaultHexTerrain getTerrain() { DefaultHexTerrain terrain = new DefaultHexTerrain(); terrain.setId(id); terrain.setName(name); terrain.setColor(color); terrain.setSymbol(symbol); return terrain; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSymbol(int id) { symbol = RepositoryHexSymbol.getInstance().getSymbol(id); } } public static RepositoryHexTerrain createRepository() { RepositoryHexTerrain repository = new RepositoryHexTerrain(); RepositoryHexTerrain defaultRepository = getDefaultRepository(); for (HexTerrain terrain : defaultRepository.getTerrains()) { HexTerrain customTerrain = new DefaultHexTerrain(terrain); repository.addTerrain(customTerrain); } return repository; } }
Python
UTF-8
3,822
2.78125
3
[]
no_license
if __name__ == "__main__": #Importing some libraries import numpy as np import pandas as pd 2 #Getting rid of pesky warnings def warn(*args, **kwargs): pass import warnings warnings.warn = warn np.warnings.filterwarnings('ignore') #START HERE column_names = [ "age", #2 "sex", #3 "painloc", #4 "painexer", #5 "relrest", #6 "systolic resting-blood-pressure", #9 "smoke", #12 "famhist", #17 "max-heart-rate-achieved", #31 "heart-disease" #57 ] #Importing the dataset location = 'longBeachVA.csv' dataset = pd.read_csv(location) X = dataset.iloc[:, [2, 3, 4, 5, 6, 9, 12, 17, 31]].values Y = dataset.iloc[:, 57].values #Replace all 'heart-disease' values greater than 0 because my goal is not to classify the disease type for x,i in enumerate(Y): if i>0:Y[x]=1 #Plotting Data #import matplotlib.pyplot as plt #myB = pd.DataFrame(data=X+Y, columns=column_names) #axes = scatter_matrix(myB, alpha=0.2, figsize=(6, 6), diagonal='kde') #corr = myB.corr().as_matrix() #for ax in axes.ravel(): # ax.set_xlabel(ax.get_xlabel(), fontsize=10, rotation=90) # ax.set_ylabel(ax.get_ylabel(), fontsize=10, rotation=0) #for i, j in zip(*plt.np.triu_indices_from(axes, k=1)): # axes[i, j].annotate("%.3f" %corr[i,j], (0.8, 0.8), xycoords='axes fraction', ha='center', va='center') #plt.show() #Taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing_values=-9, strategy='most_frequent', axis=0) imputer.fit(X[:, [6,7]]) X[:, [6,7]] = imputer.transform(X[:, [6,7]]) #Replace old data with new one. imputer = Imputer(missing_values=-9, strategy='mean', axis=0) imputer.fit(X[:, [5,8]]) X[:, [5,8]] = imputer.transform(X[:, [5,8]]) # Replace old data with new one. #Splitting the dataset into the Training set and Test set from sklearn.model_selection._split import train_test_split from imblearn.combine import SMOTEENN smote_enn = SMOTEENN() X_resampled, y_resampled = smote_enn.fit_sample(X, Y) X_train, X_test, Y_Train, Y_Test = train_test_split(X_resampled, y_resampled, test_size=0.25) #Use actual data for tests and not the data created through imbalanced-learn new = train_test_split(X, Y, test_size=0.25) X_test = new[1] Y_Test = new[3] #Feature scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #Using Pipeline import sklearn.pipeline from sklearn.neural_network import MLPClassifier from sklearn.decomposition import KernelPCA from imblearn.pipeline import make_pipeline select = sklearn.feature_selection.SelectPercentile(sklearn.feature_selection.f_classif) clf = MLPClassifier(solver='lbfgs', learning_rate='constant', activation='tanh') kernel = KernelPCA() pipeline = make_pipeline(kernel, clf) pipeline.fit(X_train, Y_Train) #Testing #from sklearn import metrics #from sklearn.metrics import classification_report #y_pred = pipeline.predict(X_test) #report = metrics.classification_report(Y_Test, y_pred) #print report #User-input v = [] for i in column_names[:-1]: v.append(input(i+": ")) answer = np.array(v) answer = answer.reshape(1,-1) answer = sc_X.transform(answer) print ("Predicts:" + str(pipeline.predict(answer))) #If prediction == 0, then the person doesn't have heart-disease #else prediction == 1, then person has heart-disease
C++
UTF-8
6,529
2.609375
3
[ "MIT" ]
permissive
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* utils.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hherin <hherin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/26 18:56:49 by lucaslefran #+# #+# */ /* Updated: 2021/06/14 20:51:36 by hherin ### ########.fr */ /* */ /* ************************************************************************** */ #include "utils.hpp" char asciiToLower(char in) { if (in >= 'A' && in <= 'Z') return in + ('a' - 'A'); return in; } std::string convertNbToString(size_t nb) { std::ostringstream oss; oss << nb; return oss.str(); } std::vector<std::string> stringDelimSplit(std::string const &str, const char *delim) { static std::vector<std::string> strArray; // use static to return the vector size_t posinit = 0, posfind = 0; strArray.clear(); while (posfind < str.size()){ posfind = str.find(delim, posinit + 1); if (posfind != std::string::npos){ strArray.push_back(str.substr(posinit, posfind - posinit)); posinit = posfind; } else{ strArray.push_back(str.substr(posinit, str.size() - posinit)); posfind = str.size(); } } return strArray; } std::vector<std::string> splitWithSep(std::string line, char sep) { std::vector<std::string> res; std::istringstream s(line); while (std::getline(s, line, sep)) if (!line.empty()) res.push_back(line); return res; } std::pair<const std::string, const Location*> matchLocation(const std::map<std::string, Location>* loc, const std::string& locName) { std::pair<bool, std::map<std::string, Location>::const_iterator> bestMatch(0, loc->begin()); // Checking each location name, and saving the most long match. As we stored location names in a map, // they're already sorted form smaller to longest same words, no need to check size: the last match will // be the longest possible match (ex: if searching for "bla", "bl" location will be stored after "b" location) for (std::map<std::string, Location>::const_iterator it = loc->begin(); it != loc->end(); ++it) { if (!it->first.compare(0, std::string::npos, locName, 0, it->first.size())) { bestMatch.first = true; bestMatch.second = it; } } // Case there was no match if (!bestMatch.first) return std::pair<const std::string, const Location*>("", 0); return std::pair<const std::string, const Location*>(bestMatch.second->first, &bestMatch.second->second); } // srv = list of virtual server for one port, names.first = name of virtual server, names.second = location name std::pair<const std::string, const Location*> locationSearcher(const std::vector<ServerInfo> *srv, std::pair<std::string, std::string> const &names) { // loop for each virtual server for a specific port for (size_t i = 0; i < srv->size(); i++){ std::vector<std::string> sinfoNames = (*srv)[i].getNames(); // loop for each names in each server block for (size_t j = 0; j < sinfoNames.size(); j++) { // virtual server is found if (!sinfoNames[j].compare(0, names.first.size() + 1, names.first)) return matchLocation((*srv)[i].getLocation(), names.second); } } // Case no server_names match, using default server block (the first one) return matchLocation((*srv)[0].getLocation(), names.second); } const ServerInfo* findVirtServ(const std::vector<ServerInfo>* infoVirServs, const std::string& hostValue) { // Looking in each virtual server names if one match host header field value for (std::vector<ServerInfo>::const_iterator virtServ = infoVirServs->begin(); virtServ != infoVirServs->end(); ++virtServ) { for (std::vector<std::string>::const_iterator servNames = virtServ->getNames().begin(); servNames != virtServ->getNames().end(); ++servNames) { // If we match one server name, saving this virtual server if (*servNames == hostValue) return &(*virtServ); } } // Case no match return 0; } size_t isExtension(const std::string& uri) { size_t dotPos = uri.find_last_of("."); if (dotPos == std::string::npos) return std::string::npos; size_t slashPos = uri.find_last_of("/"); // If last '.' is after last '/', returning the dot position to compare // the extension return dotPos = (dotPos > slashPos) ? dotPos : std::string::npos; } std::string* getCgiExecutableName(const std::string& uri, const Location* loc) { size_t dotPos = isExtension(uri); // Target ends with a '/', no extension so no cgi if (dotPos == std::string::npos) return 0; // Case target is a script (ends by .cgi) if (!uri.compare(dotPos, std::string::npos, ".cgi")) return new std::string(".cgi"); // Case target match an extension in the appropriate location block, // we return the executable name std::map<std::string, std::string>::const_iterator it; if (loc && (it = loc->getCgiExe().find(std::string(uri.c_str() + dotPos))) != loc->getCgiExe().end()) return new std::string(it->second); // Case the extension doesn't match anything return 0; } void printLog(const std::string &msg, const std::string& addInfo) { // current date and time on the current system time_t now = time(0); // convert now to string form and removing '\n' std::string date(ctime(&now)); date.resize(date.length() - 1); #if defined DEBUG std::cout << "[" << date << "] " << msg; if (!addInfo.empty()) std::cout << "-------------------------\n" << addInfo << "-------------------------\n\n"; #else std::cout << "[" << date << "] " << msg; (void)addInfo; #endif } std::pair<std::string, std::string> *SplitPathForExec(std::string const &path) { static std::pair<std::string, std::string> pathAndFile; size_t posLastSlash = path.find_last_of("/"); pathAndFile.first.clear(); pathAndFile.second.clear(); pathAndFile.first = "."; pathAndFile.first += path.substr(0, posLastSlash); pathAndFile.second = "."; pathAndFile.second += path.substr(posLastSlash); return &pathAndFile; }
PHP
UTF-8
2,430
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Contact; use App\Http\Resources\ContactCollection; use Illuminate\Http\Request; class ContactController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return new ContactCollection(Contact::all()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $contact = new Contact([ 'name' => $request->get('name'), 'email' => $request->get('email'), 'contact' => $request->get('contact'), ]); if($contact->save()) { return response(['success' => true, "msg" => "Data saved successfully!"], 200); } else { return response(['errors' => true], 500); } } /** * Display the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function show($id) { return view('show'); $contact = json_encode(Contact::find($id)); return view('show', compact('contact')); } /** * Show the form for editing the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function edit(Contact $contact) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function update(Request $request, Contact $contact) { // } /** * Remove the specified resource from storage. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function destroy($id) { $contact = Contact::find($id); if($contact->delete()) { return response(['success' => true, "msg" => "Data delete successfully!"], 200); } else { return response(['errors' => true], 500); } } }
JavaScript
UTF-8
2,035
3.03125
3
[]
no_license
//Grab the articles as a json $.getJSON("/articles", function (data) { for (var i = 0; i < data.length; i++) { // $("#articles").append("<p data-id='" + data[i]._id + "'>" + data[i].title + "<br />" + data[i].link + "</p>"); $(".article").append("<div class='card'> <div class='card-body'><h5 class='card-title'>" + data[i].title + "</h5><p class='card-text'>" + "<a href='" + data[i].link + "'> " + data[i].link + " <a href='#' class='save-btn btn btn-primary' data-id=" + data[i]._id + ">Save Article</a></div></div></div>"); } }); $('#scrape-btn').on('click', function () { $.ajax({ method: "GET", url: "/scrape" }) .then(function (data) { console.log(data); location.reload(); }); }) $(document).on("click", '.save-btn', function () { console.log('working') var thisId = $(this).attr("data-id"); $.ajax({ method: "PUT", url: "/saved/" + thisId, }) .then(function (data) { console.log("article saved"); // location.reload(); }); }); $.getJSON("/saved", function (data) { for (var i = 0; i < data.length; i++) { // $("#articles").append("<p data-id='" + data[i]._id + "'>" + data[i].title + "<br />" + data[i].link + "</p>"); $(".save").append("<div class='card'> <div class='card-body'><h5 class='card-title'>" + data[i].title + "</h5><p class='card-text'>" + "<a href='" + data[i].link + "'> " + data[i].link + " <a href='#' class='remove-btn btn btn-primary' data-id=" + data[i]._id + ">Remove Article</a></div></div></div>"); } }); $(document).on("click", ".remove-btn", function () { event.preventDefault(); // Grabs the article's id var thisId = $(this).attr("data-id"); // Make an ajax call to unsave the article $.ajax({ method: "PUT", url: "/unsaved/" + thisId }) .then(function () { console.log("Article has been unsaved"); location.reload(); }) })
JavaScript
UTF-8
1,615
2.625
3
[ "MIT" ]
permissive
var mongodb = require('mongodb'); var compile = require('./compile'); var uuid = require('node-uuid'); var Schema = module.exports = function() { }; Schema.prototype.translate = function(schema, value) { var type = schema.subtype || schema.type; switch(type) { case 'UUID': var uuid_text; // Encoded by Base64 if (value.length == 48) uuid_text = new Buffer(value, 'base64').toString(); else uuid_text = value; var source = uuid.parse(uuid_text); return new mongodb.Binary(new Buffer(source), mongodb.Binary.SUBTYPE_UUID); case 'Date': var i = value % 1000; return new mongodb.Timestamp(i, Math.floor(value * 0.001)); case 'Integer': var isInteger_re = /^\s*(\+|-)?\d+\s*$/; // Convert to integer if value is not integer type if (String(value).search(isInteger_re) != -1) return parseInt(value); return value; default: return value; } }; Schema.prototype.getData = function(schema, value) { var type = schema.subtype || schema.type; switch(type) { case 'UUID': var source = new Buffer(value.value(), 'binary'); var uuid_text = uuid.unparse(source); return new Buffer(uuid_text).toString('base64'); case 'Date': var low = value.getLowBits(); var lowStr = ''; if (low < 100) { lowStr = '0' + low.toString(); } else { lowStr = low.toString(); } return parseInt(value.getHighBits().toString() + lowStr); default: return value; } }; Schema.prototype.package = function(schema, value) { return this.translate(schema, value); } Schema.prototype.unpackage = function(schema, value) { return this.getData(schema, value); };
C++
UTF-8
2,838
2.875
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include "note.hpp" #include "utils/util.h" Note::Note() { get_randomness(pk, 32); get_randomness(rho, 32); } std::string Note::cm() const { return computeCommitment(rho, pk, value); } std::string Note::spend_nf(const std::string& sk) const { return computeSpendNullifier(rho, sk); } std::string Note::send_nf() const { return computeSendNullifier(rho); } std::string Note::computeSendNullifier(const std::string& rho) { unsigned char rho_array[rho.size()/2]; unsigned char send_nf[32]; hex_str_to_array(rho, rho_array); computeSendNullifier(rho_array, send_nf); return array_to_hex_str(send_nf, 32); } std::string Note::computeSpendNullifier(const std::string& rho, const std::string& sk) { unsigned char rho_array[rho.size()/2]; unsigned char sk_array[sk.size()/2]; unsigned char spend_nf[32]; hex_str_to_array(rho, rho_array); hex_str_to_array(sk, sk_array); computeSpendNullifier(rho_array, sk_array, spend_nf); return array_to_hex_str(spend_nf, 32); } std::string Note::computeCommitment(const std::string& rho, const std::string& pk, uint64_t value) { unsigned char rho_array[rho.size()/2]; unsigned char pk_array[pk.size()/2]; unsigned char cm[32]; hex_str_to_array(rho, rho_array); hex_str_to_array(pk, pk_array); computeCommitment(rho_array, pk_array, value, cm); return array_to_hex_str(cm, 32); } void Note::set_rho(const std::string& new_rho) { rho = new_rho; } void Note::set_pk(const std::string& new_pk) { rho = new_pk; } void Note::set_sk(const std::string& new_sk) { rho = new_sk; } void Note::set_value(uint64_t new_value) { rho = new_value; } void Note::computeSendNullifier(unsigned char *rho, unsigned char *send_nf) { unsigned char data[33]; data[0] = 0x00; for(int i = 0; i < 32; i++) { data[i+1] = rho[i]; } sha256(data, 33, send_nf); return; } void Note::computeSpendNullifier(unsigned char *rho, unsigned char *sk, unsigned char *spend_nf) { unsigned char data[65]; data[0] = 0x01; for(int i = 0; i < 32; i++) { data[i+1] = rho[i]; } for(int i = 0; i < 32; i++) { data[i+33] = sk[i]; } sha256(data, 65, spend_nf); return; } void Note::computeCommitment(unsigned char *rho, unsigned char *pk, uint64_t value, unsigned char *commitment) { unsigned char data[64+sizeof(value)]; for(int i = 0; i < 32; i++) { data[i] = rho[i]; } for(int i = 0; i < 32; i++) { data[i+32] = pk[i]; } for(int i = 0; i < sizeof(value); i++) { data[i+64] = (value >> (8 * i)) & 255; // little endian, big endian will use << operator } sha256(data, 64+sizeof(value), commitment); return; }
C#
UTF-8
1,170
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.Serialization.Json; using System.Threading.Tasks; using WeatherApiMvcApp.Models.ApiModels; namespace WeatherApiMvcApp.DAL { public class DataAccess : IDataAccess { private const string _baseAddress = "http://api.openweathermap.org"; private const string _apiKey = "aa97b493f1c079f2d2db4538efb4d75c"; // Makes a request to webApi and serialize the JSON-respons into a proper model public async Task<RootObject> GetWeather(string searchUri) { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(_baseAddress); HttpResponseMessage responseMessage = await client.GetAsync($"{searchUri}&appid={_apiKey}"); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RootObject)); Stream stream = await responseMessage.Content.ReadAsStreamAsync(); RootObject model = (RootObject)serializer.ReadObject(stream); return model; } } } }
Java
UTF-8
4,771
2.296875
2
[]
no_license
package com.example.demo; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.example.demo.Model.PatientBookingDetails; import java.util.List; public class MyBookingAdapter extends RecyclerView.Adapter<BookingViewHolder> { private Context mContext; private List<PatientBookingDetails> myBookingList; public MyBookingAdapter(Context mContext, List<PatientBookingDetails> myBookingList) { this.mContext = mContext; this.myBookingList = myBookingList; } // Connect The Template RecycleRow Booking Data @Override public BookingViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View mView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycle_row_bookingdata,viewGroup,false); return new BookingViewHolder(mView); } // Set the text from database through Model Class @Override public void onBindViewHolder(@NonNull final BookingViewHolder holder, final int i) { holder.mBookingDate.setText("Booking Date: " + myBookingList.get(i).getBookingDate()); // holder.mBookingTime.setText("Booking Time: " + myBookingList.get(i).getBookingTime()); holder.mDoctorName.setText("With Dr. " + myBookingList.get(i).getRegistredDoctorName()); holder.mPatientName.setText("Dear: " + myBookingList.get(i).getPatientName()); holder.mSlot.setText("Slot: " + myBookingList.get(i).getSlot()); //holder.mAge.setText("Age: " + myBookingList.get(i).getPatientAge()); //holder.mGender.setText("Gender: " + myBookingList.get(i).getPatientGender()); //holder.mPhoneNo.setText("Phone No: " + myBookingList.get(i).getPatientPhoneNo()); //holder.mAddress.setText("Address: " + myBookingList.get(i).getPatientAddress()); holder.mAppointmentDate.setText("Date: " + myBookingList.get(i).getAppointmentDate()); holder.mCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext,DetailAppointmentLetter.class); intent.putExtra("BookingDate",myBookingList.get(holder.getAdapterPosition()).getBookingDate()); intent.putExtra("BookingTime",myBookingList.get(holder.getAdapterPosition()).getBookingTime()); intent.putExtra("PatientName",myBookingList.get(holder.getAdapterPosition()).getPatientName()); intent.putExtra("PatientAge",myBookingList.get(holder.getAdapterPosition()).getPatientAge()); intent.putExtra("PatientGender",myBookingList.get(holder.getAdapterPosition()).getPatientGender()); intent.putExtra("PatientAddress",myBookingList.get(holder.getAdapterPosition()).getPatientAddress()); intent.putExtra("PatientPhoneno",myBookingList.get(holder.getAdapterPosition()).getPatientPhoneNo()); intent.putExtra("AppointmentDate",myBookingList.get(holder.getAdapterPosition()).getAppointmentDate()); intent.putExtra("AppointmentSlot",myBookingList.get(holder.getAdapterPosition()).getSlot()); intent.putExtra("BookedDoctorName",myBookingList.get(holder.getAdapterPosition()).getRegistredDoctorName()); intent.putExtra("keyValue",myBookingList.get(holder.getAdapterPosition()).getKey()); mContext.startActivity(intent); } }); } @Override public int getItemCount() { return myBookingList.size(); } } class BookingViewHolder extends RecyclerView.ViewHolder{ TextView mBookingDate,mBookingTime,mDoctorName,mPatientName,mSlot,mAge,mGender,mPhoneNo,mAddress,mAppointmentDate; CardView mCardView; public BookingViewHolder(@NonNull View itemView) { super(itemView); mBookingDate = itemView.findViewById(R.id.booking_date); //mBookingTime = itemView.findViewById(R.id.booking_time); mDoctorName = itemView.findViewById(R.id.tvDoctorName); mPatientName = itemView.findViewById(R.id.tvPatientName); mSlot = itemView.findViewById(R.id.tvSlot); //mAge = itemView.findViewById(R.id.tvAge); //mGender = itemView.findViewById(R.id.tvGender); //mPhoneNo = itemView.findViewById(R.id.tvPhoneNo); //mAddress = itemView.findViewById(R.id.tvAddress); mAppointmentDate = itemView.findViewById(R.id.tvDate); mCardView = itemView.findViewById(R.id.myCardView); } }
Java
UTF-8
4,849
1.546875
2
[ "BSD-2-Clause" ]
permissive
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("bl") @Implements("ApproximateRouteStrategy") public class ApproximateRouteStrategy extends RouteStrategy { @ObfuscatedName("bc") @ObfuscatedSignature( descriptor = "Lke;" ) static StudioGame field473; @ObfuscatedName("fw") static String field471; ApproximateRouteStrategy() { } // L: 12776 @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(IIILgh;I)Z", garbageValue = "-425355466" ) @Export("hasArrived") public boolean hasArrived(int var1, int var2, int var3, CollisionMap var4) { return var2 == super.approxDestinationX && var3 == super.approxDestinationY; // L: 12780 } @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "(IIB)Lki;", garbageValue = "-103" ) @Export("getWidgetChild") public static Widget getWidgetChild(int var0, int var1) { Widget var2 = class92.getWidget(var0); // L: 239 if (var1 == -1) { // L: 240 return var2; } else { return var2 != null && var2.children != null && var1 < var2.children.length ? var2.children[var1] : null; // L: 241 242 } } @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "(I)V", garbageValue = "-630623402" ) public static void method1110() { class273.midiPcmStream.clear(); // L: 42 class273.musicPlayerStatus = 1; // L: 43 ClanChannelMember.musicTrackArchive = null; // L: 44 } // L: 45 @ObfuscatedName("k") @ObfuscatedSignature( descriptor = "(I)[Lcq;", garbageValue = "768338863" ) static AttackOption[] method1108() { return new AttackOption[]{AttackOption.AttackOption_hidden, AttackOption.field1285, AttackOption.AttackOption_alwaysRightClick, AttackOption.field1283, AttackOption.AttackOption_dependsOnCombatLevels}; // L: 12729 } @ObfuscatedName("ir") @ObfuscatedSignature( descriptor = "(Lca;IIII)V", garbageValue = "611280226" ) @Export("addPlayerToMenu") static final void addPlayerToMenu(Player var0, int var1, int var2, int var3) { if (ModelData0.localPlayer != var0) { // L: 10138 if (Client.menuOptionsCount < 400) { // L: 10139 String var4; if (var0.skillLevel == 0) { // L: 10141 var4 = var0.actions[0] + var0.username + var0.actions[1] + IgnoreList.method6430(var0.combatLevel, ModelData0.localPlayer.combatLevel) + " " + " (" + "level-" + var0.combatLevel + ")" + var0.actions[2]; } else { var4 = var0.actions[0] + var0.username + var0.actions[1] + " " + " (" + "skill-" + var0.skillLevel + ")" + var0.actions[2]; // L: 10142 } int var5; if (Client.isItemSelected == 1) { // L: 10143 Projectile.insertMenuItemNoShift("Use", Client.selectedItemName + " " + "->" + " " + class166.colorStartTag(16777215) + var4, 14, var1, var2, var3); // L: 10144 } else if (Client.isSpellSelected) { // L: 10147 if ((class113.selectedSpellFlags & 8) == 8) { // L: 10148 Projectile.insertMenuItemNoShift(Client.selectedSpellActionName, Client.selectedSpellName + " " + "->" + " " + class166.colorStartTag(16777215) + var4, 15, var1, var2, var3); // L: 10149 } } else { for (var5 = 7; var5 >= 0; --var5) { // L: 10154 if (Client.playerMenuActions[var5] != null) { // L: 10155 short var6 = 0; // L: 10156 if (Client.playerMenuActions[var5].equalsIgnoreCase("Attack")) { // L: 10157 if (Client.playerAttackOption == AttackOption.AttackOption_hidden) { // L: 10158 continue; } if (AttackOption.AttackOption_alwaysRightClick == Client.playerAttackOption || Client.playerAttackOption == AttackOption.AttackOption_dependsOnCombatLevels && var0.combatLevel > ModelData0.localPlayer.combatLevel) { // L: 10159 var6 = 2000; // L: 10160 } if (ModelData0.localPlayer.team != 0 && var0.team != 0) { // L: 10162 if (var0.team == ModelData0.localPlayer.team) { // L: 10163 var6 = 2000; } else { var6 = 0; // L: 10164 } } else if (AttackOption.field1283 == Client.playerAttackOption && var0.isClanMember()) { // L: 10166 var6 = 2000; // L: 10167 } } else if (Client.playerOptionsPriorities[var5]) { // L: 10170 var6 = 2000; } boolean var7 = false; // L: 10171 int var8 = Client.playerMenuOpcodes[var5] + var6; // L: 10172 Projectile.insertMenuItemNoShift(Client.playerMenuActions[var5], class166.colorStartTag(16777215) + var4, var8, var1, var2, var3); // L: 10173 } } } for (var5 = 0; var5 < Client.menuOptionsCount; ++var5) { // L: 10178 if (Client.menuOpcodes[var5] == 23) { // L: 10179 Client.menuTargets[var5] = class166.colorStartTag(16777215) + var4; // L: 10180 break; } } } } } // L: 10184 }
Python
UTF-8
130
3.375
3
[]
no_license
# Largest prime factor n = 600851475143 i = 2 while i ** 2 < n: while n % i == 0: n = n / i i += 1 print(n)
Java
UTF-8
2,417
2.921875
3
[]
no_license
package lt.andrej.demo.serviceimpl; import lt.andrej.demo.service.ActionsService; import org.springframework.stereotype.Service; import javax.swing.plaf.IconUIResource; import java.util.ArrayList; import java.util.List; import java.util.Random; @Service public class ActionsServiceImpl implements ActionsService { @Override public int sumValues(int num1, int num2) { return num1 + num2; } @Override public int substraction(int num1, int num2) { return num1 - num2; } @Override public List<Integer> randomValueList0(int num1, int num2) { int min = num1; int max = num2; List<Integer> list = new ArrayList<>(); List<Integer> newList = new ArrayList<>(); for (int i = 0; i <=max; i++){ list.add(i); } for (int i = 0; i <15; i++) { int currentNum = random(min, list.size()); newList.add(list.get(currentNum)); list.remove(currentNum); } return newList; } @Override public List<Integer> randomValueList() { int min = 0; int max = 25; /* List<Integer> list = new ArrayList<>(); while () { if (list.contains(randomNum)) { list.add(randomNum); counter++; } } */ List<Integer> list = new ArrayList<>(); List<Integer> newList = new ArrayList<>(); for (int i = 0; i <=max; i++){ list.add(i); } for (int i = 0; i <15; i++) { int currentNum = random(min, list.size()); newList.add(list.get(currentNum)); list.remove(currentNum); } return newList; } @Override public List<Integer> randomValuesDividedFour(int param) { int min = 0; int max = 1000; int counter = 0; List<Integer> list = new ArrayList<>(); while (param > counter) { int randomNum =random(0, 1000); if (randomNum%4 == 0) { if (!list.contains(randomNum)) { list.add(randomNum); counter++; } } } return list; } private int random(int min, int max) { Random rand = new Random(); int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; } }
Java
UTF-8
1,759
1.984375
2
[]
no_license
package com.xrosscode.plugin.wechat.redenvelop; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; /** * @author johnsonlee */ public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.getPreferenceManager().setSharedPreferencesName(Preferences.PREFERENCES_NAME); super.addPreferencesFromResource(R.xml.preferences); final Preferences preferences = new Preferences(this); final Preference prefAutoGoHome = findPreference(Preferences.PREFERENCES_AUTO_GO_HOME); final Preference prefAutoGoHomeDelayTime = findPreference(Preferences.PREFERENCES_AUTO_GO_HOME_DELAY_TIME); prefAutoGoHome.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { final Boolean enabled = Boolean.parseBoolean(String.valueOf(newValue)); prefAutoGoHomeDelayTime.setEnabled(enabled); return true; } }); prefAutoGoHomeDelayTime.setEnabled(preferences.autoGoHome()); prefAutoGoHomeDelayTime.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(final Preference preference, final Object newValue) { try { return 0 < Long.parseLong(String.valueOf(newValue)); } catch (final NumberFormatException e) { return false; } } }); } }
Java
UTF-8
6,631
1.914063
2
[]
no_license
package bhtech.com.cabbydriver.DrivingToCustomer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.maps.model.LatLng; import bhtech.com.cabbydriver.ChangeDropOffLocation.ChangeDropOffLocationController; import bhtech.com.cabbydriver.ChooseRouteToDestination.ChooseRouteToDestinationController; import bhtech.com.cabbydriver.FindCustomer.FindCustomerController; import bhtech.com.cabbydriver.R; import bhtech.com.cabbydriver.SlidingMenu.SlidingMenuController; import bhtech.com.cabbydriver.object.ContantValuesObject; import bhtech.com.cabbydriver.object.ErrorObj; import bhtech.com.cabbydriver.object.LocationObject; import bhtech.com.cabbydriver.object.PhoneObject; import bhtech.com.cabbydriver.object.StringObject; import bhtech.com.cabbydriver.object.TaxiRequestObj; public class DrivingToCustomerController extends SlidingMenuController implements DrivingToCustomerInterface.Listener { Context context = this; DrivingToCustomerModel model = new DrivingToCustomerModel(context); DrivingToCustomerWithoutNaviView withoutNaviView = new DrivingToCustomerWithoutNaviView(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setView(withoutNaviView, getString(R.string.driving_to_customer)); withoutNaviView.setListener(this); withoutNaviView.setDatasource(model); model.getCurrentRequest(new DrivingToCustomerModel.OnGetCurrentRequest() { @Override public void Success() { if (TaxiRequestObj.getInstance().getStatus() == ContantValuesObject.TaxiRequestStatusWaitingPickupPassenger) { withoutNaviView.setEnableButtonStart(); } } @Override public void Failure(ErrorObj error) { showAlertDialog(error.errorMessage).show(); } }); } @Override public void buttonPickUpUserClick() { model.driverPickUpCustomer(new DrivingToCustomerModel.DriverPickUpCustomer() { @Override public void Success() { withoutNaviView.setEnableButtonStart(); } @Override public void Failure(ErrorObj error) { showAlertDialog(error.errorMessage).show(); } }); } @Override public void buttonShowNaviClick() { try { LatLng latLng = TaxiRequestObj.getInstance().getToLocation(); startActivity(LocationObject.showNavigationOnGoogleMap(latLng)); } catch (Exception e) { showAlertDialog(context.getString(R.string.your_google_map_is_out_of_date)).show(); } } @Override public void buttonCallClick() { if (!StringObject.isNullOrEmpty(model.getCustomerPhoneNumber())) { startActivity(PhoneObject.makePhoneCall(model.getCustomerPhoneNumber())); } else { showAlertDialog(getString(R.string.can_not_get_customer_phone_number)).show(); } } @Override public void buttonMessageClick() { if (!StringObject.isNullOrEmpty(model.getCustomerPhoneNumber())) { startActivity(PhoneObject.sendSMS(model.getCustomerPhoneNumber())); } else { showAlertDialog(getString(R.string.can_not_get_customer_phone_number)).show(); } } @Override public void buttonChangeLocation() { startActivity(new Intent(context, ChangeDropOffLocationController.class)); finishActivity(); } @Override public void buttonStartClick() { model.startGoToDestination(new DrivingToCustomerModel.StartGoToDestination() { @Override public void Success() { startActivity(new Intent(context, ChooseRouteToDestinationController.class)); finishActivity(); } @Override public void Failure(ErrorObj error) { showAlertDialog(error.errorMessage).show(); } }); } @Override public void withoutNaviViewCreated() { if (TaxiRequestObj.getInstance().getStatus() == ContantValuesObject.TaxiRequestStatusWaitingPickupPassenger) { withoutNaviView.setEnableButtonStart(); } else { //Do nothing } withoutNaviView.reloadView(); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if (intent.getAction().equals(ContantValuesObject.GCM_INTENT_FILTER_ACTION)) { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String messageType = gcm.getMessageType(intent); if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { } else { String data = intent.getStringExtra(ContantValuesObject.DATA); Log.w("ChooseRouteToCustomer", data); showAlertDialog(getString(R.string.user_cancel_request)).show() .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { TaxiRequestObj.getInstance().setStatus(ContantValuesObject.TaxiRequestStatusCancelled); startActivity(new Intent(context, FindCustomerController.class)); finishActivity(); } }); } } } }; @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(ContantValuesObject.GCM_INTENT_FILTER_ACTION); filter.addAction(ContantValuesObject.CONNECTIVITY_CHANGE_INTENT_FILTER_ACTION); this.registerReceiver(receiver, filter); } @Override public void onBackPressed() { } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } }
Python
UTF-8
2,001
2.640625
3
[]
no_license
#!/user/bin/env python # -*- encoding:utf-8 -*_ ''' @File:main.py @Time:2020/02/27 22:34:58 @Author:zoudaokou @Version:1.0 @Contact:wangchao0804@163.com @desc:读取txt中的公司注册信息链接,解析数据,存入数据库 ''' from tqdm import tqdm from EntClass import EntItem from SaveDataToSql import save_to_sql from HandleSqlData import handle_data from Parse_Ent_Info import parse_buiness_data import time # import multiprocessing def get_link_from_txt(path): print('\n' + '*' * 100) print('获取公司注册信息链接...............') with open(path, 'r', encoding='utf-8') as f: link_list = f.readlines() pbar = tqdm(range(len(link_list)), desc='共计%s家企业' % len(link_list), leave=True, position=1) for i in pbar: link_list[i] = 'h' + link_list[i].split(':h')[1].replace('\n', '') print('所有公司链接获取完成...............') print('*' * 100 + '\n') return link_list def loads_data(link_list): start_time = time.time() entlist = [] print('\n' + '*' * 100) print('获取公司对象中.............') # pool = multiprocessing.Pool(processes=4) pbar = tqdm(link_list, desc='共计%s家企业' % len(link_list), leave=True, position=1) for link in pbar: try: entdata = parse_buiness_data(link) # entdata = pool.apply_async(parse_buiness_data,(link,)) ent = EntItem(entdata) entlist.append(ent) except Exception as e: continue # pool.close() # pool.join() end_time = time.time() print('公司对象获取完成.............') print('总耗时%s' % (end_time - start_time)) print('*' * 100 + '\n') return entlist if __name__ == "__main__": path = r'智慧交通linklist.txt' link_list = get_link_from_txt(path) entlist = loads_data(link_list) save_to_sql(entlist) handle_data()
Markdown
UTF-8
843
2.796875
3
[]
no_license
--- title: Simple HTTP Server layout: post tags: - Linux - Simple HTTP Server --- localhost &#8216; da simple HTTP Server kurulumu bir kaç farklı method ile yapılabilir. #### **Grunt ya da Gulp** Grunt ya da Gulp ile basit bir HTTP Server kurulumu gerceklestirilebilir. Ayrıntı icin [buraya][1] tıklayınız. #### **Python** Linux base sistemde kurulu olan Python&#8217;nu kullanarak tek bir kod satırı ile HTTP Server kurulumu yapılabilir. {% highlight bash %} python -m SimpleHTTPServer {% endhighlight %} #### **Prax** Mac OS X &#8216; de ki [pow][3] &#8216; a alternatif bir cozum olarak kullanılabilir. Ayrıntılı bilgi için [buraya][4] tıklayınız. [1]: https://github.com/gruntjs/grunt-contrib-connect [2]: https://npmjs.org/package/http-server [3]: http://pow.cx/ [4]: https://github.com/ysbaddaden/prax
Python
UTF-8
3,626
2.625
3
[ "MIT" ]
permissive
from __future__ import print_function from __future__ import print_function import locale from django.conf import settings from django import template from datetime import date from itertools import groupby import datetime import calendar register = template.Library() def do_schedules(parser, token): """ The template tag's syntax is {% event_calendar year month event_list %} """ # Force French locale locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8') try: tag_name, year, month, event_list = token.split_contents() except ValueError: raise Exception("tag requires three arguments") return EventCalendarNode(year, month, event_list) class EventCalendarNode(template.Node): """ Process a particular node in the template. Fail silently. """ def __init__(self, year, month, event_list): try: self.year = template.Variable(year) self.month = template.Variable(month) self.event_list = template.Variable(event_list) except ValueError: raise template.TemplateSyntaxError def render(self, context): try: # Get the variables from the context so the method is thread-safe. my_event_list = self.event_list.resolve(context) my_year = self.year.resolve(context) my_month = self.month.resolve(context) events = self.group_by_day(my_event_list) num_days = calendar.monthrange(my_year, my_month)[1] days = [datetime.date(my_year, my_month, day) for day in range(1, num_days + 1)] body = '' for day in days: day_events = list() if str(day) in events: for event in events[str(day)]: day_events.append(event) body += self.formatday(str(day), day_events) return body except ValueError: return except template.VariableDoesNotExist: return def formatday(self, full_date, events): day = full_date[-2:] today = date.today() if int(today.day + 1) == int(day): display = 'show' else: display = 'hide' if day != 0: body = '<div class="list-group {0} {2}" data-src={1}>'.format(day, full_date, display) for schedule in settings.DAY_SCHEDULES: if events: for key, event in enumerate(events): if schedule[:2] != event['date_refill'][11:13]: body += '<button type="button" class="list-group-item" data-src={0}>{1}</button>'.format( schedule[:5], schedule, ) break else: del events[key] break else: body += '<button type="button" class="list-group-item" data-src={0}>{1}</button>'.format(schedule[:5], schedule) body += '</div>' return body return def group_by_day(self, events): groups = {} events = sorted(events, key=lambda x: x['date_refill']) for key, group in groupby(events, lambda x: x['date_refill'][:10]): list_of = [] for thing in group: list_of.append(thing) groups.update({key: list_of}) return groups # Register the template tag so it is available to templates register.tag("schedules", do_schedules)
Java
UTF-8
7,682
1.78125
2
[ "MIT" ]
permissive
package com.simibubi.create.content.contraptions.actors.seat; import java.util.List; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import com.google.common.base.Optional; import com.simibubi.create.AllBlocks; import com.simibubi.create.AllShapes; import com.simibubi.create.AllTags.AllEntityTags; import com.simibubi.create.foundation.block.ProperWaterloggedBlock; import com.simibubi.create.foundation.utility.BlockHelper; import com.simibubi.create.infrastructure.config.AllConfigs; import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.core.NonNullList; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.TamableAnimal; import net.minecraft.world.entity.monster.Shulker; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.DyeColor; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition.Builder; import net.minecraft.world.level.material.FluidState; import net.minecraft.world.level.pathfinder.BlockPathTypes; import net.minecraft.world.level.pathfinder.PathComputationType; import net.minecraft.world.phys.AABB; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.EntityCollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public class SeatBlock extends Block implements ProperWaterloggedBlock { protected final DyeColor color; protected final boolean inCreativeTab; public SeatBlock(Properties properties, DyeColor color, boolean inCreativeTab) { super(properties); this.color = color; this.inCreativeTab = inCreativeTab; registerDefaultState(defaultBlockState().setValue(WATERLOGGED, false)); } @Override protected void createBlockStateDefinition(Builder<Block, BlockState> pBuilder) { super.createBlockStateDefinition(pBuilder.add(WATERLOGGED)); } @Override public BlockState getStateForPlacement(BlockPlaceContext pContext) { return withWater(super.getStateForPlacement(pContext), pContext); } @Override public BlockState updateShape(BlockState pState, Direction pDirection, BlockState pNeighborState, LevelAccessor pLevel, BlockPos pCurrentPos, BlockPos pNeighborPos) { updateWater(pLevel, pState, pCurrentPos); return pState; } @Override public FluidState getFluidState(BlockState pState) { return fluidState(pState); } @Override public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> p_149666_2_) { if (group != CreativeModeTab.TAB_SEARCH && !inCreativeTab) return; super.fillItemCategory(group, p_149666_2_); } @Override public void fallOn(Level p_152426_, BlockState p_152427_, BlockPos p_152428_, Entity p_152429_, float p_152430_) { super.fallOn(p_152426_, p_152427_, p_152428_, p_152429_, p_152430_ * 0.5F); } @Override public void updateEntityAfterFallOn(BlockGetter reader, Entity entity) { BlockPos pos = entity.blockPosition(); if (entity instanceof Player || !(entity instanceof LivingEntity) || !canBePickedUp(entity) || isSeatOccupied(entity.level, pos)) { if (entity.isSuppressingBounce()) { super.updateEntityAfterFallOn(reader, entity); return; } Vec3 vec3 = entity.getDeltaMovement(); if (vec3.y < 0.0D) { double d0 = entity instanceof LivingEntity ? 1.0D : 0.8D; entity.setDeltaMovement(vec3.x, -vec3.y * (double) 0.66F * d0, vec3.z); } return; } if (reader.getBlockState(pos) .getBlock() != this) return; sitDown(entity.level, pos, entity); } @Override public BlockPathTypes getAiPathNodeType(BlockState state, BlockGetter world, BlockPos pos, @Nullable Mob entity) { return BlockPathTypes.RAIL; } @Override public VoxelShape getShape(BlockState p_220053_1_, BlockGetter p_220053_2_, BlockPos p_220053_3_, CollisionContext p_220053_4_) { return AllShapes.SEAT; } @Override public VoxelShape getCollisionShape(BlockState p_220071_1_, BlockGetter p_220071_2_, BlockPos p_220071_3_, CollisionContext ctx) { if (ctx instanceof EntityCollisionContext ecc && ecc.getEntity() instanceof Player) return AllShapes.SEAT_COLLISION_PLAYERS; return AllShapes.SEAT_COLLISION; } @Override public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult p_225533_6_) { if (player.isShiftKeyDown()) return InteractionResult.PASS; ItemStack heldItem = player.getItemInHand(hand); DyeColor color = DyeColor.getColor(heldItem); if (color != null && color != this.color) { if (world.isClientSide) return InteractionResult.SUCCESS; BlockState newState = BlockHelper.copyProperties(state, AllBlocks.SEATS.get(color) .getDefaultState()); world.setBlockAndUpdate(pos, newState); return InteractionResult.SUCCESS; } List<SeatEntity> seats = world.getEntitiesOfClass(SeatEntity.class, new AABB(pos)); if (!seats.isEmpty()) { SeatEntity seatEntity = seats.get(0); List<Entity> passengers = seatEntity.getPassengers(); if (!passengers.isEmpty() && passengers.get(0) instanceof Player) return InteractionResult.PASS; if (!world.isClientSide) { seatEntity.ejectPassengers(); player.startRiding(seatEntity); } return InteractionResult.SUCCESS; } if (world.isClientSide) return InteractionResult.SUCCESS; sitDown(world, pos, getLeashed(world, player).or(player)); return InteractionResult.SUCCESS; } public static boolean isSeatOccupied(Level world, BlockPos pos) { return !world.getEntitiesOfClass(SeatEntity.class, new AABB(pos)) .isEmpty(); } public static Optional<Entity> getLeashed(Level level, Player player) { List<Entity> entities = player.level.getEntities((Entity) null, player.getBoundingBox() .inflate(10), e -> true); for (Entity e : entities) if (e instanceof Mob mob && mob.getLeashHolder() == player && SeatBlock.canBePickedUp(e)) return Optional.of(mob); return Optional.absent(); } public static boolean canBePickedUp(Entity passenger) { if (passenger instanceof Shulker) return false; if (passenger instanceof Player) return false; if (AllEntityTags.IGNORE_SEAT.matches(passenger)) return false; if (!AllConfigs.server().logistics.seatHostileMobs.get() && !passenger.getType() .getCategory() .isFriendly()) return false; return passenger instanceof LivingEntity; } public static void sitDown(Level world, BlockPos pos, Entity entity) { if (world.isClientSide) return; SeatEntity seat = new SeatEntity(world, pos); seat.setPos(pos.getX() + .5f, pos.getY(), pos.getZ() + .5f); world.addFreshEntity(seat); entity.startRiding(seat, true); if (entity instanceof TamableAnimal ta) ta.setInSittingPose(true); } public DyeColor getColor() { return color; } @Override public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) { return false; } }
Python
UTF-8
926
4.09375
4
[]
no_license
lista= [3,5,9,4,1,7] lista_texto=['gato', 'zebra', 'pato', 'rato', 'arara',] lista.sort() #ordena em ordem crescente lista_texto.sort() #ordena em ordem alfabética print(lista) print(lista_texto) lista_texto.reverse() #ordena decresente alfabetica print(lista_texto) # print(lista_texto[1]) #irá imprimir o texto da 2 posição, pois conta do 0 # print(sum(lista)) #imprime o somatório dos valores da lista # print(max(lista)) #immprime o maior valor da lista, para o menor usa min # # if 'lobo' in lista_texto: #verifica se há o texto na lista # print('Existe lobo na lista') # else: # print('Não existe lobo na lista. Será incluído') # lista_texto.append('lobo') # print(lista_texto) #lista_texto.pop(1) #pop retira da lista a posição em parenteses, sem informar retira o ultimo da lista. #print(lista_texto) # lista_texto.remove('rato') #remove da lista a string informada. # print(lista_texto)
Java
UTF-8
238
1.703125
2
[]
no_license
package com.itheima.jd.dao; import java.util.List; import com.itheima.jd.pojo.ProductModel; import com.itheima.jd.vo.QueryVo; public interface SolrDao { public List<ProductModel> getResultModelFromSolr(QueryVo vo) throws Exception; }
Java
UTF-8
274
2.75
3
[]
no_license
package day1.basics; public class Card { private String face; private String suit; public Card(String cardFace,String cardSuit) { face=cardFace; suit=cardSuit; } public String toString() { return face+" of "+suit; } }
C++
UTF-8
781
3.125
3
[]
no_license
#include<stdio.h> #include<math.h> #define PI 3.14 void nhap(int &a, int &b, int &c){ do { printf("Nhap a: "); scanf("%d",&a); } while (a==0); printf("Nhap b,c: "); scanf("%d%d",&b,&c); } void giaiPhuongTrinhBac2(int a,int b, int c){ float delta = pow(b,2)- 4*a*c; if(delta < 0){ printf("Phuong trinh vo nghiem!"); } else if(delta == 0){ float x = (float)-b/(2*a); printf("Phuong trinh co mot nghiem: %d.2f",x); } else { float x1,x2; x1 = (-b - sqrt(delta))/(2*a); x2 = (-b + sqrt(delta))/(2*a); printf("Phuong trinh co hai nghiem phan biet: x1 = %.2f va x2 = %.2f",x1,x2); } } int main(){ int a,b,c; nhap(a,b,c); giaiPhuongTrinhBac2(a,b,c); return 0; }
TypeScript
UTF-8
2,350
2.734375
3
[]
no_license
import { Model, DataTypes, Optional } from 'sequelize'; import jwt from 'jsonwebtoken'; import bcrypt from 'bcrypt'; import sequelizeInstance from '../connection'; export interface UserAttributes { id: number; name: string; email: string; password: string; createdAt: Date; updatedAt: Date; deletedAt: Date | null; } export type JwtEncodedUserData = Omit<UserAttributes, 'password' | 'deletedAt'>; export interface UserCreationAttributes extends Optional< UserAttributes, 'id' | 'createdAt' | 'updatedAt' | 'deletedAt' > {} class User extends Model<UserAttributes, UserCreationAttributes> implements UserAttributes { public readonly id!: number; public name!: string; public email!: string; public password!: string; public readonly createdAt!: Date; public readonly updatedAt!: Date; public readonly deletedAt!: Date | null; public generateToken = (): string => { const secret = process.env.JWT_SECRET || 'jsonwebtoken'; const dataToEncode: JwtEncodedUserData = { id: this.id, name: this.name, email: this.email, createdAt: this.createdAt, updatedAt: this.updatedAt, }; const token = jwt.sign(dataToEncode, secret); return token; }; public toJSON = (): object => { return { ...super.toJSON(), password: undefined }; }; } User.init( { id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, }, name: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true, }, password: { type: DataTypes.STRING, allowNull: false, }, createdAt: { type: DataTypes.DATE, allowNull: false, }, updatedAt: { type: DataTypes.DATE, allowNull: false, }, deletedAt: { type: DataTypes.DATE, allowNull: true, }, }, { tableName: 'users', modelName: 'User', sequelize: sequelizeInstance, paranoid: true, defaultScope: { attributes: { exclude: ['deletedAt'], }, }, } ); User.beforeCreate(async (user) => { const hashedPassword = await bcrypt.hash(user.password, 10); // eslint-disable-next-line no-param-reassign user.password = hashedPassword; }); export default User;
C#
UTF-8
1,156
2.609375
3
[]
no_license
using System; using System.Threading.Tasks; using DotNetCore.CAP; namespace Service.Sample { public interface ISampleRepository { Task<bool> CreateSample(ConsignCreatedResult consignCreatedResult); } public class SampleRepository : ICapSubscribe, ISampleRepository { private readonly SampleContext _sampleContext; public SampleRepository(SampleContext sampleContext) { _sampleContext = sampleContext; } [CapSubscribe("consign.main")] public async Task<bool> CreateSample(ConsignCreatedResult consignCreatedResult) { Console.WriteLine("consignNo:" + consignCreatedResult.ConsignNo); _sampleContext.Add(new Sample { Id = Guid.NewGuid(), ConsignNo = consignCreatedResult.ConsignNo, SampleNo = SampleNoGernerator(consignCreatedResult.ConsignNo) }); await _sampleContext.SaveChangesAsync(); return true; } private string SampleNoGernerator(string consignNo) { return consignNo + "-1"; } } }
JavaScript
UTF-8
1,087
4.15625
4
[]
no_license
function calcular() { // Pega valor dos números e da operção let n1 = parseFloat(document.getElementById('numero1').value); let n2 = parseFloat(document.getElementById('numero2').value); let op = parseFloat(document.getElementById('operacao').value); let re = 0; // Valida se realmente são valores numéricos if (isNaN(n1) || n1 == '') { return alert('Digite um número válido para o primeiro valor.'); } if (isNaN(n2) || n2 == '') { return alert('Digite um número válido para o segundo valor.'); } // Valida operação if (isNaN(op) || op == '') { return alert('Operação inválida'); } switch (parseFloat(op)) { case 1: re = (n1 + n2); break; case 2: re = n1 - n2; break; case 3: re = n1 * n2; break; case 4: re = n1 / n2; break; default: alert('Operação inválida'); } document.getElementById('resultado').innerHTML = re.toFixed(2); }
Python
UTF-8
1,403
3.375
3
[]
no_license
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ if not head or not head.next: return head leng, p = 0, head while p: p = p.next leng += 1 half1 = (leng-1) / 2 + (leng-1) % 2 p, cnt, half2 = head.next, 0, None while p: cnt += 1 if cnt == half1: half2 = p.next p.next = None # 这里是要点,不然环状 break p = p.next half2 = self.reverseList(half2) pre, q = head, half2 while q != None: curp = pre pre = pre.next curq = q q = q.next curq.next = curp.next curp.next = curq def reverseList(self, head): if not head: return head tmp = ListNode(-1) tmp.next = head p = head.next tmp.next.next = None while p: cur = p p = p.next cur.next = tmp.next tmp.next = cur return tmp.next
TypeScript
UTF-8
2,760
2.59375
3
[]
no_license
import { Injectable } from '@angular/core'; import { environment } from "../../environments/environment"; import { User, UserQuery, UserResponse } from "../models/users-response"; import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from "@angular/common/http"; import { throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class RestService { baseUrl = environment.baseUrl; token = environment.apiAccessToken; constructor(private http: HttpClient) { } /** * Get user list * @param query Query parameters for search * @returns Array<Users> */ getUsers(query: UserQuery = {}) { let queryParams: string = ''; // Process query parameters Object.entries(query).forEach( ([key, value]) => { if (queryParams.length > 0) { queryParams += '&'; } queryParams += `${key}=${value}`; } ); // only if any parameter, include question mark if (queryParams.length > 0) { queryParams = '?' + queryParams; } return this.http.get<UserResponse>(this.baseUrl + queryParams) .pipe( catchError(this.handleError) ); } /** * Create new user * @param data User info * @returns User data confirmation */ createUser(data: User) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.token}` }) }; return this.http.post<UserResponse>(this.baseUrl, data, httpOptions) .pipe( catchError(this.handleError) ); } /** * Update user info * @param data New values for user * @returns User data confirmation */ updateUser(data: User) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.token}` }) }; return this.http.put<UserResponse>(`${this.baseUrl}/${data.id}`, data, httpOptions) .pipe( catchError(this.handleError) ); } /** * Delete user by id * @param id Id to delete * @returns User data confirmation */ deleteUser(id: number) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.token}` }) }; return this.http.delete(`${this.baseUrl}/${id}`, httpOptions) .pipe( catchError(this.handleError) ); } /** * Error Handler * @param error * @returns */ private handleError(error: HttpErrorResponse) { // Write error in console console.error(`Error code: ${error.status}, body: `, error.error); // Return error messaje return throwError(error.error); } }
C#
UTF-8
763
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp26 { class Program { static void Main(string[] args) { Rect(); } static void Rect() { int[,] Matrixs; Matrixs = new int[6,6]; for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) Matrixs[i, j] = i * j; for (int i = 0; i < 6; i++) { for(int j = 0; j < 6; j++) Console.WriteLine(Matrixs[i,j] + "/t"); Console.WriteLine(); } Console.WriteLine(); } } }
Java
UTF-8
1,468
2.140625
2
[]
no_license
package com.example.socialnetworkfortravellers.ApplicationLayer.Services.BaseServices.queriesGetDataServices; import androidx.annotation.NonNull; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; public class QueriesGetDataService implements IQueriesGetDataService { private Query mDatabaseReference; private IQueriesGetDataServiceCallBack mQueriesGetDataServiceCallBack; @Override public void setUpDatabaseReference(Query mDatabaseReference) { this.mDatabaseReference = mDatabaseReference; } @Override public void getData() { mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { mQueriesGetDataServiceCallBack.onDataChange(dataSnapshot); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { mQueriesGetDataServiceCallBack.onCancelled(databaseError); } }); } @Override public void setUpQueriesGetDataServiceCallBack(IQueriesGetDataServiceCallBack queriesGetDataServiceCallBack) { this.mQueriesGetDataServiceCallBack = queriesGetDataServiceCallBack; } }
Python
UTF-8
1,372
3.78125
4
[]
no_license
if __name__ == '__main__': #1. Utwórz listę o nazwie marketing z elementami: #-loyality program #-client promotion #-market research marketing =['loyality program','client promotion','market research'] print(marketing) #2. Dodaj do listy element 'public relations' marketing.append('public relation') print(marketing) #3. Wyświetl pozycję numer 3 print(marketing[3]) #4. Wstaw na pozycję numer 2 element 'investor relations' marketing.insert(2,'investor relation') print(marketing) #5. Chcesz jednak aby lista znajdowała się w zmiennej # o nazwie emailMarketing. Skopiuj elementy z # listy marketing do listy emailMarketing emailMarketing = marketing.copy() print(emailMarketing) #6. Posortuj listę emailMarketing emailMarketing.sort() print(emailMarketing) #7. Utwórz nową jednoelementową listę internalEmails. # Jedyny element to 'internal communication' internalEmails =['internal communication'] #8. Dodaj listę internalEmails do listy emailMarketing print('------------------------------') emailMarketing.extend(internalEmails) print(emailMarketing) #9. Utwórz tuple, którego wartości pochodzą z # listy emailMarketing. Podczas wyświetlania # tuple zwróć uwagę na nawiasy, z jakich skorzystał Python emailMarketingTuple = tuple(emailMarketing) print(emailMarketingTuple)
C#
UTF-8
6,054
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Tetris { public partial class SimpleGameForm : Form { Graphics graphic; Gameplay play; public SimpleGameForm() { InitializeComponent(); graphic = CreateGraphics(); } private void GameTimer_Tick(object sender, EventArgs e) //add { switch (play.NowFigure) { case "cube": if (play.cube.Fall) { play.cube.FallDown(play.gameField); play.gameField.DrawField(graphic, play.cube.mainBrush, play.cube.fallenBrush, play.NextFigure); } else { play.NextFigures(graphic); } break; case "line": if (play.line.Fall) { play.line.FallDown(play.gameField); play.gameField.DrawField(graphic, play.line.mainBrush, play.line.fallenBrush, play.NextFigure); } else { play.NextFigures(graphic); } break; case "ltype": if (play.ltype.Fall) { play.ltype.FallDown(play.gameField); play.gameField.DrawField(graphic, play.ltype.mainBrush, play.ltype.fallenBrush, play.NextFigure); } else { play.NextFigures(graphic); } break; case "jtype": if (play.jtype.Fall) { play.jtype.FallDown(play.gameField); play.gameField.DrawField(graphic, play.jtype.mainBrush, play.jtype.fallenBrush, play.NextFigure); } else { play.NextFigures(graphic); } break; case "ttype": if (play.ttype.Fall) { play.ttype.FallDown(play.gameField); play.gameField.DrawField(graphic, play.ttype.mainBrush, play.ttype.fallenBrush, play.NextFigure); } else { play.NextFigures(graphic); } break; //case "stype": // if (play.stype.Fall) // { // play.stype.FallDown(play.gameField); // play.gameField.DrawField(graphic, play.stype.mainBrush, play.stype.fallenBrush, play.NextFigure); // } // else { play.NextFigures(graphic); } // break; //case "ztype": // if (play.ztype.Fall) // { // play.ztype.FallDown(play.gameField); // play.gameField.DrawField(graphic, play.ztype.mainBrush, play.ztype.fallenBrush, play.NextFigure); // } // else { play.NextFigures(graphic); } // break; } Score.Text = play.Score.ToString(); //if (play.Score == 1) // GameTimer.Interval = 100; } private void GameForm_KeyUp(object sender, KeyEventArgs e) { GameTimer.Stop(); play.KeyPress(graphic, e); GameTimer.Start(); } private void Start_Click(object sender, EventArgs e) { Start.Enabled = false; Stop.Enabled = true; play = new Gameplay(); play.Start(graphic); GameTimer.Start(); Time.Start(); } private void Stop_Click(object sender, EventArgs e) { Start.Enabled = true; Stop.Enabled = false; play.Stop(graphic); GameTimer.Stop(); Time.Stop(); } private void Time_Tick(object sender, EventArgs e) { play.Time += 1; int hour = 0, minutes = 0, seconds = 0; seconds = play.Time % 3600 % 60; if (seconds == 60) { minutes += 1; seconds = 0; } minutes += play.Time % 3600 / 60; if (minutes == 60) { hour += 1; minutes = 0; } hour += play.Time / 3600; #region output time if (hour < 10) { if (minutes < 10) { if (seconds < 10) GameTime.Text = "0" + hour + ":0" + minutes + ":0" + seconds; else GameTime.Text = "0" + hour + ":0" + minutes + ":" + seconds; } else { if (seconds < 10) GameTime.Text = "0" + hour + ":" + minutes + ":0" + seconds; else GameTime.Text = "0" + hour + ":" + minutes + ":" + seconds; } } else { if (minutes < 10) { if (seconds < 10) GameTime.Text = hour + ":0" + minutes + ":0" + seconds; else GameTime.Text = hour + ":0" + minutes + ":" + seconds; } else { if (seconds < 10) GameTime.Text = hour + ":" + minutes + ":0" + seconds; else GameTime.Text = hour + ":" + minutes + ":" + seconds; } } #endregion } } }
Java
UTF-8
2,826
2.71875
3
[]
no_license
package com.qc.my3DComputer.domain; import java.io.Serializable; /** * position * @author */ public class Position implements Serializable { private Integer id; /** * 单位mm */ private Integer x; private Integer y; private Integer z; private String state; private static final long serialVersionUID = 1L; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getX() { return x; } public void setX(Integer x) { this.x = x; } public Integer getY() { return y; } public void setY(Integer y) { this.y = y; } public Integer getZ() { return z; } public void setZ(Integer z) { this.z = z; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } Position other = (Position) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getX() == null ? other.getX() == null : this.getX().equals(other.getX())) && (this.getY() == null ? other.getY() == null : this.getY().equals(other.getY())) && (this.getZ() == null ? other.getZ() == null : this.getZ().equals(other.getZ())) && (this.getState() == null ? other.getState() == null : this.getState().equals(other.getState())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getX() == null) ? 0 : getX().hashCode()); result = prime * result + ((getY() == null) ? 0 : getY().hashCode()); result = prime * result + ((getZ() == null) ? 0 : getZ().hashCode()); result = prime * result + ((getState() == null) ? 0 : getState().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", x=").append(x); sb.append(", y=").append(y); sb.append(", z=").append(z); sb.append(", state=").append(state); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
Shell
UTF-8
381
3.203125
3
[]
no_license
#!/bin/bash [ -z $1 ] && echo 'sh check_tel.sh eth0' && exit 1 date=`date '+%Y-%m-%d %H:%M'` pcap_path=/tmp/tel_$1.pcap ssh -tt 127.0.0.1 "sudo /usr/sbin/tcpdump -i $1 -t -c 100 -s 0 -w $pcap_path > /dev/null 2>&1" 2>/dev/null pcap_info=`/usr/sbin/capinfos -y $pcap_path | grep '^Data'` traffic=`echo $pcap_info | awk '{print $4}'` echo "$date check_tel_$1 net_total:$traffic"
Python
UTF-8
3,933
2.609375
3
[]
no_license
#!/usr/bin/env python ''' dyn_ip_chk A dynamic IP checker script. written by Jared Epstein ### Planned Features: -add daemonizing (-d) -won't allow -o with daemon (only logging) -add a new option that will alert (email?) if IP changes ### Known Issues: -must be run with sudo for logging to work ''' #IMPORTS - built-ins import optparse import sys import os import time import urllib2 import json import logging import logging.handlers # CONSTANTS # basics NAME = "dyn_ip_chk" VER = "0.0.1" HOST = os.uname()[1] PID = os.getpid() PIDFILE = "/var/run/" + NAME + ".pid" # logging LOG_FILE = "/var/log/" + NAME + ".log" LOG_ROLLOVER_BYTES = 500000 # 500KB LOG_ROLLOVER_COUNT = 10 # args DESC = "dyn_ip_chk will query for the public IP and log what it finds" EPILOG = """ Version: %(ver)s """ % {'ver': VER} # ARGS parser = optparse.OptionParser(description=DESC, epilog=EPILOG) parser.add_option( '-V', '--version', help='print version and exit', dest="version", default=False, action="store_true") parser.add_option( '-v', '--verbose', help='enable verbose logging', dest="verbose", default=False, action="store_true") parser.add_option( '-o', '--out', help='output response to stdout', dest="out", default=False, action="store_true") options, args = parser.parse_args() # set up argument parser if options.version: # no need to go further if this is all we want print(VER) sys.exit() # LOGGING try: basedir = os.path.dirname(LOG_FILE) if not os.path.exists(basedir): os.makedirs(basedir) log_create = True except Exception: log_create = False try: scr_logger = logging.getLogger(NAME) scr_logger.setLevel(logging.DEBUG) scr_fh = logging.handlers.RotatingFileHandler( LOG_FILE, maxBytes=LOG_ROLLOVER_BYTES, backupCount=LOG_ROLLOVER_COUNT) scr_fh.setLevel(logging.DEBUG) scr_formatter = logging.Formatter( '%(asctime)s ' + HOST + ' ' + NAME + '[' + str(PID) + ']: %(message)s', "%Y-%m-%dT%H:%M:%S" + time.strftime('%z')) scr_fh.setFormatter(scr_formatter) scr_logger.addHandler(scr_fh) log_create = True except Exception: log_create = False # METHODS def read_site(site,hdr): ''' pulls content from provided site and returns content returns error if the request fails ''' if options.verbose: if log_create == True: scr_logger.info("read_site()") req = urllib2.Request(site, headers=hdr) try: page = urllib2.urlopen(req) content = page.read() except urllib2.HTTPError, e: content = e.fp.read() if options.verbose: if log_create == True: scr_logger.info("read_site() failed: " + content) return content def parse_response(content): ''' parses json provided from read_site() if read_site() failed to pull json, this will return None ''' if options.verbose: if log_create == True: scr_logger.info("parse_response()") try: load = json.loads(content) ip = load["ip"] return ip except Exception: return None # MAIN def main(argv): # main script wrapper function if log_create == True: scr_logger.info("Starting dyn_ip_chk") site = "https://api.ipify.org/?format=json" hdr = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'} ip_address = parse_response(read_site(site,hdr)) if ip_address != None: if log_create == True: scr_logger.info("Public IP address is: " + ip_address) if options.out: print(ip_address) else: if log_create == True: scr_logger.info("Failed to retrieve public IP") if options.out: print("Failed to retrieve public IP") if __name__ == "__main__": main(sys.argv[1:])
PHP
UTF-8
2,716
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Http\Resources\MaterialResource; use App\Models\Material; use App\Models\Supplier; use Illuminate\Http\Request; class MaterialController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return MaterialResource::collection(Material::paginate()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'suppliers' => 'required|array', 'suppliers.*' => 'required|exists:suppliers,id', ]); $material = new Material; $material->name = $request->name; $material->save(); $material->suppliers()->attach($request->suppliers); return new MaterialResource($material); } /** * Display the specified resource. * * @param \App\Models\Material $material * @return \Illuminate\Http\Response */ public function show(Material $material) { return new MaterialResource(Material::with('suppliers')->where('id',$material->id)->first()); } /** * Show the form for editing the specified resource. * * @param \App\Models\Material $material * @return \Illuminate\Http\Response */ public function edit(Material $material) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Material $material * @return \Illuminate\Http\Response */ public function update(Request $request, Material $material) { $validated = $request->validate([ 'name' => 'required|string|max:255', 'suppliers' => 'required|array', 'suppliers.*' => 'required|exists:suppliers,id', ]); $material->name = $request->name; $material->suppliers()->sync($request->suppliers); $material->save(); return new MaterialResource($material); } /** * Remove the specified resource from storage. * * @param \App\Models\Material $material * @return \Illuminate\Http\Response */ public function destroy(Material $material) { $material->delete(); } }
SQL
UTF-8
5,105
3.953125
4
[]
no_license
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; CREATE SCHEMA IF NOT EXISTS `sistema` DEFAULT CHARACTER SET utf8 COLLATE utf8_spanish2_ci ; CREATE TABLE IF NOT EXISTS `sistema`.`usuario` ( `id_usuario` INT(11) NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(255) NOT NULL, `apellido` VARCHAR(255) NOT NULL, `contrasena` VARCHAR(255) NOT NULL, `fecha_nacimiento` DATE NULL DEFAULT NULL, `nombre_usuario` VARCHAR(255) NOT NULL, `perfil` VARCHAR(300) NULL DEFAULT 'img/perfil.jpg', `activo` TINYINT(1) NULL DEFAULT 1, `rol` INT(11) NOT NULL DEFAULT 1, PRIMARY KEY (`id_usuario`), UNIQUE INDEX `nombre_usuario_UNIQUE` (`nombre_usuario` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`producto` ( `id_producto` INT(11) NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(255) NOT NULL, `precio` INT(11) NOT NULL, `descripcion` VARCHAR(300) NULL DEFAULT NULL, `poster` VARCHAR(500) NULL DEFAULT NULL, `id_categoria` INT(11) NOT NULL, `id_marca` INT(11) NOT NULL, `fecha_ingreso` DATE NULL DEFAULT NULL, `usuario_ingreso` INT(11) NOT NULL, PRIMARY KEY (`id_producto`), UNIQUE INDEX `id_producto_UNIQUE` (`id_producto` ASC), INDEX `fk_producto_categoria_idx` (`id_categoria` ASC), INDEX `fk_producto_marca1_idx` (`id_marca` ASC), INDEX `fk_producto_usuario1_idx` (`usuario_ingreso` ASC), CONSTRAINT `fk_producto_categoria` FOREIGN KEY (`id_categoria`) REFERENCES `sistema`.`categoria` (`id_categoria`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_producto_marca1` FOREIGN KEY (`id_marca`) REFERENCES `sistema`.`marca` (`id_marca`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_producto_usuario1` FOREIGN KEY (`usuario_ingreso`) REFERENCES `sistema`.`usuario` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`marca` ( `id_marca` INT(11) NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(255) NOT NULL, `descripcion` VARCHAR(300) NOT NULL, `fecha_integracion` DATE NULL DEFAULT NULL, PRIMARY KEY (`id_marca`), UNIQUE INDEX `id_marca_UNIQUE` (`id_marca` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`categoria` ( `id_categoria` INT(11) NOT NULL AUTO_INCREMENT, `nombre` VARCHAR(255) NOT NULL, `descripcion` VARCHAR(500) NOT NULL DEFAULT 'Ejemplo de categoria', PRIMARY KEY (`id_categoria`), UNIQUE INDEX `id_categoria_UNIQUE` (`id_categoria` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`factura` ( `id_factura` INT(11) NOT NULL AUTO_INCREMENT, `fecha_facturacion` DATE NOT NULL, `descripcion` VARCHAR(300) NULL DEFAULT 'Venta de productos domesticos', `usuario_id_facturacion` INT(11) NOT NULL, `subtotal` INT(11) NOT NULL, `total` INT(11) NOT NULL, PRIMARY KEY (`id_factura`), UNIQUE INDEX `id_factura_UNIQUE` (`id_factura` ASC), INDEX `fk_factura_usuario1_idx` (`usuario_id_facturacion` ASC), CONSTRAINT `fk_factura_usuario1` FOREIGN KEY (`usuario_id_facturacion`) REFERENCES `sistema`.`usuario` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`descripcion` ( `id_descripcion` INT(11) NOT NULL AUTO_INCREMENT, `cantidad` INT(11) NOT NULL DEFAULT 1, `precio` INT(11) NULL DEFAULT NULL, `factura_id_factura` INT(11) NOT NULL, `producto_id_producto` INT(11) NOT NULL, PRIMARY KEY (`id_descripcion`), UNIQUE INDEX `id_descripcion_UNIQUE` (`id_descripcion` ASC), INDEX `fk_descripcion_factura1_idx` (`factura_id_factura` ASC), INDEX `fk_descripcion_producto1_idx` (`producto_id_producto` ASC), CONSTRAINT `fk_descripcion_factura1` FOREIGN KEY (`factura_id_factura`) REFERENCES `sistema`.`factura` (`id_factura`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_descripcion_producto1` FOREIGN KEY (`producto_id_producto`) REFERENCES `sistema`.`producto` (`id_producto`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_spanish2_ci; CREATE TABLE IF NOT EXISTS `sistema`.`ingresados` ( `fecha_ingreso` DATE NOT NULL, `usuario_id` INT(11) NOT NULL, `tipo` TINYINT(1) NOT NULL, PRIMARY KEY (`fecha_ingreso`), INDEX `fk_ingresados_usuario1_idx` (`usuario_id` ASC), CONSTRAINT `fk_ingresados_usuario1` FOREIGN KEY (`usuario_id`) REFERENCES `sistema`.`usuario` (`id_usuario`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE = utf8_spanish2_ci; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
C++
UTF-8
1,782
3.15625
3
[]
no_license
#ifndef STRING_H_ #define STRING_H_ #include <iostream> /* * The next line is used because Codewarrior has a conflict with * the STL string. Make sure to put the #include of this file * AFTER all the system includes. */ #define string String class StringIndexOutOfBounds {}; class string { public: string(const char *cstring = ""); // Constructor string(const string & str); // Copy constructor ~string() { delete[] buffer; } // Destructor const string& operator=(const string & rhs); // Copy const string& operator+=(const string & rhs); // Append const char* c_str() const { return buffer; } // Return C-style string int length() const { return strLength; } // Return string length char operator[](int k) const; // Accessor operator[] char& operator[](int k); // Mutator operator[] enum { MAX_LENGTH = 1024 }; // Maximum length for input string private: char *buffer; // storage for characters int strLength; // length of string (# of characters) int bufferLength; // capacity of buffer }; std::ostream& operator<<(std::ostream& out, const string& str); // Output std::istream& operator>>(std::istream& in, string& str); // Input std::istream& getline(std::istream& in, string& str); // Read line bool operator==(const string& lhs, const string& rhs); // Compare == bool operator!=(const string& lhs, const string& rhs); // Compare != bool operator< (const string& lhs, const string& rhs); // Compare < bool operator<=(const string& lhs, const string& rhs); // Compare <= bool operator> (const string& lhs, const string& rhs); // Compare > bool operator>=(const string& lhs, const string& rhs); // Compare >= #endif
Java
UTF-8
7,196
4
4
[]
no_license
package code02; import org.apache.commons.lang.ArrayUtils; import java.util.ArrayList; import java.util.List; public class ArrayUtil { /** * 给定一个整形数组a , 对该数组的值进行置换 例如: a = [7, 9 , 30, 3] , 置换后为 [3, 30, 9,7] 如果 a = [7, 9, 30, 3, 4] , 置换后为 [4,3, 30 , 9,7] * @param origin * @return */ public void reverseArray(int[] origin){ if (origin == null || origin.length <= 1){ return; } int head = 0; int tail = origin.length - 1; int tmp; while (head != tail){ //调换位置 tmp = origin[head]; origin[head] = origin[tail]; origin[tail] = tmp; head ++; tail --; } } /** * 现在有如下的一个数组: int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} * 要求将以上数组中值为0的项去掉,将不为0的值存入一个新的数组,生成的新数组为: * {1,3,4,5,6,6,5,4,7,6,7,5} * @param oldArray * @return */ public int[] removeZero(int[] oldArray){ if (oldArray == null || oldArray.length < 1){ return null; } List<Integer> newList = new ArrayList<Integer>(); for(int number : oldArray){ if(number != 0){ newList.add(number); } } Integer[] result = new Integer[newList.size()]; result = (Integer[]) newList.toArray(result); return ArrayUtils.toPrimitive(result); } /** * 给定两个已经排序好的整形数组, a1和a2 , 创建一个新的数组a3, 使得a3 包含a1和a2 的所有元素, 并且仍然是有序的 * 例如 a1 = [3, 5, 7,8] a2 = [4, 5, 6,7] 则 a3 为[3,4,5,6,7,8] , 注意: 已经消除了重复 * @param array1 * @param array2 * @return */ public int[] merge(int[] array1, int[] array2){ if(array1 == null && array2 == null){ return null; } if(array1 == null){ return array2; } if(array2 == null){ return array1; } int[] newArray = new int[array1.length + array2.length]; int m = 0,n = 0, k = 0; while (m < array1.length && n < array2.length){ if(array1[m] <= array2[n]){ newArray[k++] = array1[m++]; }else { newArray[k++] = array2[n++]; } } if(m >= array1.length){ while (n < array2.length){ newArray[k++] = array2[n++]; } } if(n >= array2.length){ while (m < array1.length){ newArray[k++] = array1[m++]; } } return newArray; } /** * 把一个已经存满数据的数组 oldArray的容量进行扩展, 扩展后的新数据大小为oldArray.length + size * 注意,老数组的元素在新数组中需要保持 * 例如 oldArray = [2,3,6] , size = 3,则返回的新数组为 * [2,3,6,0,0,0] * @param oldArray * @param size * @return */ public int[] grow(int [] oldArray, int size){ int[] newArray = new int[oldArray.length + size]; int i = 0; for (; i < oldArray.length; i++) { newArray[i] = oldArray[i]; } for (int j = 0; j < size; j++){ newArray[i++] = 0; } return newArray; } /** * 斐波那契数列为:1,1,2,3,5,8,13,21...... ,给定一个最大值, 返回小于该值的数列 * 例如, max = 15 , 则返回的数组应该为 [1,1,2,3,5,8,13] * max = 1, 则返回空数组 [] * @param max * @return */ //也就是需要生成一个小于max值的fibonacci数组 public int[] fibonacci(int max){ if(max < 2){ return new int[]{}; } if(max < 3){ return new int[]{1,1}; } List<Integer> list = new ArrayList<Integer>(); list.add(0,1); list.add(1,1); int i=0; while (list.get(i) + list.get(i+1) < max){ list.add(i+2,list.get(i) + list.get(i+1)); i++; } int[] newArray = new int[list.size()]; for (int j = 0; j < list.size(); j++) { newArray[j] = list.get(j).intValue(); } return newArray; } /** * 返回小于给定最大值max的所有素数数组 * 例如max = 23, 返回的数组为[2,3,5,7,11,13,17,19] * @param max * @return * * 原理: * 1,判断一个数字是否为素数,一个数 n 如果是合数,那么它的所有的因子不超过sqrt(n) * 2,当i是素数的时候,i的所有的倍数必然是合数。 */ public int[] getPrimes(int max){ if(max <= 2){ return null; } boolean[] prime = new boolean[max + 1]; for (int i = 2; i <= max; i++) { if(i%2 == 0){ prime[i] = false; //偶数 }else { prime[i] = true; } } for (int i = 2; i <= Math.sqrt(max) ; i++) { if(prime[i]){//奇数 //如果i是素数,那么把i的倍数标记为非素数 for(int j = i+i; j <= max; j += i){ prime[j] = false; } } } List num = new ArrayList<Integer>(); for (int i = 2; i <= max; i++) { if(prime[i]){ num.add(i); } } Integer[] result = new Integer[num.size()]; result = (Integer[]) num.toArray(result); return ArrayUtils.toPrimitive(result); } /** * 所谓“完数”, 是指这个数恰好等于它的因子之和,例如6=1+2+3 * 给定一个最大值max, 返回一个数组, 数组中是小于max 的所有完数 * @param max * @return */ public int[] getPerfectNumbers(int max){ if(max < 6){ return null; } List<Integer> perfectNumlist = new ArrayList<Integer>(); for (int j = 6;j <= max; j++){ List<Integer> factorNumlist = new ArrayList<Integer>(); factorNumlist.add(1); for (int i = 2; i < j; i++) { if(j % i == 0){ factorNumlist.add(i); } } int sum = 0; for(Integer num : factorNumlist){ sum += num; } if(sum == j){ perfectNumlist.add(j); } } Integer[] result = new Integer[perfectNumlist.size()]; result = (Integer[]) perfectNumlist.toArray(result); return ArrayUtils.toPrimitive(result); } /** * 用seperator 把数组 array给连接起来 * 例如array= [3,8,9], seperator = "-" * 则返回值为"3-8-9" * @param array * @param seperator * @return */ public String join(int[] array, String seperator){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < array.length - 1; i++) { sb.append(array[i]); sb.append(seperator); } sb.append(array[array.length - 1]); return sb.toString(); } public void printArr(int[] array){ for(int num : array){ System.out.print(num + " "); } } }
C++
UTF-8
1,686
2.796875
3
[ "MIT" ]
permissive
#include "shared/runtime/iObject.hpp" #include "shared/runtime/iStandardClass.hpp" Runtime::iObject::iObject(Runtime::iStandardClass *klass) { this->klass = klass; }; Runtime::iObject::iObject(std::string name) { // does nothing as we don't have a runtime setup/booted yet }; Runtime::iObject::~iObject() { if (this->klass != nullptr) { //delete(this->klass); } }; Runtime::iStandardClass* Runtime::iObject::getStandardClass() { return this->klass; }; void Runtime::iObject::setStandardClass(Runtime::iStandardClass *klass) { this->klass = klass; } std::string Runtime::iObject::getName() { if (this->klass) { return this->klass->getName(); } return DEFAULT_CLASS_NAME; }; Runtime::iStandardClass* Runtime::iObject::getInstanceVariable(std::string name) { if(this->hasInstanceVariable(name)) { return this->instanceVariables[name]; } // TODO: throw exception return nullptr; } bool Runtime::iObject::hasInstanceVariable(std::string name) { if (this->instanceVariables.count(name) > 0) { return true; } return false; } void Runtime::iObject::setInstanceVariable(std::string name, Runtime::iStandardClass* value) { // TODO: check datatypes etc. this->instanceVariables[name] = value; } Runtime::iPrimitiveDataType* Runtime::iObject::getValue() { // default to void return new Runtime::iPrimitiveDataType(); } std::map<std::string, Runtime::iMethod*> Runtime::iObject::getMethods() { return this->methods; } std::map<std::string, Runtime::iStandardClass*> Runtime::iObject::getInstanceVariables() { return this->instanceVariables; } Runtime::iStandardClass* Runtime::iObject::clone() { return nullptr; }
SQL
UTF-8
574
2.78125
3
[ "MIT" ]
permissive
CREATE DATABASE `appetiser-apps-testdb` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; CREATE TABLE `events` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `event` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `datefrom` date NOT NULL, `dateto` date NOT NULL, `active` int(11) NOT NULL, `mon` int(11) NOT NULL, `tue` int(11) NOT NULL, `wed` int(11) NOT NULL, `thu` int(11) NOT NULL, `fri` int(11) NOT NULL, `sat` int(11) NOT NULL, `sun` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
PHP
UTF-8
1,790
2.6875
3
[]
no_license
<?php namespace Infira\omg\helper; use Infira\Utils\RuntimeMemory as Rm; use Infira\Utils\File; use Infira\Utils\Variable; use Infira\omg\Omg; use Infira\console\Bin; class Tpl { const REMOVE_LINE = '__REMOVE_LINE__'; public static function __callStatic($method, $args) { return self::Smarty()->$method(...$args); } public static function render(string $tpl, array $vars = []) { $smarty = self::Smarty(); $smarty->assign($vars); if (!file_exists($tpl)) { alert("Smarty template <strong>" . $tpl . "</strong> ei leitud"); return false; } return $smarty->fetch($tpl); } public static function assign($var, $value = null): \Smarty { return self::Smarty()->assign($var, $value); } public static function Smarty(): \Smarty { return Rm::once('View->Smarty', function () { $smarty = new \Smarty(); $smarty->error_unassigned = true; $smarty->error_reporting = E_ALL; $smarty->caching = false; $smarty->compile_check = true; $smarty->force_compile = true; $smarty->setCompileDir(Bin::getPath('../tmp/compiledTemplates')); return $smarty; }); } public static function load(string $name, array $variables = [], array $replaces = []): string { $ext = File::getExtension($name); $tpl = Bin::getPath("../src/templates/$name"); if (!file_exists($tpl)) { Omg::error("template $tpl does not exist"); } if (in_array($ext, ['txt', 'php'])) { $src = File::getContent($tpl); $src = preg_replace('/\/\/(%\w+\%)/m', '$1', $src); $res = Variable::assign($variables, $src); } else { self::assign($variables); $res = self::render($tpl); } foreach ($replaces as $from => $to) { $res = str_replace($from, $to, $res); } return $res; } }
Java
UTF-8
1,532
2.875
3
[]
no_license
package io.ruin.model.achievements.listeners.experienced; import io.ruin.api.utils.NumberUtils; import io.ruin.model.achievements.Achievement; import io.ruin.model.achievements.AchievementListener; import io.ruin.model.achievements.AchievementStage; import io.ruin.model.entity.player.Player; public class PracticeMakesPerfect implements AchievementListener { @Override public String name() { return "Practice Makes Perfect"; } @Override public AchievementStage stage(Player player) { if(player.cookedFood == 0) return AchievementStage.NOT_STARTED; if(player.cookedFood < 1000) return AchievementStage.STARTED; return AchievementStage.FINISHED; } @Override public String[] lines(Player player, boolean finished) { return new String[]{ Achievement.slashIf("A growing mastery for the skill, a lesson is learned by grabbing", finished), Achievement.slashIf("one too many hot pans with uncovered hands.", finished), "", Achievement.slashIf("<col=000080>Assignment</col>: Cook 1,000 pieces of food", finished), Achievement.slashIf("<col=000080>Reward</col>: Cooking Gauntlets", finished), "", "<col=000080>Cooked Food: <col=800000>" + NumberUtils.formatNumber(player.cookedFood) }; } @Override public void started(Player player) { } @Override public void finished(Player player) { } }
C
UTF-8
825
3.1875
3
[]
no_license
/* int isspace(int x) { return (x == ' ' || x == '\t' || x == '\n' || x == '\v' || x == '\f' || x == '\r'); } int isdigit(int x) { return (x >= '0' && x <= '9'); } int isxdigit(int x) { return ((x >= 'A' && x <= 'F') && (x >= 'a' && x <= 'f') && (x >= '0' && x <= '9')); } int isalpha(int x) { return (x >= 'A' && x <= 'z'); } int toupper(int x) { return (x + 26); } int tolower(int x) { return (x - 26); } int isprint(int x) { return (x >= 0x1f || x == 0x7f); } int isalnum(int x) { return (isdigit(x) || isalpha(x)); } int iscntrl(int x) { return !isprint(x); } int isgraph(int x) { return (isprint(x) && x != ' '); } int isupper(int x) { return (x >= 'A' && x <= 'Z'); } int islower(int x) { return (x >= 'a' && x <= 'z'); } int ispunct(int x) { return (isgraph(x) && !isalnum(x)); }*/ #define INLINE #include <ctype.h>
C++
UTF-8
2,680
2.53125
3
[]
no_license
/* -*- C++ -*- * Copyright (C) 2009 Trinity Core <http://www.trinitycore.org> * Copyright (C) 2012 Morpheus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * @file * @brief Implementation of Data_Store class. * @author raczman <raczman@gmail.com> * @date 2009-12-29 * */ #include "DBC_File.h" namespace Morpheus { namespace DBC { DBC_File::DBC_File(const char* src) { this->file.open(src, std::fstream::binary); if (!file) throw DBC_Read_Exception("Could not open file!", src); if (this->read_uint32() != 0x43424457) throw DBC_Read_Exception("File is not a valid DBC store.", src); this->records = this->read_uint32(); this->fields = this->read_uint32(); this->record_size = this->read_uint32(); this->string_block_size = this->read_uint32(); this->field_size = this->record_size / this->fields; // We will be using this as a pointer into beggining of string table // So, let's get down to math! // Complete data size is records times records size. We add header size to it // And size of NULL that precedes string block. this->data_size = (this->records * this->record_size) + 20; this->file_name = src; } uint32 DBC_File::read_uint32() { uint32 ret; file.read(reinterpret_cast<char*>(&ret), 4); return ret; } float DBC_File::read_float() { float ret; file.read(reinterpret_cast<char*>(&ret), 4); return ret; } std::string DBC_File::read_string() { if (this->string_block_size <= 1) throw DBC_Read_Exception("DBC doesn't have string block.", file_name); uint32 offset = this->read_uint32(); uint32 get_ptr = this->file.tellg(); this->file.seekg(this->data_size + offset); std::string ret; char c; while (1) { file.read(&c, 1); if (c == '\00') break; ret += c; } this->file.seekg(get_ptr); return ret; } void DBC_File::skip_field() { file.seekg(this->field_size, std::ios_base::cur); } }; };
Markdown
UTF-8
2,631
3.203125
3
[ "MIT" ]
permissive
--- author: "joostdecock" caption: "Пам'ятаєте, коли нам дозволили виходити на вулицю?" date: "2021-01-17" intro: "Ліф-блок Bella для жіночого одягу" title: "Ліф-блок Bella для жіночого одягу" --- Ми щойно опублікували нову викрійку на цьому сайті: [Белла, блок ліфа для жіночого одягу](/designs/bella/). Це блок з нагрудною і талієвою виточками, а також талієвою виточкою ззаду. Моєю метою, коли я вирішила зайнятися жіночим одягом, було створити один фундаментальний блок, з якого потім можна було б цілу низку різноманітного одягу. Ось чому у нас є [Бріанна](/designs/breanna/), яку я розробила з нуля. На жаль, це не стало тим кінцем, на який я - можливо, наївно - сподівався. Для Bella я працювала з представником індустрії, щоб реалізувати дизайн, який зазвичай використовується для комерційного виробництва одягу. Тому мені цікаво подивитися, що з цього вийде. Спочатку я планувала також зробити варіацію з плечовою виточкою спереду, щоб замінити нагрудну виточку, , але зрештою я вирішила просто випустити її, а не працювати над нею довше. До чого я веду: ##### Я роблю перерву в жіночому одязі Мені здається, що я витрачаю тут багато зусиль для малого результату. Це пригнічує мене, і мені потрібна перемога. Я хочу працювати над чимось, що можна не лише спроектувати, але й виготовити та носити. Щось, що приносить мені радість і змушує мене відчувати, що я знаю, що роблю. Тож, хоча я й надалі допомагатиму людям, які самі хочуть створювати дизайн для жінок, я беру перерву в роботі над жіночим одягом.
C#
UTF-8
1,022
3.484375
3
[]
no_license
using System; public class CurrencyConverter { public static void Main() { decimal cash = decimal.Parse(Console.ReadLine()); string inn = Console.ReadLine(); string outt = Console.ReadLine(); const decimal usd = 1.79549m; const decimal eur = 1.95583m; const decimal gbp = 2.53405m; const decimal bgn = 1.0m; switch (inn) { case "USD": cash = cash * usd; break; case "EUR": cash = cash * eur; break; case "GBP": cash = cash * gbp; break; } switch (outt) { case "USD": cash = cash / usd; break; case "EUR": cash = cash / eur; break; case "GBP": cash = cash / gbp; break; } Console.WriteLine($"{Math.Round(cash, 2)} {outt}"); } }
Markdown
UTF-8
6,104
2.703125
3
[]
no_license
--- title: Lessons learnt from live streaming church type: article tags: date: 2020-03-24 intro: On Sunday we all learnt a lot of lessons about livestreaming… Here are the lessons we learnt at The Globe Church. --- **As we face further into lockdown of the UK, our churches have embraced livestreaming as a way of keeping in touch with our church families.** I'm not going to write a how-to guide, there are [plenty of those on the internet](https://covid.churcheshandbook.co.uk/livestreaming), instead this is a note of the lessons that we learnt this week at [The Globe Church](https://www.globe.church/live). --- ## ✅ Plan it! You wouldn't go into a service unplanned. Make sure you have a clear service plan in place for the live stream. What video clips are going to be used when, who is speaking to camera, what backing music, etc. ## ✅ You don't need to map your normal service to this medium Our church services run with a certain order to make use of the time and the space. Half way through the service the kids might go out to their seperate groups… this doesn't happen through a livestream… (admittedly in Zoom, kids can have their own breakout rooms in Zoom). Think carefully about what might need to change, or what you could change. ## ✅ Make sure you've got the right music license I've [written a summary of this](/blog/2020/covid-19-live-streaming-song-licensing) but make sure that you've got the correct licence in play to cover your copyright, having a band cover songs is fine, but you'll need the [CCLI streaming license](https://uk.ccli.com/streaming/#need-to-know) if you want to display lyrics for people to sing along with, otherwise limit yourselves to [songs in the public domain](https://songselect.ccli.com/search/results?List=publicdomain). ## ✅ Go wired Wi-Fi is everywhere, which means that with lots of devices floating around, everything can be slow with interference. If you can, plug a cable from the router into the computer that is running the livestream. If you can't, kick every device off the network. ## ✅ Test everything. Everything. Not run a livestream before? Run a test. Not spoken to camera before? Run a test. Not done a tech setup like this before? Run a test! Check the audio levels through the camera, not just what they sound like in the room. Check what you're pointing the camera at… take the time to make it look good; don't cut of the tops of people's head in the frame. You don't need to be fancy moving the camera all over the place - a fixed camera on a tripod is [more than enough](https://www.youtube.com/watch?v=3AUGRNks8d4). Also… [test your upload speed](https://beta.speedtest.net/). ## ✅ Tell people where it is At The Globe Church we're running everything from [www.globe.church/live](https://www.globe.church/live). We have shared that link in whole church emails, through social media, in WhatsApp chats, in banners across the church website. We're running it through the [/live](https://www.globe.church/live) page for a couple of reasons: - Each live stream URL from YouTube and Facebook is different, we're just embedding that URL into our [/live](https://www.globe.church/live) page - this gives us one place to keep upto date. Every email we send out will always have the right link in it. - We control the page - [/live](https://www.globe.church/live) is on our website, not Facebook and YouTube's page with 101 other distractions on it competing for attention. [/live](https://www.globe.church/live) has on it what we want people to see, and we're adding content and improving it day by day. ## ✅ Expect guests On Sundays you preach for people who have been Christians for decades, as well as people who are just beginning to explore Christianity. It's the same here. You're not talking to Sunday regulars anymore! My parents near Brighton are tuning in (👋&nbsp;Mum and&nbsp;Dad), people are sharing the link with their housemates, and their neighbours. It's on the internet, so it's public. Expect guests. As a preacher, you're getting no feedback from the room - explain the Gospel clearly, as if it is the first time someone is hearing it. ## ✅ People are mobile On The Globe Church website 61% of visitors we visiting from a mobile device (70% if you include tablets). Laptops can be carried anywhere in the house or flat too. Don't think that people are going to be all gathering around a TV set. How does that change how you put your time together? ## ✅ What happens next? Think about after the service… there's no tea and biscuits any more. What do you want people to do? Think about individuals sitting on their own in their bedrooms, think about families gathered in their front-rooms around a TV, think about flatmates who have spent too much time with each other this week. What do you want them to do next? _A couple of suggestions:_ - If someone is just discovering Jesus for the first time, what resource do you want to point them to? - If someone is on their own… prompt them to make some notes, to think, to pray, to reflect, then maybe to call someone and talk about what they've been listening too. - If people are in a group, they are in an instant small group - have some discussion questions ready. ## ✅ Be okay with not being polished You're not a big US megachurch with a slick setup, that's okay - that's not what it is about. Be you, make mistakes (we broadcast Jonty upside down this morning), learn from them. This isn't about being the insta-perfect image, don't get trapped in that millenial/influencer dream. Just show people Jesus. ## ⚠️ Beware: the novelty will wear off This week was fun, this is a new way of doing church, it feels novel right!? Next week, when we have all spent our lives having conversations mediated by a webcam, sitting in-front a computer, tablet or mobile device on Sunday for church won’t be as appealing. Let's think carefully about how we engage our church families outside the live stream. --- These are lessons from week one. We're going to learn more next week. Keep going friends!
Java
UTF-8
299
2.03125
2
[]
no_license
package com.Shop2Drop.Shop2Drop.repository; import com.Shop2Drop.Shop2Drop.entity.User; import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<User,Long> { User findByUsername(String username); User findByEmail(String email); }
Markdown
UTF-8
1,659
2.65625
3
[]
no_license
# Guidance on what to consider across the board for all projects. 1. Design a theoretical process for the pipeline which is efficient for the team to use in the project. CI/ CD 2. If required setup GitLAB server and Jenkins server 3. Create gitlab; accounts; branching strategy. 4. Create jenkins; accounts; access 5. Decide what parts you want to automate 6. Automate this process stage by stage 7. Create accounts in AWS and AZURE - dev and ops as well as billing, logging, etc.. 8. How many environments do we need, demo, dev, testing, prod, pen testing. 9. How long are environments taking to build? Why is taking so long? 10. When is the go-live date?!! **IMPORTANT** 11. What are the demands of the app in the production environment. NOTES: Pipeline will never be given a priority, it's an Ops engineers job to convince the team that this is a priority and to push to make sure that this is made a priority. First define a theoretical process showing how code will go from your machine to production, this needs to be efficient for the whole team and should be clearly defined. In a project meeting you will decide the strategy and pipeline, you will also decide the branch naming conventions. Most of the time this will adhere to the naming convention in the Jira ticket name. Jira101-VPC for example. The ticket will be reviewed to check the acceptance criteria has been met. Make sure you use the Jenkins job in the merge request if used, as otherwise the merge will be rejected. What is the standard of merge requests?, What is the branching naming convention? Git branch names should marry with things like JIRA tickets numbers
C++
UTF-8
4,450
3.1875
3
[]
no_license
/** * Calculating the Sieve Eratosthenes to a given limit, Multithreding. * * @author * Abdalrahman Ibrahim <a2ibrahim@edu.aau.at> */ #include <bits/stdc++.h> #include <omp.h> using namespace std; class SieveEratosthenes { private: public: int _limit; int p; int i; int x; SieveEratosthenes() = default; ~SieveEratosthenes() = default; void SieveEratosthenes_original(int _limit); void SieveEratosthenes_parallel(int _limit); void PrintSieve(int _limit); }; void SieveEratosthenes::SieveEratosthenes_original(int _limit) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool _prime[_limit + 1]; // Converts the value ch to unsigned char 'true' and copies it into each of // the first n characters of the object pointed to by _prime[] memset(_prime, true, sizeof(_prime)); for (int p = 2; p * p <= _limit; p++) { // If prime[p] is not changed, then it is a prime if (_prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p * p; i <= _limit; i += p) _prime[i] = false; } } }; void SieveEratosthenes::SieveEratosthenes_parallel(int _limit) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. bool _prime[_limit + 1]; // Converts the value ch to unsigned char 'true' and copies it into each of // the first n characters of the object pointed to by _prime[] memset(_prime, true, sizeof(_prime)); int sqrt_limit = int(sqrt(_limit)) +1; int procs = omp_get_num_procs(); // get number of process int nthreads = procs * 2; #pragma omp parallel for shared(p,sqrt_limit,_prime) private(i) schedule(dynamic,1) num_threads(nthreads) for (int p = 2; p <= sqrt_limit; p++) { // If prime[p] is not changed, then it is a prime if (_prime[p] == true) { // Update all multiples of p greater than or // equal to the square of it // numbers which are multiple of p and are // less than p^2 are already been marked. for (int i = p; i <= sqrt_limit; i += p) _prime[i] = false; } } }; void SieveEratosthenes::PrintSieve(int _limit) { bool _prime[_limit + 1]; // Print all prime numbers for (int p = 2; p <= _limit; p++) if (_prime[p]) cout << p << " "; }; //********************PROFILER Using Chrono********************// struct profiler { std::string name; std::chrono::high_resolution_clock::time_point p; profiler(std::string const &n) : name(n), p(std::chrono::high_resolution_clock::now()) {} ~profiler() { //using dura = std::chrono::duration<double>; //using dura = std::chrono::microseconds; using elapsednas = std::chrono::nanoseconds; using elapsedmic = std::chrono::microseconds; using elapsedmis = std::chrono::milliseconds; auto d = std::chrono::high_resolution_clock::now() - p; std::cout << name << "Time Measured: " << std::chrono::duration_cast<elapsednas>(d).count() << "[µs] ," << std::chrono::duration_cast<elapsedmic>(d).count() << "[ns] ," << std::chrono::duration_cast<elapsedmis>(d).count() << "[ms] " << std::endl; } }; #define PROFILE_BLOCK(pbn) profiler _pfinstance(pbn) //********************PROFILER Using Chrono********************// int main() { // Select limit // int const limit = 50; //Uncomment this and line 150, 159 see results int const limit = 999999; // max number // Class instance of the Sieve Eratosthenes SieveEratosthenes SE; // Find all prime number using original sieve eratosthenes { PROFILE_BLOCK("Sieve Eratosthenes Original "); SE.SieveEratosthenes_original(limit); } // SE.PrintSieve(limit); { PROFILE_BLOCK("Sieve Eratosthenes Original "); SE.SieveEratosthenes_parallel(limit); } // Print the those primes // SE.PrintSieve(limit); }
C++
UTF-8
8,092
2.796875
3
[]
no_license
// // Created by sapir on 10/12/17. // #include "FirstClient.h" #include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <limits> #include <cstdlib> #include <climits> #include <sstream> FirstClient::FirstClient(Board* board, GameLogic* logic, int** validMoves, Board::State playerChar, int typeOfGame,ConsolePrinting* con, const char* filename): Player(board,logic,validMoves,playerChar,typeOfGame,con,filename), con(con) { this->copyBoard = board; this->copyLogic = logic; this->moves = validMoves; this->typeOfGame = typeOfGame; } void FirstClient::connectToServer() { // Create a socket point clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (clientSocket == -1) { throw "Error opening socket"; } // Convert the ip string to a network address struct in_addr address; if (!inet_aton(serverIP.c_str(), &address)) { throw "Can't parse IP address"; } // Get a hostent structure for the given host address struct hostent *server; server = gethostbyaddr((const void *) &address, sizeof address, AF_INET); if (server == NULL) { throw "Host is unreachable"; } // Create a structure for the server address struct sockaddr_in serverAddress; bzero((char *) &address, sizeof(address)); serverAddress.sin_family = AF_INET; memcpy((char *) &serverAddress.sin_addr.s_addr, (char *) server->h_addr, server->h_length); // htons converts values between host and network byte orders serverAddress.sin_port = htons(serverPort); // Establish a connection with the TCP server if (connect(clientSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) == -1) { throw "Error connecting to server"; } ////////////////playerChoose(); } void FirstClient::UpdateArgs(int firstarg, int secondarg) { ssize_t numToSend; // Write 2 numbers t numToSend = write(clientSocket, &firstarg, sizeof(firstarg)); if (numToSend == -1) { throw "Error writing arg1 to socket"; } numToSend = write(clientSocket, &secondarg, sizeof(secondarg)); if (numToSend == -1) { throw "Error writing arg2 to socket"; } } void FirstClient::doTurn(int typeOfGame, Board *board, ConsolePrinting *con, Cell *&c) { //x and y are the values that are scaned from the user int y = 0, x = 0; char xchar, ychar; char dummy = ' '; bool isThereMoves = copyLogic->validMoves(copyBoard->getBoard(), this->moves, this->GetplayerType()); con->itsYourMove(this->GetplayerType()); con->possibleMoves(this->moves); cout<<"Please enter your move row,col:"; // now we check if the inserted values are valid in the array if (isThereMoves) { while (true) { cin >>x >>dummy>>y; xchar = x; ychar = y; if (xchar > 8 || xchar < 1 || ychar < 1 || ychar > 8 || (dummy != ',')) { cout << "invalid value, please enter 'row,col' between 1-8" << endl; cin.clear(); std::cin.ignore(INT_MAX, '\n'); continue; } // we got ints. // player starts from 1. our board starts from 0 x-=1; y-=1; if(InvalidInValidArray(x,y) != 1){ cout << "your move is not possible, please enter a move from the showed possible moves" << endl; cin.clear(); std::cin.ignore(INT_MAX, '\n'); continue; } if (copyLogic->checkInput(copyBoard->getBoard(), x, y)) break; } // p->setI(x); // p->setJ(y); //moves to the game!!!!!!!!!!! //if the turn worked succesfully c = new Cell(x,y); // send to server stringstream ss; ss << x; ss << ","; ss << y; write(clientSocket, ss.str().c_str(), ss.str().size()+1); } else { //bad arguments if the turn failed c = new Cell(-1,-1); // send to server string no_move_msg = "NoMove"; write(clientSocket, (void *)(no_move_msg.c_str()), strlen(no_move_msg.c_str()) + 1); } } int FirstClient::InvalidInValidArray(int x, int y) { if(this->moves[x][y] == 1) { return 1; } else { return 0; } } int FirstClient::getMoveFromServer() { ssize_t n; // Read the result from the server char msg[10]; n = read(clientSocket, msg, sizeof(msg)); if (n == -1) { throw "Error reading result from socket"; } return atoi(msg); } void FirstClient::noMove(ConsolePrinting* con) { string anyKey; con->noMorePosMove(this->GetplayerType()); con->pressAnyKeyToCont(); getline(cin, anyKey); getline(cin, anyKey); con->newLine(); UpdateArgs(-1, -1); } void FirstClient::finishGame() { int result = -2; ssize_t n; string end_str = "EndGame"; n = write(this->clientSocket, end_str.c_str(), sizeof(end_str)); if (n == -1) { throw "Error reading result from socket"; } close(this->clientSocket); } /* void FirstClient::playerChoose() { string command, name; int choose, n; int check1 = 0; int check2 =0; while(check1==0) { con->printClientMenu(); cin >> choose; while (check2 == 0) { cin>>choose; cout<<endl; if(choose != 1 && choose!= 2 && choose!= 3) { con->noValidOption(); } else check2 = 1; } switch (choose) { case 1: { con->chooseGameOptions(); cin >> name; command = "start "; command = command + name; WriteToServer(command); string checkCommand = ReadFromServer(<#initializer#>); cin.ignore(); if (checkCommand == "Exist") { con->printString(checkCommand); close(this->clientSocket); connectToServer(); } else { check1 = 1; } break; } case 2: { command = "list_games"; WriteToServer(command); string receivedMessage = ReadFromServer(<#initializer#>); con->printString(receivedMessage); close(this->clientSocket); break; } case 3: { con->EnterNameOfGame(); command = "join "; command = command + name; WriteToServer(command); string checkCommand; = ReadFromServer(<#initializer#>); cin.ignore(); if (checkCommand == "UnavailableGame") { con->printString(checkCommand); close(this->clientSocket); connectToServer(); } else { check1 = 1; } break; } default: { con->printString(" Input invalid, try again."); } } } } */ int FirstClient::WriteToServer(string command) { //char commandBuffer[50] = {0}; int check = send(clientSocket, (char *)command.c_str(), command.size()+1, 0); if (check == -1) { //throw "Error writing to server"; cout << "Error writing to server" << endl; } else if (check == 0) { con->printString("Server disconnected"); } return check; } int FirstClient::ReadFromServer(string &command_str) { char command[50] = {0}; int r = recv(clientSocket, &command, sizeof(command), 0); if (r == -1) { con->printString("Error reading result from socket"); } else if (r == 0) { con->printString("Server disconnected"); } command_str = string(command); return r; }
C
UTF-8
927
3.15625
3
[]
no_license
#include <stdio.h> int main() { int number = 0; scanf("%d",&number); int numberlist[3] = {0}; char numberch[3]; sprintf(numberch,"%d",number); for (int h = 0; h < 3; h ++) { numberlist[h] = (int)numberch[h] - 48; } if (numberlist[0] != 0) { while (1) { printf("B"); numberlist[0] -= 1; if (numberlist[0] == 0) { break; } } } if (numberlist[1] != 0) { while (1) { printf("S"); numberlist[1] -= 1; if (numberlist[1] == 0) { break; } } } for (int r = 0; r < numberlist[2]; r ++) { int stack = r; printf("%d",stack + 1); if (stack + 1 == numberlist[2]) { break; } } return 0; }
Java
UTF-8
422
2.515625
3
[]
no_license
public class Controller { public static void main(String[] args) { Ponta ponta1 = new Ponta(0.7); Ponta ponta2 = new Ponta(0.7); Lapiseira c1 = new Lapiseira("BIC", ponta1); c1.status(); c1.escrever(); c1.setPonta(ponta1); c1.escrever(); c1.status(); c1.escrever(); c1.escrever(); c1.escrever(); c1.escrever(); c1.escrever(); c1.setPonta(ponta2); c1.escrever(); c1.escrever(); } }
Markdown
UTF-8
12,665
2.9375
3
[]
no_license
--- layout: post title: "Publishing a Ruby Gem with a React-based front end" description: "Using Rack middleware in a Gem to serve assets from a React build" date: 2021-05-30 08:43:00 -0400 comments: true tags: [rails, rack, ruby, gem, rubygems, middleware, html] --- ## Motivation As stated in the [last post](/2021/04/23/a-gem-with-a-view.html), our goal package up a front end interface for [FactoryBot](https://github.com/thoughtbot/factory_bot) and distribute the functionality as a Ruby Gem. This post will take what we've learned and build that gem. We'll leave the details of the FactoryBot hackery for another post; here we'll focus on getting the Gem built and published so that its front and back ends are correctly hooked up to any application that wishes to use it. ## Quick Recap We left off last time with one html, one javascript, and one css file being served together using `Rack::Static`. We did this by creating our own Rack app / middleware that could be mounted in a Rails app simply with ```ruby mount ABigStick.new, at: "/abigstick", as: "abigstick" ``` The basics of the `ABigStick` app looked like this: ```ruby class ABigStick def call(env) static_app.call(env) end def static_app Rack::Static.new(nil, static_options) end # ... end ``` We'll build on this, serving the full output of a `create-react-app` build instead of a simple html file. This presents a few challenges we'll have to address; read on! We'll also add routes to back-end features, requiring a slightly more nuanced Rack app than our initial example. ## Project Structure There are a few parts to keep track of, so it might help to see the project structure from the beginning. Without defending this choice at all, I'm calling the gem "factory_burgers", so here we go: ``` factory_burgers ├── Gemfile ├── factory_burgers-ui │   └── # source code for UI assets (React / jsx) ├── factory_burgers.gemspec ├── lib │   ├── assets │   | └── # build output from factory_burgers-ui │   ├── factory_burgers │   | └── # source code for gem (ruby), including models and mmiddleware │   └── factory_burgers.rb ├── spec │   └── # tests └── test_apps    └── # example rails apps that use the gem ``` This is simplified, of course. To see more, [check it out](https://github.com/ozydingo/factory_burgers) on Github. ## The Front End The source code for the front-end assets are in the `factory_burgers-ui` folder. As a quick note on iteration, I started by running [`create-react-app`](https://reactjs.org/docs/create-a-new-react-app.html) inside that folder, and iterated toward replacing the stock assets with source files from my already app-resident React code. I'm not going to dive into the code or components themselves, since that's not the point of this post. Instead, I'll just make a few notes on a couple tweaks required to make this work. #### Homepage `create-react-app` is built for a standalone app, and by default will generate links to assets at the server root (e.g. `<script src=/my_file.js />`). This won't work for us because that request will get handled by Rails, which will not match it to our gem's middleware, and we'll just get a `404: Not Found`. To fix this, we need to tell `create-react-app` to use relative links, preserving path the gem middleware is mounted at. We can do this by adding the following our `factory_burgers-ui/package.json` file: ```json "homepage": "./" ``` #### Copying Build Assets A typical developer user of this gem should not have use our static asset build process. In fact, short of forking the repo, they have no need for the React source code at all. So we will not include the `factory_burgers-ui` folder for distribution. Instead, we will copy the build assets into `lib/assets` by adding this to our `package.json`: ```json "build": "react-scripts build && cp -r build/* ../lib/assets" ``` This way, every build will dump the assets to a git-managed location we can distribute and reference from our middleware. ## The Middleware Using the middleware we started out with, we can get our unnecessarily shiny front-end up and running. But that's not the whole game; we still need a connection to the back end. Specifically, we need to do two things: 1. Get a list of available FactoryBot factories along with their properties to display to the user. 2. Submit requests to our app to build resources using those factories. The code to actually do these things is out of scope for this post, abstracted away behind a `FactoryBurgers` module that might be the subject of another post. We simply need to use this module in our middleware, and set up routes to our server that allow the front end to make these requests. We still don't want to make usage any more complicated than ```ruby mount FactoryBurgers::App, at: "/factory_burgers", as: "factory_burgers" ``` so we'll use Rack's `map` feature to handle specific routes nested under `/factory_burgers`. To do this, instead of a simple Rack app with a `call` method, we'll use [`Rack::Builder`](https://www.rubydoc.info/gems/rack/Rack/Builder). Without further ado, `lib/factory_burgers/app.rb`: ```ruby module FactoryBurgers App = Rack::Builder.new do map("/data") { run Middleware::Data.new } map("/build") { run Middleware::Build.new } run Middleware::Static.new end end ``` Requests to `/factory_burgers/*` are handled by this app. This app, in turn, will match `/factory_burgers/data` and `/factory_burgers/data` and pass those requests to instance of `Middleware::Data` and `Middleware::Build`, respectively. If the request matches neither, including the index page and all assets linked to from that page, the request is handled by `Middleware::Static`. Perfect. #### `Middleware::Static` `Middleware::Static` is basically the same as the app we defined in our last post. ```ruby module FactoryBurgers module Middleware class Static def call(env) return slashpath_redirect(env["REQUEST_PATH"]) if slashpath_redirect?(env) rack_static.call(env) end def rack_static Rack::Static.new(nil, static_options) end def static_options {urls: [""], root: asset_path, index: 'index.html'} end def asset_path @asset_path ||= FactoryBurgers.root.join("assets/") end end end end ``` Like before, we're configuring our `Rack::Static` instead to server assets from `asset_path`, but this time we're abstracting part of that definition to the top-level `FactoryBurgers` module ```ruby module FactoryBurgers class << self def root @root ||= Pathname(__dir__).expand_path end end end ``` Now what's up with `slashpath_redirect`? This method is here to address an issue with our `Rack::Statis` approach. Specifically, if an end user navigates to `<DOMAIN>/factory_burgers/`, everything is hunky-dory. But if the user navigates to `<DOMAMIN/factory_burgers` (without the trailing slash), the relative paths we worked so briefly to set up will not work because the browser does not interpret `factory_burgers` as a directory. Therefore, we redirect such requests to `<DOMAIN>/factory_burgers/`: ```ruby def slashpath_redirect?(env) # Only check for a trailing slash if this request is to the mount location. env["REQUEST_PATH"] == env["SCRIPT_NAME"] && env["REQUEST_PATH"][-1] != "/" end # Append `/` to the path and redirect def slashpath_redirect(path) return [ 302, {'Location' => "#{path}/", 'Content-Type' => 'text/html', 'Content-Length' => '0'}, [], ] end ``` There's probably a better way to do this. 2. `Middleware::Data` The purpose of this middleware is to provide the initial list of factories to the front-end. The behavior will be nicely abstracted away behind `FactoryBurgers` modules and classes, so we can focus for now only on the Rack interaction ```ruby module FactoryBurgers module Middleware class Data def call(*) factories = FactoryBurgers::Introspection.factories.sort_by(&:name) factory_data = factories.map { |factory| factory_data(factory) } return [200, {"Content-Type" => "application/json"}, [JSON.dump(factory_data)]] end def factory_data(factory) FactoryBurgers::Models::Factory.new(factory).to_h end end end end ``` Nothing crazy going on here. Our back-end code has a method that collects a list of factories (`FactoryBurgers::Introspection.factories`) and a class that maps these objects into data required by the front-end (`FactoryBurgers::Models::Factory.new(factory).to_h`). We request this from the front end using `fetch("./data")`, and use the response to build the form. 3. `Middleware::Build` This one gets a little more complicated, and we won't dive into the specifics of the UI options to build custom objects using our factories, nor the error handling. For now, let's just see this as an example of how to parameters in a Rack app via `Rack::Request#params`. This is done in our `paramters` method, which is called from `build`, which is in turn called from the main `call` method. ```ruby module FactoryBurgers module Middleware class Build def call(env) resource = build(env) object_data = FactoryBurgers::Models::FactoryOutput.new(resource).data response_data = {ok: true, data: object_data} return [200, {"Content-Type" => "application/json"}, [JSON.dump(response_data)]] rescue StandardError => err log_error(err) return [500, {"Content-Type" => "application/json"}, [JSON.dump({ok: false, error: err.message})]] end def build(env) params = paramters(env) factory = params.fetch("factory") traits = params["traits"]&.keys attributes = attribute_overrides(params["attributes"]) return FactoryBurgers::Builder.new.build(factory, traits, attributes) end def paramters(env) request(env).params end def request(env) Rack::Request.new(env) end # ... end end end ``` We can use request parameters in `build`, and we construct the response body as JSON using `FactoryBurgers::Models::FactoryOutput`. The details on the other side of that wall will be the subject of another post. ## The Gem All that's left is to bundle this up as a gem! There's really nothing here you can't get by reading the [rubygems guide](https://guides.rubygems.org/make-your-own-gem/), but I'll just show that which is relevant to this project setup. Here's our `factory-brugers.gemspec` file: ```ruby require File.expand_path('./lib/factory_burgers/version') Gem::Specification.new do |s| s.name = 'factory_burgers' s.version = FactoryBurgers::VERSION # ... all thue standard stuff ... s.files = Dir["lib/**/*"] s.add_dependency "factory_bot", ">= 4" s.add_dependency "rack", ">= 1" s.add_development_dependency "activerecord", ">= 4" s.add_development_dependency "sqlite3" # ... end ``` Our development dependencies include `acctiverecord` and `sqlite3`, just enough to build functional ActiveRecord models that can be built with factories for our test harness. To build the gem, the usual rules apply: `gem build factory-brugers.gemspec`, `gem push factory_burgers-x.y.z.gem`. Since we're coordinating a Ruby gem and a Javascript React app, we're going one step further and providing a [`Makefile`](https://github.com/ozydingo/factory_burgers/blob/main/Makefile) that coordinates the asset build, Javascript linting, Ruby linting, and test suite as dependencies of building the gem and pushing it to rubygems.org. ## Summing up * We put our front end build source in a distribution-hidden folder and copy the build output into `lib`. * We needed a couple minor tweaks to a standard `create-react-app` build process to make this work as a mounted app served by Rails. * We constructed our Rack app using `Rack::Builder` to define a couple nested routes to handle non-static back-end requests at `/<MOUNT_PATH>/data` and `/<MOUNT_PATH>/build` * We built separate apps to handle these non-static requests, using parameters that can be obtained from `env` and calling back-end code from ouur gem. * We built and published the gem using standard tooling, including a Makefile to help keep everything built correctly. In the next post, we'll go over the guts of `FactoryBurgers`, since there's a lot of cool stuff in there to allow `FactoryBot` to work will in a non-automated-test environment.
JavaScript
UTF-8
1,965
2.6875
3
[ "Apache-2.0" ]
permissive
"use strict"; let assert = require('assert'); let CVHandler = require("../lib/cv-handler.js") describe('CVHandler', () => { before(() => { }); after(() => { }); it("should be able to collect correct population values and median", (done) =>{ var records = [{"IPP" : 1, "MSRPOPL" : 1 , "values": [2]}, {"IPP" : 1, "MSRPOPL" : 0 , "values": []}, {"IPP" : 0, "MSRPOPL" : 0 , "values": []}, {"IPP" : 1, "MSRPOPL" : 1 , "values": [4]}, {"IPP" : 2, "MSRPOPL" : 2 , "values": [3,5]}, {"IPP" : 3, "MSRPOPL" : 2 , "values": [8,11]}, ] var p = new CVHandler("MEDIAN"); p.start(); records.forEach(rec =>{ p.handleRecord(rec); }); p.finished(); var values = p.results(); assert.equal(8, values.IPP, "IPP should be 8"); assert.equal(6, values.MSRPOPL, "MSRPOPL should be 6"); assert.equal(4.5, values.OBSERV, "OBSERV should be 4.5"); assert.equal(6, p.count, "Count should be 6"); done(); }); it("should be able to collect correct population values and average", (done) =>{ var records = [{"IPP" : 1, "MSRPOPL" : 1 , "values": [2]}, {"IPP" : 1, "MSRPOPL" : 0 , "values": []}, {"IPP" : 0, "MSRPOPL" : 0 , "values": []}, {"IPP" : 1, "MSRPOPL" : 1 , "values": [4]}, {"IPP" : 2, "MSRPOPL" : 2 , "values": [3,5]}, {"IPP" : 3, "MSRPOPL" : 2 , "values": [8,11]}, ] var p = new CVHandler("AVERAGE"); p.start(); records.forEach(rec =>{ p.handleRecord(rec); }); p.finished(); var values = p.results(); assert.equal(8, values.IPP, "IPP should be 8"); assert.equal(6, values.MSRPOPL, "MSRPOPL should be 6"); assert.equal(5.5, values.OBSERV, "OBSERV should be 5.5"); assert.equal(6, p.count, "Count should be 6"); done(); }); });
C#
UTF-8
2,947
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Windows; namespace Acme_Used_CarsWPFcs { public static class VehicleDB { public static List<Vehicle> GetVehicles() { SqlConnection con = Acme_Used_CarsDB.GetConnection(); List<Vehicle> vehList = new List<Vehicle>(); SqlCommand command = new SqlCommand(); command.CommandText = "select * from Vehicle"; command.CommandType = CommandType.Text; command.Connection = con; try { con.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Vehicle v = new Vehicle(); v.InventoryID = Convert.ToInt32(reader[0]); v.Manufacturer = reader[1].ToString(); v.ModelName = reader[2].ToString(); v.Year = Convert.ToInt32(reader[3]); v.VehicleID = reader[4].ToString(); v.CostValue = Convert.ToDecimal(reader[5]); vehList.Add(v); } reader.Close(); } catch (SqlException err) { MessageBox.Show(err.Message, "Database Error"); } finally { con.Close(); } return vehList; } public static bool InsertVehicle(Vehicle vehicle) { int rows = 0; SqlConnection con = Acme_Used_CarsDB.GetConnection(); SqlCommand command = new SqlCommand(); command.CommandText = "insert into Vehicle values (@inventoryid,@manufacturer,@ModelName,@year,@vehicleid,@costvalue)"; command.CommandType = CommandType.Text; command.Connection = con; command.Parameters.AddWithValue("@inventoryid", vehicle.InventoryID); command.Parameters.AddWithValue("@manufacturer", vehicle.Manufacturer); command.Parameters.AddWithValue("@ModelName", vehicle.ModelName); command.Parameters.AddWithValue("@year", vehicle.Year); command.Parameters.AddWithValue("@vehicleid", vehicle.VehicleID); command.Parameters.AddWithValue("@costvalue", vehicle.CostValue); try { con.Open(); rows = command.ExecuteNonQuery(); } catch (SqlException err) { MessageBox.Show(err.Message, "Database Error"); } finally { con.Close(); } if (rows == 1) { return true; } else { return false; } } } }
Java
UTF-8
1,059
2.75
3
[]
no_license
package Processadores; import java.util.Random; import java.util.Vector; import util.Processo; public class GerenciadorHReceptor extends Gerenciador { public GerenciadorHReceptor (int numProc) { super (numProc); proc_ = new Vector<Processador>(); for (int i = 0; i < nProc_; i++) { proc_.add(new ProcessadorReceptor(i)); } } @Override public boolean tryReceiveProcess (int numProcessador) { Random rand = new Random(); for (int i = 1; i <= RETRY; i++) { int r = rand.nextInt(nProc_); while (r == numProcessador) r = rand.nextInt(nProc_); if (getTempoDeProcessamentoTotal() == 0) return false; float coef = proc_.elementAt(r).getTempoProcessamento() / getTempoDeProcessamentoTotal(); if (coef > Processador.LIMIT_MAX && proc_.elementAt(r).getNumProcessos() > 1) { Processo p = proc_.elementAt(r).receiveLastProcess(); // Mudou a cpu printCPUChange(r, numProcessador); p.cpu_ = numProcessador; proc_.elementAt(numProcessador).addProcess(p); return true; } } return false; } }
Java
UTF-8
576
1.859375
2
[]
no_license
package com.spring.model; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class MapDAO implements InterMapDAO { @Resource private SqlSessionTemplate sqlsession; // 해당상품의 지도정보 불러오기 @Override public HashMap<String, String> mapInfo(HashMap<String, String> paraMap) { HashMap<String, String> mapInfo = sqlsession.selectOne("finalproject4.mapInfo", paraMap); return mapInfo; } }
Go
UTF-8
771
4.40625
4
[]
no_license
package main import "fmt" type myDb struct{} func main() { var a interface{} a = 1 // Setting values as int switching(a) a = "Abc" // Setting values as string switching(a) a = myDb{} // Setting values as myDb switching(a) a = nil // Setting values as nil switching(a) a = 1.0 // Setting values as float for default case switching(a) } // switching accepts the a interface values and selects a cases according to the values it holds func switching(a interface{}) { switch a.(type) { case int: fmt.Println("a holds integer") case string: fmt.Println("a holds string") case nil: fmt.Println("The interface value is nil") case myDb: fmt.Println("The a hold myDb type value") default: fmt.Println("Default - No case is satisfied") } }
Python
UTF-8
905
3.046875
3
[]
no_license
from collections import Counter def output(t, res): casestr = "Case #" + str(t+1) +": " status = str(res) if res != None else "impossible" outputLine = casestr+status print outputLine def main(): ############################################1 T = int( raw_input() ) for t in xrange(T): N = int(raw_input()) w1 = [] w2 = [] for n in xrange(N): words = raw_input().split() w1.append(words[0]) w2.append(words[1]) c1 = Counter(w1) c2 = Counter(w2) u1 = [x for x,y in c1.iteritems() if y == 1] u2 = [x for x,y in c2.iteritems() if y == 1] realT = 0 for i in xrange(N): if w1[i] in u1 or w2[i] in u2: realT +=1 output(t, N - realT) if __name__ == "__main__": main()
PHP
UTF-8
3,846
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Departamentos; class DepartamentosController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $departamentos = Departamentos::all(); return view("departamentos.index",['departamentos'=>$departamentos]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view("departamentos.create"); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $departamento = new Departamentos; $departamento->fill($request->all()); if($departamento->save()){ return redirect('/departamentos')->with([ 'flash_message' => 'Departamento agregado.', 'flash_class' => 'alert-success' ]); }else{ return view("departamentos.create",[ "departamento" => $departamento, "flash_message" => "Ah ocurrido un error.", "flash_class" => "alert-danger" ]); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $departamentos = Departamentos::findOrFail($id); $area = $departamentos->areas(); $areas = (object)["areas"=>$area,"count"=>$area->count(),'users'=>$departamentos->users()]; return view('departamentos.view',['departamento'=>$departamentos,'areas'=>$areas]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $departamentos = Departamentos::findOrFail($id); return view('departamentos.edit',['departamento'=>$departamentos]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $departamento = Departamentos::findOrFail($id); $departamento->fill($request->all()); if($departamento->save()){ return redirect("/departamentos/{$id}")->with(["flash_message"=>"Cambios guardados con exito.","flash_class"=>"alert-success"]); }else{ return view("departamentos.edit", [ "departamento" => $departamento, "flash_message" => "Ha ocurrido un error.", "flash_class" => "alert-danger" ]); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $departamentos = Departamentos::find($id); if($departamentos){ if($departamentos->areas()->count() > 0 || $departamentos->users() > 0){ return redirect("/departamentos/{$id}")->with([ "flash_message" => "No se pueden eliminar departamentos con asignaciones.", "flash_class" => "alert-danger" ]); }else{ Departamentos::destroy($id); return redirect('/departamentos')->with([ "flash_message" => "Departamento eliminado.", "flash_class" => "alert-success" ]); } }else{ return redirect('/departamentos')->with([ "flash_message"=>"Departamento no encontrado.", "flash_class" => "alert-danger" ]); } }//Destroy }
JavaScript
UTF-8
1,246
2.796875
3
[ "MIT" ]
permissive
import GenesisBlock from './genesisBlock.js'; export default class Blockchain { constructor(wallet) { this._blocks = new Map(); this.headOfChain = new GenesisBlock(wallet); this._blocks.set(this.headOfChain.hash, this.headOfChain); } size() { return this._blocks.size; } add(block) { if(!block.isVerified()) { // only accept valid blocks return; } if(block.previousHash != this.headOfChain.hash) { throw new Error('The block to be added does not reference the previous block correctly!') } this._blocks.set(block.hash, block); this.headOfChain = block; } getBlock(hash) { return this._blocks.get(hash); } isValid() { const blocks = Array.from(this._blocks).reverse(); for(let i = 0; i < blocks.length; i++) { if (blocks[i][1].previousHash === "" && i === blocks.length - 1) { return true; } if(blocks[i][1].hash !== blocks[i][1]._hash().digest().toHex()) { return false; } if (this._blocks.get(blocks[i][1].previousHash).hash !== blocks[i][1].previousHash) { return false; } } } forEach(callback) { this._blocks.forEach((value) => callback(value)); } }
Python
UTF-8
396
2.578125
3
[ "MIT" ]
permissive
from unittest import TestCase from qbo import utils class TestUtils(TestCase): def test_valid(self): parsed = utils.parse_int("12345") assert parsed == 12345 def test_invalid(self): parsed = utils.parse_int("test") assert parsed is None def test_invalid_with_default(self): parsed = utils.parse_int("test", 42) assert parsed is 42
Markdown
UTF-8
7,952
3.25
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "Dates(!) and Hashes(?) and Names, Oh My!!: The Weekly Challenge #132" author: "Dave Jacoby" date: "2021-09-27 17:50:50 -0400" categories: "" --- [Weekly Challenge 12*11!](https://theweeklychallenge.org/blog/perl-weekly-challenge-132/) ### TASK #1 › Mirror Dates > Submitted by: Mark Anderson > You are given a date (yyyy/mm/dd). > > Assuming, the given date is your date of birth. Write a script to find the mirror dates of the given date. > > Dave Cross has built cool site that does something similar. So, the steps are: - Find the number of days between then and now - Count back that many days from then - Count forward that many days from now Before we start getting _too_ clever on implmentation details, let me quote at length from [Lord Dave Rolsky of House Absolute](https://presentations.houseabsolute.com/a-date-with-perl/#3): > Do Not Write Your Own Date and Time Manipulation Code! > _Do Not Write Your Own Date and Time Manipulation Code!_ > **Do Not Write Your Own Date and Time Manipulation Code!** > _**Do Not Write Your Own Date and Time Manipulation Code!**_ In our case, we have been gifted [DateTime](https://metacpan.org/pod/DateTime), which allows us to rethink the previous step list as: - `my $delta = $now->delta_days($then)->in_units("days")` - `$then->subtract( days => $diff )` - `$now->add( days => $diff )` I take a few more steps — What's now? When was then? Do we want to modify now and then? How do we easily format dates correctly? — but that's the important parts. I reiterate a few of the points and go into further detail on DateTime below, but that's the core part of it. #### Show Me The Code ```perl #!/usr/bin/env perl use strict; use warnings; use feature qw{ say postderef signatures }; no warnings qw{ experimental }; # Do Not Write Your Own Date and Time Manipulation Code! # Do Not Write Your Own Date and Time Manipulation Code! # Do Not Write Your Own Date and Time Manipulation Code! # Do Not Write Your Own Date and Time Manipulation Code! # Do Not Write Your Own Date and Time Manipulation Code! use DateTime; my @examples; push @examples, '2021/09/18'; push @examples, '1975/10/10'; push @examples, '1967/07/08'; push @examples, '1970/01/01'; for my $input (@examples) { my $output= mirror_dates($input); say <<"END"; Input: $input Output: $output END } # takes the date as a string, in the ONE TRUE FORMAT: YYYY/MM/DD # That makes the epoch 1970/01/01 # The program CAN handle non-padded days and months, but when you're # dealling with a LOT of dates, non-zero,padding makes you wonder if # 1970123 is Jan 23 or Dec 3. sub mirror_dates ( $date_str ) { # The default time zone for new DateTime objects, except where stated # otherwise, is the "floating" time zone. This concept comes from the # iCal standard. A floating datetime is one which is not anchored to # any particular time zone. In addition, floating datetimes do not # include leap seconds, since we cannot apply them without knowing the # datetime's time zone. my $now = DateTime->now()->set_time_zone('floating'); my ( $y, $m, $d ) = split m{/}, $date_str; my $then = DateTime->new( year => $y, month => $m, day => $d, time_zone => 'floating' ); # the time difference between now and then, expressed in days my $diff = $now->delta_days($then)->in_units('days'); # add and subtract in a DateTime context act on the object, which # isn't the result I would expect from $semi_numerical_thing->add(number) # so we clone it and modify the clone. # I mean, we COULD, but for testing, I was printing now and then as well # as past and future, just to be sure I was right. my $past = $then->clone; $past->subtract( days => $diff ); my $future = $now->clone; $future->add( days => $diff ); return join ', ', $future->ymd, $past->ymd; } ``` ```text Input: 2021/09/18 Output: 2021-10-06, 2021-09-09 Input: 1975/10/10 Output: 2067-09-15, 1929-10-22 Input: 1967/07/08 Output: 2075-12-18, 1913-04-17 Input: 1970/01/01 Output: 2073-06-23, 1918-04-07 ``` ### TASK #2 › Hash Join > Submitted by: Mohammad S Anwar > Write a script to implement Hash Join algorithm as suggested by wikipedia. ``` 1. For each tuple r in the build input R` 1.1 Add r to the in-memory hash table` 1.2 If the size of the hash table equals the maximum in-memory size:` 1.2.1 Scan the probe input S, and add matching join tuples to the output relation` 1.2.2 Reset the hash table, and continue scanning the build input R` 2. Do a final scan of the probe input S and add the resulting join tuples to the output relation` ``` I'm very Hrmm about it. Let's look at the example data given. ```perl @player_ages = ( [20, "Alex" ], [28, "Joe" ], [38, "Mike" ], [18, "Alex" ], [25, "David" ], [18, "Simon" ], ); @player_names = ( ["Alex", "Stewart"], ["Joe", "Root" ], ["Mike", "Gatting"], ["Joe", "Blog" ], ["Alex", "Jones" ], ["Simon","Duane" ], ); ``` First names are _horrible_ keys. Trust me, a person who has been the fifth "Dave" in the room. One of my friends in college took on "Dave 2" just to allow us to be easily disambiguated. Ages are _worse_; in any classroom, from kindergarden to college, most everyone will be within 365 days of your age, unless you or they are an extreme outlier. So, here, we're seeing a couple of Alexes and a few Joes. We have a David, but he's got no last name, so he's bounced (!), all the Joes are the same age, and there are two Alexes, distinguished by age and last name, _but_ we have no indication of which name goes to which age, so we create two fake Alexes. Read [Falsehoods Programmers Believe About Names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) for more information. I mean, I came out with output that matches the example, but _dang_ this is dirty data! #### Show Me The Code ```perl #!/usr/bin/env perl use strict; use warnings; use feature qw{ say postderef signatures }; no warnings qw{ experimental }; my @player_ages = ( [ 20, "Alex" ], [ 28, "Joe" ], [ 38, "Mike" ], [ 18, "Alex" ], [ 25, "David" ], [ 18, "Simon" ], ); my @player_names = ( [ "Alex", "Stewart" ], [ "Joe", "Root" ], [ "Mike", "Gatting" ], [ "Joe", "Blog" ], [ "Alex", "Jones" ], [ "Simon", "Duane" ], ); say join "\n", hash_join( \@player_ages, \@player_names ); sub hash_join ( $array1, $array2 ) { my @output; my $hash = {}; for my $e ( $array1->@* ) { my ( $age, $firstname ) = $e->@*; push $hash->{$firstname}->{age}->@*, $age; } for my $e ( $array2->@* ) { my ( $firstname, $lastname ) = $e->@*; push $hash->{$firstname}->{lastname}->@*, $lastname; } for my $firstname ( sort keys $hash->%* ) { next unless defined $hash->{$firstname}{age}; next unless defined $hash->{$firstname}{lastname}; my @ages = $hash->{$firstname}{age}->@*; my @lastnames = $hash->{$firstname}{lastname}->@*; for my $age ( reverse sort @ages ) { for my $lastname ( reverse sort @lastnames ) { push @output, join ",\t", ' ' . $age, $firstname, $lastname; } } } return join "\n", @output; } ``` ```text 20, Alex, Stewart 20, Alex, Jones 18, Alex, Stewart 18, Alex, Jones 28, Joe, Root 28, Joe, Blog 38, Mike, Gatting 18, Simon, Duane ``` #### If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo.](https://github.com/jacoby/jacoby.github.io)
Java
UTF-8
4,200
2.109375
2
[]
no_license
package cn.merryyou.web.controller; import cn.merryyou.dto.User; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.Date; import static cn.merryyou.utils.ObjectMapperUtils.asJsonString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created on 2017/12/19 0019. * * @author zlf * @email i@merryyou.cn * @since 1.0 */ @RunWith(SpringRunner.class) @SpringBootTest @Slf4j public class UserControllerTest { @Autowired private WebApplicationContext context; private MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void search() throws Exception { String result = mockMvc.perform(get("/user") .param("username", "admin") .param("age", "18") .param("size", "15") .param("page", "4") .param("sort", "age,desc") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(jsonPath("$.length()").value(3)) .andReturn().getResponse().getContentAsString(); log.info(result); } @Test public void getInfo() throws Exception { String result = mockMvc.perform(get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(jsonPath("$.username").value("admin")) .andReturn().getResponse().getContentAsString(); log.info(result); } @Test public void getInfoFail() throws Exception { mockMvc.perform(get("/user/a") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().is4xxClientError()); } @Test public void create() throws Exception { User user = new User(); user.setUsername("admin"); user.setPassword("admin"); user.setBirthday(new Date()); String result = mockMvc.perform(post("/user") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(asJsonString(user))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").isNotEmpty()) .andReturn().getResponse().getContentAsString(); log.info(result); } @Test public void update() throws Exception { User user = new User(); user.setId(1); user.setUsername("admin"); user.setPassword("admin"); user.setBirthday(new Date()); String result = mockMvc.perform(put("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8) .content(asJsonString(user))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").isNotEmpty()) .andReturn().getResponse().getContentAsString(); log.info(result); } @Test public void deleteUser() throws Exception { mockMvc.perform(delete("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); } @Test public void fileUploadTest() throws Exception { mockMvc.perform(fileUpload("/file") .file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello world!".getBytes("UTF-8")))) .andExpect(status().isOk()); } }
JavaScript
UTF-8
3,823
3
3
[]
no_license
const fs = require('fs'); const http = require('http'); const $ = require('cheerio'); const createCsvWriter = require('csv-writer').createObjectCsvWriter; /* Getting the current date. Code is taken from https://stackoverflow.com/questions/1531093/how-do-i-get-the-current-date-in-javascript */ let dateObject = new Date(); let day = dateObject.getDate(); let month = dateObject.getMonth() + 1; let year = dateObject.getFullYear(); let hour = dateObject.getHours(); let minute = dateObject.getMinutes(); let second = dateObject.getSeconds(); if (day < 10) { day = `0${day}`; } if (month < 10) { month = `0${month}`; } if (hour < 10) { hour = `0${hour}`; } if (minute < 10) { minute = `0${minute}`; } if (second < 10) { second = `0${second}`; } let date = `${year}-${month}-${day}`; let time = `${hour}:${minute}:${second}`; /* Creating headers for a CSV file with the help of CSV-writer package */ const csvWriter = createCsvWriter({ path: `./data/${date}.csv`, header: [ {id: 'title', title: 'TITLE'}, {id: 'price', title: 'PRICE'}, {id: 'imgURL', title: 'IMGURL'}, {id: 'tshirtURL', title: 'TSHIRTURL'}, {id: 'time', title: 'TIME'} ] }); /* Making a request to the URL we're interested in */ const mainURL = 'http://shirts4mike.com'; const entryURL = '/shirts.php'; const dataToStore = []; /* This function gathers information from every individual page of each T-shirt and stores this data in an array */ const gatherInformation = (generalURL, urlOfTshirt, numberOfLinks) => { http.get(`${generalURL}/${urlOfTshirt}`, response => { let bodyTshirt = ""; response.on('data', data => { bodyTshirt += data.toString(); }); response.on('end', () => { const title = $('.shirt-details h1', bodyTshirt).contents()[0].next.data; // title const price = $('.price', bodyTshirt).text(); // price const imgURL = $('.shirt-picture span img', bodyTshirt).attr('src'); //img URL const tshirtURL =`${generalURL}/${urlOfTshirt}`; //URL time = `${time}`; let tshirtInfo = { title: title, price: price, imgURL: imgURL, tshirtURL: tshirtURL, time: time }; dataToStore.push(tshirtInfo); /* When data from each link is stored in array, a CSV file is created */ if (dataToStore.length === numberOfLinks) { csvWriter.writeRecords(dataToStore) .then(() => { console.log('...Done'); }); } }); // on.end }) //http.get } // gatherInformation /*******************************************/ /* This function connects to entry URL and collects all links to individual pages of every T-shirt */ const connectToEntryURL = (url, additionalUrl) => { const request = http.get(`${url}${additionalUrl}`, response => { /* Reading data from the response */ let body = ""; response.on('data', data => { body += data.toString(); }); response.on('end', ()=> { /* Checking whether a "data" folder exists. If not, create it.*/ if (!fs.existsSync('./data')) { fs.mkdirSync('./data'); } // Gathering links from every t-shirt url const tshirtsLinks = $('.products li > a', body); for (let i = 0; i < tshirtsLinks.length; i += 1) { gatherInformation(url, tshirtsLinks[i].attribs.href, tshirtsLinks.length); } }); //end }); // end of request request.on('error', error => { if (error.code == "ENOTFOUND") { console.error(`There has been a 404 error. Cannot connect to ${mainURL}`); } }); } //connectToEnryURL connectToEntryURL(mainURL, entryURL);
C++
UTF-8
766
3.234375
3
[]
no_license
#include<iostream> using namespace std; #include<string.h> int checkidentical(char *s1,char *s2) { int i,a=1; for(i=0;s1[i]!='\0';i++) { if(s1[i]>=65 && s1[i]<=92) { s1[i]=s1[i]+32; } } for(i=0;s2[i]!='\0';i++) { if(s2[i]>=65 && s2[i]<=92) { s2[i]=s2[i]+32; } } for(i=0;s1[i]!='\0';i++) { if(s1[i]!=s2[i]) { a=0; break; } } return a; } int main() { string s1,s2; cout<<"enter two strings : "; getline(cin,s1); getline(cin,s2); char str1[s1.size()+1]; strcpy(str1,s1.c_str()); char str2[s2.size()+1]; strcpy(str2,s2.c_str()); cout<<checkidentical(str1,str2); }
Python
UTF-8
843
3.1875
3
[]
no_license
def trap(height): ans = 0 l = len(height) for i in range(l): max_left,max_right = 0,0 for j in range(i, -1, -1): max_left = max(max_left, height[j]) for k in range(i, l): max_right = max(max_right, height[k]) ans += min(max_left, max_right) - height[i] return ans def dpTrap(height): ans = 0 l = len(height) max_left = [0]*l max_right = [0]*l max_left[0] = height[0] for i in range(1, l): max_left[i] = max(height[i], max_left[i-1]) max_right[l-1] = height[l-1] for j in range(l-2, -1, -1): max_right[j] = max(height[j], max_right[j+1]) for i in range(l): ans += min(max_left[i], max_right[i]) - height[i] return ans l = [0,1,0,2,1,0,1,3,2,1,2,1] #print(trap(l)) print(dpTrap(l))
C++
UTF-8
1,126
2.828125
3
[ "MIT" ]
permissive
/// @file test_invert.cc /// @brief test invert /// @author Jeff Perry <jeffsp@gmail.com> /// @version 1.0 /// @date 2013-06-12 #include "horny_toad/horny_toad.h" #include <iostream> using namespace std; using namespace jack_rabbit; using namespace horny_toad; void test1 (bool verbose) { raster<float> x (3, 3); x (0, 0) = 1; x (0, 1) = 3; x (0, 2) = 3; x (1, 0) = 1; x (1, 1) = 4; x (1, 2) = 3; x (2, 0) = 1; x (2, 1) = 3; x (2, 2) = 4; raster<float> y (3, 3); y (0, 0) = 7; y (0, 1) = -3; y (0, 2) = -3; y (1, 0) = -1; y (1, 1) = 1; y (1, 2) = 0; y (2, 0) = -1; y (2, 1) = 0; y (2, 2) = 1; if (verbose) { print2d (clog, x); print2d (clog, y); print2d (clog, invert (x)); } raster<float> z = invert (x); for (size_t i = 0; i < x.size (); ++i) VERIFY (about_equal (z[i], y[i])); } int main (int argc, char **) { try { const bool verbose = (argc != 1); test1 (verbose); return 0; } catch (const exception &e) { cerr << e.what () << endl; return -1; } }
JavaScript
UTF-8
5,273
2.625
3
[]
no_license
(() => { var addButton = document.getElementById('addBeerButton'); var beerList = document.getElementById('beerList'); //TODO: find out where to put these transformable env variables var apiURI = 'https://shielded-coast-63607.herokuapp.com'; // var apiURI = 'http://localhost:5000'; const getBeerList = () => { const ajax = liteAjax('POST', `${apiURI}/graphql/beers`); ajax({ postObj: JSON.stringify({ query: `{ beers { _id name rating } }` }), successCallback: (data) => { renderBeers(data); } }); }; const renderBeers = (responseString) => { const beers = JSON.parse(responseString).data.beers; const frag = document.createDocumentFragment(); beers.forEach((beer) => { const html = buildBeerCard(beer); const divEl = document.createElement('div'); divEl.innerHTML = html; divEl.id = beer._id; frag.append(divEl); }) document.getElementById('beerList').append(frag); }; const ratingChangeHandler = (evt) => { if (evt.target.className === 'tracked-beer-rating') { const newRating = evt.target.value; evt.target.previousSibling.childNodes[1].textContent = newRating; evt.target.style = 'display: none;'; } }; const beerListEventHandler = (evt) => { if (evt.target.className.indexOf('fa-close') > -1) { const idNode = evt.target.parentNode.parentNode; const ajax = liteAjax('DELETE', `${apiURI}/beerTracker/api/deleteBeer/${idNode.id}`); ajax({ successCallback: (status) => { idNode.remove(); } }); } else if (evt.target.className.indexOf('update-beer') > -1) { const ajax = liteAjax('PUT', `${apiURI}/beerTracker/api/updateBeer/${evt.target.parentNode.id}`); const beerName = evt.target.parentNode.getElementsByTagName('input')[0].value; const beerRating = evt.target.previousSibling.childNodes[1].textContent; const postObj = JSON.stringify({ name: beerName, rating: beerRating }); ajax({ postObj: postObj, successCallback: (status) => { console.log(status); }}); } }; const addBeerHandler = () => { const beerName = document.getElementById('beerName').value; const beerRating = document.getElementById('beerRating').value; if (beerName) { const ajax = liteAjax('POST', `${apiURI}/beerTracker/api/addBeer`); const postObj = JSON.stringify({ name: beerName, rating: beerRating }); ajax({ postObj: postObj, successCallback: (data) => { let beer = JSON.parse(data); const template = buildBeerCard(beer); let divEl = document.createElement('div'); divEl.innerHTML = template; divEl.id = beer._id; document.getElementById('beerList').append(divEl); } }); } else { alert('Please enter a beer name!'); } }; const ratingSelectElementToggler = (evt) => { if (evt.target.parentNode.className && evt.target.parentNode.className.indexOf('tracked-beer-rating-btn') > -1) { evt.target.parentNode.nextSibling.style = ''; } else { const selects = document.getElementsByTagName('select'); Array.prototype.forEach.call(selects, (element) => { if (element.style === 'display: none;' || element.id === 'beerRating') return; element.style = 'display: none;'; }); } }; //helpers const buildBeerCard = (beer) => { const html = `<a class="remove-beer"><i class="fa fa-close"></i></a> <input type="text" value="${beer.name}" class="tracked-beer-name" /> <br> <div style="position: relative; display: inline-block;"> <button class="fa-stack tracked-beer-rating-btn" type="button"><i class="fa fa-star fa-stack-2x"></i><strong class="fa-stack-1x rating-text">${beer.rating}</strong></button><select size="5" name="rating" class="tracked-beer-rating" style="display: none;"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div><a class="update-beer">Update</a>`; return html; }; const liteAjax = (type, url) => { let xhr = new XMLHttpRequest(); xhr.open(type, url); xhr.setRequestHeader('Content-Type', 'application/json'); return (params) => { xhr.send(params.postObj); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { params.successCallback(xhr.responseText); } } } return xhr; } }; //listeners document.addEventListener('click', ratingSelectElementToggler); document.addEventListener('change', ratingChangeHandler); document.addEventListener('DOMContentLoaded', getBeerList); beerList.addEventListener('click', beerListEventHandler); addButton.addEventListener('click', addBeerHandler); })();
Java
UTF-8
3,049
2.296875
2
[]
no_license
package tramitedoc.concytec.action; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import tramitedoc.concytec.util.Constantes; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; public class AActionSubirPDFFirmado extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub //String dato=request.getParameter("rutaDestinoFirmado"); String pdf64=request.getParameter("param"); String nombre=request.getParameter("nombre"); String namePdf="C:"+Constantes.CarpetaArchivosDesarrolloenTramiteFirmados.getNombre()+nombre; System.out.println("===================="); System.out.println("Entre a Subir PDF"); System.out.println("Ruta "+namePdf); byte[] pdfByte=Base64.decode(pdf64); if(pdfByte!=null){ escribirFile(pdfByte, namePdf); } //FileInputStream is=new FileInputStream(file); //copiando pdf en directorio temporal request.setAttribute("servicioExito", "SI"); //return mapping.findForward("exito"); return null; } private static void escribirFile(byte[] pdf,String namePdf) throws IOException{ File file = new File(namePdf); file.createNewFile(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pdf); OutputStream outputStream = new FileOutputStream(namePdf); int data; while ((data = byteArrayInputStream.read()) != -1) { outputStream.write(data); } outputStream.close(); byteArrayInputStream.close(); } /*private void eliminarFichero(String pstrCodDoc){ String pathSep = File.separator; String path =getServletContext().getRealPath("/")+"TempPDF"+pathSep+pstrCodDoc+".pdf"; File f = new File(path); if ( f.exists() ){ System.out.println("method:eliminarFichero | INFO | class:com.servlet.DownloadFichero | Eliminar archivo de la carpeta TempPDF"); try { if (f.delete()) System.out.println("method:eliminarFichero | INFO | class:com.servlet.DownloadFichero | Archivo elminado"); else System.out.println("method:eliminarFichero | INFO | class:com.servlet.DownloadFichero | No se pudo eliminar archivo"); } catch (Exception e) { System.out.println("method:eliminarFichero | ERROR | class:com.servlet.DownloadFichero | error= "+ e.getMessage()); } }else{ System.out.println("method:eliminarFichero | INFO | class:com.servlet.DownloadFichero | No existe el archivo para ser eliminado"); } }*/ }
Python
UTF-8
4,550
2.75
3
[]
no_license
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains import time import gspread from oauth2client.service_account import ServiceAccountCredentials from selenium.webdriver.chrome.options import Options # block to send messages def message_send(): search_input3 = driver.find_element_by_xpath('/html/body/mw-app/div/main/mw-main-container/div/mw-conversation-container/div/div/mws-message-compose/div/div[2]/div/mws-autosize-textarea/textarea') search_input3.send_keys(message) search_input3.send_keys(Keys.ENTER) # this block will check whether the chrome will run background or not def display_check(display): if display[0] == 'y': print(" Launching chrome") return True elif display[0] == "n": print("All operations Will be done in background") return True else: return False while True: try: display = input('Do You want to see the display of sending messages type Yes or No ').lower() if display_check(display): break except ValueError: print("Sorry, Wrong Input Try Again") # to check whether to send single message to all the contacts from google sheet or send custom message def sms_check_value(sms_check): if sms_check == 1: print('Message from the Message Box will be Sent') return True elif sms_check == 2: print('Custom message from Message Column will be sent') return True else: return False while True: try: sms_check = int(input('Send messages from (Message box Press 1) or (Press 2 for Sending Custom message) from C column ')) if sms_check_value(sms_check): break except ValueError: print("Sorry, Wrong Input Try Again") #To Run the Program headless without opening any physical window if display[0] == 'n': chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920x1080") chrome_options.binary_location = 'C:\link\Link_gen_lav\Canary\Chrome SxS\Application\chrome.exe' driver = webdriver.Chrome(options=chrome_options, executable_path='C:\Codes_projects_python\SMS Sender\chromedrivercanary.exe') elif display[0] =='y': driver = webdriver.Chrome('C:\Codes_projects_python\SMS Sender\chromedriver') #-----------------------------#---------------------------------- #authentication to Login and access google sheet and open and read the Sheet scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) client = gspread.authorize(creds) # open the google sheet thru which we can send the messages which contains mobile numbers and message sheet = client.open('SMS - Google').sheet1 #Open The chrome and login using the credentials and opening the website driver.get("https://messages.google.com/web/authentication") driver.implicitly_wait(100) # click toggle so that it rememebers the scanned qr code so that if refresh is done will not require to again scan. driver.find_element_by_class_name('mat-slide-toggle-thumb').click() time.sleep(25) #---------------------------------y-------#-------------------------------- #To check the count of the Names to control the Loop # [ have inputed the counta function of excel in sheet on this cell i think it can also be done thru length function in python ( didnot work forme.) z = int(sheet.cell(1,5).value) #Initialize a = 2 #while loop to check and tell the program to stop while a <= z: # if loop to check the id are already generated? if sheet.cell(a, 4).value != 'Sent': driver.get('https://messages.google.com/web/conversations/new') time.sleep(10) # Mobile Number Area clearing and entering data Mobile = sheet.cell(a,2).value search_input2 = driver.find_element_by_class_name('input') search_input2.send_keys(Mobile) search_input2.send_keys(Keys.ENTER) time.sleep(10) # to check and send SMS # Message Area clearing and entering data if sms_check == 1: message = sheet.cell(2, 10).value message_send() elif sms_check == 2: message = sheet.cell(a, 3).value message_send() #update in sheet as message Status sent sheet.update_cell(a, 4, 'Sent') a+=1 else: a += 1 driver.quit()
JavaScript
UTF-8
2,082
2.59375
3
[]
no_license
const graphql = require('graphql'); const gameType = require('../../types/gameType'); const { Game, gameSchema } = require('../../../models/game'); const enums = require('../../../utils/enums'); const mutation = { type: new graphql.GraphQLList(gameType.type), args: { input: { type: new graphql.GraphQLList(gameType.inputTypeMutation) } }, resolve: (value, { input }) => { return new Promise((resolve, reject) => { let promisesGames = input.map(async inputGame => { switch (inputGame.mutationType) { case enums.mutationType.ADD: return addGame(inputGame) .then(result => { return result; }) .catch(err => { return err; });; case enums.mutationType.UPDATE: updateGame(inputGame); break; case enums.mutationType.DELETE: deleteGame(inputGame); break; default: return new Error('Opa! Não encontramos a operação para um usuario.'); } }); Promise.all(promisesGames).then((results) => { let resultado = []; let erros = []; results.map(async resultGame => { if (!!resultGame.errors) erros.push(resultGame.errors); resultado.push(resultGame); }); if (erros.length > 0) reject(erros); else resolve(resultado); }) .catch((err) => { return err }); }); } }; const addGame = async (gameAdd) => { console.log(gameAdd.players); const game = new Game(gameAdd); //console.log(game); try { const gameDB = await game.save(); return { ...gameDB._doc }; } catch (err) { throw err; } // return game // .save() // .then(result => { // return { ...result._doc }; // }) // .catch(err => { // return err; // }); }; const updateGame = (gameAdd) => { console.log('update essa porra ai', gameAdd); }; const deleteGame = (gameAdd) => { console.log('deleta essa porra ai', gameAdd); }; module.exports = mutation;
Python
UTF-8
679
2.578125
3
[]
no_license
from pymongo import MongoClient ############################################# class MongoConnection: def __init__(self): self.client = MongoClient( host="localhost", port=27017, connect=False ) ######################################### def connect_articles_db(self): return self.client['articles'] ######################################### def connect_users_db(self): return self.client['users'] ############################################# # m = MongoConnection() # db = m.connect_articles_db() # col = db['article'] # cats = col.distinct('category') # for cat in cats: # col.update_many({'category': cat}, {'$set':{'category': cat.lower()}})