hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ff2729fa783050c4a40122e18de1ad0109897045 | 54,627 | py | Python | tickettool/embassytool.py | DarthNoxix/noxixcog | 7e66e2ee6a059317c64ff3444b102fee85eb83be | [
"MIT"
] | null | null | null | tickettool/embassytool.py | DarthNoxix/noxixcog | 7e66e2ee6a059317c64ff3444b102fee85eb83be | [
"MIT"
] | null | null | null | tickettool/embassytool.py | DarthNoxix/noxixcog | 7e66e2ee6a059317c64ff3444b102fee85eb83be | [
"MIT"
] | null | null | null | import discord
import datetime
import typing
from redbot.core import Config, commands, modlog
from redbot.core.bot import Red
from copy import copy
import io
import chat_exporter
from dislash import ActionRow, Button, ButtonStyle
from .settings import settings
from .utils import utils
# Credits:
# Thanks to @epic guy on Discord for the basic syntax (command groups, commands) and also commands (await ctx.send, await ctx.author.send, await ctx.message.delete())!
# Thanks to @YamiKaitou on Discord for the technique in the init file to load the interaction client only if it is not loaded! Before this fix, when a user clicked on a button, the actions would be launched about 10 times, which caused huge spam and a loop in the channel.
# Thanks to the developers of the cogs I added features to as it taught me how to make a cog! (Chessgame by WildStriker, Captcha by Kreusada, Speak by Epic guy and Rommer by Dav)
# Thanks to all the people who helped me with some commands in the #coding channel of the redbot support server!
class EmbassyTool(settings, commands.Cog):
"""A cog to manage an embassy system!"""
def __init__(self, bot):
self.bot = bot
self.data: Config = Config.get_conf(
self,
identifier=937480369417,
force_registration=True,
)
self.embassy_guild = {
"settings": {
"enable": False,
"logschannel": None,
"category_open": None,
"category_close": None,
"admin_role": None,
"support_role": None,
"embassy_role": None,
"view_role": None,
"ping_role": None,
"nb_max": 5,
"create_modlog": False,
"close_on_leave": False,
"create_on_react": False,
"color": 0x01d758,
"thumbnail": "http://www.quidd.it/wp-content/uploads/2017/10/Embassy-add-icon.png",
"audit_logs": False,
"close_confirmation": False,
"emoji_open": "❓",
"emoji_close": "🔒",
"last_nb": 0000,
"embed_button": {
"title": "Open An Embassy",
"description": ( "To open an embassy with us please press the button below.\n"
"If you have a serious matter that you need handled now please dm Klaus or Valentinos.\n"
"We hope you enjoy your stay!"),
},
},
"embassys": {},
}
self.data.register_guild(**self.embassy_guild)
async def get_config(self, guild: discord.Guild):
config = await self.bot.get_cog("EmbassyTool").data.guild(guild).settings.all()
if config["logschannel"] is not None:
config["logschannel"] = guild.get_channel(config["logschannel"])
if config["category_open"] is not None:
config["category_open"] = guild.get_channel(config["category_open"])
if config["category_close"] is not None:
config["category_close"] = guild.get_channel(config["category_close"])
if config["admin_role"] is not None:
config["admin_role"] = guild.get_role(config["admin_role"])
if config["support_role"] is not None:
config["support_role"] = guild.get_role(config["support_role"])
if config["embassy_role"] is not None:
config["embassy_role"] = guild.get_role(config["embassy_role"])
if config["view_role"] is not None:
config["view_role"] = guild.get_role(config["view_role"])
if config["ping_role"] is not None:
config["ping_role"] = guild.get_role(config["ping_role"])
return config
async def get_embassy(self, channel: discord.TextChannel):
config = await self.bot.get_cog("EmbassyTool").data.guild(channel.guild).embassys.all()
if str(channel.id) in config:
json = config[str(channel.id)]
else:
return None
embassy = Embassy.from_json(json, self.bot)
embassy.bot = self.bot
embassy.guild = embassy.bot.get_guild(embassy.guild)
embassy.owner = embassy.guild.get_member(embassy.owner)
embassy.channel = embassy.guild.get_channel(embassy.channel)
embassy.claim = embassy.guild.get_member(embassy.claim)
embassy.created_by = embassy.guild.get_member(embassy.created_by)
embassy.opened_by = embassy.guild.get_member(embassy.opened_by)
embassy.closed_by = embassy.guild.get_member(embassy.closed_by)
embassy.deleted_by = embassy.guild.get_member(embassy.deleted_by)
embassy.renamed_by = embassy.guild.get_member(embassy.renamed_by)
members = embassy.members
embassy.members = []
for m in members:
embassy.members.append(channel.guild.get_member(m))
if embassy.created_at is not None:
embassy.created_at = datetime.datetime.fromtimestamp(embassy.created_at)
if embassy.opened_at is not None:
embassy.opened_at = datetime.datetime.fromtimestamp(embassy.opened_at)
if embassy.closed_at is not None:
embassy.closed_at = datetime.datetime.fromtimestamp(embassy.closed_at)
if embassy.deleted_at is not None:
embassy.deleted_at = datetime.datetime.fromtimestamp(embassy.deleted_at)
if embassy.renamed_at is not None:
embassy.renamed_at = datetime.datetime.fromtimestamp(embassy.renamed_at)
if embassy.first_message is not None:
embassy.first_message = embassy.channel.get_partial_message(embassy.first_message)
return embassy
async def get_audit_reason(self, guild: discord.Guild, author: typing.Optional[discord.Member]=None, reason: typing.Optional[str]=None):
if reason is None:
reason = "Action taken for the embassy system."
config = await self.bot.get_cog("EmbassyTool").get_config(guild)
if author is None or not config["audit_logs"]:
return f"{reason}"
else:
return f"{author.name} ({author.id}) - {reason}"
async def get_embed_important(self, embassy, more: bool, author: discord.Member, title: str, description: str):
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
actual_color = config["color"]
actual_thumbnail = config["thumbnail"]
embed: discord.Embed = discord.Embed()
embed.title = f"{title}"
embed.description = f"{description}"
embed.set_thumbnail(url=actual_thumbnail)
embed.color = actual_color
embed.timestamp = datetime.datetime.now()
embed.set_author(name=author, url=author.avatar_url, icon_url=author.avatar_url)
embed.set_footer(text=embassy.guild.name, icon_url=embassy.guild.icon_url)
embed.add_field(
inline=True,
name="Embassy ID:",
value=f"{embassy.id}")
embed.add_field(
inline=True,
name="Owned by:",
value=f"{embassy.owner.mention} ({embassy.owner.id})")
embed.add_field(
inline=True,
name="Channel:",
value=f"{embassy.channel.mention} - {embassy.channel.name} ({embassy.channel.id})")
if more:
if embassy.closed_by is not None:
embed.add_field(
inline=False,
name="Closed by:",
value=f"{embassy.owner.mention} ({embassy.owner.id})")
if embassy.deleted_by is not None:
embed.add_field(
inline=True,
name="Deleted by:",
value=f"{embassy.deleted_by.mention} ({embassy.deleted_by.id})")
if embassy.closed_at:
embed.add_field(
inline=False,
name="Closed at:",
value=f"{embassy.closed_at}")
embed.add_field(
inline=False,
name="Reason:",
value=f"{embassy.reason}")
return embed
async def get_embed_action(self, embassy, author: discord.Member, action: str):
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
actual_color = config["color"]
embed: discord.Embed = discord.Embed()
embed.title = f"Embassy {embassy.id} - Action taken"
embed.description = f"{action}"
embed.color = actual_color
embed.timestamp = datetime.datetime.now()
embed.set_author(name=author, url=author.avatar_url, icon_url=author.avatar_url)
embed.set_footer(text=embassy.guild.name, icon_url=embassy.guild.icon_url)
embed.add_field(
inline=False,
name="Reason:",
value=f"{embassy.reason}")
return embed
async def check_limit(self, member: discord.Member):
config = await self.bot.get_cog("EmbassyTool").get_config(member.guild)
data = await self.bot.get_cog("EmbassyTool").data.guild(member.guild).embassys.all()
to_remove = []
count = 1
for id in data:
channel = member.guild.get_channel(int(id))
if channel is not None:
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(channel)
if embassy.created_by == member and embassy.status == "open":
count += 1
if channel is None:
to_remove.append(id)
if not to_remove == []:
data = await self.bot.get_cog("EmbassyTool").data.guild(member.guild).embassys.all()
for id in to_remove:
del data[str(id)]
await self.bot.get_cog("EmbassyTool").data.guild(member.guild).embassys.set(data)
if count > config["nb_max"]:
return False
else:
return True
async def create_modlog(self, embassy, action: str, reason: str):
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
if config["create_modlog"]:
case = await modlog.create_case(
embassy.bot,
embassy.guild,
embassy.created_at,
action_type=action,
user=embassy.created_by,
moderator=embassy.created_by,
reason=reason,
)
return case
return
def decorator(enable_check: typing.Optional[bool]=False, embassy_check: typing.Optional[bool]=False, status: typing.Optional[str]=None, embassy_owner: typing.Optional[bool]=False, admin_role: typing.Optional[bool]=False, support_role: typing.Optional[bool]=False, embassy_role: typing.Optional[bool]=False, view_role: typing.Optional[bool]=False, guild_owner: typing.Optional[bool]=False, claim: typing.Optional[bool]=None, claim_staff: typing.Optional[bool]=False, members: typing.Optional[bool]=False):
async def pred(ctx):
config = await ctx.bot.get_cog("EmbassyTool").get_config(ctx.guild)
if enable_check:
if not config["enable"]:
return
if embassy_check:
embassy = await ctx.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
if embassy is None:
return
if status is not None:
if not embassy.status == status:
return False
if claim is not None:
if embassy.claim is not None:
check = True
elif embassy.claim is None:
check = False
if not check == claim:
return False
if ctx.author.id in ctx.bot.owner_ids:
return True
if embassy_owner:
if ctx.author == embassy.owner:
return True
if admin_role and config["admin_role"] is not None:
if ctx.author in config["admin_role"].members:
return True
if support_role and config["support_role"] is not None:
if ctx.author in config["support_role"].members:
return True
if embassy_role and config["embassy_role"] is not None:
if ctx.author in config["embassy_role"].members:
return True
if view_role and config["view_role"] is not None:
if ctx.author in config["view_role"].members:
return True
if guild_owner:
if ctx.author == ctx.guild.owner:
return True
if claim_staff:
if ctx.author == embassy.claim:
return True
if members:
if ctx.author in embassy.members:
return True
return False
return True
return commands.check(pred)
@commands.guild_only()
@commands.group(name="embassy")
async def embassy(self, ctx):
"""Commands for using the embassy system."""
@embassy.command(name="create")
async def command_create(self, ctx, *, reason: typing.Optional[str]="No reason provided."):
"""Create a embassy.
"""
config = await self.bot.get_cog("EmbassyTool").get_config(ctx.guild)
limit = config["nb_max"]
category_open = config["category_open"]
category_close = config["category_close"]
if not config["enable"]:
await ctx.send(f"The embassy system is not activated on this server. Please ask an administrator of this server to use the `{ctx.prefix}embassyset` subcommands to configure it.")
return
if not await self.bot.get_cog("EmbassyTool").check_limit(ctx.author):
await ctx.send(f"Sorry. You have already reached the limit of {limit} open embassys.")
return
if not category_open.permissions_for(ctx.guild.me).manage_channels or not category_close.permissions_for(ctx.guild.me).manage_channels:
await ctx.send("The bot does not have `manage_channels` permission on the 'open' and 'close' categories to allow the embassy system to function properly. Please notify an administrator of this server.")
return
embassy = Embassy.instance(ctx, reason)
await embassy.create()
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status=None, embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="export")
async def command_export(self, ctx):
"""Export all the messages of an existing embassy in html format.
Please note: all attachments and user avatars are saved with the Discord link in this file.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
transcript = await chat_exporter.export(embassy.channel, embassy.guild)
if not transcript is None:
file = discord.File(io.BytesIO(transcript.encode()),
filename=f"transcript-embassy-{embassy.id}.html")
await ctx.send("Here is the html file of the transcript of all the messages in this embassy.\nPlease note: all attachments and user avatars are saved with the Discord link in this file.", file=file)
await ctx.tick(message="Done.")
@decorator(enable_check=True, embassy_check=True, status="close", embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="open")
async def command_open(self, ctx, *, reason: typing.Optional[str]="No reason provided."):
"""Open an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
await embassy.open(ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status="open", embassy_owner=True, admin_role=True, support_role=True, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="close")
async def command_close(self, ctx, confirmation: typing.Optional[bool]=None, *, reason: typing.Optional[str]="No reason provided."):
"""Close an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
if confirmation is None:
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
confirmation = not config["close_confirmation"]
if not confirmation:
embed: discord.Embed = discord.Embed()
embed.title = f"Do you really want to close the embassy {embassy.id}?"
embed.color = config["color"]
embed.set_author(name=ctx.author.name, url=ctx.author.avatar_url, icon_url=ctx.author.avatar_url)
response = await utils(embassy.bot).ConfirmationAsk(ctx, embed=embed)
if not response:
return
embassy.reason = reason
await embassy.close(ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status=None, embassy_owner=True, admin_role=True, support_role=True, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="rename")
async def command_rename(self, ctx, new_name: str, *, reason: typing.Optional[str]="No reason provided."):
"""Rename an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
await embassy.rename(new_name, ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status=None, embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="delete")
async def command_delete(self, ctx, confirmation: typing.Optional[bool]=False, *, reason: typing.Optional[str]="No reason provided."):
"""Delete an existing embassy.
If a log channel is defined, an html file containing all the messages of this embassy will be generated.
(Attachments are not supported, as they are saved with their Discord link)
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
config = await self.bot.get_cog("EmbassyTool").get_config(embassy.guild)
if not confirmation:
embed: discord.Embed = discord.Embed()
embed.title = f"Do you really want to delete all the messages of the embassy {embassy.id}?"
embed.description = "If a log channel is defined, an html file containing all the messages of this embassy will be generated. (Attachments are not supported, as they are saved with their Discord link)"
embed.color = config["color"]
embed.set_author(name=ctx.author.name, url=ctx.author.avatar_url, icon_url=ctx.author.avatar_url)
response = await utils(embassy.bot).ConfirmationAsk(ctx, embed=embed)
if not response:
return
embassy.reason = reason
await embassy.delete(ctx.author)
@decorator(enable_check=False, embassy_check=True, status="open", embassy_owner=False, admin_role=True, support_role=True, embassy_role=False, view_role=False, guild_owner=True, claim=False, claim_staff=False, members=False)
@embassy.command(name="claim")
async def command_claim(self, ctx, member: typing.Optional[discord.Member]=None, *, reason: typing.Optional[str]="No reason provided."):
"""Claim an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
if member is None:
member = ctx.author
await embassy.claim_embassy(member, ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status=None, embassy_owner=False, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=True, claim_staff=True, members=False)
@embassy.command(name="unclaim")
async def command_unclaim(self, ctx, *, reason: typing.Optional[str]="No reason provided."):
"""Unclaim an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
await embassy.unclaim_embassy(embassy.claim, ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status="open", embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=False, members=False)
@embassy.command(name="owner")
async def command_owner(self, ctx, new_owner: discord.Member, *, reason: typing.Optional[str]="No reason provided."):
"""Change the owner of an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
if new_owner is None:
new_owner = ctx.author
await embassy.change_owner(new_owner, ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status="open", embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="add")
async def command_add(self, ctx, member: discord.Member, *, reason: typing.Optional[str]="No reason provided."):
"""Add a member to an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
await embassy.add_member(member, ctx.author)
await ctx.tick(message="Done.")
@decorator(enable_check=False, embassy_check=True, status=None, embassy_owner=True, admin_role=True, support_role=False, embassy_role=False, view_role=False, guild_owner=True, claim=None, claim_staff=True, members=False)
@embassy.command(name="remove")
async def command_remove(self, ctx, member: discord.Member, *, reason: typing.Optional[str]="No reason provided."):
"""Remove a member to an existing embassy.
"""
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(ctx.channel)
embassy.reason = reason
await embassy.remove_member(member, ctx.author)
await ctx.tick(message="Done.")
@commands.Cog.listener()
async def on_button_click(self, inter):
if inter.clicked_button.custom_id == "close_embassy_button":
permissions = inter.channel.permissions_for(inter.author)
if not permissions.read_messages and not permissions.send_messages:
return
permissions = inter.channel.permissions_for(inter.guild.me)
if not permissions.read_messages and not permissions.read_message_history:
return
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(inter.channel)
if embassy is not None:
if embassy.status == "open":
async for message in inter.channel.history(limit=1):
p = await self.bot.get_valid_prefixes()
p = p[0]
msg = copy(message)
msg.author = inter.author
msg.content = f"{p}embassy close"
inter.bot.dispatch("message", msg)
await inter.send(f"You have chosen to close this embassy. If this embassy is not closed, you do not have the necessary permissions.", ephemeral=True)
if inter.clicked_button.custom_id == "claim_embassy_button":
permissions = inter.channel.permissions_for(inter.author)
if not permissions.read_messages and not permissions.send_messages:
return
permissions = inter.channel.permissions_for(inter.guild.me)
if not permissions.read_messages and not permissions.read_message_history:
return
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(inter.channel)
if embassy is not None:
if embassy.claim is None:
async for message in inter.channel.history(limit=1):
p = await self.bot.get_valid_prefixes()
p = p[0]
msg = copy(message)
msg.author = inter.author
msg.content = f"{p}embassy claim"
inter.bot.dispatch("message", msg)
await inter.send(f"You have chosen to claim this embassy. If this embassy is not claimed, you do not have the necessary permissions.", ephemeral=True)
if inter.clicked_button.custom_id == "create_embassy_button":
permissions = inter.channel.permissions_for(inter.author)
if not permissions.read_messages and not permissions.send_messages:
return
permissions = inter.channel.permissions_for(inter.guild.me)
if not permissions.read_messages and not permissions.read_message_history:
return
async for message in inter.channel.history(limit=1):
p = await self.bot.get_valid_prefixes()
p = p[0]
msg = copy(message)
msg.author = inter.author
msg.content = f"{p}embassy create"
inter.bot.dispatch("message", msg)
await inter.send(f"Your embassy has been created!.", ephemeral=True)
return
@commands.Cog.listener()
async def on_guild_channel_delete(self, old_channel: discord.abc.GuildChannel):
data = await self.bot.get_cog("EmbassyTool").data.guild(old_channel.guild).embassys.all()
if not str(old_channel.id) in data:
return
del data[str(old_channel.id)]
await self.bot.get_cog("EmbassyTool").data.guild(old_channel.guild).embassys.set(data)
return
@commands.Cog.listener()
async def on_member_remove(self, member: discord.Member):
config = await self.bot.get_cog("EmbassyTool").get_config(member.guild)
data = await self.bot.get_cog("EmbassyTool").data.guild(member.guild).embassys.all()
if config["close_on_leave"]:
for channel in data:
channel = member.guild.get_channel(int(channel))
embassy = await self.bot.get_cog("EmbassyTool").get_embassy(channel)
if embassy.owner == member and embassy.status == "open":
await embassy.close(embassy.guild.me)
return
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
if not payload.guild_id:
return
guild = payload.member.guild
channel = guild.get_channel(payload.channel_id)
member = guild.get_member(payload.user_id)
if member == guild.me or member.bot:
return
config = await self.bot.get_cog("EmbassyTool").get_config(guild)
if config["enable"]:
if config["create_on_react"]:
if str(payload.emoji) == str("🎟️"):
permissions = channel.permissions_for(member)
if not permissions.read_messages and not permissions.send_messages:
return
permissions = channel.permissions_for(guild.me)
if not permissions.read_messages and not permissions.read_message_history:
return
async for message in channel.history(limit=1):
p = await self.bot.get_valid_prefixes()
p = p[0]
msg = copy(message)
msg.author = member
msg.content = f"{p}embassy create"
self.bot.dispatch("message", msg)
return
class Embassy:
"""Representation of a embassy"""
def __init__(self,
bot,
id,
owner,
guild,
channel,
claim,
created_by,
opened_by,
closed_by,
deleted_by,
renamed_by,
members,
created_at,
opened_at,
closed_at,
deleted_at,
renamed_at,
status,
reason,
logs_messages,
save_data,
first_message):
self.bot: Red = bot
self.id: int = id
self.owner: discord.Member = owner
self.guild: discord.Guild = guild
self.channel: discord.TextChannel = channel
self.claim: discord.Member = claim
self.created_by: discord.Member = created_by
self.opened_by: discord.Member = opened_by
self.closed_by: discord.Member = closed_by
self.deleted_by: discord.Member = deleted_by
self.renamed_by: discord.Member = renamed_by
self.members: typing.List[discord.Member] = members
self.created_at: datetime.datetime = created_at
self.opened_at: datetime.datetime = opened_at
self.closed_at: datetime.datetime = closed_at
self.deleted_at: datetime.datetime = deleted_at
self.renamed_at: datetime.datetime = renamed_at
self.status: str = status
self.reason: str = reason
self.logs_messages: bool = logs_messages
self.save_data: bool = save_data
self.first_message: discord.Message = first_message
@staticmethod
def instance(ctx, reason: typing.Optional[str]="No reason provided."):
embassy = Embassy(
bot=ctx.bot,
id=None,
owner=ctx.author,
guild=ctx.guild,
channel=None,
claim=None,
created_by=ctx.author,
opened_by=ctx.author,
closed_by=None,
deleted_by=None,
renamed_by=None,
members=[],
created_at=datetime.datetime.now(),
opened_at=None,
closed_at=None,
deleted_at=None,
renamed_at=None,
status="open",
reason=reason,
logs_messages=True,
save_data=True,
first_message=None,
)
return embassy
@staticmethod
def from_json(json: dict, bot: Red):
embassy = Embassy(
bot=bot,
id=json["id"],
owner=json["owner"],
guild=json["guild"],
channel=json["channel"],
claim=json["claim"],
created_by=json["created_by"],
opened_by=json["opened_by"],
closed_by=json["closed_by"],
deleted_by=json["deleted_by"],
renamed_by=json["renamed_by"],
members=json["members"],
created_at=json["created_at"],
opened_at=json["opened_at"],
closed_at=json["closed_at"],
deleted_at=json["deleted_at"],
renamed_at=json["renamed_at"],
status=json["status"],
reason=json["reason"],
logs_messages=json["logs_messages"],
save_data=json["save_data"],
first_message=json["first_message"],
)
return embassy
async def save(embassy):
if not embassy.save_data:
return
bot = embassy.bot
guild = embassy.guild
channel = embassy.channel
embassy.bot = None
if embassy.owner is not None:
embassy.owner = int(embassy.owner.id)
if embassy.guild is not None:
embassy.guild = int(embassy.guild.id)
if embassy.channel is not None:
embassy.channel = int(embassy.channel.id)
if embassy.claim is not None:
embassy.claim = embassy.claim.id
if embassy.created_by is not None:
embassy.created_by = int(embassy.created_by.id)
if embassy.opened_by is not None:
embassy.opened_by = int(embassy.opened_by.id)
if embassy.closed_by is not None:
embassy.closed_by = int(embassy.closed_by.id)
if embassy.deleted_by is not None:
embassy.deleted_by = int(embassy.deleted_by.id)
if embassy.renamed_by is not None:
embassy.renamed_by = int(embassy.renamed_by.id)
members = embassy.members
embassy.members = []
for m in members:
embassy.members.append(int(m.id))
if embassy.created_at is not None:
embassy.created_at = float(datetime.datetime.timestamp(embassy.created_at))
if embassy.opened_at is not None:
embassy.opened_at = float(datetime.datetime.timestamp(embassy.opened_at))
if embassy.closed_at is not None:
embassy.closed_at = float(datetime.datetime.timestamp(embassy.closed_at))
if embassy.deleted_at is not None:
embassy.deleted_at = float(datetime.datetime.timestamp(embassy.deleted_at))
if embassy.renamed_at is not None:
embassy.renamed_at = float(datetime.datetime.timestamp(embassy.renamed_at))
if embassy.first_message is not None:
embassy.first_message = int(embassy.first_message.id)
json = embassy.__dict__
data = await bot.get_cog("EmbassyTool").data.guild(guild).embassys.all()
data[str(channel.id)] = json
await bot.get_cog("EmbassyTool").data.guild(guild).embassys.set(data)
return data
async def create(embassy, name: typing.Optional[str]="embassy"):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
logschannel = config["logschannel"]
overwrites = await utils(embassy.bot).get_overwrites(embassy)
emoji_open = config["emoji_open"]
ping_role = config["ping_role"]
embassy.id = config["last_nb"] + 1
name = f"{emoji_open}-{name}-{embassy.id}"
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=embassy.created_by, reason=f"Creating the embassy {embassy.id}.")
embassy.channel = await embassy.guild.create_text_channel(
name,
overwrites=overwrites,
category=config["category_open"],
topic=embassy.reason,
reason=reason,
)
if config["create_modlog"]:
await embassy.bot.get_cog("EmbassyTool").create_modlog(embassy, "embassy_created", reason)
if embassy.logs_messages:
buttons = ActionRow(
Button(
style=ButtonStyle.grey,
label="Close",
emoji="🔒",
custom_id="close_embassy_button",
disabled=False
),
Button(
style=ButtonStyle.grey,
label="Claim",
emoji="🙋♂️",
custom_id="claim_embassy_button",
disabled=False
)
)
if ping_role is not None:
optionnal_ping = f" ||{ping_role.mention}||"
else:
optionnal_ping = ""
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_important(embassy, False, author=embassy.created_by, title="Embassy Created", description="Thank you for creating a embassy on this server!")
embassy.first_message = await embassy.channel.send(f"{embassy.created_by.mention}{optionnal_ping}", embed=embed, components=[buttons])
if logschannel is not None:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_important(embassy, True, author=embassy.created_by, title="Embassy Created", description=f"The embassy was created by {embassy.created_by}.")
await logschannel.send(f"Report on the creation of the embassy {embassy.id}.", embed=embed)
await embassy.bot.get_cog("EmbassyTool").data.guild(embassy.guild).settings.last_nb.set(embassy.id)
if config["embassy_role"] is not None:
if embassy.owner:
try:
embassy.owner.add_roles(config["embassy_role"], reason=reason)
except discord.HTTPException:
pass
await embassy.save()
return embassy
async def export(embassy):
if embassy.channel:
transcript = await chat_exporter.export(embassy.channel, embassy.guild)
if not transcript is None:
transcript_file = discord.File(io.BytesIO(transcript.encode()),
filename=f"transcript-embassy-{embassy.id}.html")
return transcript_file
return None
async def open(embassy, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Opening the embassy {embassy.id}.")
logschannel = config["logschannel"]
emoji_open = config["emoji_open"]
emoji_close = config["emoji_close"]
embassy.status = "open"
embassy.opened_by = author
embassy.opened_at = datetime.datetime.now()
embassy.closed_by = None
embassy.closed_at = None
new_name = f"{embassy.channel.name}"
new_name = new_name.replace(f"{emoji_close}-", "", 1)
new_name = f"{emoji_open}-{new_name}"
await embassy.channel.edit(name=new_name, category=config["category_open"], reason=reason)
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=embassy.opened_by, action="Embassy Opened")
await embassy.channel.send(embed=embed)
if logschannel is not None:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_important(embassy, True, author=embassy.opened_by, title="Embassy Opened", description=f"The embassy was opened by {embassy.opened_by}.")
await logschannel.send(f"Report on the close of the embassy {embassy.id}.", embed=embed)
if embassy.first_message is not None:
try:
buttons = ActionRow(
Button(
style=ButtonStyle.grey,
label="Close",
emoji="🔒",
custom_id="close_embassy_button",
disabled=False
),
Button(
style=ButtonStyle.grey,
label="Claim",
emoji="🙋♂️",
custom_id="claim_embassy_button",
disabled=False
)
)
embassy.first_message = await embassy.channel.fetch_message(int(embassy.first_message.id))
await embassy.first_message.edit(components=[buttons])
except discord.HTTPException:
pass
await embassy.save()
return embassy
async def close(embassy, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Closing the embassy {embassy.id}.")
logschannel = config["logschannel"]
emoji_open = config["emoji_open"]
emoji_close = config["emoji_close"]
embassy.status = "close"
embassy.closed_by = author
embassy.closed_at = datetime.datetime.now()
new_name = f"{embassy.channel.name}"
new_name = new_name.replace(f"{emoji_open}-", "", 1)
new_name = f"{emoji_close}-{new_name}"
await embassy.channel.edit(name=new_name, category=config["category_close"], reason=reason)
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=embassy.closed_by, action="Embassy Closed")
await embassy.channel.send(embed=embed)
if logschannel is not None:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_important(embassy, True, author=embassy.closed_by, title="Embassy Closed", description=f"The embassy was closed by {embassy.closed_by}.")
await logschannel.send(f"Report on the close of the embassy {embassy.id}.", embed=embed)
if embassy.first_message is not None:
try:
buttons = ActionRow(
Button(
style=ButtonStyle.grey,
label="Close",
emoji="🔒",
custom_id="close_embassy_button",
disabled=True
),
Button(
style=ButtonStyle.grey,
label="Claim",
emoji="🙋♂️",
custom_id="claim_embassy_button",
disabled=True
)
)
embassy.first_message = await embassy.channel.fetch_message(int(embassy.first_message.id))
await embassy.first_message.edit(components=[buttons])
except discord.HTTPException:
pass
await embassy.save()
return embassy
async def rename(embassy, new_name: str, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Renaming the embassy {embassy.id}. (`{embassy.channel.name}` to `{new_name}`)")
emoji_open = config["emoji_open"]
emoji_close = config["emoji_close"]
embassy.renamed_by = author
embassy.renamed_at = datetime.datetime.now()
if embassy.status == "open":
new_name = f"{emoji_open}-{new_name}"
elif embassy.status == "close":
new_name = f"{emoji_close}-{new_name}"
else:
new_name = f"{new_name}"
await embassy.channel.edit(name=new_name, reason=reason)
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=embassy.renamed_by, action="Embassy Renamed")
await embassy.channel.send(embed=embed)
await embassy.save()
return embassy
async def delete(embassy, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
logschannel = config["logschannel"]
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Deleting the embassy {embassy.id}.")
embassy.deleted_by = author
embassy.deleted_at = datetime.datetime.now()
if embassy.logs_messages:
if logschannel is not None:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_important(embassy, True, author=embassy.deleted_by, title="Embassy Deleted", description=f"The embassy was deleted by {embassy.deleted_by}.")
transcript = await chat_exporter.export(embassy.channel, embassy.guild)
if not transcript is None:
file = discord.File(io.BytesIO(transcript.encode()),
filename=f"transcript-embassy-{embassy.id}.html")
await logschannel.send(f"Report on the deletion of the embassy {embassy.id}.", embed=embed, file=file)
await embassy.channel.delete(reason=reason)
data = await embassy.bot.get_cog("EmbassyTool").data.guild(embassy.guild).embassys.all()
del data[str(embassy.channel.id)]
await embassy.bot.get_cog("EmbassyTool").data.guild(embassy.guild).embassys.set(data)
return embassy
async def claim_embassy(embassy, member: discord.Member, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Claiming the embassy {embassy.id}.")
if member.bot:
await embassy.channel.send("A bot cannot claim a embassy.")
return
embassy.claim = member
overwrites = embassy.channel.overwrites
overwrites[member] = (
discord.PermissionOverwrite(
attach_files=True,
read_messages=True,
read_message_history=True,
send_messages=True,
)
)
if config["support_role"] is not None:
overwrites[config["support_role"]] = (
discord.PermissionOverwrite(
view_channel=True,
read_messages=True,
read_message_history=True,
send_messages=False,
attach_files=True,
)
)
await embassy.channel.edit(overwrites=overwrites, reason=reason)
if embassy.first_message is not None:
try:
buttons = ActionRow(
Button(
style=ButtonStyle.grey,
label="Close",
emoji="🔒",
custom_id="close_embassy_button",
disabled=False
),
Button(
style=ButtonStyle.grey,
label="Claim",
emoji="🙋♂️",
custom_id="claim_embassy_button",
disabled=True
)
)
embassy.first_message = await embassy.channel.fetch_message(int(embassy.first_message.id))
await embassy.first_message.edit(components=[buttons])
except discord.HTTPException:
pass
await embassy.save()
return embassy
async def unclaim_embassy(embassy, member: discord.Member, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Claiming the embassy {embassy.id}.")
embassy.claim = None
if config["support_role"] is not None:
overwrites = embassy.channel.overwrites
overwrites[config["support_role"]] = (
discord.PermissionOverwrite(
view_channel=True,
read_messages=True,
read_message_history=True,
send_messages=True,
attach_files=True,
)
)
await embassy.channel.edit(overwrites=overwrites, reason=reason)
await embassy.channel.set_permissions(member, overwrite=None, reason=reason)
if embassy.first_message is not None:
try:
buttons = ActionRow(
Button(
style=ButtonStyle.grey,
label="Close",
emoji="🔒",
custom_id="close_embassy_button",
disabled=False if embassy.status == "open" else True
),
Button(
style=ButtonStyle.grey,
label="Claim",
emoji="🙋♂️",
custom_id="claim_embassy_button",
disabled=False
)
)
embassy.first_message = await embassy.channel.fetch_message(int(embassy.first_message.id))
await embassy.first_message.edit(components=[buttons])
except discord.HTTPException:
pass
await embassy.save()
return embassy
async def change_owner(embassy, member: discord.Member, author: typing.Optional[discord.Member]=None):
config = await embassy.bot.get_cog("EmbassyTool").get_config(embassy.guild)
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Changing owner of the embassy {embassy.id}.")
if member.bot:
await embassy.channel.send("You cannot transfer ownership of a embassy to a bot.")
return
if config["embassy_role"] is not None:
if embassy.owner:
try:
embassy.owner.remove_roles(config["embassy_role"], reason=reason)
except discord.HTTPException:
pass
embassy.members.append(embassy.owner)
embassy.owner = member
embassy.remove(embassy.owner)
overwrites = embassy.channel.overwrites
overwrites[member] = (
discord.PermissionOverwrite(
attach_files=True,
read_messages=True,
read_message_history=True,
send_messages=True,
)
)
await embassy.channel.edit(overwrites=overwrites, reason=reason)
if config["embassy_role"] is not None:
if embassy.owner:
try:
embassy.owner.add_roles(config["embassy_role"], reason=reason)
except discord.HTTPException:
pass
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=author, action="Owner Modified")
await embassy.channel.send(embed=embed)
await embassy.save()
return embassy
async def add_member(embassy, member: discord.Member, author: typing.Optional[discord.Member]=None):
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Adding a member to the embassy {embassy.id}.")
if member.bot:
await embassy.channel.send("You cannot add a bot to a embassy.")
return
if member in embassy.members:
await embassy.channel.send("This member already has access to this embassy.")
return
if member == embassy.owner:
await embassy.channel.send("This member is already the owner of this embassy.")
return
embassy.members.append(member)
overwrites = embassy.channel.overwrites
overwrites[member] = (
discord.PermissionOverwrite(
attach_files=True,
read_messages=True,
read_message_history=True,
send_messages=True,
)
)
await embassy.channel.edit(overwrites=overwrites, reason=reason)
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=author, action=f"Member {member.mention} ({member.id}) Added")
await embassy.channel.send(embed=embed)
await embassy.save()
return embassy
async def remove_member(embassy, member: discord.Member, author: typing.Optional[discord.Member]=None):
reason = await embassy.bot.get_cog("EmbassyTool").get_audit_reason(guild=embassy.guild, author=author, reason=f"Removing a member to the embassy {embassy.id}.")
if member.bot:
await embassy.channel.send("You cannot remove a bot to a embassy.")
return
if not member in embassy.members:
await embassy.channel.send("This member is not in the list of those authorised to access the embassy.")
return
embassy.members.remove(member)
await embassy.channel.set_permissions(member, overwrite=None, reason=reason)
if embassy.logs_messages:
embed = await embassy.bot.get_cog("EmbassyTool").get_embed_action(embassy, author=author, action=f"Member {member.mention} ({member.id}) Removed")
await embassy.channel.send(embed=embed)
await embassy.save()
return embassy
| 51.681173 | 509 | 0.593571 |
e40cbe9f6ef60b46ba56918129f819050b76f422 | 285 | cs | C# | src/OpenTl.Schema/_generated/_Entities/InputChannel/TInputChannelEmpty.cs | zzz8415/OpenTl.Schema | 9fc37541179736508aa1ae85732093dc36223222 | [
"MIT"
] | null | null | null | src/OpenTl.Schema/_generated/_Entities/InputChannel/TInputChannelEmpty.cs | zzz8415/OpenTl.Schema | 9fc37541179736508aa1ae85732093dc36223222 | [
"MIT"
] | null | null | null | src/OpenTl.Schema/_generated/_Entities/InputChannel/TInputChannelEmpty.cs | zzz8415/OpenTl.Schema | 9fc37541179736508aa1ae85732093dc36223222 | [
"MIT"
] | null | null | null | // ReSharper disable All
namespace OpenTl.Schema
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0xee8c1e86)]
public sealed class TInputChannelEmpty : IInputChannel, IEmpty
{
}
}
| 15.833333 | 63 | 0.764912 |
e23fe4a4a72f9249c20acaff36dc75647dfc2d35 | 3,143 | py | Python | cytomine_hms/reader.py | Cytomine-ULiege/Cytomine-HMS | c8ceeae09d7b7e9c5f02abf20933ffe5e928abf0 | [
"Apache-2.0"
] | 1 | 2020-05-14T07:54:21.000Z | 2020-05-14T07:54:21.000Z | cytomine_hms/reader.py | Cytomine-ULiege/Cytomine-HMS | c8ceeae09d7b7e9c5f02abf20933ffe5e928abf0 | [
"Apache-2.0"
] | null | null | null | cytomine_hms/reader.py | Cytomine-ULiege/Cytomine-HMS | c8ceeae09d7b7e9c5f02abf20933ffe5e928abf0 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# * Copyright (c) 2009-2020. Authors: see NOTICE file.
# *
# * 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.
import numpy as np
from rasterio.features import geometry_mask
from rasterio.transform import IDENTITY
from shapely.affinity import affine_transform
from shapely.geometry import box, Point, LineString
def change_referential(geometry, height):
"""
Return the geometry given in cartesian coordinate system to a matrix-like coordinate system.
:param height: The height of the image having this geometry
:param geometry: The geometry in cartesian coordinate system
:return: The geometry in matrix-like coordinate system
"""
if type(geometry) in [Point, LineString]:
matrix = [1, 0, 0, -1, 0, height - 1]
else:
matrix = [1, 0, 0, -1, 0, height]
return affine_transform(geometry, matrix)
def prepare_geometry(hdf5, geometry):
"""
Get a valid geometry in matrix-like coordinate system
:param hdf5: The HDF5 file the geometry must be valid for
:param geometry: The geometry in cartesian coordinate system
:return: A valid geometry in matrix-like coordinate system
"""
image_width = hdf5['width'][()]
image_height = hdf5['height'][()]
image_geometry = box(0, 0, image_width, image_height)
return change_referential(geometry.intersection(image_geometry), image_height)
def prepare_slices(hdf5, min_slice, max_slice):
n_slices = hdf5['nSlices'][()]
if not min_slice or min_slice < 0 or min_slice > n_slices:
min_slice = 0
if not max_slice or max_slice < min_slice or max_slice > n_slices:
max_slice = n_slices
return min_slice, max_slice
def get_mask(hdf5, geometry):
image_width = hdf5['width'][()]
image_height = hdf5['height'][()]
return geometry_mask([geometry], (image_height, image_width), transform=IDENTITY, invert=True)
def get_bounds(mask):
i, j = np.nonzero(mask)
return np.s_[np.min(i):np.max(i)+1, np.min(j):np.max(j)+1]
def extract_profile(hdf5, mask, slices):
"""
Get profile data as matrix
:param hdf5: The HD5 file with profile data
:param mask: The geometry mask
:param slices: A Python slice of image slices
:return:
"""
bounds = get_bounds(mask) + (slice(*slices),)
return hdf5['data'][bounds]
def get_projection(profile, proj_func, axis=-1):
return proj_func(profile, axis=axis)
def get_cartesian_indexes(hdf5, mask):
image_height = hdf5['height'][()]
y_indexes, x_indexes = mask.nonzero()
y_indexes = image_height - 1 - y_indexes
return x_indexes, y_indexes
| 32.071429 | 98 | 0.700605 |
f3313ee8715a59870dbd0e3d753f38008fc7f3a0 | 24,693 | dart | Dart | test/photobooth/view/photobooth_page_test.dart | hjhgitw/photobooth | 5374d6f16fa942acdf80f9b1ba2b58360fc689da | [
"MIT"
] | 3 | 2021-06-02T16:26:18.000Z | 2022-03-30T22:14:33.000Z | test/photobooth/view/photobooth_page_test.dart | hjhgitw/photobooth | 5374d6f16fa942acdf80f9b1ba2b58360fc689da | [
"MIT"
] | null | null | null | test/photobooth/view/photobooth_page_test.dart | hjhgitw/photobooth | 5374d6f16fa942acdf80f9b1ba2b58360fc689da | [
"MIT"
] | 1 | 2021-09-15T01:40:10.000Z | 2021-09-15T01:40:10.000Z | // ignore_for_file: prefer_const_constructors
import 'dart:convert';
import 'dart:ui' as ui;
import 'package:bloc_test/bloc_test.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:io_photobooth/assets.g.dart';
import 'package:io_photobooth/footer/footer.dart';
import 'package:io_photobooth/photobooth/photobooth.dart';
import 'package:io_photobooth/stickers/stickers.dart';
import 'package:mocktail/mocktail.dart';
import 'package:photobooth_ui/photobooth_ui.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import '../../helpers/helpers.dart';
class MockCameraPlatform extends Mock
with MockPlatformInterfaceMixin
implements CameraPlatform {}
class FakeCameraOptions extends Fake implements CameraOptions {}
class MockImage extends Mock implements ui.Image {}
class MockCameraImage extends Mock implements CameraImage {}
class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState>
implements PhotoboothBloc {}
class FakePhotoboothEvent extends Fake implements PhotoboothEvent {}
class FakePhotoboothState extends Fake implements PhotoboothState {}
class FakeDragUpdate extends Fake implements DragUpdate {}
void main() {
setUpAll(() {
registerFallbackValue<CameraOptions>(FakeCameraOptions());
registerFallbackValue<PhotoboothEvent>(FakePhotoboothEvent());
registerFallbackValue<PhotoboothState>(FakePhotoboothState());
registerFallbackValue<DragUpdate>(FakeDragUpdate());
});
const cameraId = 1;
late CameraPlatform cameraPlatform;
late CameraImage cameraImage;
setUp(() {
cameraImage = MockCameraImage();
cameraPlatform = MockCameraPlatform();
CameraPlatform.instance = cameraPlatform;
when(() => cameraImage.width).thenReturn(4);
when(() => cameraImage.height).thenReturn(3);
when(() => cameraPlatform.init()).thenAnswer((_) async => {});
when(
() => cameraPlatform.create(any()),
).thenAnswer((_) async => cameraId);
when(() => cameraPlatform.play(any())).thenAnswer((_) async => {});
when(() => cameraPlatform.stop(any())).thenAnswer((_) async => {});
when(() => cameraPlatform.dispose(any())).thenAnswer((_) async => {});
when(() => cameraPlatform.takePicture(any()))
.thenAnswer((_) async => cameraImage);
});
group('PhotoboothPage', () {
test('is routable', () {
expect(PhotoboothPage.route(), isA<MaterialPageRoute>());
});
testWidgets('displays a PhotoboothView', (tester) async {
when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox());
await tester.pumpApp(PhotoboothPage());
await tester.pumpAndSettle();
expect(find.byType(PhotoboothView), findsOneWidget);
});
});
group('PhotoboothView', () {
late PhotoboothBloc photoboothBloc;
setUp(() {
photoboothBloc = MockPhotoboothBloc();
when(() => photoboothBloc.state).thenReturn(PhotoboothState());
});
testWidgets('renders Camera', (tester) async {
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
expect(find.byType(Camera), findsOneWidget);
});
testWidgets('renders placeholder when initializing', (tester) async {
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
expect(find.byType(SizedBox), findsOneWidget);
});
testWidgets('renders error when unavailable', (tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraUnknownException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(find.byType(PhotoboothError), findsOneWidget);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets(
'renders camera access denied error '
'when cameraPlatform throws CameraNotAllowed exception',
(tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraNotAllowedException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(
find.byKey(Key('photoboothError_cameraAccessDenied')),
findsOneWidget,
);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets(
'renders camera not found error '
'when cameraPlatform throws CameraNotFound exception', (tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraNotFoundException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(
find.byKey(Key('photoboothError_cameraNotFound')),
findsOneWidget,
);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets(
'renders camera not supported error '
'when cameraPlatform throws CameraNotSupported exception',
(tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraNotSupportedException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(
find.byKey(Key('photoboothError_cameraNotSupported')),
findsOneWidget,
);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets(
'renders unknown error '
'when cameraPlatform throws CameraUnknownException exception',
(tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraUnknownException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(
find.byKey(Key('photoboothError_unknown')),
findsOneWidget,
);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets('renders error when not allowed', (tester) async {
when(
() => cameraPlatform.create(any()),
).thenThrow(const CameraNotAllowedException());
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(find.byType(PhotoboothError), findsOneWidget);
verifyNever(() => cameraPlatform.play(any()));
});
testWidgets('renders preview when available', (tester) async {
const key = Key('__target__');
const preview = SizedBox(key: key);
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
expect(find.byType(PhotoboothPreview), findsOneWidget);
expect(find.byKey(key), findsOneWidget);
});
testWidgets('renders landscape camera when orientation is landscape',
(tester) async {
when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox());
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 400));
await tester.pumpApp(PhotoboothPage());
await tester.pumpAndSettle();
final aspectRatio = tester.widget<AspectRatio>(find.byType(AspectRatio));
expect(aspectRatio.aspectRatio, equals(PhotoboothAspectRatio.landscape));
});
testWidgets(
'adds PhotoCaptured with landscape aspect ratio '
'when photo is snapped', (tester) async {
const preview = SizedBox();
final image = CameraImage(
data: 'data:image/png,${base64.encode(transparentImage)}',
width: 1280,
height: 720,
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 400));
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
when(
() => cameraPlatform.takePicture(cameraId),
).thenAnswer((_) async => image);
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(image: image),
);
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
final photoboothPreview = tester.widget<PhotoboothPreview>(
find.byType(PhotoboothPreview),
);
photoboothPreview.onSnapPressed();
await tester.pumpAndSettle();
verify(
() => photoboothBloc.add(
PhotoCaptured(
aspectRatio: PhotoboothAspectRatio.landscape,
image: image,
),
),
).called(1);
});
testWidgets('renders portrait camera when orientation is portrait',
(tester) async {
when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox());
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
await tester.pumpApp(PhotoboothPage());
await tester.pumpAndSettle();
final aspectRatio = tester.widget<AspectRatio>(find.byType(AspectRatio));
expect(aspectRatio.aspectRatio, equals(PhotoboothAspectRatio.portrait));
});
testWidgets(
'adds PhotoCaptured with portrait aspect ratio '
'when photo is snapped', (tester) async {
const preview = SizedBox();
final image = CameraImage(
data: 'data:image/png,${base64.encode(transparentImage)}',
width: 1280,
height: 720,
);
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
when(
() => cameraPlatform.takePicture(cameraId),
).thenAnswer((_) async => image);
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(image: image),
);
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
final photoboothPreview = tester.widget<PhotoboothPreview>(
find.byType(PhotoboothPreview),
);
photoboothPreview.onSnapPressed();
await tester.pumpAndSettle();
verify(
() => photoboothBloc.add(
PhotoCaptured(
aspectRatio: PhotoboothAspectRatio.portrait,
image: image,
),
),
).called(1);
});
testWidgets('navigates to StickersPage when photo is taken',
(tester) async {
const preview = SizedBox();
final image = CameraImage(
data: 'data:image/png,${base64.encode(transparentImage)}',
width: 1280,
height: 720,
);
tester.setDisplaySize(const Size(2500, 2500));
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
when(
() => cameraPlatform.takePicture(cameraId),
).thenAnswer((_) async => image);
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(image: image),
);
await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc);
await tester.pumpAndSettle();
final photoboothPreview = tester.widget<PhotoboothPreview>(
find.byType(PhotoboothPreview),
);
photoboothPreview.onSnapPressed();
await tester.pumpAndSettle();
expect(find.byType(StickersPage), findsOneWidget);
});
});
group('PhotoboothPreview', () {
late PhotoboothBloc photoboothBloc;
setUp(() {
photoboothBloc = MockPhotoboothBloc();
when(() => photoboothBloc.state).thenReturn(PhotoboothState());
});
testWidgets('renders dash, sparky, dino, and android buttons',
(tester) async {
const key = Key('__target__');
const preview = SizedBox(key: key);
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byType(CharacterIconButton), findsNWidgets(4));
});
testWidgets('renders FlutterIconLink', (tester) async {
const key = Key('__target__');
const preview = SizedBox(key: key);
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byType(FlutterIconLink), findsOneWidget);
});
testWidgets('renders FirebaseIconLink', (tester) async {
const key = Key('__target__');
const preview = SizedBox(key: key);
when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview);
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byType(FirebaseIconLink), findsOneWidget);
});
testWidgets('renders only android when only android is selected',
(tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.android)],
),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(
find.byKey(
const Key('photoboothPreview_android_draggableResizableAsset'),
),
findsOneWidget,
);
expect(find.byType(AnimatedAndroid), findsOneWidget);
});
testWidgets('adds PhotoCharacterDragged when dragged', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.android)],
),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
await tester.drag(
find.byKey(
const Key('photoboothPreview_android_draggableResizableAsset'),
),
Offset(10, 10),
warnIfMissed: false,
);
verify(
() => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())),
);
});
testWidgets('renders only dash when only dash is selected', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.dash)],
),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(
find.byKey(const Key('photoboothPreview_dash_draggableResizableAsset')),
findsOneWidget,
);
expect(find.byType(AnimatedDash), findsOneWidget);
});
testWidgets('adds PhotoCharacterDragged when dragged', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(characters: [PhotoAsset(id: '0', asset: Assets.dash)]),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
await tester.drag(
find.byKey(const Key('photoboothPreview_dash_draggableResizableAsset')),
Offset(10, 10),
warnIfMissed: false,
);
verify(
() => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())),
);
});
testWidgets('renders only sparky when only sparky is selected',
(tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.sparky)],
),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(
find.byKey(
const Key('photoboothPreview_sparky_draggableResizableAsset'),
),
findsOneWidget,
);
expect(find.byType(AnimatedSparky), findsOneWidget);
});
testWidgets('renders only dino when only dino is selected', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(characters: [PhotoAsset(id: '0', asset: Assets.dino)]),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(
find.byKey(
const Key('photoboothPreview_dino_draggableResizableAsset'),
),
findsOneWidget,
);
expect(find.byType(AnimatedDino), findsOneWidget);
});
testWidgets('adds PhotoCharacterDragged when dragged', (tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.sparky)],
),
);
const preview = SizedBox();
tester.setDisplaySize(Size(2500, 2500));
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
await tester.drag(
find.byKey(
const Key('photoboothPreview_sparky_draggableResizableAsset'),
),
Offset(10, 10),
warnIfMissed: false,
);
verify(
() => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())),
);
});
testWidgets('renders dash, sparky, dino, and android when all are selected',
(tester) async {
when(() => photoboothBloc.state).thenReturn(
PhotoboothState(characters: [
PhotoAsset(id: '0', asset: Assets.android),
PhotoAsset(id: '1', asset: Assets.dash),
PhotoAsset(id: '2', asset: Assets.sparky),
PhotoAsset(id: '3', asset: Assets.dino),
]),
);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(find.byType(DraggableResizable), findsNWidgets(4));
expect(find.byType(AnimatedAndroid), findsOneWidget);
expect(find.byType(AnimatedDash), findsOneWidget);
expect(find.byType(AnimatedDino), findsOneWidget);
expect(find.byType(AnimatedSparky), findsOneWidget);
});
testWidgets(
'displays a LandscapeCharactersIconLayout '
'when orientation is landscape', (tester) async {
tester.setDisplaySize(landscapeDisplaySize);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(
preview: preview,
onSnapPressed: () {},
),
),
);
await tester.pumpAndSettle();
expect(find.byType(LandscapeCharactersIconLayout), findsOneWidget);
});
testWidgets(
'displays a PortraitCharactersIconLayout '
'when orientation is portrait', (tester) async {
tester.setDisplaySize(portraitDisplaySize);
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byType(PortraitCharactersIconLayout), findsOneWidget);
});
testWidgets('tapping on dash button adds PhotoCharacterToggled',
(tester) async {
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(
const Key('photoboothView_dash_characterIconButton'),
));
expect(tester.takeException(), isNull);
verify(
() => photoboothBloc.add(
PhotoCharacterToggled(character: Assets.dash),
),
).called(1);
});
testWidgets('tapping on sparky button adds PhotoCharacterToggled',
(tester) async {
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(
const Key('photoboothView_sparky_characterIconButton'),
));
expect(tester.takeException(), isNull);
verify(
() => photoboothBloc.add(
PhotoCharacterToggled(character: Assets.sparky),
),
).called(1);
});
testWidgets('tapping on android button adds PhotoCharacterToggled',
(tester) async {
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(
const Key('photoboothView_android_characterIconButton'),
));
expect(tester.takeException(), isNull);
verify(
() => photoboothBloc.add(
PhotoCharacterToggled(character: Assets.android),
),
).called(1);
});
testWidgets('tapping on dino button adds PhotoCharacterToggled',
(tester) async {
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(
const Key('photoboothView_dino_characterIconButton'),
));
expect(tester.takeException(), isNull);
verify(
() => photoboothBloc.add(
PhotoCharacterToggled(character: Assets.dino),
),
).called(1);
});
testWidgets('tapping on background adds PhotoTapped', (tester) async {
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(
const Key('photoboothPreview_background_gestureDetector'),
));
expect(tester.takeException(), isNull);
verify(() => photoboothBloc.add(PhotoTapped())).called(1);
});
testWidgets(
'renders CharactersCaption on mobile when no character is selected',
(tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
when(() => photoboothBloc.state).thenReturn(PhotoboothState());
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byType(CharactersCaption), findsOneWidget);
});
testWidgets(
'does not render CharactersCaption on mobile when '
'any character is selected', (tester) async {
tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000));
when(() => photoboothBloc.state).thenReturn(PhotoboothState(
characters: [PhotoAsset(id: '0', asset: Assets.android)],
));
const preview = SizedBox();
await tester.pumpApp(
BlocProvider.value(
value: photoboothBloc,
child: PhotoboothPreview(preview: preview, onSnapPressed: () {}),
),
);
await tester.pump();
expect(find.byType(CharactersCaption), findsNothing);
});
});
}
| 32.110533 | 80 | 0.63277 |
55eda764ce880519c268d9877244ffcef44b048f | 3,056 | swift | Swift | Pods/AI/AI/src/Requests/QueryRequest.swift | johnnyperdomo/Simple-Ai-App | 35b485d1d041a80c5cb24002cabf08fce7c5ac84 | [
"MIT"
] | 12 | 2018-10-15T15:49:48.000Z | 2020-08-21T07:56:45.000Z | Pods/AI/AI/src/Requests/QueryRequest.swift | mohsinalimat/Simple-Ai-Chat | 021e106fc1dc484e97041f838b44b18c94245045 | [
"MIT"
] | 2 | 2019-01-30T10:33:08.000Z | 2019-11-11T08:25:05.000Z | Pods/AI/AI/src/Requests/QueryRequest.swift | mohsinalimat/Simple-Ai-Chat | 021e106fc1dc484e97041f838b44b18c94245045 | [
"MIT"
] | 4 | 2019-06-19T04:25:14.000Z | 2021-12-08T14:03:20.000Z | //
// QueryRequest.swift
// AI
//
// Created by Kuragin Dmitriy on 13/11/15.
// Copyright © 2015 Kuragin Dmitriy. All rights reserved.
//
import Foundation
public enum Language {
case english
case spanish
case russian
case german
case portuguese
case portuguese_Brazil
case french
case italian
case japanese
case korean
case chinese_Simplified
case chinese_HongKong
case chinese_Taiwan
}
extension Language {
var stringValue: String {
switch self {
case .english:
return "en"
case .spanish:
return "es"
case .russian:
return "ru"
case .german:
return "de"
case .portuguese:
return "pt"
case .portuguese_Brazil:
return "pt-BR"
case .french:
return "fr"
case .italian:
return "it"
case .japanese:
return "ja"
case .korean:
return "ko"
case .chinese_Simplified:
return "zh-CN"
case .chinese_HongKong:
return "zh-HK"
case .chinese_Taiwan:
return "zh-TW"
}
}
}
public protocol QueryRequest: Request {
associatedtype ResponseType = QueryResponse
var queryParameters: QueryParameters { get }
var language: Language { get }
}
extension QueryRequest where Self: QueryContainer {
func query() -> String {
return "v=20150910"
}
}
public struct Entry {
public var value: String
public var synonyms: [String]
}
public struct Entity {
public var id: String? = .none
public var name: String
public var entries: [Entry]
}
public struct QueryParameters {
public var contexts: [Context] = []
public var resetContexts: Bool = false
public var sessionId: String? = SessionStorage.defaultSessionIdentifier
public var timeZone: TimeZone? = TimeZone.autoupdatingCurrent
public var entities: [Entity] = []
public init() {}
}
extension QueryParameters {
func jsonObject() -> [String: Any] {
var parameters = [String: Any]()
parameters["contexts"] = contexts.map({ (context) -> [String: Any] in
return ["name": context.name, "parameters": context.parameters]
})
parameters["resetContexts"] = resetContexts
if let sessionId = sessionId {
parameters["sessionId"] = sessionId
}
if let timeZone = timeZone {
parameters["timezone"] = timeZone.identifier
}
parameters["entities"] = entities.map({ (entity) -> [String: Any] in
var entityObject = [String: Any]()
entityObject["name"] = entity.name
entityObject["entries"] = entity.entries.map({ (entry) -> [String:Any] in
["value": entry.value, "synonyms": entry.synonyms]
})
return entityObject
})
return parameters
}
}
| 24.253968 | 85 | 0.571335 |
e769b47b2da76a1bf79353e507e183ac74219b0b | 6,001 | php | PHP | tests/unit/App/Service/GithubImportTest.php | lancesiast/OPEN-SALT | 9c80f0fa7a1568ebe4bef18b5e96b6f1325cfbeb | [
"MIT"
] | null | null | null | tests/unit/App/Service/GithubImportTest.php | lancesiast/OPEN-SALT | 9c80f0fa7a1568ebe4bef18b5e96b6f1325cfbeb | [
"MIT"
] | null | null | null | tests/unit/App/Service/GithubImportTest.php | lancesiast/OPEN-SALT | 9c80f0fa7a1568ebe4bef18b5e96b6f1325cfbeb | [
"MIT"
] | null | null | null | <?php
namespace App\Service;
use App\Entity\Framework\LsDoc;
use App\Entity\Framework\LsItem;
use \Codeception\Util\Stub;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\Persistence\ManagerRegistry;
class GithubImportTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
protected $validItemKeys = [
'identifier' => 'Identifier',
'fullStatement' => 'fullStatement',
'humanCodingScheme' => 'Human+Coding Scheme',
'abbreviatedStatement' => 'Abbreviated Statement',
'conceptKeywords' => 'ConceptKeywords',
'notes' => 'Notes',
'language' => 'Language',
'educationLevel' => 'educationLevel',
'cfItemType' => 'CFItemType',
'license' => 'License',
'isChildOf' => 'Is Child Of',
'isPartOf' => 'IsPartOf',
'replacedBy' => 'replacedBy',
'exemplar' => 'Exemplar',
'hasSkillLevel' => 'hasSkillLevel',
'isRelatedTo' => 'IsRelatedTo'
];
protected $validCSVContent = <<<EOT
Identifier,fullStatement,Human Coding Scheme,Abbreviated Statement,ConceptKeywords,Notes,Language,educationLevel,CFItemType,License,CFAssociationGroupIdentifier,Is Child Of,IsPartOf,replacedBy,Exemplar,hasSkillLevel,IsRelatedTo
38ce84d0-87de-4937-b030-b1f1eab03ce0,"Perceptions of one's own abilities, interests, skills, values, attitudes, beliefs, etc. that contribute to understanding the self",H.N.SK,Self-Knowledge,,,en,,,,,H.N,,,,,
de5aa87c-c344-4a36-ae61-498b083a324b,"States of perceiving, feeling, or being conscious of oneself, education, work, and the gaps among them",H.N.SK.AW,Awareness,,,en,,,,,H.N.SK,,,,,
c37224f3-0d6d-4bee-bf1e-66de6591da48,"state in which an individual is able to recognize oneself as an individual in relationship to others and the environment; there is a capacity for introspection and becoming aware of one's traits, feelings, and behavior",H.N.SK.AW.SAW,Self-Awareness,,,en,,,,,H.N.SK.AW,,,,,
2b88ba69-d07e-4ff0-92f5-8bec2b056a85,"Recognize that people have similarities and differences in their interests, values, and skills",H.N.SK.AW.SAW.1,,,,en,,,,,H.N.SK.AW.SAW,,,,,38ce84d0-87de-4937-b030-b1f1eab03ce0
50159f69-74ed-41a6-b6f2-9ba61d5678d9,"Recognize that trying new things can help you to better understand your interests, values, and skills",H.N.SK.AW.SAW.2,,,,en,,,,,H.N.SK.AW.SAW,,,,,
d61aa556-b961-4a54-9775-0f50a12d527b,Learn how to keep track of the tasks you need to do for school and how well you did them,H.N.SK.AW.SAW.3,,,,en,,,,,H.N.SK.AW.SAW,,,,,
0bd6c580-8cc8-45eb-a6b4-ed9f02bb0b13,"Learn how your personal interests, values, and skills can relate to the education plan you build for high school",H.N.SK.AW.SAW.4,,,,en,,,,,H.N.SK.AW.SAW,,,,,
239c8a41-df9d-420c-a881-1e8946683a84,Recognize that initial education or occupation choices can and will likely change,H.N.SK.AW.SAW.5,,,,en,,,,,H.N.SK.AW.SAW,,,,,
48e016cc-ca5b-464e-9e87-bc18ca633d49,"Learn how your interests, values, and skills are connected to your decisions to enroll in certain electives when developing your high school class schedule",H.N.SK.AW.SAW.6,,,,en,,,,,H.N.SK.AW.SAW,,,,,
98f62df-4065-48b5-8a65-f6c6fb49b686,Recognize that choices about your postsecondary education or occupation can change through additional exploration,H.N.SK.AW.SAW.7,,,,en,,,,,H.N.SK.AW.SAW,,,,,
EOT;
// I used a custom and uniq fullStatement to check item does not be created with the identifier already persisted
protected $repeatedItemOnCSV = <<<EOT
Identifier,fullStatement,Human Coding Scheme,Abbreviated Statement,ConceptKeywords,Notes,Language,educationLevel,CFItemType,License,CFAssociationGroupIdentifier,Is Child Of,IsPartOf,replacedBy,Exemplar,hasSkillLevel,IsRelatedTo
38ce84d0-87de-4937-b030-b1f1eab03ce0,"RYcknN3uf9nFcah5bdEg7tuyPnRtxXBFvnQXAYCP8jyCsQ3NYrJEz2smDwkJsVydp9etRmC7zwySGWEgufaGgs4CwYtqEdvPY4jeQx73H3k8wY9hYa4RNwbUaph8hZYt",H.N.SK,Self-Knowledge,,,en,,,,,H.N,,,,,
de5aa87c-c344-4a36-ae61-498b083a324b,"aHq97MnW2sEAn5LgCByW7K8tVu6gBPqck6QmKHbfYu4m2FE42UWkDpmcyapeW6ghgxsVNRdWJKL2dxUKzUtsFdpaUYDFzM9CrYdXmaZkkUjc4uyCtF54rG2Ne5Jy7trF",H.N.SK.AW,Awareness,,,en,,,,,H.N.SK,,,,,
EOT;
/** @var EntityManager */
protected $em;
protected $lsDoc;
public function _before(){
$this->tester->ensureUserExistsWithRole('Editor');
$this->em = $this->getModule('Doctrine2')->em;
$this->lsDoc = new LsDoc();
$this->lsDoc->setTitle('LsDoc Tested');
$this->lsDoc->setCreator('GithubImporter Tester');
$this->em->persist($this->lsDoc);
$this->em->flush();
}
public function testSaveItem(){
$githubImporter = new GithubImport($this->em);
$githubImporter->parseCSVGithubDocument($this->validItemKeys, $this->validCSVContent, $this->lsDoc->getId(), 'all', []);
$this->em->flush();
$dataToSeeInDatabase = [
['identifier' => '38ce84d0-87de-4937-b030-b1f1eab03ce0'],
['identifier' => '48e016cc-ca5b-464e-9e87-bc18ca633d49'],
['identifier' => '2b88ba69-d07e-4ff0-92f5-8bec2b056a85']
];
foreach($dataToSeeInDatabase as $dataToSee){
$this->tester->seeInRepository(LsItem::class, $dataToSee);
}
}
public function testSaveItemAssociations(){
$githubImporter = new GithubImport($this->em);
$githubImporter->parseCSVGithubDocument($this->validItemKeys, $this->validCSVContent, $this->lsDoc->getId(), 'all', []);
$this->em->flush();
$lsItemToCheck = $this->em->getRepository(LsItem::class)->findOneBy(array('identifier' => '2b88ba69-d07e-4ff0-92f5-8bec2b056a85'));
// associations include its inverse associations
$this->assertEquals(9, count((array)$lsItemToCheck->getAssociations()));
}
}
| 63.840426 | 310 | 0.685719 |
7889f513ef252419e0bf4e212c960483d4081875 | 101 | lua | Lua | test/src/declare02.lua | trarck/unluac | ca885dbf5a14b7467ce90f1e91b49401c2959138 | [
"MIT"
] | 6 | 2015-10-21T07:14:10.000Z | 2019-10-24T15:38:20.000Z | unluac-hgcode/test/src/declare02.lua | duangsuse/AUnluac | 61c106fe7de0b1d6636f29564ffb1aea89e1643f | [
"MIT"
] | null | null | null | unluac-hgcode/test/src/declare02.lua | duangsuse/AUnluac | 61c106fe7de0b1d6636f29564ffb1aea89e1643f | [
"MIT"
] | 4 | 2016-07-10T00:55:09.000Z | 2021-08-09T07:29:26.000Z | print("begin")
local x, y, z
print("begin")
local a, b, c
c = 4
print(c)
local d, e, f
d = 8
print(d) | 11.222222 | 14 | 0.594059 |
aa5eae41e493119daf5c060e7c8868728088ced5 | 255 | rb | Ruby | lib/msf/core/model/web_template.rb | cbgabriel/metasploit-framework | 0d1ed5c8257ecafceeb1375dda075b32e8ad2996 | [
"OpenSSL",
"Unlicense"
] | 1 | 2021-10-24T00:08:26.000Z | 2021-10-24T00:08:26.000Z | lib/msf/core/model/web_template.rb | cbgabriel/metasploit-framework | 0d1ed5c8257ecafceeb1375dda075b32e8ad2996 | [
"OpenSSL",
"Unlicense"
] | null | null | null | lib/msf/core/model/web_template.rb | cbgabriel/metasploit-framework | 0d1ed5c8257ecafceeb1375dda075b32e8ad2996 | [
"OpenSSL",
"Unlicense"
] | null | null | null | module Msf
class DBManager
class WebTemplate < ActiveRecord::Base
belongs_to :campaign
extend SerializedPrefs
serialize :prefs
serialized_prefs_attr_accessor :exploit_type
serialized_prefs_attr_accessor :exploit_name, :exploit_opts
end
end
end
| 14.166667 | 60 | 0.835294 |
6ddd9fe3deacebce79062d9b6378ae8903b80132 | 5,734 | h | C | src/CUDAlib.h | guimondmm/waifu2x-converter-cpp | 14b5fac5e06190f7c22cd07c9cbd496773886928 | [
"BSD-3-Clause"
] | 380 | 2015-05-31T01:25:40.000Z | 2022-03-19T08:26:24.000Z | src/CUDAlib.h | guimondmm/waifu2x-converter-cpp | 14b5fac5e06190f7c22cd07c9cbd496773886928 | [
"BSD-3-Clause"
] | 26 | 2015-07-28T08:53:35.000Z | 2020-02-21T10:27:07.000Z | src/CUDAlib.h | liangdai/waifu2xcpp | 4e2f21cdeea792de4d8485013ee04c99c8a33e67 | [
"BSD-3-Clause"
] | 66 | 2015-05-31T04:02:36.000Z | 2022-01-27T10:28:02.000Z | #ifndef CUDALIB_H
#define CUDALIB_H
#include <stddef.h>
#include <stdint.h>
#ifdef _WIN32
#define CUDAAPI __stdcall
#else
#define CUDAAPI
#endif
typedef uintptr_t CUdeviceptr;
typedef enum cudaError_enum {
CUDA_SUCCESS = 0
} CUresult;
typedef enum CUjit_option_enum {
CU_JIT_MAX_REGISTERS = 0,
CU_JIT_THREADS_PER_BLOCK = 1,
CU_JIT_WALL_TIME = 2,
CU_JIT_INFO_LOG_BUFFER = 3,
CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES = 4,
CU_JIT_ERROR_LOG_BUFFER = 5,
CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES = 6,
CU_JIT_OPTIMIZATION_LEVEL = 7,
CU_JIT_CACHE_MODE=14,
} CUjit_option;
typedef enum CUdevice_attribute_enum {
CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16,
CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75,
} CUdevice_attribute;
typedef enum CUjit_cacheMode_enum {
CU_JIT_CACHE_OPTION_NONE = 0,
CU_JIT_CACHE_OPTION_CG,
CU_JIT_CACHE_OPTION_CA
} CUjit_cacheMode;
typedef enum CUfunc_cache_enum {
CU_FUNC_CACHE_PREFER_NONE = 0,
CU_FUNC_CACHE_PREFER_SHARED = 1,
CU_FUNC_CACHE_PREFER_L1 = 2,
CU_FUNC_CACHE_PREFER_EQUAL = 3
} CUfunc_cache;
typedef enum CUsharedconfig_enum {
CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE = 0,
CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE = 1,
CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE = 2
} CUsharedconfig;
typedef int CUdevice;
typedef struct CUctx_st *CUcontext;
typedef struct CUmod_st *CUmodule;
typedef struct CUfunc_st *CUfunction;
typedef struct CUstream_st *CUstream;
#define CU_CTX_SCHED_BLOCKING_SYNC 0x4
typedef CUresult (CUDAAPI * tcuInit)(unsigned int Flags);
typedef CUresult (CUDAAPI * tcuDriverGetVersion)(int *ver);
typedef CUresult (CUDAAPI * tcuDeviceGetCount)(int *count);
typedef CUresult (CUDAAPI * tcuDeviceGetName)(char *name, int len, CUdevice dev);
typedef CUresult (CUDAAPI * tcuCtxCreate)(CUcontext *ret, unsigned int flags, CUdevice dev);
typedef CUresult (CUDAAPI * tcuCtxDestroy)(CUcontext ret);
typedef CUresult (CUDAAPI * tcuModuleLoadData)(CUmodule *module, const void *image);
typedef CUresult (CUDAAPI * tcuModuleLoadDataEx)(CUmodule *module, const void *image, unsigned int n, CUjit_option *o, void **ov);
typedef CUresult (CUDAAPI * tcuModuleUnload)(CUmodule mod);
typedef CUresult (CUDAAPI * tcuModuleGetFunction)(CUfunction *hfunc, CUmodule mod, const char *name);
typedef CUresult (CUDAAPI * tcuStreamCreate)(CUstream *str, unsigned int Flags);
typedef CUresult (CUDAAPI * tcuStreamDestroy)(CUstream str);
typedef CUresult (CUDAAPI * tcuMemAlloc)(CUdeviceptr *dptr, size_t bytesize);
typedef CUresult (CUDAAPI * tcuMemFree)(CUdeviceptr dptr);
typedef CUresult (CUDAAPI * tcuCtxSetCurrent)(CUcontext ctxt);
typedef CUresult (CUDAAPI * tcuCtxPushCurrent)(CUcontext ctxt);
typedef CUresult (CUDAAPI * tcuCtxPopCurrent)(CUcontext *ctxt);
typedef CUresult (CUDAAPI * tcuStreamSynchronize)(CUstream stream);
typedef CUresult (CUDAAPI * tcuMemcpyHtoD)(CUdeviceptr dst, const void *src, size_t byte);
typedef CUresult (CUDAAPI * tcuMemcpyHtoDAsync)(CUdeviceptr dst, const void *src, size_t byte, CUstream str);
typedef CUresult (CUDAAPI * tcuMemcpyDtoH)(void *dst, CUdeviceptr src, size_t byte);
typedef CUresult (CUDAAPI * tcuLaunchKernel)(CUfunction f,
unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ,
unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ,
unsigned int sharedMemBytes,
CUstream str, void **kernelParams, void **extra);
typedef CUresult (CUDAAPI * tcuCtxSetCacheConfig)(CUfunc_cache c);
typedef CUresult (CUDAAPI * tcuFuncSetSharedMemConfig)(CUfunction func, CUsharedconfig config);
typedef CUresult (CUDAAPI * tcuCtxSetSharedMemConfig)(CUsharedconfig config);
typedef CUresult (CUDAAPI * tcuDeviceGetAttribute)(int *pi, CUdevice_attribute attr, CUdevice dev);
typedef CUresult (CUDAAPI * tcuProfilerStart)(void);
#define FOR_EACH_CUDA_FUNC(F,F_V2) \
F(cuInit) \
F(cuDriverGetVersion) \
F(cuDeviceGetCount) \
F(cuDeviceGetName) \
F_V2(cuCtxCreate) \
F_V2(cuCtxDestroy) \
F(cuModuleLoadData) \
F(cuModuleLoadDataEx) \
F(cuModuleUnload) \
F(cuModuleGetFunction) \
F(cuStreamCreate) \
F_V2(cuStreamDestroy) \
F_V2(cuMemAlloc) \
F_V2(cuMemFree) \
F_V2(cuMemcpyHtoD) \
F_V2(cuMemcpyHtoDAsync) \
F_V2(cuMemcpyDtoH) \
F(cuCtxSetCurrent) \
F(cuStreamSynchronize) \
F_V2(cuCtxPushCurrent) \
F_V2(cuCtxPopCurrent) \
F(cuLaunchKernel) \
F(cuCtxSetCacheConfig) \
F(cuFuncSetSharedMemConfig) \
F(cuCtxSetSharedMemConfig) \
F(cuDeviceGetAttribute) \
F(cuProfilerStart) \
#define CUDA_PROTOTYPE(name) \
extern t##name name;
FOR_EACH_CUDA_FUNC(CUDA_PROTOTYPE,CUDA_PROTOTYPE)
#endif
| 43.439394 | 131 | 0.629055 |
f1b9cb4e326c110ce0f9f1613d1381fe67ae3c30 | 5,835 | rb | Ruby | ccmixter_download.rb | dohliam/ccmixter-download | 2b1813aa1c354834ca7c7e8c89fae07c6faeed9b | [
"MIT"
] | 2 | 2016-06-14T18:40:27.000Z | 2016-06-16T07:37:52.000Z | ccmixter_download.rb | dohliam/ccmixter-download | 2b1813aa1c354834ca7c7e8c89fae07c6faeed9b | [
"MIT"
] | 1 | 2021-10-09T12:30:38.000Z | 2021-10-10T20:32:18.000Z | ccmixter_download.rb | dohliam/ccmixter-download | 2b1813aa1c354834ca7c7e8c89fae07c6faeed9b | [
"MIT"
] | null | null | null | #!/usr/bin/ruby
require 'fileutils'
require 'open-uri'
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "\n ==ccmixter-download - a tool for batch downloading and streaming songs from ccMixter==\n Usage: ccmixter_download_artist.rb [OPTIONS]"
opts.on("-c", "--license LICENSE", "Filter tracks by license") { |v| options[:license] = v }
opts.on("-d", "--download", "Download all tracks") { options[:download] = true }
opts.on("-f", "--save-to-file", "Save urls to tracklist file") { options[:save] = true }
opts.on("-i", "--id ID", "Get results for track id (or url)") { |v| options[:id] = v }
opts.on("-l", "--limit NUMBER", "Specify results limit (default 200)") { |v| options[:limit] = v }
opts.on("-m", "--markdown", "Print out playlist in markdown format with links") { options[:markdown] = true }
opts.on("-p", "--print", "Print tracklist") { options[:print] = true }
opts.on("-q", "--query KEYWORD", "Search for a keyword") { |v| options[:search] = v }
opts.on("-R", "--remixes ID", "Get remixes of a given track by id number") { |v| options[:remixes] = v }
opts.on("-r", "--recommended", "Sort by highest recommended uploads") { options[:recommended] = true }
opts.on("-s", "--stream", "Stream entire playlist (requires mplayer)") { options[:stream] = true }
opts.on("-t", "--tag TAG", "Specify tag name") { |v| options[:tag] = v }
opts.on("-u", "--user USER", "Specify user name") { |v| options[:user] = v }
opts.on("-w", "--raw", "Output raw track array values (debugging)") { options[:raw] = true }
end.parse!
def get_url_content(params)
url = "http://ccmixter.org/api/query?f=html&t=links_by_dl_ul&chop=0" + params
URI.open(escape_url(url)).read
end
def get_track_list(params)
content = get_url_content(params)
content.scan(/<a href="(http:\/\/ccmixter.org\/(?:content|contests)\/.*?)">/)
end
def download_all_tracks(params, descriptor)
mp3 = get_track_list(params)
download_count = 1
puts " ** Fetching remote mp3s..."
mp3.uniq.each do |m|
filename = m[0].gsub(/.*\//, "")
FileUtils.mkdir_p descriptor
progress = download_count.to_f / mp3.uniq.length.to_f * 100
File.write(descriptor + "/" + filename, URI.open(m[0], "Referer" => "http://ccmixter.org/").read, {mode: 'wb'})
puts " ##{download_count.to_s} of #{mp3.uniq.length.to_s}: #{filename} saved to #{descriptor} directory! (#{progress.round(2).to_s}%)"
download_count += 1
end
puts " ** All files saved to download folder!"
end
def tracklist_to_file(params, filename)
mp3 = get_track_list(params)
mp3.uniq.each do |m|
File.open(filename, "w") { |f| f << mp3.join("\n") }
end
end
def save_tracklist(params, basename)
filename = basename + ".txt"
tracklist_to_file(params, filename)
puts " ** Tracklist saved to #{filename}!"
end
def stream_playlist(params, basename)
filename = "/tmp/" + basename + ".tmp"
tracklist_to_file(params, filename)
exec("mplayer -referrer http://ccmixter.org/ -playlist #{filename}")
end
def print_tracklist(params)
mp3 = get_track_list(params)
mp3.uniq.each do |m|
puts m
end
end
def raw_tracklist(params)
mp3 = get_track_list(params)
mp3.uniq.each do |m|
p m
end
end
def get_track_info(params)
content = get_url_content(params)
content.scan(/^\s+<li>\n\s+<a href="(http:\/\/ccmixter.org\/files\/.*?\/.*?)" class="cc_file_link">(.*?)<\/a>by <a href="(http:\/\/ccmixter.org\/people\/.*?)">(.*?)<\/a>\n\s+<a href="(http:\/\/ccmixter.org\/(?:content|contests)\/.*?)">(.*?)<\/a>\n\s+<\/li>/)
end
def print_markdown(params)
info = get_track_info(params)
info.each do |i|
ccmixter_link = i[0]
title = i[1]
artist_link = i[2]
artist_name = i[3]
file_download_link = i[4]
file_type = i[5]
puts "* _[#{title}](#{ccmixter_link})_: **[#{artist_name}](#{artist_link})** ([#{file_type}](#{file_download_link}))\n"
end
end
def get_descriptor(desc_array)
desc = "untitled"
join = desc_array.join("@").gsub(/(^@+)|(@+$)/, "").gsub(/@+/, "_").gsub(/ /, "-")
if join != ""
desc = join
end
desc
end
def get_id(url)
url.gsub(/.*\//, "")
end
params = ""
user = ""
tag = ""
search = ""
license = ""
limit = ""
sort = ""
id = ""
desc_arr = ["", "", "", ""]
if options[:limit]
limit = "&limit=" + options[:limit]
end
if options[:recommended]
sort = "&sort=num_scores"
end
if options[:user]
user = "&u=" + options[:user]
desc_arr[0] = options[:user]
end
if options[:tag]
tag = "&tags=" + options[:tag]
desc_arr[1] = options[:tag]
end
if options[:search]
kw = options[:search]
search = "&search=" + kw.gsub(/ /, "+") + "&search_type=match"
desc_arr[2] = kw
end
if options[:license]
license = "&lic=" + options[:license]
desc_arr[3] = options[:license]
end
if options[:id]
id = get_id(options[:id])
desc_arr[4] = id
id = "&ids=" + id
end
if options[:remixes]
id = get_id(options[:remixes])
desc_arr[4] = "remixes_of_" + id
id = "&remixes=" + id
end
def escape_url(url)
if url.match(/%/)
url = CGI.unescape(url)
end
url.gsub(/(.)/) { |u| u.match(URI::UNSAFE) ? CGI.escape(u) : u }
end
descriptor = get_descriptor(desc_arr)
basename = descriptor + "_ccmixter_tracklist"
params = user + tag + search + license + limit + sort + id
if params == ""
if ARGV[0]
params = "&tags=" + ARGV[0]
puts get_track_list(params)
else
puts " ** No arguments specified. Please use the -h option for help."
end
exit
end
if options[:download]
download_all_tracks(params, descriptor)
elsif options[:save]
save_tracklist(params, basename)
elsif options[:print]
print_tracklist(params)
elsif options[:markdown]
print_markdown(params)
elsif options[:stream]
stream_playlist(params, basename)
elsif options[:raw]
raw_tracklist(params)
else
puts get_track_list(params)
end
| 27.139535 | 264 | 0.635818 |
2712308c7df82b6675732bcb39136172d46b68ee | 1,458 | rb | Ruby | dm-adjust/lib/dm-adjust/adapters/data_objects_adapter.rb | spurton/dm-more | fe9e7ca23fbbfb1075c2f28efac3301edff32e9d | [
"MIT"
] | 1 | 2016-05-09T00:16:35.000Z | 2016-05-09T00:16:35.000Z | dm-adjust/lib/dm-adjust/adapters/data_objects_adapter.rb | spurton/dm-more | fe9e7ca23fbbfb1075c2f28efac3301edff32e9d | [
"MIT"
] | null | null | null | dm-adjust/lib/dm-adjust/adapters/data_objects_adapter.rb | spurton/dm-more | fe9e7ca23fbbfb1075c2f28efac3301edff32e9d | [
"MIT"
] | null | null | null | module DataMapper
module Adapters
class DataObjectsAdapter < AbstractAdapter
def adjust(attributes, query)
# TODO: if the query contains any links, a limit or an offset
# use a subselect to get the rows to be updated
properties = []
bind_values = []
# make the order of the properties consistent
query.model.properties(name).each do |property|
next unless attributes.key?(property)
properties << property
bind_values << attributes[property]
end
statement, conditions_bind_values = adjust_statement(properties, query)
bind_values.concat(conditions_bind_values)
execute(statement, *bind_values)
end
module SQL
private
def adjust_statement(properties, query)
where_statement, bind_values = where_statement(query.conditions)
statement = "UPDATE #{quote_name(query.model.storage_name(name))}"
statement << " SET #{set_adjustment_statement(properties)}"
statement << " WHERE #{where_statement}" unless where_statement.blank?
return statement, bind_values
end
def set_adjustment_statement(properties)
properties.map { |p| "#{quote_name(p.field)} = #{quote_name(p.field)} + ?" }.join(', ')
end
end # module SQL
include SQL
end # class DataObjectsAdapter
end # module Adapters
end # module DataMapper
| 30.375 | 97 | 0.646776 |
665069919e733a7dfd70a00b75ecdf06fdd55f37 | 1,697 | py | Python | minesweeper/cell.py | jfdion/mine-sweeper | 27b11dc945bb088a72c5b2e45629e8d6473fb787 | [
"MIT"
] | null | null | null | minesweeper/cell.py | jfdion/mine-sweeper | 27b11dc945bb088a72c5b2e45629e8d6473fb787 | [
"MIT"
] | null | null | null | minesweeper/cell.py | jfdion/mine-sweeper | 27b11dc945bb088a72c5b2e45629e8d6473fb787 | [
"MIT"
] | null | null | null | class Cell:
"""
| (-1, -1) | (0, -1) | (1, -1) |
| (-1, 0) | x | (1, 0) |
| (-1, 1) | (0, 1) | (1, 1) |
"""
__positions = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
"""
| | (0, -1) | |
| (-1, 0) | x | (1, 0) |
| | (0, 1) | |
"""
__cross_positions = [(0, -1), (-1, 0), (1, 0), (0, 1)]
def __init__(self, x, y, grid, is_mine=False):
self.__x = x
self.__y = y
self.__grid = grid
self.__is_mine = is_mine
self.__is_revealed = False
self.__neighbor_mines = 0
def to_string(self):
if not self.__is_revealed:
return "?"
elif self.__is_mine:
return "!"
elif self.__neighbor_mines > 0:
return str(self.__neighbor_mines)
else:
return " "
def revealed(self):
return self.__is_revealed
def is_mine(self):
return self.__is_mine
def neighbor_count(self):
return self.__neighbor_mines
def update_neighbor_count(self):
self.__neighbor_mines = 0
if self.__is_mine:
return
for (x, y) in self.__positions:
if self.__grid.exists(self.__x + x, self.__y + y) and \
self.__grid.is_mine(self.__x + x, self.__y + y):
self.__neighbor_mines += 1
def reveal(self):
if self.__is_revealed:
return
self.__is_revealed = True
if not self.__is_mine and not self.__neighbor_mines > 0:
for (x, y) in self.__cross_positions:
self.__grid.reveal(self.__x + x, self.__y + y)
| 28.762712 | 88 | 0.476724 |
0648fe9297329fd269e433e73e34f25b72d90701 | 169 | sql | SQL | sql/007_password_reset.sql | acphynix/doctors | 7f9b94e0985b5543c67fa5894c2be828d7c276e8 | [
"Apache-2.0"
] | null | null | null | sql/007_password_reset.sql | acphynix/doctors | 7f9b94e0985b5543c67fa5894c2be828d7c276e8 | [
"Apache-2.0"
] | null | null | null | sql/007_password_reset.sql | acphynix/doctors | 7f9b94e0985b5543c67fa5894c2be828d7c276e8 | [
"Apache-2.0"
] | null | null | null | -- drop table if exists password_reset;
CREATE TABLE `password_reset` (
`user_id` int(10) unsigned NOT NULL,
`reset_code` varchar(24),
PRIMARY KEY (`user_id`)
); | 28.166667 | 39 | 0.704142 |
5de996fa4d288cf20fa94093dc1352dea15f8d33 | 7,167 | cpp | C++ | tests/vu/test_runner.cpp | unknownbrackets/ps2autotests | 97469ffbed8631277b94e28d01dabd702aa97ef3 | [
"0BSD"
] | 25 | 2015-04-07T23:13:49.000Z | 2021-09-27T08:03:53.000Z | tests/vu/test_runner.cpp | unknownbrackets/ps2autotests | 97469ffbed8631277b94e28d01dabd702aa97ef3 | [
"0BSD"
] | 42 | 2015-04-27T03:12:48.000Z | 2018-05-08T13:53:39.000Z | tests/vu/test_runner.cpp | unknownbrackets/ps2autotests | 97469ffbed8631277b94e28d01dabd702aa97ef3 | [
"0BSD"
] | 8 | 2015-04-26T06:29:01.000Z | 2021-05-27T09:50:03.000Z | #include <assert.h>
#include <common-ee.h>
#include <string.h>
#include <timer.h>
#include "test_runner.h"
static const bool DEBUG_TEST_RUNNER = false;
static u32 vu_reg_pos = 0x100;
// 16 integer regs, 32 float regs, 3 status regs.
static u32 vu_reg_size = 16 * (16 + 32 + 3);
static u8 *const vu0_reg_mem = vu0_mem + vu_reg_pos;
static u8 *const vu1_reg_mem = vu1_mem + vu_reg_pos;
// Helper to "sleep" the ee for a few ticks (less than a second.)
// This is used to wait for the vu test to finish.
// We don't use interlock in case it stalls.
static void delay_ticks(int t) {
u32 goal = cpu_ticks() + t;
while (cpu_ticks() < goal) {
continue;
}
}
// Determine whether the specified vu is running or not.
static bool vu_running(int vu) {
// Must be 0 or 1. Change to 0 or (1 << 8).
u32 mask = vu == 0 ? 1 : (1 << 8);
u32 stat;
asm volatile (
"cfc2 %0, $29"
: "=r"(stat)
);
return (stat & mask) != 0;
}
void TestRunner::Execute() {
// Just to be sure.
RunnerExit();
InitRegisters();
InitFlags();
if (vu_ == 1) {
if (DEBUG_TEST_RUNNER) {
printf("Calling vu0 code.\n");
}
asm volatile (
// This writes to cmsar1 ($31). The program is simply at 0.
"ctc2 $0, $31\n"
);
} else {
if (DEBUG_TEST_RUNNER) {
printf("Calling vu0 code.\n");
}
asm volatile (
// Actually call the microcode.
"vcallms 0\n"
);
}
if (DEBUG_TEST_RUNNER) {
printf("Waiting for vu to finish.\n");
}
// Spin while waiting for the vu unit to finish.
u32 max_ticks = cpu_ticks() + 100000;
while (vu_running(vu_)) {
if (cpu_ticks() > max_ticks) {
printf("ERROR: Timed out waiting for vu code to finish.\n");
// TODO: Force stop?
break;
}
delay_ticks(200);
}
if (DEBUG_TEST_RUNNER && !vu_running(vu_)) {
printf("Finished with vu code.\n");
}
}
void TestRunner::RunnerExit() {
using namespace VU;
// The goal here is to store all the registers from the VU side.
// This way we're not testing register transfer, we're testing VU interaction.
// Issues with spilling may be more obvious this way.
// First, integers.
u32 pos = vu_reg_pos / 16;
for (int i = 0; i < 16; ++i) {
Wr(ISW(DEST_XYZW, Reg(VI00 + i), VI00, pos++));
}
// Then floats.
Wr(IADDIU(VI02, VI00, pos));
for (int i = 0; i < 32; ++i) {
Wr(SQ(DEST_XYZW, Reg(VF00 + i), VI00, pos++));
}
// Lastly, flags (now that we've saved integers.)
Wr(FCGET(VI01));
Wr(ISW(DEST_XYZW, VI01, VI00, pos++));
Wr(FMOR(VI01, VI00));
Wr(ISW(DEST_XYZW, VI01, VI00, pos++));
Wr(FSOR(VI01, 0));
Wr(ISW(DEST_XYZW, VI01, VI00, pos++));
// And actually write an exit (just two NOPs, the first with an E bit.)
SafeExit();
if (DEBUG_TEST_RUNNER) {
printf("Emitted exit code.\n");
}
}
void TestRunner::InitRegisters() {
// Clear the register state (which will be set by the code run in RunnerExit.)
if (vu_ == 1) {
memset(vu1_reg_mem, 0xCC, vu_reg_size);
} else {
memset(vu0_reg_mem, 0xCC, vu_reg_size);
}
}
void TestRunner::InitFlags() {
// Grab the previous values.
asm volatile (
// Try to clear them first, if possible.
"vnop\n"
"ctc2 $0, $16\n"
"ctc2 $0, $17\n"
"ctc2 $0, $18\n"
// Then read.
"vnop\n"
"cfc2 %0, $16\n"
"cfc2 %1, $17\n"
"cfc2 %2, $18\n"
: "=&r"(status_), "=&r"(mac_), "=&r"(clipping_)
);
if (clipping_ != 0) {
printf("WARNING: Clipping flag was not cleared.\n");
}
}
u16 TestRunner::GetValueAddress(const u32 *val) {
u16 ptr = 0;
if (vu_ == 0) {
assert(val >= (u32 *)vu0_mem && val < (u32 *)(vu0_mem + vu0_mem_size));
ptr = ((u8 *)val - vu0_mem) / 16;
} else {
assert(val >= (u32 *)vu1_mem && val < (u32 *)(vu1_mem + vu1_mem_size));
ptr = ((u8 *)val - vu1_mem) / 16;
}
return ptr;
}
void TestRunner::WrLoadFloatRegister(VU::Dest dest, VU::Reg r, const u32 *val) {
using namespace VU;
assert(r >= VF00 && r <= VF31);
u16 ptr = GetValueAddress(val);
if ((ptr & 0x3FF) == ptr) {
Wr(LQ(dest, r, VI00, ptr));
} else {
// This shouldn't happen? Even with 16kb, all reads should be < 0x400.
printf("Unhandled pointer load.");
assert(false);
}
}
void TestRunner::WrSetIntegerRegister(VU::Reg r, u32 v) {
using namespace VU;
assert(r >= VI00 && r <= VI15);
assert((v & 0xFFFF) == v);
// Except for 0x8000, we can get to everything with one op.
if (v == 0x8000) {
Wr(IADDI(r, VI00, -1));
Wr(ISUBIU(r, r, 0x7FFF));
} else if (v & 0x8000) {
Wr(ISUBIU(r, VI00, v & ~0x8000));
} else {
Wr(IADDIU(r, VI00, v));
}
}
void TestRunner::WrLoadIntegerRegister(VU::Dest dest, VU::Reg r, const u32 *val) {
using namespace VU;
assert(r >= VI00 && r <= VI15);
u16 ptr = GetValueAddress(val);
if ((ptr & 0x3FF) == ptr) {
Wr(ILW(dest, r, VI00, ptr));
} else {
// This shouldn't happen? Even with 16kb, all reads should be < 0x400.
printf("Unhandled pointer load.");
assert(false);
}
}
void TestRunner::PrintRegister(VU::Reg r, bool newline) {
using namespace VU;
if (r >= VI00 && r <= VI15) {
PrintIntegerRegister(r - VI00);
} else {
PrintVectorRegister(r);
}
if (newline) {
printf("\n");
}
}
void TestRunner::PrintIntegerRegister(int i) {
const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem;
// The integer registers are first, so it's just at the specified position.
const u32 *p = (const u32 *)(regs + 16 * i);
printf("%04x", *p);
}
union FloatBits {
float f;
u32 u;
};
static inline void printFloatString(const FloatBits &bits) {
// We want -0.0 and -NAN to show as negative.
// So, let's just print the sign manually with an absolute value.
FloatBits positive = bits;
positive.u &= ~0x80000000;
char sign = '+';
if (bits.u & 0x80000000) {
sign = '-';
}
printf("%c%0.2f", sign, positive.f);
}
static inline void printFloatBits(const FloatBits &bits) {
printf("%08x/", bits.u);
printFloatString(bits);
}
void TestRunner::PrintRegisterField(VU::Reg r, VU::Field field, bool newline) {
using namespace VU;
assert(r >= VF00 && r <= VF31);
const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem;
const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + r));
printFloatBits(p[field]);
if (newline) {
printf("\n");
}
}
void TestRunner::PrintVectorRegister(int i) {
const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem;
// Skip the 16 integer registers, and jump to the vector.
const FloatBits *p = (const FloatBits *)(regs + 16 * (16 + i));
// Let's just print each lane separated by a space.
printFloatBits(p[0]);
printf(" ");
printFloatBits(p[1]);
printf(" ");
printFloatBits(p[2]);
printf(" ");
printFloatBits(p[3]);
}
void TestRunner::PrintStatus(bool newline) {
const u8 *regs = vu_ == 0 ? vu0_reg_mem : vu1_reg_mem;
// Skip 16 integer regs and 32 vector regs, to get a base for the status regs.
const u32 *flags = (const u32 *)(regs + 16 * (16 + 32));
// Note that they are spaced out by 16 bytes (4 words.)
u32 clipping = flags[0];
u32 mac = flags[4];
u32 status = flags[8];
if (status == status_ && mac == mac_ && clipping == clipping_) {
printf(" (no flag changes)");
} else {
printf(" st=+%04x,-%04x, mac=+%04x,-%04x, clip=%08x", status & ~status_, ~status & status_, mac & ~mac_, ~mac & mac_, clipping);
}
if (newline) {
printf("\n");
}
}
| 23.89 | 130 | 0.629273 |
04202ed91f6617459d5a06e05cf8a0160a83bf8d | 2,287 | cc | C++ | third-party/qthread/qthread-src/test/benchmarks/finepoints/partSendPrototype/mpiBaseTest5.cc | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 1,602 | 2015-01-06T11:26:31.000Z | 2022-03-30T06:17:21.000Z | third-party/qthread/qthread-src/test/benchmarks/finepoints/partSendPrototype/mpiBaseTest5.cc | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 11,789 | 2015-01-05T04:50:15.000Z | 2022-03-31T23:39:19.000Z | third-party/qthread/qthread-src/test/benchmarks/finepoints/partSendPrototype/mpiBaseTest5.cc | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 498 | 2015-01-08T18:58:18.000Z | 2022-03-20T15:37:45.000Z | #include <time.h>
#include <qthread/qthread.h>
#include <qthread/barrier.h>
#include <qthread/qloop.h>
#include <mpi.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct args {
int rank;
int numIterations;
char* sendBuf;
char* recvBuf;
int numThreads;
size_t threadPart;
int other;
MPI_Request *requests;
} arg_t;
static long sleep1;
static long sleepPlus;
static qt_barrier_t *wait_on_me;
static void worker( unsigned long tid, unsigned long, void *arg ){
arg_t *a = (arg_t *)arg;
int rank = a->rank;
int numIterations = a->numIterations;
char *sendBuf = a->sendBuf;
char *recvBuf = a->recvBuf;
int numThreads = a->numThreads;
size_t threadPart = a->threadPart;
int other = (rank + 1) % 2;
int rc;
int iteration;
struct timespec req,rem;
req.tv_sec = 0;
if ( numThreads > 1 && tid == numThreads - 1 ) {
req.tv_nsec = sleepPlus;
} else {
req.tv_nsec = sleep1;
}
size_t bufSize = numThreads * threadPart;
for ( iteration = 0; iteration < numIterations; iteration++ ) {
if ( 0 == rank ) {
qt_barrier_enter(wait_on_me);
// rc = clock_nanosleep(CLOCK_REALTIME,0,&req, &rem);
if ( 0 != rc ) {
printf("rc=%s rem %li\n",strerror(rc),rem.tv_nsec);
}
if ( tid == 0 ) {
rc = MPI_Send( (char*) sendBuf, bufSize, MPI_CHAR, other, 0xdead, MPI_COMM_WORLD );
assert( rc == MPI_SUCCESS );
}
} else {
qt_barrier_enter(wait_on_me);
if ( tid == 0 ){
rc = MPI_Recv( (char*) recvBuf, bufSize, MPI_CHAR, other, 0xdead, MPI_COMM_WORLD, MPI_STATUS_IGNORE );
assert( rc == MPI_SUCCESS );
}
}
}
}
double doTest5( int rank, int numIterations, char* sendBuf, char* recvBuf, int numThreads, size_t threadPart, double compTime, double noise )
{
// each thread
arg_t arg;
double start,duration;
start = MPI_Wtime();
sleep1 = compTime * 1000000000;
sleepPlus = (compTime + ( compTime * noise)) * 1000000000 ;
qt_loop(0, numThreads, worker, &arg);
duration = MPI_Wtime() - start;
if ( numThreads > 1 ) {
duration -= sleepPlus / 1000000000.0 * numIterations;
} else {
duration -= sleep1 / 1000000000.0 * numIterations;
}
return duration;
}
| 23.10101 | 141 | 0.637079 |
06fdc9a1f105198d36e30385ea61aa831b5f5d77 | 1,239 | py | Python | gslides/__init__.py | michael-gracie/gslides | 6400184454630e05559b20e8c6e6f52f42175d9c | [
"MIT"
] | 17 | 2021-08-12T14:18:18.000Z | 2022-02-20T18:54:35.000Z | gslides/__init__.py | michael-gracie/gslides | 6400184454630e05559b20e8c6e6f52f42175d9c | [
"MIT"
] | 17 | 2021-05-01T02:05:30.000Z | 2022-03-04T06:09:02.000Z | gslides/__init__.py | michael-gracie/gslides | 6400184454630e05559b20e8c6e6f52f42175d9c | [
"MIT"
] | 3 | 2021-08-29T20:23:47.000Z | 2021-12-09T18:36:40.000Z | # -*- coding: utf-8 -*-
"""Top-level package for gslides."""
__author__ = """Michael Gracie"""
__email__ = ""
__version__ = "0.1.1"
from typing import Optional
from google.oauth2.credentials import Credentials
from .config import CHART_PARAMS, Creds, Font, PackagePalette
creds = Creds()
package_font = Font()
package_palette = PackagePalette()
def initialize_credentials(credentials: Optional[Credentials]) -> None:
"""Intializes credentials for all classes in the package.
:param credentials: Credentials to build api connection
:type credentials: google.oauth2.credentialsCredentials
"""
creds.set_credentials(credentials)
def set_font(font: str) -> None:
"""Sets the font for all objects
:param font: Font
:type font: str
"""
package_font.set_font(font)
def set_palette(palette: str) -> None:
"""Sets the palette for all charts
:param palette: The palette to use
:type palette: str
"""
package_palette.set_palette(palette)
from .chart import Chart, Series # noqa
from .colors import Palette # noqa
from .frame import Frame # noqa
from .presentation import Presentation # noqa
from .spreadsheet import Spreadsheet # noqa
from .table import Table # noqa
| 23.377358 | 71 | 0.716707 |
e952118a45db223ca9422075e248cf877fc4029c | 1,396 | asm | Assembly | samples/a8/games/zilch/rmt_feat.asm | zbyti/Mad-Pascal | 546cae9724828f93047080109488be7d0d07d47e | [
"MIT"
] | 1 | 2021-12-15T23:47:19.000Z | 2021-12-15T23:47:19.000Z | samples/a8/games/zilch/rmt_feat.asm | michalkolodziejski/Mad-Pascal | 0a7a1e2f379e50b0a23878b0d881ff3407269ed6 | [
"MIT"
] | null | null | null | samples/a8/games/zilch/rmt_feat.asm | michalkolodziejski/Mad-Pascal | 0a7a1e2f379e50b0a23878b0d881ff3407269ed6 | [
"MIT"
] | null | null | null | ;* --------BEGIN--------
;* D:\atari\workspaceMadPascal\zilch\assets\zilch.rmt
FEAT_SFX equ 1
FEAT_GLOBALVOLUMEFADE equ 0 ;RMTGLOBALVOLUMEFADE variable
FEAT_NOSTARTINGSONGLINE equ 0
FEAT_INSTRSPEED equ 3
FEAT_CONSTANTSPEED equ 5 ;(0 times)
FEAT_COMMAND1 equ 1 ;(62 times)
FEAT_COMMAND2 equ 0 ;(0 times)
FEAT_COMMAND3 equ 0 ;(0 times)
FEAT_COMMAND4 equ 0 ;(0 times)
FEAT_COMMAND5 equ 1 ;(1 times)
FEAT_COMMAND6 equ 0 ;(0 times)
FEAT_COMMAND7SETNOTE equ 0 ;(0 times)
FEAT_COMMAND7VOLUMEONLY equ 0 ;(0 times)
FEAT_PORTAMENTO equ 1 ;(2 times)
FEAT_FILTER equ 0 ;(0 times)
FEAT_FILTERG0L equ 0 ;(0 times)
FEAT_FILTERG1L equ 0 ;(0 times)
FEAT_FILTERG0R equ 0 ;(0 times)
FEAT_FILTERG1R equ 0 ;(0 times)
FEAT_BASS16 equ 1 ;(5 times)
FEAT_BASS16G1L equ 0 ;(0 times)
FEAT_BASS16G3L equ 0 ;(0 times)
FEAT_BASS16G1R equ 0 ;(0 times)
FEAT_BASS16G3R equ 0 ;(0 times)
FEAT_VOLUMEONLYG0L equ 0 ;(0 times)
FEAT_VOLUMEONLYG2L equ 0 ;(0 times)
FEAT_VOLUMEONLYG3L equ 0 ;(0 times)
FEAT_VOLUMEONLYG0R equ 0 ;(0 times)
FEAT_VOLUMEONLYG2R equ 0 ;(0 times)
FEAT_VOLUMEONLYG3R equ 0 ;(0 times)
FEAT_TABLETYPE equ 1 ;(4 times)
FEAT_TABLEMODE equ 1 ;(2 times)
FEAT_TABLEGO equ 1 ;(7 times)
FEAT_AUDCTLMANUALSET equ 0 ;(0 times)
FEAT_VOLUMEMIN equ 1 ;(3 times)
FEAT_EFFECTVIBRATO equ 0 ;(0 times)
FEAT_EFFECTFSHIFT equ 0 ;(0 times)
;* --------END--------
| 34.04878 | 58 | 0.714183 |
4bd76e5636d924135ea282fd29a8252b244ba27e | 15,853 | h | C | sdk-6.5.20/src/bcm/dnx/field/map/field_map_local.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/bcm/dnx/field/map/field_map_local.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/bcm/dnx/field/map/field_map_local.h | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | /** \file field_map_local.h
* *
* Contains definitions to be used only internally by map module only
*
* Created on: Dec 6, 2017
*/
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#ifndef SRC_BCM_DNX_FIELD_FIELD_MAP_LOCAL_H_
#define SRC_BCM_DNX_FIELD_FIELD_MAP_LOCAL_H_
/*
* Include files
* {
*/
#include <bcm_int/dnx/field/field_context.h>
/*
* }
*/
/*
* Globals
* For internal map submodule usage
* {
*/
extern const dnx_field_context_param_t context_param_set[bcmFieldContextParamCount][bcmFieldStageCount];
extern const dnx_field_range_map_t range_map_legacy[DNX_FIELD_RANGE_TYPE_NOF][DNX_FIELD_STAGE_NOF];
extern dnx_field_sw_qual_info_t dnx_sw_qual_info[DNX_FIELD_SW_QUAL_NOF];
extern const dnx_field_qual_input_type_info_t dnx_input_type_info[DNX_FIELD_INPUT_TYPE_NOF];
extern const dnx_field_qual_map_t dnx_global_qual_map[bcmFieldQualifyCount];
extern const char *bcm_qual_description[bcmFieldQualifyCount];
extern dnx_field_header_qual_info_t dnx_header_qual_info[DNX_FIELD_HEADER_QUAL_NOF];
extern dnx_field_layer_record_qual_info_t dnx_layer_record_qual_info[DNX_FIELD_LR_QUAL_NOF];
extern const dnx_field_action_map_t dnx_global_action_map[bcmFieldActionCount];
extern dnx_field_base_action_info_t dnx_sw_action_info[DNX_FIELD_SW_ACTION_NOF];
extern const char *dnx_field_qual_class_names[DNX_FIELD_QUAL_CLASS_NOF];
extern const char *dnx_field_action_class_names[DNX_FIELD_ACTION_CLASS_NOF];
extern const char *bcm_action_description[bcmFieldActionCount];
extern const char *dnx_field_input_types_names[DNX_FIELD_INPUT_TYPE_NOF];
/*
* }
*/
/*
* Macros
* For internal map submodule usage
* {
*/
/** Flags for BCM to DNX conversion cb */
#define CHECK_BARE_METAL_SUPPORT 0x01
/**
* Check whether the conversion CB is supported in BareMetal mode.
* if yes, _SHR_E_NONE is returned, otherwise _SHR_E_UNAVAIL
*/
#define DNX_FIELD_CB_BLOCK_FOR_BARE_METAL(_flags)\
if(_flags & CHECK_BARE_METAL_SUPPORT) \
{ \
SHR_SET_CURRENT_ERR(_SHR_E_UNAVAIL); \
SHR_EXIT(); \
} \
#define DNX_FIELD_CB_UNBLOCK_FOR_BARE_METAL(_flags) \
if(_flags & CHECK_BARE_METAL_SUPPORT) \
{ \
SHR_SET_CURRENT_ERR(_SHR_E_NONE); \
SHR_EXIT(); \
} \
/*
* } Macros
*/
/*
* Type definitions
* For internal map submodule usage
* {
*/
/**
* Information assigned to each 'dnx action'
* See dnx_field_map_action_info.
*/
typedef struct
{
/*
* Keep class inside info
*/
dnx_field_action_class_e class;
/*
* Keep dnx stage inside info
*/
dnx_field_stage_e dnx_stage;
/**
* Field ID associated with this action, to be used while configuring TCAM entries
*/
dbal_fields_e field_id;
/**
* Actual action that is used to configure FES
* This field in info should be used rather than action id part of dnx action
*/
dnx_field_action_type_t action_type;
/**
* BCM action id
*/
bcm_field_action_t bcm_action;
/**
* If the DNX action is a user defined action (class is DNX_FIELD_ACTION_CLASS_USER),
* contains the action upon which the UDA is based.
*/
dnx_field_action_t base_dnx_action;
/**
* If the DNX action is a user defined action (class is DNX_FIELD_ACTION_CLASS_USER),
* contains the prefix of the action.
*/
uint32 prefix;
/**
* If the DNX action is a user defined action (class is DNX_FIELD_ACTION_CLASS_USER),
* contains the size in bits of the prefix of the action.
*/
unsigned int prefix_size;
/**
* Signal or signals, which are corresponding to the action.
*/
char *signal_name[DNX_DATA_MAX_FIELD_DIAG_NOF_SIGNALS_PER_ACTION];
} dnx_field_map_action_info_t;
/**
* \brief Structure returned by dnx qualifier to info mapping, include all data for CE(FFC) configuration
*/
typedef struct
{
int size;
/*
* Keep class inside info
*/
dnx_field_qual_class_e class;
/*
* Keep dnx stage inside info
*/
dnx_field_stage_e dnx_stage;
/**
* Field ID associated with this qualifier, to be used while configuring TCAM entries
*/
dbal_fields_e field_id;
/**
* Offset from base - type of base depends on FCC type
*/
int offset;
/*
* bcm qualifier that is mapped to this dnx one, if 0 no bcm qualifier is mapped to it
*/
bcm_field_qualify_t bcm_qual;
/*
* Info about signal or signals, which are corresponding to the qualifier.
*/
dnx_field_map_qual_signal_info_t signal_info[DNX_DATA_MAX_FIELD_DIAG_NOF_SIGNALS_PER_QUALIFIER];
} dnx_field_qual_info_t;
/**
* Information collected from DNX DATA regarding a layer record qualifier.
* See dnx_field_map_qual_layer_record_info.
* see dnx_field_map_qual_info.
*/
typedef struct
{
/*
* Whether the layer record is valid for the unit/stage.
*/
int valid;
/*
* The offset of the qualifier within the layer record.
*/
int offset;
/*
* The size in bits of the qualifier
*/
int size;
} dnx_field_map_qual_layer_record_pbus_info_t;
/*
* }
*/
/*
* All routines in this section serves for callback converting bcm quals and action data into dnx one
* {
*/
shr_error_e dnx_field_convert_gport_to_dst(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_rif_intf_to_dst(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_port_with_core(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_sys_port_gport_to_port(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_port_without_core(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_trap_gport(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_trap_gport_to_hw_dest(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ingress_sniff_gport_to_code(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ingress_snoop_gport_to_code(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_egress_trap_gport_to_strength(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_egress_snoop_gport_to_strength(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_egress_trap_id(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_egress_sniff_gport_to_profile(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_global_in_lif(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_global_out_lif(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_global_out_lif_add_valid(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_rif_intf_to_lif(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_rif_intf_to_lif_add_valid(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_rif_intf_to_rpf_out_lif_encoded(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_gport_to_rpf_out_lif_encoded(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_color(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_stat_lm_index(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_vlan_format(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_app_type(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_app_type_predef_only(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ext_stat(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ext_stat_with_valid(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_latency_flow_id(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_stat_profile(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_fwd_domain(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_oam(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ipt_command(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_packet_strip(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ace_stat_meter_object(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ace_stat_counter_object(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_parsing_start_offset(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_parsing_start_type(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_system_header_profile(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_learn_info_key_2(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_forwarding_type(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
shr_error_e dnx_field_convert_ac_in_lif_wide_data_extended(
int unit,
uint32 flags,
int core,
uint32 *bcm_data,
uint32 *dnx_data);
/*
* }
*/
/*
* All routines in this section serves for callback converting context parameters
* {
*/
shr_error_e dnx_field_convert_context_sys_header_profile(
int unit,
dnx_field_stage_e dnx_stage,
dnx_field_context_t context_id,
uint32 param_value,
struct dnx_field_context_param_e *context_param,
dnx_field_dbal_entry_t * field_dbal_entry);
shr_error_e dnx_field_convert_context_param_key_val(
int unit,
dnx_field_stage_e dnx_stage,
dnx_field_context_t field_context_id,
uint32 param_value,
struct dnx_field_context_param_e *context_param,
dnx_field_dbal_entry_t * field_dbal_entry);
shr_error_e dnx_field_convert_context_param_header_strip(
int unit,
dnx_field_stage_e dnx_stage,
dnx_field_context_t field_context_id,
uint32 param_value,
struct dnx_field_context_param_e *context_param,
dnx_field_dbal_entry_t * field_dbal_entry);
/*
* }
*/
/*
* All routines in this section serves for callback converting CS qual types
* {
*/
/**
* \brief
* Returns the context selection DNX qualifier for the cascaded BCM qualifier
* with the given fg_id (given as cs_qual_index) in the given context_id.
*/
shr_error_e dnx_field_convert_cs_qual_type_cascaded_group(
int unit,
uint32 cs_qual_index,
dnx_field_context_t context_id,
bcm_field_qualify_t bcm_qual,
dbal_fields_e * cs_dnx_qual_p);
/**
* \brief
* Returns the context selection BCM qualifier for the cascaded DNX qualifier
* and provides the fg_id (given as cs_qual_index_p) in the given context_id.
*/
shr_error_e dnx_field_convert_cs_qual_type_cascaded_group_back(
int unit,
dnx_field_context_t context_id,
dbal_fields_e cs_dnx_qual,
bcm_field_qualify_t * bcm_qual_p,
uint32 *cs_qual_index_p);
/*
* }
*/
/**
* \brief Retrieve the DNX DATA information about a layer record qualifier ID.
* \param [in] unit - Identifier of HW platform.
* \param [in] stage - Stage identifier
* \param [in] dnx_qual_id - DNX qualifier ID
* \param [out] lr_qual_info_p - The information retrieved
* \return
* \retval _SHR_E_NONE - On success
* \retval Other - Other errors as per shr_error_e
* \remark
*/
shr_error_e dnx_field_map_qual_layer_record_info_get(
int unit,
dnx_field_stage_e stage,
dnx_field_qual_id_t dnx_qual_id,
dnx_field_map_qual_layer_record_pbus_info_t * lr_qual_info_p);
/**
* \brief
* Maps BCM System header profile to DNX system header profile ENUMS
* \param [in] unit - Device Id.
* \param [in] bcm_sys_hdr_profile - BCM Sys hdr profile Enum.
* \param [out] dnx_sys_hdr_profile_p - DNX Sys hdr profile Enum.
* \return
* shr_error_e - Error Type
* \remark
* * None
* \see
* * None
*/
shr_error_e dnx_field_map_system_header_profile_bcm_to_dnx(
int unit,
bcm_field_system_header_profile_t bcm_sys_hdr_profile,
dnx_field_context_sys_hdr_profile_e * dnx_sys_hdr_profile_p);
/**
* \brief
* Gets the offset in the metadata of a signal that can be used by a qualifier.
* Used for virtual wire qualifiers.
* \param [in] unit - Device ID.
* \param [in] stage - Stage
* \param [in] signal_name - The name of the signal the VW is mapped to.
* \param [in] offset_within_signal - When an offset within the signal is required.
* \param [out] is_qual_available_p - Whether the signal can be read as qualifier.
* \param [out] offset_p - The offset on the metadata of the signal.
* only relevant if is_qual_available_p is TRUE.
* \return
* shr_error_e - Error Type
* \remark
* * None
* \see
* * None
*/
shr_error_e dnx_field_qual_vw_signal_offset(
int unit,
dnx_field_stage_e stage,
char *signal_name,
int offset_within_signal,
int *is_qual_available_p,
int *offset_p);
/**
* \brief
* Checks whether the conversion CB has a BareMetal support check.
* \param [in] unit - Device ID
* \param [in] conversion_cb - conversion CB
* \param [in] bare_metal_support - param to verify the CB function support BareMetal
* \return
* shr_error_e - Error Type
* \remark
* * None
* \see
* * None
*/
shr_error_e dnx_field_bare_metal_support_check(
int unit,
field_data_conversion_cb conversion_cb,
int *bare_metal_support);
#endif /* SRC_BCM_DNX_FIELD_FIELD_MAP_LOCAL_H_ */
| 25.203498 | 134 | 0.704409 |
439d5b09f4c878f46dd0ce09cf442dff591a0c20 | 708 | tsx | TypeScript | packages/icons/src/SketchCircleFilled.tsx | xl-vision/xl-vision | 360ef052a74d38e6674cd5d5d6979c405c53d647 | [
"MIT"
] | 12 | 2019-11-16T03:49:55.000Z | 2022-03-16T11:00:37.000Z | packages/icons/src/SketchCircleFilled.tsx | xl-vision/xl-vision | 360ef052a74d38e6674cd5d5d6979c405c53d647 | [
"MIT"
] | 237 | 2019-04-04T05:11:59.000Z | 2022-03-30T05:25:58.000Z | packages/icons/src/SketchCircleFilled.tsx | xl-vision/xl-vision | 360ef052a74d38e6674cd5d5d6979c405c53d647 | [
"MIT"
] | 4 | 2019-03-03T07:35:49.000Z | 2021-02-16T15:27:32.000Z | /* eslint-disable */
import React from 'react';
import createIcon from './utils/createIcon';
export default createIcon(<svg viewBox="0 0 1024 1024"><path d="m582.3 625.6 147.9-166.3h-63.4zm90-202.3h62.5l-92.1-115.1zm-274.7 36L512 684.5l114.4-225.2zM512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm286.7 380.2L515.8 762.3c-1 1.1-2.4 1.7-3.8 1.7s-2.8-.6-3.8-1.7L225.3 444.2a5.14 5.14 0 0 1-.2-6.6L365.6 262c1-1.2 2.4-1.9 4-1.9h284.6c1.6 0 3 .7 4 1.9l140.5 175.6a4.9 4.9 0 0 1 0 6.6zm-190.5-20.9L512 326.1l-96.2 97.2zM420.3 301.1l-23.1 89.8 88.8-89.8zm183.4 0H538l88.8 89.8zm-222.4 7.1-92.1 115.1h62.5zm-87.5 151.1 147.9 166.3-84.5-166.3z" /></svg>, 'SketchCircleFilled');
| 118 | 613 | 0.69209 |
b21df2d494a509fda6a665cf65096ca8341ef469 | 1,612 | kt | Kotlin | bitcoincore/src/test/kotlin/io/horizontalsystems/bitcoincore/utils/NetworkUtilsTest.kt | softskillpro/bitcoin-kit-android | 9b62a7b7869326ff22b43ee6db7ccfff86294303 | [
"MIT"
] | 105 | 2018-10-24T05:02:13.000Z | 2022-03-24T05:47:16.000Z | bitcoincore/src/test/kotlin/io/horizontalsystems/bitcoincore/utils/NetworkUtilsTest.kt | softskillpro/bitcoin-kit-android | 9b62a7b7869326ff22b43ee6db7ccfff86294303 | [
"MIT"
] | 156 | 2018-10-22T09:22:36.000Z | 2022-02-15T05:26:16.000Z | bitcoincore/src/test/kotlin/io/horizontalsystems/bitcoincore/utils/NetworkUtilsTest.kt | softskillpro/bitcoin-kit-android | 9b62a7b7869326ff22b43ee6db7ccfff86294303 | [
"MIT"
] | 66 | 2019-01-07T20:06:36.000Z | 2022-03-29T05:53:44.000Z | package io.horizontalsystems.bitcoincore.utils
import okhttp3.OkHttpClient
import okhttp3.Request
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import java.net.URL
import javax.net.ssl.SSLHandshakeException
internal class NetworkUtilsTest {
// System is Unable to find valid certification path to below URL
private val CERT_ERROR_TEST_URL = "https://cashexplorer.bitcoin.com/api/sync/"
@Test
fun testUnsafeHttpRequest() {
assertDoesNotThrow {
doUnsafeHttpRequest()
}
assertThrows(SSLHandshakeException::class.java) { doSafeHttpRequest() }
assertThrows(SSLHandshakeException::class.java) { doUrlConnectionRequest() }
}
private fun doSafeHttpRequest() {
doOkHttpRequest(OkHttpClient.Builder().build())
}
private fun doUnsafeHttpRequest() {
doOkHttpRequest(NetworkUtils.getUnsafeOkHttpClient())
}
private fun doUrlConnectionRequest() {
URL(CERT_ERROR_TEST_URL)
.openConnection()
.apply {
connectTimeout = 5000
readTimeout = 60000
setRequestProperty("Accept", "application/json")
}.getInputStream()
.use {
//Success
}
}
private fun doOkHttpRequest(httpClient: OkHttpClient) {
val request = Request.Builder().url(CERT_ERROR_TEST_URL).build()
return httpClient.newCall(request)
.execute()
.use {
//success
}
}
} | 28.280702 | 84 | 0.616005 |
4fdf6706c300b870a16c494777befac4d07af6d4 | 73 | rb | Ruby | lib/noticent/version.rb | Belibaste/noticent | 1ba2ea320b5ec26b188168008f61538921c0bc2b | [
"Apache-2.0"
] | null | null | null | lib/noticent/version.rb | Belibaste/noticent | 1ba2ea320b5ec26b188168008f61538921c0bc2b | [
"Apache-2.0"
] | null | null | null | lib/noticent/version.rb | Belibaste/noticent | 1ba2ea320b5ec26b188168008f61538921c0bc2b | [
"Apache-2.0"
] | null | null | null | # frozen_string_literal: true
module Noticent
VERSION ||= "0.0.4"
end
| 12.166667 | 29 | 0.712329 |
aebfdf1e66b1b9b03014989e39141c36fd6a7a8e | 1,169 | cs | C# | stellar-dotnet-sdk-xdr/generated/TimeBounds.cs | payshares-labs/dotnet-stellar-sdk | 3a43858b098e516dbb9e5fb9cbbd0512c532cf2d | [
"Apache-2.0"
] | null | null | null | stellar-dotnet-sdk-xdr/generated/TimeBounds.cs | payshares-labs/dotnet-stellar-sdk | 3a43858b098e516dbb9e5fb9cbbd0512c532cf2d | [
"Apache-2.0"
] | null | null | null | stellar-dotnet-sdk-xdr/generated/TimeBounds.cs | payshares-labs/dotnet-stellar-sdk | 3a43858b098e516dbb9e5fb9cbbd0512c532cf2d | [
"Apache-2.0"
] | null | null | null | // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
using System;
namespace stellar_dotnet_sdk.xdr
{
// === xdr source ============================================================
// struct TimeBounds
// {
// TimePoint minTime;
// TimePoint maxTime; // 0 here means no maxTime
// };
// ===========================================================================
public class TimeBounds
{
public TimeBounds() { }
public TimePoint MinTime { get; set; }
public TimePoint MaxTime { get; set; }
public static void Encode(XdrDataOutputStream stream, TimeBounds encodedTimeBounds)
{
TimePoint.Encode(stream, encodedTimeBounds.MinTime);
TimePoint.Encode(stream, encodedTimeBounds.MaxTime);
}
public static TimeBounds Decode(XdrDataInputStream stream)
{
TimeBounds decodedTimeBounds = new TimeBounds();
decodedTimeBounds.MinTime = TimePoint.Decode(stream);
decodedTimeBounds.MaxTime = TimePoint.Decode(stream);
return decodedTimeBounds;
}
}
}
| 34.382353 | 91 | 0.553464 |
442d92e3b892724cd063343a3c14e7e350c1d09d | 1,502 | py | Python | ExercStrings14.py | marcelocmedeiros/ExerciciosComStrings | 1555b3a730394db5a4f7e4183cb617b15d529a09 | [
"MIT"
] | 1 | 2020-05-25T12:52:32.000Z | 2020-05-25T12:52:32.000Z | ExercStrings14.py | marcelocmedeiros/ExerciciosComStrings | 1555b3a730394db5a4f7e4183cb617b15d529a09 | [
"MIT"
] | null | null | null | ExercStrings14.py | marcelocmedeiros/ExerciciosComStrings | 1555b3a730394db5a4f7e4183cb617b15d529a09 | [
"MIT"
] | null | null | null | # Marcelo Campos de Medeiros
# ADS UNIFIP
# Exercicios Com Strings
# https://wiki.python.org.br/ExerciciosComStrings
'''
Leet spek generator. Leet é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras, como números por exemplo. A própria palavra leet admite muitas variações, como l33t ou 1337. O uso do leet reflete uma subcultura relacionada ao mundo dos jogos de computador e internet, sendo muito usada para confundir os iniciantes e afirmar-se como parte de um grupo. Pesquise sobre as principais formas de traduzir as letras. Depois, faça um programa que peça uma texto e transforme-o para a grafia leet speak.
'''
print('='*30)
print('{:*^30}'.format(' Leet spek generator '))
print('='*30)
print()
#primeiramente deve-se criar o dicióonario para cada letras do alfabeto e sua correspondente
leet = {
'A': '4',
'B': '8',
'C': '<',
'D': '[)',
'E': '&',
'F': 'ph',
'G': '6',
'H': '#',
'I': '1',
'J': 'j',
'K': '|<',
'L': '|_',
'M': '|\/|',
'N': '/\/',
'O': '0',
'P': '|*',
'Q': '9',
'R': 'l2',
'S': '5',
'T': '7',
'U': 'v',
'V': 'V',
'W': 'vv',
'X': '><',
'Y': '`/',
'Z': '2'
}
texto = input('Informe um texto: ')
print()
# usando for passar por cada letrar do texto e
for i in texto.upper():
# verificar se alfabetico o texto imprime seu correspondete valor
if i.isalpha():
print(leet[i], end='')
else:
print (' ')
print()
| 26.821429 | 529 | 0.579228 |
fdaa882fc546bef0c2351ef6ae08ae460edc484b | 15,775 | css | CSS | css/stylesheet.css | jakeoid/simple-dark-wanikani | abafe3b41fb8ea6cba402573ca8d185622691a34 | [
"MIT"
] | null | null | null | css/stylesheet.css | jakeoid/simple-dark-wanikani | abafe3b41fb8ea6cba402573ca8d185622691a34 | [
"MIT"
] | null | null | null | css/stylesheet.css | jakeoid/simple-dark-wanikani | abafe3b41fb8ea6cba402573ca8d185622691a34 | [
"MIT"
] | null | null | null | :root { --dark: #424242; --background: #212121; --light: #616161; --lightest: #757575; --body: #FFFFFF; --enabled: #64FFDA; --disabled: #F44336; --radicals: #00A1F1; --kanji: #F100A1; --vocabulary: #A100F1; }
.small-caps { color: inherit !important; }
.dashboard .lattice-single-character { background-image: none !important; }
.dashboard .lattice-single-character a { box-shadow: none !important; }
.progress { background: var(--dark); }
.progress .bar { background: var(--light) !important; }
[class*="-icon"] { box-shadow: none !important; border-radius: 2px; }
[class*="-icon"].kanji-icon { background: var(--kanji); }
[class*="-icon"].vocabulary-icon { background: var(--vocabulary); }
[class*="-icon"].radical-icon { background: var(--radicals); }
body, html { background: var(--background) !important; color: var(--body); }
h1, h2, h3, h4, h5, h6 { color: inherit; }
* { text-shadow: none !important; }
footer #hotkeys { background: var(--light); }
footer #hotkeys a { color: var(--body) !important; }
footer #hotkeys a:hover { color: var(--body) !important; }
.navbar-inner { background: var(--dark) !important; box-shadow: none !important; border: none !important; }
.navbar-inner * { text-shadow: none !important; }
div.navbar-inner li:not(.title) a span, div.navbar-inner li.title a span:first-child { border: none; border: 5px solid var(--light) !important; background-color: transparent !important; box-shadow: none !important; text-shadow: none !important; }
div.navbar:not(.navbar-fixed-top) div.navbar-inner li a span { width: 3.5em !important; height: 3.5em !important; }
div.navbar.navbar-fixed-top div.navbar-inner li.top { width: 40px !important; }
.nav li .dropdown-menu { background: var(--lightest) !important; }
.nav li .dropdown-menu:before, .nav li .dropdown-menu:after { border-bottom-color: var(--lightest) !important; }
.nav li .dropdown-menu a:hover { background: rgba(0, 0, 0, 0.1) !important; }
.nav li.dropdown.open.radicals .dropdown-toggle span { border-color: var(--radicals) !important; }
.nav li.dropdown.open.kanji .dropdown-toggle span { border-color: var(--kanji) !important; }
.nav li.dropdown.open.vocabulary .dropdown-toggle span { border-color: var(--vocabulary) !important; }
.nav li.dropdown.open .dropdown-toggle { box-shadow: none !important; background: var(--light) !important; }
.nav li.dropdown.open .dropdown-toggle span { border-color: var(--lightest) !important; }
div.navbar-inner li:not(.radicals):not(.kanji):not(.vocabulary) a { color: var(--body) !important; }
div.navbar-inner li:not(.open):hover.radicals a { color: var(--radicals) !important; }
div.navbar-inner li:not(.open):hover.kanji a { color: var(--kanji) !important; }
div.navbar-inner li:not(.open):hover.vocabulary a { color: var(--vocabulary) !important; }
div.navbar-inner li:not(.title):not(.account) a span, div.navbar-inner li:not(.title):not(.account) a span:hover { background-image: none !important; }
section.blog, section.forum-topics-list { display: none !important; }
header div.user-info { background: var(--dark) !important; color: var(--body) !important; box-shadow: none !important; }
header div.user-info div[class*=span] { color: #EEEEEE !important; }
.knowledge-distribution, .wall-of-shame { background: var(--background) !important; color: var(--body); }
.knowledge-distribution h3 span, .wall-of-shame h3 span { background: rgba(0, 0, 0, 0.1) !important; text-shadow: none !important; box-shadow: none !important; }
.knowledge-distribution .progress, .wall-of-shame .progress { background: var(--dark) !important; }
#reviews-summary, #lessons-summary { }
#reviews-summary header nav, #lessons-summary header nav { border: none !important; }
#reviews-summary header nav #back-dashboard, #lessons-summary header nav #back-dashboard { border: none !important; box-shadow: none !important; }
#reviews-summary header nav #review-queue-count, #lessons-summary header nav #review-queue-count { background: var(--dark) !important; }
#reviews-summary #review-stats [id*="review-stats-"], #reviews-summary .pure-g-r div.pure-u-1, #lessons-summary #review-stats [id*="review-stats-"], #lessons-summary .pure-g-r div.pure-u-1 { box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1) !important; background: var(--dark) !important; }
#reviews-summary #review-stats [id*="review-stats-"]:not(#review-stats-answered-correctly), #lessons-summary #review-stats [id*="review-stats-"]:not(#review-stats-answered-correctly) { background: var(--light) !important; }
#reviews-summary #review-stats-answered-correctly:after, #lessons-summary #review-stats-answered-correctly:after { border-color: transparent transparent transparent var(--dark) !important; }
#reviews-summary h3, #lessons-summary h3 { border-color: var(--light) !important; }
#reviews-summary h3 span, #lessons-summary h3 span { background: var(--dark) !important; color: #FFFFFF; }
#reviews-summary h3 span strong, #lessons-summary h3 span strong { background: var(--light) !important; }
#reviews-summary #radicals > div > ul > li, #reviews-summary #kanji > div > ul > li, #reviews-summary #vocabulary > div > ul > li, #reviews-summary .burn > ul > li, #reviews-summary .enlighten > ul > li, #reviews-summary .master > ul > li, #reviews-summary .guru > ul > li, #reviews-summary .apprentice > ul > li, #reviews-summary .guru > ul > li, #lessons-summary #radicals > div > ul > li, #lessons-summary #kanji > div > ul > li, #lessons-summary #vocabulary > div > ul > li, #lessons-summary .burn > ul > li, #lessons-summary .enlighten > ul > li, #lessons-summary .master > ul > li, #lessons-summary .guru > ul > li, #lessons-summary .apprentice > ul > li, #lessons-summary .guru > ul > li { box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.2) !important; }
#reviews-summary #radicals h2, #reviews-summary #radicals > div > ul > li.vocabulary, #lessons-summary #radicals h2, #lessons-summary #radicals > div > ul > li.vocabulary { background: var(--radicals) !important; }
#reviews-summary #vocabulary h2, #reviews-summary #vocabulary > div > ul > li.vocabulary, #lessons-summary #vocabulary h2, #lessons-summary #vocabulary > div > ul > li.vocabulary { background: var(--vocabulary) !important; }
#reviews-summary #kanji h2, #reviews-summary #kanji > div > ul > li.kanji, #lessons-summary #kanji h2, #lessons-summary #kanji > div > ul > li.kanji { background: var(--kanji) !important; }
#reviews #question #character, #lessons #question #character { box-shadow: none !important; }
#reviews #question #character.kanji, #lessons #question #character.kanji { background: var(--kanji) !important; }
#reviews #question #character.vocabulary, #lessons #question #character.vocabulary { background: var(--vocabulary) !important; }
#reviews #question #character.radical, #lessons #question #character.radical { background: var(--radical) !important; }
#reviews #question #question-type, #lessons #question #question-type { box-shadow: none !important; background: var(--light) !important; border-color: var(--light) !important; color: var(--body) !important; }
#reviews #answer-form input[type=text] span, #reviews #additional-content ul li span, #lessons #answer-form input[type=text] span, #lessons #additional-content ul li span { background: var(--light); color: var(--body) !important; box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.2); }
#reviews #answer-form input[type=text] span:hover:before, #reviews #additional-content ul li span:hover:before, #lessons #answer-form input[type=text] span:hover:before, #lessons #additional-content ul li span:hover:before { background: var(--lightest) !important; color: var(--body) !important; box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.2) !important; }
#reviews #answer-form input[type=text].active:before, #reviews #additional-content ul li.active:before, #lessons #answer-form input[type=text].active:before, #lessons #additional-content ul li.active:before { border-color: transparent transparent var(--lightest) transparent; }
#reviews #answer-form input[type=text].active span i, #reviews #additional-content ul li.active span i, #lessons #answer-form input[type=text].active span i, #lessons #additional-content ul li.active span i { color: #FFFFFF !important; }
#reviews #answer-form button, #lessons #answer-form button { background: var(--lightest); color: var(--body) !important; }
#reviews fieldset:not(.correct):not(.incorrect) input, #lessons fieldset:not(.correct):not(.incorrect) input { background: var(--lightest) !important; box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1); color: #FFFFFF !important; }
#reviews fieldset:not(.correct):not(.incorrect) button, #lessons fieldset:not(.correct):not(.incorrect) button { background: rgba(0, 0, 0, 0.1) !important; }
#reviews fieldset.correct input, #lessons fieldset.correct input { background: var(--enabled) !important; box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1); }
#reviews fieldset.correct button, #lessons fieldset.correct button { background: rgba(0, 0, 0, 0.2) !important; }
#reviews fieldset.incorrect input, #lessons fieldset.incorrect input { background: var(--disabled) !important; box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1); }
#reviews fieldset.incorrect button, #lessons fieldset.incorrect button { background: rgba(0, 0, 0, 0.2) !important; }
#reviews #information, #lessons #information { background: var(--lightest); box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.2) !important; }
#reviews #information:before, #lessons #information:before { border-color: transparent transparent var(--light) transparent; }
#reviews #information #item-info h2, #lessons #information #item-info h2 { color: #FFFFFF; border-bottom: 2px solid #FFFFFF; box-shadow: none !important; }
#reviews #information #item-info #related-items ul li a, #lessons #information #item-info #related-items ul li a { color: #FFFFFF; }
#reviews #information #item-info #related-items ul span, #lessons #information #item-info #related-items ul span { box-shadow: none !important; }
#reviews #information #item-info #all-info, #lessons #information #item-info #all-info { background: var(--light); color: #FFFFFF; }
#reviews #information .highlight-kanji, #lessons #information .highlight-kanji { background: var(--kanji); }
#reviews #information .highlight-radical, #lessons #information .highlight-radical { background: var(--radicals); }
#reviews #information .highlight-vocabulary, #lessons #information .highlight-vocabulary { background: var(--vocabulary); }
#main { }
#main section#timeln, #main section.review-status, #main section.srs-progress, #main section.progression, #main section.dashboard-sub-section { padding: 1rem; margin: 1rem 0rem; border: none !important; border-radius: 0px; width: calc(100% - 2rem); background: var(--dark); color: var(--body) !important; box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1); }
#main section#timeln *, #main section.review-status *, #main section.srs-progress *, #main section.progression *, #main section.dashboard-sub-section * { border: none; }
#main section#timeln span, #main section.review-status span, #main section.srs-progress span, #main section.progression span, #main section.dashboard-sub-section span { color: inherit; }
#main section#timeln #timeline, #main section.review-status #timeline, #main section.srs-progress #timeline, #main section.progression #timeline, #main section.dashboard-sub-section #timeline { width: 100%; }
#main section.srs-progress ul * { background-image: none !important; border-radius: 0px; box-shadow: none; }
#main #search #main-ico-search { color: #FFFFFF; }
#main #search form .search-query { border-radius: 0px; background: var(--dark); border: none; box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1); }
#main #timeln-graph .kan { fill: var(--kanji) !important; }
#main #timeln-graph .voc { fill: var(--vocabulary) !important; }
#main #timeln-graph .rad { fill: var(--radicals) !important; }
#main #timeln .link, #main g.label-y text, #main g.label-x text { color: var(--body); filL: var(--body); }
#main #timeline .grid .shadow { stroke: var(--body); }
#main #timeline .arrows .cur { stroke: var(--body); }
#main .selfstudy label { color: var(--body); }
#main .selfstudy .btn-group .btn { border: none; box-shadow: none; color: var(--body); background: var(--dark); height: 30px; }
#main .selfstudy .btn-group .btn.on { background: var(--enabled); }
#main .selfstudy .btn-group select { border-radius: 0px; -webkit-appearance: none; outline: none; }
#main .selfstudy .btn-group:last-child { margin: 0rem 1rem; }
#main .dashboard-sub-section h3, #main .dashboard-sub-section div.see-more { background: var(--light); border: none; box-shadow: none; border-radius: 2px; margin: .2rem 0rem; }
#main .none-available { background: var(--lightest); }
#main .none-available td { padding: 2rem 0rem; color: var(--body); }
#main .none-available td div { box-shadow: none; }
#main .kotoba-table-list tr[id|=vocabulary] { background: var(--vocabulary); }
#main .kotoba-table-list tr[id|=kanji] { background: var(--kanji); }
#main .kotoba-table-list tr[id|=radical] { background: var(--radicals); }
#main .additional-info, #main .page-list, #main section[id|=level] header { background: var(--dark) !important; color: var(--body) !important; }
#main .additional-info *, #main .page-list *, #main section[id|=level] header * { border: none; }
#main .additional-info ul li.page-list-header, #main .page-list ul li.page-list-header, #main section[id|=level] header ul li.page-list-header { display: none; }
#main .additional-info ul li a, #main .page-list ul li a, #main section[id|=level] header ul li a { background: var(--light); color: var(--body); }
#main .additional-info.additional-info.legend span, #main .page-list.additional-info.legend span, #main section[id|=level] header.additional-info.legend span { box-shadow: none; }
#main .additional-info h2, #main .additional-info h3, #main .page-list h2, #main .page-list h3, #main section[id|=level] header h2, #main section[id|=level] header h3 { color: #FFFFFF; }
#main ul.multi-character-grid li, #main ul.single-character-grid li { border: none; }
#main ul.multi-character-grid li:hover, #main ul.single-character-grid li:hover { box-shadow: none; }
#main ul.multi-character-grid li[id|=kanji], #main ul.single-character-grid li[id|=kanji] { background: var(--kanji); }
#main ul.multi-character-grid li[id|=vocabulary], #main ul.single-character-grid li[id|=vocabulary] { background: var(--vocabulary); }
#main ul.multi-character-grid li[id|=radical], #main ul.single-character-grid li[id|=radical] { background: var(--radicals); }
#main section.progression { color: var(--body); }
#main section.progression h3 { color: var(--body); }
#main section.progression div .chart .progress { padding: .2rem; border-radius: 2px; background: var(--light) !important; box-shadow: none !important; }
#main section.progression div .chart .progress .bar { border-radius: 2px; box-shadow: none !important; background: var(--lightest) !important; }
#main section.progression div .chart .progress .threshold { color: var(--body); }
#main section.progression .radicals-progress .chart .progress .bar { background: var(--radicals) !important; }
#main section.progression .kanji-progress .chart .progress .bar { background: var(--kanji) !important; }
#main section.progression .pct90 { background: var(--lightest); }
#loading, #additional-content-load { background-color: var(--light) !important; }
#answer-exception span { background: var(--lightest); box-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1); }
#answer-exception span:before { border-color: transparent transparent var(--light) transparent; }
.popover { box-shadow: none !important; width: 300px; }
#WKO_button { background: #F44336 !important; }
| 58.86194 | 751 | 0.7129 |
0afc016cb2ad600d0973d9fe36410b8fa969a4cb | 1,761 | cpp | C++ | src/TE_WeatherShield.cpp | systronix/TE_WeatherShield | 1a0526834fc64f567232da2ffcde968d144e2d66 | [
"MIT"
] | null | null | null | src/TE_WeatherShield.cpp | systronix/TE_WeatherShield | 1a0526834fc64f567232da2ffcde968d144e2d66 | [
"MIT"
] | null | null | null | src/TE_WeatherShield.cpp | systronix/TE_WeatherShield | 1a0526834fc64f567232da2ffcde968d144e2d66 | [
"MIT"
] | null | null | null | #include "TE_WeatherShield.h"
TEWeatherShield::TEWeatherShield(void) {}
void TEWeatherShield::begin(void) {
selectSensor(Sensor_NONE);
HTU21D.begin();
MS5637.begin();
MS8607.begin();
TSYS01.begin();
TSD305.begin();
}
void TEWeatherShield::selectSensor(enum TEWeatherShield_Sensor sensor) {
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
switch (sensor) {
case Sensor_HTU21D:
Serial.printf("Select HTU21D\n");
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
delay(5);
break;
case Sensor_MS5637:
Serial.printf("Select MS5637\n");
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, LOW);
delay(5);
break;
case Sensor_MS8607:
Serial.printf("Select MS8607\n");
digitalWrite(9, LOW);
digitalWrite(10, LOW);
digitalWrite(11, HIGH);
delay(5);
break;
case Sensor_TSYS01:
Serial.printf("Select TSYS01\n");
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
digitalWrite(11, LOW);
delay(5);
break;
case Sensor_TSD305:
Serial.printf("Select TSD305\n");
digitalWrite(9, LOW);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
delay(5);
break;
case Sensor_NONE:
Serial.printf("ERROR! Select Sensor_NONE: %u\n", sensor);
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
break;
}
}
void TEWeatherShield::selectHTU21D() { selectSensor(Sensor_HTU21D); }
void TEWeatherShield::selectMS5637() { selectSensor(Sensor_MS5637); }
void TEWeatherShield::selectMS8607() { selectSensor(Sensor_MS8607); }
void TEWeatherShield::selectTSYS01() { selectSensor(Sensor_TSYS01); }
void TEWeatherShield::selectTSD305() { selectSensor(Sensor_TSD305); }
| 23.797297 | 72 | 0.679727 |
74465c2e3d20236d4a5ce80d9ca2c1ebf709548b | 94 | css | CSS | no-styles/src/App.css | trickypr/Graphics-Library-Perfromance-Test | 04bdf60f6eb51d3938a67aef62dead6614d5aee6 | [
"Unlicense"
] | null | null | null | no-styles/src/App.css | trickypr/Graphics-Library-Perfromance-Test | 04bdf60f6eb51d3938a67aef62dead6614d5aee6 | [
"Unlicense"
] | null | null | null | no-styles/src/App.css | trickypr/Graphics-Library-Perfromance-Test | 04bdf60f6eb51d3938a67aef62dead6614d5aee6 | [
"Unlicense"
] | null | null | null | .card {
background-color: lightgrey;
border-radius: 5px;
padding: 5px;
width: 300px;
} | 15.666667 | 30 | 0.670213 |
6af449cc3cb0f6ca029ecfc0d0eb09ddf2200e2b | 405 | h | C | cocos2dx_playground/Classes/cpg_input_KeyCodeContainer.h | R2Road/cocos2dx_playground | 6e6f349b5c9fc702558fe8720ba9253a8ba00164 | [
"Apache-2.0"
] | 9 | 2020-06-11T17:09:44.000Z | 2021-12-25T00:34:33.000Z | cocos2dx_playground/Classes/cpg_input_KeyCodeContainer.h | R2Road/cocos2dx_playground | 6e6f349b5c9fc702558fe8720ba9253a8ba00164 | [
"Apache-2.0"
] | 9 | 2019-12-21T15:01:01.000Z | 2020-12-05T15:42:43.000Z | cocos2dx_playground/Classes/cpg_input_KeyCodeContainer.h | R2Road/cocos2dx_playground | 6e6f349b5c9fc702558fe8720ba9253a8ba00164 | [
"Apache-2.0"
] | 1 | 2020-09-07T01:32:16.000Z | 2020-09-07T01:32:16.000Z | #pragma once
#include <bitset>
#include "base/CCEventKeyboard.h"
namespace cpg_input
{
const std::size_t KeyCodeContainerFirst = static_cast<std::size_t>( cocos2d::EventKeyboard::KeyCode::KEY_NONE );
const std::size_t KeyCodeContainerSize = static_cast<std::size_t>( static_cast<int>( cocos2d::EventKeyboard::KeyCode::KEY_PLAY ) + 1 );
using KeyCodeContainerT = std::bitset<KeyCodeContainerSize>;
} | 31.153846 | 136 | 0.77284 |
791a7f47c2f0b616e5fbd32eb86c877278fbe891 | 105 | sql | SQL | src/test/resources/sql/create_view/94f0ebb3.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/create_view/94f0ebb3.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/create_view/94f0ebb3.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:create_view.sql ln:564 expect:true
create view tt21v as
select * from tt5 natural inner join tt6
| 26.25 | 42 | 0.780952 |
b021e0c4a52e54d910d75d6dd63819df8a4f07bd | 4,830 | py | Python | src/routinghub/tools/simple_api_client.py | routinghub/g-colab-tools | 6dafda1e9a4605154ded69b14531d3f5dad0a248 | [
"MIT"
] | null | null | null | src/routinghub/tools/simple_api_client.py | routinghub/g-colab-tools | 6dafda1e9a4605154ded69b14531d3f5dad0a248 | [
"MIT"
] | null | null | null | src/routinghub/tools/simple_api_client.py | routinghub/g-colab-tools | 6dafda1e9a4605154ded69b14531d3f5dad0a248 | [
"MIT"
] | null | null | null | import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
import json
import time
import sys
import logging
import copy
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, Tuple, Generator
def _setup_logger():
logger = logging.getLogger('api-client')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("[%(asctime)s]: %(message)s")
ch.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.handlers.clear()
logger.addHandler(ch)
logger.propagate = False
return logger
_logger = _setup_logger()
def _retryable_session():
s = requests.Session()
retries = Retry(total=10, backoff_factor=2)
s.mount('https://', HTTPAdapter(max_retries=retries))
return s
def _add_task(
request: Dict,
apikey: str,
apihost: str = 'routinghub.com',
api: str = 'routing',
api_version: str = 'v1-devel'
) -> Dict:
host = 'https://{}'.format(apihost)
endpoint = '{}/api/{}/{}'.format(host, api, api_version)
headers = {'Authorization': 'Bearer {}'.format(apikey)}
response = _retryable_session().post('{}/add'.format(endpoint),
data=json.dumps(request),
headers=headers)
return response
def get_task_result(
task_id: str,
apikey: str,
apihost: str = 'routinghub.com',
api: str = 'routing',
api_version: str = 'v1-devel'
) -> Dict:
host = 'https://{}'.format(apihost)
endpoint = '{}/api/{}/{}'.format(host, api, api_version)
headers = {'Authorization': 'Bearer {}'.format(apikey)}
response = _retryable_session().get('{}/result/{}'.format(endpoint, task_id),
headers=headers)
return response
def _call_one(
name: str,
request: Dict,
apikey: str,
apihost: str = 'routinghub.com',
api: str = 'routing',
api_version: str = 'v1-devel'
) -> Dict:
started_at = time.perf_counter()
response = _add_task(request, apikey, apihost, api, api_version)
resp_json = response.json()
if 'id' not in resp_json or 'status' not in resp_json or response.status_code >= 300:
raise Exception('Unexpected API response: code={} body={}'.format(response.status_code, response.text))
task_id = resp_json['id']
add_task_status = resp_json['status']
_logger.info('task={} submitted: id={} status={}'.format(name, task_id, add_task_status))
response = get_task_result(task_id, apikey,apihost, api, api_version)
while response.status_code not in (200, 500):
response = get_task_result(task_id, apikey, apihost, api, api_version)
time.sleep(5)
finished_at = time.perf_counter()
response_json = response.json()
elapsed = finished_at - started_at
_logger.info('task={} completed: status={}, elapsed={}s'.format(name, response_json['status'], elapsed))
return response_json
def _call_many(
named_requests: Dict[str, Dict],
apikey: str,
apihost: str = 'routinghub.com',
api: str = 'routing',
api_version: str = 'v1-devel',
max_workers: int = 4
) -> Generator[Tuple[str, Dict], None, None]:
results = {}
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures_names = {}
for name, request in named_requests.items():
future = executor.submit(_call_one, name, request, apikey, apihost, api, api_version)
futures_names[future] = name
for future in as_completed(futures_names):
name = futures_names[future]
try:
result = future.result()
except Exception as exc:
_logger.error("task={}: exception {}".format(name, exc))
else:
yield (name, result)
_logger.info("done")
def _is_completed(task_id, results):
if task_id in results:
result = results[task_id]
if 'status' in result and result['status'] in ('completed', 'cancelled'):
return True
return False
def _notify(title, message):
command = 'osascript -e \'display notification "{}" with title "{}"\''.format(message, title)
subprocess.run(command, shell=True)
command = 'osascript -e \'say "{}" speaking rate 190\''.format(message)
subprocess.run(command, shell=True)
def call_async(
tasks: Dict[str, Dict],
apikey: str,
apihost: str = 'routinghub.com',
api: str = 'routing',
api_version: str = 'v1-devel',
max_workers: int = 4,
notify = False
) -> Generator[Tuple[str, Dict], None, None]:
yield from _call_many(tasks, apikey, apihost, api, api_version, max_workers)
if notify:
_notify('Jupyter', 'Tasks completed')
| 29.814815 | 111 | 0.636232 |
b34c8254e6a4c5b3bccbe362d148a969042a5295 | 3,403 | py | Python | python/Brunel/_affiliations.py | brunels-network/kiosk | 580b3ed55dc40a7c3427343334bc541f0e5e945e | [
"MIT"
] | 3 | 2020-08-05T11:21:47.000Z | 2020-10-19T12:40:23.000Z | python/Brunel/_affiliations.py | brunels-network/kiosk | 580b3ed55dc40a7c3427343334bc541f0e5e945e | [
"MIT"
] | 8 | 2020-08-17T09:51:23.000Z | 2020-11-30T12:07:11.000Z | python/Brunel/_affiliations.py | brunels-network/kiosk | 580b3ed55dc40a7c3427343334bc541f0e5e945e | [
"MIT"
] | 2 | 2021-03-09T11:05:15.000Z | 2021-04-15T11:25:46.000Z |
from ._affiliation import Affiliation as _Affiliation
__all__ = ["Affiliations"]
def _generate_affiliation_uid():
import uuid as _uuid
uid = _uuid.uuid4()
return "A" + str(uid)[:7]
class Affiliations:
"""This holds a registry of individual
Affiliations
"""
def __init__(self, props=None, getHook=None):
self._getHook = getHook
self.state = {
"registry": {},
}
self._names = {}
self.load(props)
def add(self, affiliation: _Affiliation):
if affiliation is None:
return None
if isinstance(affiliation, str):
if len(affiliation) == 0:
return None
# try to find an existing affiliation with this name
try:
return self.getByName(affiliation)
except Exception:
return self.add(_Affiliation({"name": affiliation}))
if not isinstance(affiliation, _Affiliation):
raise TypeError("Can only add a Affiliation to Affiliations")
try:
return self.getByName(affiliation.getName())
except Exception:
pass
id = affiliation.getID()
if id:
if id in self.state["registry"]:
raise KeyError(f"Duplicate Affiliation ID {affiliation}")
self.state["registry"][id] = affiliation
else:
uid = _generate_affiliation_uid()
while uid in self.state["registry"]:
uid = _generate_affiliation_uid()
affiliation.state["id"] = uid
self.state["registry"][uid] = affiliation
affiliation._getHook = self._getHook
self._names[affiliation.getCanonical()] = affiliation.getID()
return affiliation
def getByName(self, name):
try:
return self.get(self._names[_Affiliation.makeCanonical(name)])
except Exception:
raise KeyError(f"No Affiliation with name {name}")
def find(self, value):
if isinstance(value, _Affiliation):
return self.get(value.getID())
value = value.lstrip().rstrip().lower()
results = []
for name in self._names.keys():
if name.lower().find(value) != -1:
results.append(self.get(self._names[name]))
if len(results) == 1:
return results[0]
elif len(results) > 1:
return results
keys = "', '".join(self._names.keys())
raise KeyError(f"No affiliation matches '{value}'. Available " +
f"affiliations are '{keys}'")
def get(self, id):
try:
return self.state["registry"][id]
except Exception:
raise KeyError(f"No Affiliation with ID {id}")
def load(self, data):
if data:
for item in data:
affiliation = _Affiliation.load(item)
self.add(affiliation)
def toDry(self):
return self.state
@staticmethod
def unDry(value):
affiliations = Affiliations()
affiliations.state = value
affiliations._names = {}
for affiliation in affiliations.state["registry"].values():
affiliations._names[affiliation.getCanonical()] = \
affiliation.getID()
return affiliations
| 27.007937 | 75 | 0.560094 |
ece3b375e4b0e0d9f9d7bd50e17c19d3e627f8b8 | 701 | rb | Ruby | app/controllers/gmm_controller.rb | ennder/admin_tools_ennder | 770282b55f0a4dba6c91cd4ae69e47ae3480bf5e | [
"MIT"
] | null | null | null | app/controllers/gmm_controller.rb | ennder/admin_tools_ennder | 770282b55f0a4dba6c91cd4ae69e47ae3480bf5e | [
"MIT"
] | null | null | null | app/controllers/gmm_controller.rb | ennder/admin_tools_ennder | 770282b55f0a4dba6c91cd4ae69e47ae3480bf5e | [
"MIT"
] | null | null | null | class GmmController < ApplicationController
def index
unless defined?(@all_models)
@@all_models = {}
# Load any model classes
Dir[Rails.root.to_s + '/app/models/**/*.rb'].each do |file|
begin
Rails.logger.info "GTM: loading #{file}"
require file
rescue
Rails.logger.error "GTM: Error loading #{file}"
end
# Store it in a class object
ActiveRecord::Base.descendants.each{|m|
@@all_models[m.name] = {
:has_many => m.reflect_on_all_associations(:has_many),
:has_one => m.reflect_on_all_associations(:has_one),
:belongs_to => m.reflect_on_all_associations(:belongs_to)
}
}
end
end
@all_models = @@all_models
end
end
| 25.035714 | 63 | 0.654779 |
6f03985660ba71f02f823c5b39a1aaeecdc54b3c | 587 | prc | SQL | Scripts/SP/SP-GLOBAL_VAR_CHANGE.prc | imbok-pro/IManServer | a42931bfbfab5c480280a7d4371c050e1b0b68b5 | [
"Apache-2.0"
] | null | null | null | Scripts/SP/SP-GLOBAL_VAR_CHANGE.prc | imbok-pro/IManServer | a42931bfbfab5c480280a7d4371c050e1b0b68b5 | [
"Apache-2.0"
] | null | null | null | Scripts/SP/SP-GLOBAL_VAR_CHANGE.prc | imbok-pro/IManServer | a42931bfbfab5c480280a7d4371c050e1b0b68b5 | [
"Apache-2.0"
] | null | null | null | CREATE OR REPLACE PROCEDURE SP.GLOBAL_VAR_CHANGE(pi_name IN VARCHAR2,
pi_value IN VARCHAR2)
AS
--pragma autonomous_transaction;
BEGIN
UPDATE sp.v_globals s SET s.S_VALUE = pi_value WHERE s.name = pi_name;
-- insert into sp.a1 values (pi_name||'; '||pi_value);
-- RAISE_APPLICATION_ERROR(-20555, 'ERRORRRR!!!');
-- commit;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20555, SQLERRM);
END;
/
grant EXECUTE on SP.GLOBAL_VAR_CHANGE to PUBLIC;
create or replace public synonym GLOBAL_VAR_CHANGE for SP.GLOBAL_VAR_CHANGE; | 32.611111 | 76 | 0.703578 |
8e7dcb58034800b7e390f3a3fa1193e8913cd59b | 1,948 | js | JavaScript | js-aplication 2022/Routing/07. JS-Applications-Routing-Exercise-Resources (1)/01.Furniture/src/app.js | desislava-deneva/SoftUni | 47ef259ad2314f72ad30f470811cef4093b6a743 | [
"MIT"
] | 1 | 2022-02-13T22:20:32.000Z | 2022-02-13T22:20:32.000Z | js-aplication 2022/Routing/07. JS-Applications-Routing-Exercise-Resources (1)/01.Furniture/src/app.js | desislava-deneva/SoftUni | 47ef259ad2314f72ad30f470811cef4093b6a743 | [
"MIT"
] | null | null | null | js-aplication 2022/Routing/07. JS-Applications-Routing-Exercise-Resources (1)/01.Furniture/src/app.js | desislava-deneva/SoftUni | 47ef259ad2314f72ad30f470811cef4093b6a743 | [
"MIT"
] | null | null | null | import page from "../node_modules/page/page.mjs";
import { render } from "../node_modules/lit-html/lit-html.js";
import { createView } from "./pages/create.js";
import { dashboardView, myFurnitureView } from "./pages/dashboard.js";
import { detailsView } from "./pages/details.js";
import { editView } from "./pages/edit.js";
import { loginView } from "./pages/login.js";
import { registerView } from "./pages/register.js";
import { logout } from "./utils/apiService.js";
//debug
// import * as api from "./utils/dataService.js";
// window.api = api;
//debug
const root = document.querySelector(".container");
page("/", "/dashboard");
page("/create", decoContext, createView);
page("/dashboard", decoContext, dashboardView);
page("/details/:id", decoContext, detailsView);
page("/edit/:id", decoContext, editView);
page("/login", decoContext, loginView);
page("/register", decoContext, registerView);
page("/my-furniture", decoContext, myFurnitureView);
//done
setUserNav();
page.start();
function decoContext(ctx, next) {
ctx.render = (content) => render(content, root);
ctx.setUserNav = () => setUserNav();
setNavActive(ctx);
// console.log(ctx);
// console.log(ctx.routePath);
next();
}
function setUserNav() {
const userId = localStorage.getItem("userId");
if (userId !== null) {
document.querySelector("#user").style.display = "inline-block";
document.querySelector("#guest").style.display = "none";
} else {
document.querySelector("#user").style.display = "none";
document.querySelector("#guest").style.display = "inline-block";
}
}
function setNavActive(ctx) {
[...document.querySelectorAll("header a")].forEach((a) => {
a.classList.remove("active");
if (a.href.includes(ctx.routePath)) {
a.classList.add("active");
}
});
}
document.querySelector("#logoutBtn").addEventListener("click", async () => {
await logout();
setUserNav();
page.redirect("/dashboard");
});
| 27.828571 | 76 | 0.674538 |
72603196d887b2a38e05ce75100789d8c7fae771 | 835 | h | C | Modbus Poll/CVcAxisGrid.h | DHSERVICE56/T3000_Building_Automation_System | 77bd47a356211b1c8ad09fb8d785e9f880d3cd26 | [
"MIT"
] | 1 | 2019-12-11T05:14:08.000Z | 2019-12-11T05:14:08.000Z | Modbus Poll/CVcAxisGrid.h | DHSERVICE56/T3000_Building_Automation_System | 77bd47a356211b1c8ad09fb8d785e9f880d3cd26 | [
"MIT"
] | null | null | null | Modbus Poll/CVcAxisGrid.h | DHSERVICE56/T3000_Building_Automation_System | 77bd47a356211b1c8ad09fb8d785e9f880d3cd26 | [
"MIT"
] | 1 | 2021-05-31T18:56:31.000Z | 2021-05-31T18:56:31.000Z | // CVcAxisGrid.h : Declaration of ActiveX Control wrapper class(es) created by Microsoft Visual C++
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CVcAxisGrid
class CVcAxisGrid : public COleDispatchDriver
{
public:
CVcAxisGrid() {} // Calls COleDispatchDriver default constructor
CVcAxisGrid(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CVcAxisGrid(const CVcAxisGrid& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
LPDISPATCH get_MinorPen()
{
LPDISPATCH result;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
LPDISPATCH get_MajorPen()
{
LPDISPATCH result;
InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
};
| 23.194444 | 100 | 0.686228 |
3e2f2b043e8d59058806a3abbfd7670edd2a906d | 686 | lua | Lua | grpc-gateway/polyfill.lua | kmasuda050/lua-resty-grpc-gateway | db0be83cef8a3a9805f673057d1302c90510470f | [
"MIT"
] | 83 | 2019-04-27T06:13:13.000Z | 2022-03-29T11:13:01.000Z | grpc-gateway/polyfill.lua | kmasuda050/lua-resty-grpc-gateway | db0be83cef8a3a9805f673057d1302c90510470f | [
"MIT"
] | 30 | 2019-08-01T12:28:44.000Z | 2022-02-26T10:33:51.000Z | grpc-gateway/polyfill.lua | kmasuda050/lua-resty-grpc-gateway | db0be83cef8a3a9805f673057d1302c90510470f | [
"MIT"
] | 14 | 2019-05-21T10:33:14.000Z | 2021-11-19T09:00:52.000Z | return function()
-- nginx's gRPC proxy supports only grpcweb protocol whose request body accepts only binary proto format.
-- So if user requests with 'Content-Type: application/grpc-web-text', we need to decode request body as binary.
if ngx.req.get_headers()["Content-Type"] == "application/grpc-web-text" then
ngx.req.read_body()
local body = ngx.req.get_body_data()
local decoded, err = ngx.decode_base64(body)
if err then
ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
ngx.say("Failed to decode base64 body for grpc-web-text protocol")
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
return
end
ngx.req.set_body_data(decoded)
end
end
| 40.352941 | 114 | 0.723032 |
437b4b2d54951c4fb2080f96534d5a30db321709 | 159 | ts | TypeScript | lib/components/input/file-input/index.d.ts | mowcixo/ontimize-web-ngx-compiled | a100031f3fc1a50171a60e795b35aa1a26de9a99 | [
"Apache-2.0"
] | 27 | 2017-12-13T19:21:26.000Z | 2022-01-06T10:15:13.000Z | lib/components/input/file-input/index.d.ts | mowcixo/ontimize-web-ngx-compiled | a100031f3fc1a50171a60e795b35aa1a26de9a99 | [
"Apache-2.0"
] | 383 | 2017-09-28T14:14:00.000Z | 2022-03-31T19:06:09.000Z | lib/components/input/file-input/index.d.ts | mowcixo/ontimize-web-ngx-compiled | a100031f3fc1a50171a60e795b35aa1a26de9a99 | [
"Apache-2.0"
] | 17 | 2017-09-28T08:46:42.000Z | 2021-02-25T14:46:50.000Z | export * from './o-file-input.component';
export * from './o-file-input.module';
export * from './o-file-item.class';
export * from './o-file-uploader.class';
| 31.8 | 41 | 0.672956 |
2c6af1dce835a72fb2354a5e8c77ab11723b897b | 1,858 | py | Python | app_backend/forms/futures.py | zhanghe06/bearing_project | 78a20fc321f72d3ae05c7ab7e52e01d02904e3fc | [
"MIT"
] | 1 | 2020-06-21T04:08:26.000Z | 2020-06-21T04:08:26.000Z | app_backend/forms/futures.py | zhanghe06/bearing_project | 78a20fc321f72d3ae05c7ab7e52e01d02904e3fc | [
"MIT"
] | 13 | 2019-10-18T17:19:32.000Z | 2022-01-13T00:44:43.000Z | app_backend/forms/futures.py | zhanghe06/bearing_project | 78a20fc321f72d3ae05c7ab7e52e01d02904e3fc | [
"MIT"
] | 5 | 2019-02-07T03:15:16.000Z | 2021-09-04T14:06:28.000Z | #!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: futures.py
@time: 2019-08-13 22:39
"""
from __future__ import unicode_literals
from flask_babel import lazy_gettext as _
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, SelectField, DateField
from wtforms.validators import Optional
from app_common.maps.default import DEFAULT_SEARCH_CHOICES_STR_OPTION
class FuturesSearchForm(FlaskForm):
production_brand = SelectField(
_('production brand'),
validators=[], # 字符类型,非必填
default=DEFAULT_SEARCH_CHOICES_STR_OPTION,
description=_('production brand'),
render_kw={
'rel': 'tooltip',
'title': _('production brand'),
}
)
production_model = StringField(
_('production model'),
validators=[],
description=_('production model'),
render_kw={
'placeholder': _('production model'),
'rel': 'tooltip',
'title': _('production model'),
'autocomplete': 'off',
}
)
req_date = DateField(
_('req date'),
validators=[Optional()],
description=_('req date'),
render_kw={
'placeholder': _('req date'),
'type': 'date',
'rel': 'tooltip',
'title': _('req date'),
}
)
acc_date = DateField(
_('acc date'),
validators=[Optional()],
description=_('acc date'),
render_kw={
'placeholder': _('acc date'),
'type': 'date',
'rel': 'tooltip',
'title': _('acc date'),
}
)
op = IntegerField(
_('Option'),
validators=[],
default=0,
)
page = IntegerField(
_('page'),
validators=[],
default=1,
)
| 24.773333 | 69 | 0.550592 |
392d93ea655503631517cafb1d414ece592a2aa4 | 1,292 | py | Python | tests/pytests/unit/netapi/saltnado/test_base_handler.py | haodeon/salt | af2964f4ddbf9c5635d1528a495e473996cc7b71 | [
"Apache-2.0"
] | null | null | null | tests/pytests/unit/netapi/saltnado/test_base_handler.py | haodeon/salt | af2964f4ddbf9c5635d1528a495e473996cc7b71 | [
"Apache-2.0"
] | null | null | null | tests/pytests/unit/netapi/saltnado/test_base_handler.py | haodeon/salt | af2964f4ddbf9c5635d1528a495e473996cc7b71 | [
"Apache-2.0"
] | null | null | null | import time
import pytest
import salt.netapi.rest_tornado.saltnado as saltnado_app
from tests.support.mock import MagicMock, patch
@pytest.fixture
def arg_mock():
mock = MagicMock()
mock.opts = {
"syndic_wait": 0.1,
"cachedir": "/tmp/testing/cachedir",
"sock_dir": "/tmp/testing/sock_drawer",
"transport": "zeromq",
"extension_modules": "/tmp/testing/moduuuuules",
"order_masters": False,
"gather_job_timeout": 10.001,
}
return mock
def test__verify_auth(arg_mock):
base_handler = saltnado_app.BaseSaltAPIHandler(arg_mock, arg_mock)
with patch.object(base_handler, "get_cookie", return_value="ABCDEF"):
with patch.object(
base_handler.application.auth,
"get_tok",
return_value={"expire": time.time() + 60},
):
assert base_handler._verify_auth()
def test__verify_auth_expired(arg_mock):
base_handler = saltnado_app.BaseSaltAPIHandler(arg_mock, arg_mock)
with patch.object(base_handler, "get_cookie", return_value="ABCDEF"):
with patch.object(
base_handler.application.auth,
"get_tok",
return_value={"expire": time.time() - 60},
):
assert not base_handler._verify_auth()
| 30.046512 | 73 | 0.647059 |
dabb0a5d22eeab48a5645e63d3dfe176e49dd004 | 2,140 | dart | Dart | lib/src/models/expression_model.dart | Le127/calculator_app | 604891546cc1632f73e12e9678484bf24e9b3132 | [
"0BSD"
] | null | null | null | lib/src/models/expression_model.dart | Le127/calculator_app | 604891546cc1632f73e12e9678484bf24e9b3132 | [
"0BSD"
] | null | null | null | lib/src/models/expression_model.dart | Le127/calculator_app | 604891546cc1632f73e12e9678484bf24e9b3132 | [
"0BSD"
] | 1 | 2021-12-10T15:39:01.000Z | 2021-12-10T15:39:01.000Z | import 'package:flutter/material.dart';
import 'package:math_expressions/math_expressions.dart' as me;
import 'package:calculator_app/src/helpers/functions.dart';
class ExpressionModel extends ChangeNotifier {
String _expression = "";
bool _expressionError = false;
TextEditingController _controller = TextEditingController();
String _textError = 'Error';
bool _wasEvaluate = false;
String get expression => this._expression;
bool get expressionError => this._expressionError;
TextEditingController get controller => this._controller;
String get textError => this._textError;
void addToExpression(String value) {
this.expression = _buildNewExpression(value);
_wasEvaluate = false;
}
// Allows you to continue a calculation or start a new one
String _buildNewExpression(String value) {
if (!_wasEvaluate) {
return "${this._expression}$value";
} else if (_wasEvaluate &&
(value == '*' ||
value == '/' ||
value == '-' ||
value == '+' ||
value == '^')) {
return "${this._expression}$value";
} else {
return value;
}
}
set expression(String value) {
_expression = value;
_controller.text = value;
_controller.selection = TextSelection.collapsed(offset: value.length);
_wasEvaluate = false;
notifyListeners();
}
set expressionError(bool value) {
_expressionError = value;
notifyListeners();
}
void evaluate() {
try {
me.Expression e = me.Parser().parse(this._expression);
double result = e.evaluate(
me.EvaluationType.REAL,
me.ContextModel(),
);
this.expression = removeZeroDecimal(result.toString());
_wasEvaluate = true;
_expressionError = false;
} catch (error) {
_expressionError = true;
}
}
String result() {
try {
me.Expression e = me.Parser().parse(this._expression);
double result = e.evaluate(
me.EvaluationType.REAL,
me.ContextModel(),
);
return (removeZeroDecimal(result.toString()));
} catch (error) {
return _textError;
}
}
}
| 26.75 | 74 | 0.640654 |
b0fdda3ba1996ccb5054d8fa4862ebad666e12c0 | 1,737 | py | Python | dd/api/workflow/sql.py | octo-technology/ddapi | 08b56016bf59a02c42d79a117a8de1e23e5b4f90 | [
"Apache-2.0"
] | 4 | 2019-06-09T13:15:37.000Z | 2020-12-22T08:37:36.000Z | dd/api/workflow/sql.py | octo-technology/ddapi | 08b56016bf59a02c42d79a117a8de1e23e5b4f90 | [
"Apache-2.0"
] | null | null | null | dd/api/workflow/sql.py | octo-technology/ddapi | 08b56016bf59a02c42d79a117a8de1e23e5b4f90 | [
"Apache-2.0"
] | null | null | null | from dd.api.workflow.actions import Action
from .callables import QueryCallableBuilder, ActionCallableBuilder
class SQLOperator(object):
def __init__(self, context, dataset):
self.context = context
self.parent_dataset = dataset
def query(self, query, output_table=None, create_table=False, if_exists='replace'):
"""
Returns a new Dataset representing the result of a query.
Args:
query: the query to be executed in the database
output_table: the name of the table where the result will be
stored. If not provided, a name is generated for you.
create_table: if True, a new table is created directly in SQL, the pandas is lazy
if_exists: if table exists then the default is to 'replace'
Returns:
A new Dataset
"""
from .dataset import DatasetTransformation
callable_builder = (QueryCallableBuilder(self.context, create_table=create_table, if_exists=if_exists)
.with_query(query))
return DatasetTransformation(self.parent_dataset, self.context,
callable_builder, output_table)
def execute(self, query):
def execute_with_context(dataset, query):
# Ignores first argument passed from the parent dataset
# (see closure 'run' in .callables.ActionCallableBuilder.build())
self.context._execute(query)
callable_builder = (ActionCallableBuilder(self.context)
.with_operation(execute_with_context)
.with_kwargs(query=query))
return Action(self.context, callable_builder, self.parent_dataset)
| 43.425 | 110 | 0.647093 |
583ce622a92e4f3a706ed81259915285533fe128 | 318 | css | CSS | src/pages/404.module.css | kac2016/opensource | 741a1a1a1358c427ff135e3217ee68ad05878379 | [
"MIT"
] | 1 | 2020-04-18T17:20:48.000Z | 2020-04-18T17:20:48.000Z | src/pages/404.module.css | kac2016/opensource | 741a1a1a1358c427ff135e3217ee68ad05878379 | [
"MIT"
] | null | null | null | src/pages/404.module.css | kac2016/opensource | 741a1a1a1358c427ff135e3217ee68ad05878379 | [
"MIT"
] | 1 | 2021-07-25T06:48:13.000Z | 2021-07-25T06:48:13.000Z | @value small from "../styles/breakpoints.module.css";
.section {
composes: container from '../styles/grid.module.css';
height: 600px;
display: flex;
align-items: center;
}
.hero {
font-weight: 700;
font-size: 48px;
}
.subHero {
font-size: 24px;
}
@media small {
.section {
height: 500px;
}
}
| 13.25 | 55 | 0.632075 |
446024276a116a6e7ab7bf8d18e434086f202925 | 826 | py | Python | examples/practice/students_manager/practice04.py | zhangdapeng520/zdppy_mysql | de3a0d94a87825d60869141893d45cca27c8cedf | [
"MIT"
] | null | null | null | examples/practice/students_manager/practice04.py | zhangdapeng520/zdppy_mysql | de3a0d94a87825d60869141893d45cca27c8cedf | [
"MIT"
] | null | null | null | examples/practice/students_manager/practice04.py | zhangdapeng520/zdppy_mysql | de3a0d94a87825d60869141893d45cca27c8cedf | [
"MIT"
] | 1 | 2022-02-20T23:14:10.000Z | 2022-02-20T23:14:10.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/3/7 23:26
# @Author : 张大鹏
# @Site :
# @File : practice01.py
# @Software: PyCharm
from zdppy_mysql import Mysql
import json
m = Mysql(db="test")
# 查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩(没成绩的显示为null)
sql = """
select student.SId,student.Sname,t1.sumscore,t1.coursecount
from student ,(
select SC.SId,sum(sc.score) as sumscore ,count(sc.CId) as coursecount
from sc
GROUP BY sc.SId) as t1
where student.SId =t1.SId
"""
m.log.info(m.fetchall(sql))
m.log.info(m.fetchall(sql, to_json=True))
print("--------------------------------")
# 查有成绩的学生信息
sql = """
select *
from student
where EXISTS(select * from sc where student.SId=sc.SId)
"""
m.log.info(m.fetchall(sql))
m.log.info(m.fetchall(sql, to_json=True))
print("--------------------------------")
| 22.324324 | 73 | 0.622276 |
018ce0cd2de61b343fe8bcf3cb6669a747541af6 | 79 | rb | Ruby | app/models/spree/promese_order_decorator.rb | peterberkenbosch/spree_promese | 2bf15a1628398a682069d9f3b5bcef46ea50ec4c | [
"BSD-3-Clause"
] | null | null | null | app/models/spree/promese_order_decorator.rb | peterberkenbosch/spree_promese | 2bf15a1628398a682069d9f3b5bcef46ea50ec4c | [
"BSD-3-Clause"
] | null | null | null | app/models/spree/promese_order_decorator.rb | peterberkenbosch/spree_promese | 2bf15a1628398a682069d9f3b5bcef46ea50ec4c | [
"BSD-3-Clause"
] | 1 | 2020-12-22T12:42:52.000Z | 2020-12-22T12:42:52.000Z | module PromeseOrderDecorator
end
Spree::Order.prepend(PromeseOrderDecorator)
| 13.166667 | 43 | 0.860759 |
447d3663a31b1d15fced0d43cf268e47627e1ca7 | 2,504 | py | Python | test/app-client/batch_files/run_application.py | susanwab/elijah-provisioning | 6364f1e6c6c802033df71999435d7f7dc03ad2b6 | [
"Apache-2.0"
] | 19 | 2015-01-18T23:37:18.000Z | 2019-10-16T15:53:29.000Z | test/app-client/batch_files/run_application.py | susanwab/elijah-provisioning | 6364f1e6c6c802033df71999435d7f7dc03ad2b6 | [
"Apache-2.0"
] | 5 | 2016-06-09T15:08:51.000Z | 2018-05-07T17:45:01.000Z | test/app-client/batch_files/run_application.py | susanwab/elijah-provisioning | 6364f1e6c6c802033df71999435d7f7dc03ad2b6 | [
"Apache-2.0"
] | 15 | 2015-02-02T11:08:14.000Z | 2020-03-24T14:22:50.000Z | #!/usr/bin/env python
#
# Cloudlet Infrastructure for Mobile Computing
#
# Author: Kiryong Ha <[email protected]>
#
# Copyright (C) 2011-2013 Carnegie Mellon University
# 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.
#
import sys
from optparse import OptionParser
import time
import cloudlet_client
application_names = ["moped", "face", "graphics", "speech", "mar", "null", "webserver"]
def process_command_line(argv):
global command_type
global application_names
parser = OptionParser(usage="usage: ./run_application.py -a [app_name]" ,\
version="Desktop application client")
parser.add_option(
'-a', '--app', action='store', type='string', dest='app',
help="Set Application name among (%s)" % ",".join(application_names))
settings, args = parser.parse_args(argv)
if not len(args) == 0:
parser.error('program takes no command-line arguments; "%s" ignored.' % (args,))
if not settings.app:
parser.error("Application name is required among (%s)" % ' '.join(application_names))
return settings, args
def main(argv=None):
global command_type
global cloudlet_server_ip
global cloudlet_server_port
global is_stop_thread
global last_average_power
app_start_time = time.time()
settings, args = process_command_line(sys.argv[1:])
# run application
while True:
# Try to connect to Server program at VM until it gets some data
ret, output_file = cloudlet_client.run_application(settings.app)
if ret == 0:
break;
else:
print "waiting for client connection"
time.sleep(0.1)
app_end_time = time.time()
application_run_time = app_end_time-app_start_time
print "application run time: %f\n" % (application_run_time)
return 0
if __name__ == "__main__":
try:
status = main()
sys.exit(status)
except KeyboardInterrupt:
is_stop_thread = True
sys.exit(1)
| 31.696203 | 93 | 0.678115 |
d03813c0a96da1a770e70bf10fc0e8e94b666430 | 1,913 | hpp | C++ | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | 1 | 2021-05-19T06:35:15.000Z | 2021-05-19T06:35:15.000Z | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | null | null | null | C++ Development Root/SourceCode/Domain/Subscription/SubscriptionHandler.hpp | Dpham181/CPSC-462-GROUP-2 | 36f55ec4980e2e98d58f1f0a63ecc5070d7faa47 | [
"MIT"
] | null | null | null | #pragma once
#include <any>
#include <memory> // unique_ptr
#include <stdexcept> // runtime_error
#include <string>
#include <vector> // domain_error, runtime_error
#include "TechnicalServices/Persistence/PersistenceHandler.hpp"
namespace Domain::Subscription
{
using TechnicalServices::Persistence::UserCredentials;
using TechnicalServices::Persistence::Subcripstion;
using TechnicalServices::Persistence::PaymentOption;
using TechnicalServices::Persistence::SubscriptionStatus;
using TechnicalServices::Persistence::Paid;
// Product Package within the Domain Layer Abstract class
class SubscriptionHandler
{
public:
static std::unique_ptr<SubscriptionHandler> MaintainSubscription( const UserCredentials& User);
// Operations menu
virtual std::vector<std::string> getCommandsSubscription() =0; // retrieves the list of actions (commands)
virtual std::any executeCommandSubscription(const std::string& command, const std::vector<std::string>& args) =0; // executes one of the actions retrieved
// Operations of Maintain Subscription
// default operations
virtual SubscriptionStatus viewSubscriptionStatus() = 0 ;
virtual std::vector<PaymentOption> selectSubscription(const int SelectedId) = 0;
virtual std::string completePayment() = 0;
virtual bool verifyPaymentInformation( const std::string CCnumber, const int CVCnumber) = 0;
virtual ~SubscriptionHandler() noexcept = 0;
protected:
// Copy assignment operators, protected to prevent mix derived-type assignments
SubscriptionHandler&
operator=( const SubscriptionHandler& rhs ) = default; // copy assignment
SubscriptionHandler& operator=(SubscriptionHandler&& rhs ) = default; // move assignment
}; // class SubscriptionHandler
} // namespace Domain:: Subscription
| 39.854167 | 177 | 0.723471 |
a4e810e15236677de32383bb19e5034727725510 | 112 | sql | SQL | skysign-db/remote-communication-db/missions.sql | Tomofiles/skysign_cloud_v2 | acccf3552511d67ddf6284846e762d17c2aebb84 | [
"MIT"
] | 7 | 2020-08-03T02:28:16.000Z | 2022-02-25T11:03:06.000Z | skysign-db/remote-communication-db/missions.sql | Tomofiles/skysign_cloud_v2 | acccf3552511d67ddf6284846e762d17c2aebb84 | [
"MIT"
] | 23 | 2020-07-19T08:38:06.000Z | 2021-09-21T08:19:06.000Z | skysign-db/remote-communication-db/missions.sql | Tomofiles/skysign_cloud_v2 | acccf3552511d67ddf6284846e762d17c2aebb84 | [
"MIT"
] | null | null | null | CREATE TABLE missions (
id character varying(36) NOT NULL,
CONSTRAINT missions_pkey PRIMARY KEY (id)
);
| 22.4 | 45 | 0.723214 |
f47c7434059b16716c1061ea4aa2932da955afb7 | 7,044 | ts | TypeScript | ng-moon/src/share/components/group/group.component.ts | ng-nest/zero-moon | 1bf67a276ab0e2a76990ba1e587d78f0dfe019c0 | [
"MIT"
] | 90 | 2019-02-25T14:30:50.000Z | 2021-11-12T13:13:25.000Z | ng-moon/src/share/components/group/group.component.ts | ng-nest/zero-moon | 1bf67a276ab0e2a76990ba1e587d78f0dfe019c0 | [
"MIT"
] | 9 | 2020-04-19T00:15:40.000Z | 2022-02-12T07:30:43.000Z | ng-moon/src/share/components/group/group.component.ts | isonz/ng-nest-moon | c4625e6b32b672fe81bd102cb76cacd93538b033 | [
"MIT"
] | 21 | 2019-02-14T15:58:48.000Z | 2021-11-05T08:44:04.000Z | import {
Component, OnInit, Inject, ElementRef, Renderer2, ViewChild, TemplateRef, ViewEncapsulation
} from '@angular/core';
import { GROUPOPTION, GroupOption, GroupItem } from './group.type';
import * as _ from 'lodash';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { FormComponent } from '../form/form.component';
import { Subject } from 'rxjs';
import { ModalService } from '../modal/modal.service';
import { OverlayRef } from '@angular/cdk/overlay';
import { InputControl, Row } from '../form/form.type';
import { SettingService } from 'src/services/setting.service';
@Component({
selector: 'nm-group',
templateUrl: './group.component.html',
styleUrls: ['./group.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class GroupComponent implements OnInit {
_data: GroupItem[] = [
// {
// id: '1', label: '默认', data: [
// { id: "acd028a6-15b5-376a-dd22-ea25904af3e6", label: "账号" },
// { id: "7da73d57-8776-814b-dbb4-dd96a1f00c01", label: "密码" },
// { id: "af2817b0-2f9c-4125-c79b-3495e2953df5", label: "姓名" },
// { id: "8300d947-c1df-bd06-945d-4131bcc70acf", label: "邮箱" },
// { id: "acd028a6-15b5-376a-dd22-ea25904af3e6", label: "账号" },
// { id: "7da73d57-8776-814b-dbb4-dd96a1f00c01", label: "密码" },
// { id: "af2817b0-2f9c-4125-c79b-3495e2953df5", label: "姓名" },
// { id: "a04b47d6-2f48-915f-aa9d-89c4b71dac49", label: "手机号" }
// ]
// },
// {
// id: '2', label: '分组1', data: [
// { id: "a04b47d6-2f48-915f-aa9d-89c4b712223", label: "照片" }
// ]
// },
// {
// id: '3', label: '分组2', data: [
// { id: "a04b47d6-2f48-915f-aa9d-89c4b7133c49", label: "头像" }
// ]
// }
];
@ViewChild("formTemp") formTemp: TemplateRef<any>;
formCom: FormComponent;
@ViewChild("formCom") set _formCom(val) {
this.formCom = val;
}
private _default: GroupOption = {
panelClass: 'group'
};
submitSubject = new Subject();
cancelSubject = new Subject();
modal: OverlayRef;
select: GroupItem;
group: GroupItem;
liDashed: Element;
constructor(
@Inject(GROUPOPTION) public option: GroupOption,
private ele: ElementRef,
private renderer: Renderer2,
private setting: SettingService,
private modalService: ModalService
) { }
ngOnInit() {
this.setting.mapToObject(this._default, this.option);
this.setData();
this.setForm();
this.subject();
}
action(type, item?) {
switch (type) {
case 'add':
this.modal = this.modalService.create(this.option.addGroupOption);
setTimeout(() => this.formCom.form.reset())
break;
case 'close':
this.option.detach();
break;
case 'submit':
if (this.option.submitSubject) this.option.submitSubject.next(this.dataToResult(this._data));
this.action('close');
break;
case 'closeGroup':
if (this.modal) { this.modal.detach(); }
break;
case 'updateGroup':
this.modal = this.modalService.create(this.option.addGroupOption)
setTimeout(() => {
this.formCom.form.reset()
this.formCom.form.patchValue(item)
})
break;
case 'deleteGroup':
let remove = _.first(_.remove(this._data, (x: any) => x.id === item.id));
let first = _.first(this._data);
first.data = _.union(first.data, remove.data)
break;
}
}
subject() {
this.submitSubject.subscribe((x: GroupItem) => {
if (typeof x.data === 'undefined') x.data = [];
if (_.isEmpty(x.id)) {
x.id = this.setting.guid();
this._data.push(x);
} else {
delete x.data;
Object.assign(_.find(this._data, y => y.id === x.id), x)
}
this.action('closeGroup')
})
this.cancelSubject.subscribe(() => {
this.action('closeGroup')
})
}
setForm() {
if (!this.option.addGroupOption) {
this.option.addGroupOption = {
panelClass: 'form',
title: '分组',
templateRef: this.formTemp,
width: 300,
form: {
controls: [
new Row({
hide: true, controls: [
new InputControl({ key: "id", label: "编号" })
]
}),
new Row({
controls: [
new InputControl({ key: "label", label: "名称", col: 6 }),
new InputControl({ key: "icon", label: "图标", col: 6 })
]
})
]
}
}
}
this.option.addGroupOption.form.buttons = [
{ type: 'submit', handler: this.submitSubject },
{ type: 'cancel', handler: this.cancelSubject }
];
}
setData() {
if (this.option.data instanceof Array) {
this._data = this.formatData(this.option.data);
}
}
formatData(list: GroupItem[]) {
let defaultGroup: GroupItem = { id: this.setting.guid(), label: "默认", icon: "icon-navigation-2" }
let group = _.groupBy(list, x => {
if (!x.group) x.group = defaultGroup
return x.group.id
})
let result = _.map(group, (x, i) => {
if (x.length > 0) {
let groupItem = x[0].group;
groupItem.data = x;
return groupItem;
}
})
if (result.length === 1) { result.push({ id: this.setting.guid(), label: "分组1", data: [], icon: "icon-navigation-2" }) }
return result;
}
dataToResult(list: GroupItem[]) {
let result: GroupItem[] = [];
_.map(list, x => {
let group = _.cloneDeep(x);
delete group.data;
_.map(x.data, y => {
y.group = group
result.push(y);
})
})
return result
}
dropCdk(event: CdkDragDrop<GroupItem[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data, event.container.data, event.previousIndex, event.currentIndex);
}
}
}
| 33.865385 | 128 | 0.49276 |
d4e71210edec147aa7b4074fcf5fe0f994ad52e7 | 3,023 | ts | TypeScript | template-plugin-auth/frontend/tests/authentication.spec.ts | katherine-sussol/create-rust-app | 321b726359d679c64251504cb635ecc045e87ce3 | [
"Apache-2.0",
"MIT"
] | 263 | 2021-05-25T00:41:04.000Z | 2022-03-30T02:41:00.000Z | template-plugin-auth/frontend/tests/authentication.spec.ts | katherine-sussol/create-rust-app | 321b726359d679c64251504cb635ecc045e87ce3 | [
"Apache-2.0",
"MIT"
] | 12 | 2021-10-03T10:11:41.000Z | 2022-03-30T16:27:21.000Z | template-plugin-auth/frontend/tests/authentication.spec.ts | katherine-sussol/create-rust-app | 321b726359d679c64251504cb635ecc045e87ce3 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-10-13T00:55:04.000Z | 2022-02-19T18:26:38.000Z | import { test, expect } from "@playwright/test";
require("dotenv").config();
const test_url = process.env.TEST_URL;
const test_email = process.env.TEST_EMAIL;
const test_password = process.env.TEST_PASSWORD;
const get_ipts = async (page) => {
let emailIpt = page
.locator('[class="Form"]')
.locator('div:has-text("Email")')
.locator("input");
let passwordIpt = page
.locator('[class="Form"]')
.locator('div:has-text("Password")')
.locator("input");
return [emailIpt, passwordIpt];
};
test("home page test", async ({ page }) => {
await page.goto(test_url);
// Expect a context "React App" a substring.
await expect(page).toHaveTitle(/React App/);
await page.click("text=Login/Register");
await expect(page.locator("h1").first()).toHaveText("Login");
});
test.describe("login/register page tests", () => {
test.beforeEach(async ({ page }) => {
await page.goto(test_url);
await page.click("text=Login/Register");
});
//register tests
test("register test", async ({ page }) => {
await page.click("text=/to register/");
// await page.waitForTimeout(5000);
await expect(page.locator("h1").first()).toHaveText("Registration");
let [emailIpt, passwordIpt] = await get_ipts(page);
await emailIpt.fill(test_email);
await passwordIpt.fill(test_password);
await page.click("button >> text=Register");
await expect(page.locator("h1").first()).toHaveText("Activate");
});
//these tests require you had active your account
//login tests
test("login test", async ({ page }) => {
await expect(page.locator("h1").first()).toHaveText("Login");
let [emailIpt, passwordIpt] = await get_ipts(page);
await emailIpt.fill(test_email);
await passwordIpt.fill(test_password);
await page.click("button >> text=Login");
await expect(page.locator(".NavButton").last()).toHaveText("Logout");
await page.click("text=Logout");
await expect(page.locator(".NavButton").last()).toHaveText(
"Login/Register"
);
});
test.describe("tests after login", () => {
test.beforeEach(async ({ page }) => {
await expect(page.locator("h1").first()).toHaveText("Login");
let [emailIpt, passwordIpt] = await get_ipts(page);
await emailIpt.fill(test_email);
await passwordIpt.fill(test_password);
await page.click("button >> text=Login");
});
test.afterEach(async ({ page }) => {
let target = await page.locator(".NavButton:has-text('Logout')");
if (await target.count() !== 0) {
await target.click();
}
});
test("logout test", async ({ page }) => {
await page.click("text=Logout");
await expect(page.locator(".NavButton").last()).toHaveText(
"Login/Register"
);
});
test("refresh test", async ({ page }) => {
await expect(page.locator(".NavButton").last()).toHaveText("Logout");
await page.reload();
await expect(page.locator(".NavButton").last()).toHaveText("Logout");
});
});
});
| 31.164948 | 75 | 0.631823 |
6916a7302bb116f8b9e91e0f80ca8c162476459e | 4,173 | rb | Ruby | gems/ruby/2.2.0/gems/http-0.7.1/spec/lib/http_spec.rb | rubygem/website | 3ae3a68a42b024f4222fc805af6b14d158f8a132 | [
"MIT"
] | null | null | null | gems/ruby/2.2.0/gems/http-0.7.1/spec/lib/http_spec.rb | rubygem/website | 3ae3a68a42b024f4222fc805af6b14d158f8a132 | [
"MIT"
] | 1 | 2015-07-14T20:27:59.000Z | 2015-07-14T20:27:59.000Z | gems/ruby/2.2.0/gems/http-0.7.1/spec/lib/http_spec.rb | rubygem/website | 3ae3a68a42b024f4222fc805af6b14d158f8a132 | [
"MIT"
] | null | null | null | require 'json'
RSpec.describe HTTP do
let(:test_endpoint) { "http://#{ExampleServer::ADDR}" }
context 'getting resources' do
it 'is easy' do
response = HTTP.get test_endpoint
expect(response.to_s).to match(/<!doctype html>/)
end
context 'with URI instance' do
it 'is easy' do
response = HTTP.get URI test_endpoint
expect(response.to_s).to match(/<!doctype html>/)
end
end
context 'with query string parameters' do
it 'is easy' do
response = HTTP.get "#{test_endpoint}/params", :params => {:foo => 'bar'}
expect(response.to_s).to match(/Params!/)
end
end
context 'with query string parameters in the URI and opts hash' do
it 'includes both' do
response = HTTP.get "#{test_endpoint}/multiple-params?foo=bar", :params => {:baz => 'quux'}
expect(response.to_s).to match(/More Params!/)
end
end
context 'with headers' do
it 'is easy' do
response = HTTP.accept('application/json').get test_endpoint
expect(response.to_s.include?('json')).to be true
end
end
end
context 'with http proxy address and port' do
it 'proxies the request' do
response = HTTP.via('127.0.0.1', 8080).get test_endpoint
expect(response.headers['X-Proxied']).to eq 'true'
end
end
context 'with http proxy address, port username and password' do
it 'proxies the request' do
response = HTTP.via('127.0.0.1', 8081, 'username', 'password').get test_endpoint
expect(response.headers['X-Proxied']).to eq 'true'
end
it 'responds with the endpoint\'s body' do
response = HTTP.via('127.0.0.1', 8081, 'username', 'password').get test_endpoint
expect(response.to_s).to match(/<!doctype html>/)
end
end
context 'with http proxy address, port, with wrong username and password' do
it 'responds with 407' do
response = HTTP.via('127.0.0.1', 8081, 'user', 'pass').get test_endpoint
expect(response.status).to eq(407)
end
end
context 'without proxy port' do
it 'raises an argument error' do
expect { HTTP.via('127.0.0.1') }.to raise_error HTTP::RequestError
end
end
context 'posting forms to resources' do
it 'is easy' do
response = HTTP.post "#{test_endpoint}/form", :form => {:example => 'testing-form'}
expect(response.to_s).to eq('passed :)')
end
end
context 'posting with an explicit body' do
it 'is easy' do
response = HTTP.post "#{test_endpoint}/body", :body => 'testing-body'
expect(response.to_s).to eq('passed :)')
end
end
context 'with redirects' do
it 'is easy for 301' do
response = HTTP.with_follow(true).get("#{test_endpoint}/redirect-301")
expect(response.to_s).to match(/<!doctype html>/)
end
it 'is easy for 302' do
response = HTTP.with_follow(true).get("#{test_endpoint}/redirect-302")
expect(response.to_s).to match(/<!doctype html>/)
end
end
context 'head requests' do
it 'is easy' do
response = HTTP.head test_endpoint
expect(response.status).to eq(200)
expect(response['content-type']).to match(/html/)
end
end
describe '.auth' do
it 'sets Authorization header to the given value' do
client = HTTP.auth 'abc'
expect(client.default_headers[:authorization]).to eq 'abc'
end
it 'accepts any #to_s object' do
client = HTTP.auth double :to_s => 'abc'
expect(client.default_headers[:authorization]).to eq 'abc'
end
end
describe '.basic_auth' do
it 'fails when options is not a Hash' do
expect { HTTP.basic_auth '[FOOBAR]' }.to raise_error
end
it 'fails when :pass is not given' do
expect { HTTP.basic_auth :user => '[USER]' }.to raise_error
end
it 'fails when :user is not given' do
expect { HTTP.basic_auth :pass => '[PASS]' }.to raise_error
end
it 'sets Authorization header with proper BasicAuth value' do
client = HTTP.basic_auth :user => 'foo', :pass => 'bar'
expect(client.default_headers[:authorization])
.to match(/^Basic [A-Za-z0-9+\/]+=*$/)
end
end
end
| 29.807143 | 99 | 0.634795 |
d02ee38356273fb4595ace4790b221f429c07a1f | 93 | jbuilder | Ruby | app/views/tasks/show.json.jbuilder | victorfeijo/my_radmin | 572ae976186c6fc9ae10d59d3f10904e6aca8729 | [
"MIT"
] | 1 | 2016-06-16T20:52:14.000Z | 2016-06-16T20:52:14.000Z | app/views/tasks/show.json.jbuilder | victorfeijo/my_radmin | 572ae976186c6fc9ae10d59d3f10904e6aca8729 | [
"MIT"
] | null | null | null | app/views/tasks/show.json.jbuilder | victorfeijo/my_radmin | 572ae976186c6fc9ae10d59d3f10904e6aca8729 | [
"MIT"
] | null | null | null | json.extract! @task, :id, :name, :level, :done, :dead_line, :about, :created_at, :updated_at
| 46.5 | 92 | 0.688172 |
2c3f5e87a66a8d64f17c5ecd2e2840b191d0cad4 | 537 | py | Python | UVa-problems/787.py | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | UVa-problems/787.py | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | UVa-problems/787.py | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | ''' UVa 787 - Maximum Sub-sequence Product '''
# https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=649&page=show_problem&problem=728
# Date: 2021-10-04 17:28:52
# Runtime: 0.010
# Verdict: AC
import sys
for line in sys.stdin:
nums = list(map(int, line.split()[:-1]))
minv = nums.copy()
maxv = nums.copy()
for i in range(1, len(nums)):
a, b = minv[i - 1] * nums[i], maxv[i - 1] * nums[i]
minv[i] = min(a, b, minv[i])
maxv[i] = max(a, b, maxv[i])
print(max(maxv))
| 24.409091 | 110 | 0.595903 |
24774cce252cf232638c7cce48e9ddca94168a19 | 3,753 | php | PHP | classes/Kohana/Jam/Field/Timestamp.php | despark/jamd | c56f4936d42763d65fe59b916462605c1b49f7ae | [
"BSD-3-Clause"
] | 10 | 2015-01-10T14:40:22.000Z | 2021-03-28T20:38:17.000Z | classes/Kohana/Jam/Field/Timestamp.php | despark/jamd | c56f4936d42763d65fe59b916462605c1b49f7ae | [
"BSD-3-Clause"
] | 24 | 2015-03-17T14:05:08.000Z | 2021-01-07T16:38:04.000Z | classes/Kohana/Jam/Field/Timestamp.php | despark/jamd | c56f4936d42763d65fe59b916462605c1b49f7ae | [
"BSD-3-Clause"
] | 5 | 2015-10-20T11:31:00.000Z | 2017-10-31T09:29:44.000Z | <?php defined('SYSPATH') OR die('No direct script access.');
/**
* Handles timestamps and conversions to and from different formats
*
* All timestamps are represented internally by UNIX timestamps, regardless
* of their format in the database. When the model is saved, the value is
* converted back to the format specified by $format (which is a valid
* date() string).
*
* This means that you can have timestamp logic exist relatively independently
* of your database's format. If, one day, you wish to change the format used
* to represent dates in the database, you just have to update the $format
* property for the field.
*
* @package Jam
* @category Fields
* @author Jonathan Geiger
* @copyright (c) 2010-2011 Jonathan Geiger
* @license http://www.opensource.org/licenses/isc-license.txt
*/
abstract class Kohana_Jam_Field_Timestamp extends Jam_Field {
/**
* @var int default is NULL, which implies no date
*/
public $default = NULL;
/**
* @var boolean whether or not to automatically set now() on creation
*/
public $auto_now_create = FALSE;
/**
* @var boolean whether or not to automatically set now() on update
*/
public $auto_now_update = FALSE;
/**
* @var string a date formula representing the time in the database
*/
public $format = NULL;
/**
* Jam_Timezone object for manipulating timezones
* @var Jam_Timezone
*/
public $timezone = NULL;
/**
* Convert empty values by default because some DB's
* will convert empty strings to zero timestamps
*/
public $convert_empty = TRUE;
/**
* Sets the default to 0 if we have no format, or an empty string otherwise.
*
* @param array $options
*/
public function __construct($options = array())
{
parent::__construct($options);
if ( ! isset($options['default']) AND ! $this->allow_null)
{
// Having a implies saving we're format a string, so we want a proper default
$this->default = $this->format ? '' : 0;
}
if ($this->timezone === NULL)
{
$this->timezone = Jam_Timezone::instance();
}
}
public function get(Jam_Validated $model, $value, $is_loaded)
{
if ($this->timezone !== FALSE AND $this->timezone->is_active() AND ! $is_loaded)
{
if ( ! is_numeric($value) AND FALSE !== strtotime($value))
{
$value = strtotime($value);
}
if (is_numeric($value) AND $value AND $this->timezone !== FALSE)
{
$value = $this->timezone->convert($value, Jam_Timezone::MASTER_TIMEZONE, Jam_Timezone::USER_TIMEZONE);
}
if ($this->format AND is_numeric($value))
{
$value = date($this->format, $value);
}
}
return $value;
}
/**
* Automatically creates or updates the time and
* converts it, if necessary.
*
* @param Jam_Model $model
* @param mixed $value
* @param boolean $is_loaded
* @return int|string
*/
public function convert(Jam_Validated $model, $value, $is_loaded)
{
// Do we need to provide a default since we're creating or updating
if ((empty($value) AND ! $is_loaded AND $this->auto_now_create) OR ($is_loaded AND $this->auto_now_update))
{
$value = ($this->timezone !== FALSE) ? $this->timezone->time() : time();
}
else
{
// Convert to UNIX timestamp
if (is_numeric($value))
{
$value = (int) $value;
}
elseif (FALSE !== ($to_time = strtotime($value)))
{
$value = $to_time;
}
if (is_numeric($value) AND $value AND $this->timezone !== FALSE)
{
$value = $this->timezone->convert($value, Jam_Timezone::USER_TIMEZONE, Jam_Timezone::MASTER_TIMEZONE);
}
}
// Convert if necessary
if ($this->format AND is_numeric($value))
{
$value = date($this->format, $value);
}
return $value;
}
} // End Kohana_Jam_Field_Timestamp
| 25.882759 | 109 | 0.656808 |
e23dc5f35f215853ae7c41cdd0ac1444b4034c84 | 138 | py | Python | example.py | DennisThomas-25/bq-code | 23313538304b86f15313b5969dbbf2db1632c7b1 | [
"Apache-2.0"
] | null | null | null | example.py | DennisThomas-25/bq-code | 23313538304b86f15313b5969dbbf2db1632c7b1 | [
"Apache-2.0"
] | null | null | null | example.py | DennisThomas-25/bq-code | 23313538304b86f15313b5969dbbf2db1632c7b1 | [
"Apache-2.0"
] | null | null | null | def add(a,b):
return a+b
def substract(a,b):
return a * b
## Imagine I made a valid change
def absolut(a,b):
return np.abs(a,b)
| 11.5 | 32 | 0.630435 |
d61ea08292b692afdc63faa2383f28f737ae2dea | 2,250 | dart | Dart | lib/pages/about/about_page.dart | xinlc/flutter_jiandan | cda0696a3b097fc82ff1d83806ce5cd48bbc446b | [
"MIT"
] | 6 | 2018-09-30T06:09:51.000Z | 2020-11-18T02:19:40.000Z | lib/pages/about/about_page.dart | xinlc/flutter_jiandan | cda0696a3b097fc82ff1d83806ce5cd48bbc446b | [
"MIT"
] | null | null | null | lib/pages/about/about_page.dart | xinlc/flutter_jiandan | cda0696a3b097fc82ff1d83806ce5cd48bbc446b | [
"MIT"
] | null | null | null | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class AboutPage extends StatelessWidget {
TextStyle textStyle = new TextStyle(
color: Colors.blue,
decoration: new TextDecoration.combine([TextDecoration.underline])
);
Future<Null> _launchInBrowser(String url) async {
if (await canLaunch(url)) {
await launch(url, forceSafariVC: false, forceWebView: false);
} else {
throw 'Could not launch $url';
}
}
Widget _buildAuthorLink() {
return GestureDetector(
child: Container(
margin: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('作者:'),
Text( 'Leo', style: textStyle,),
],
),
),
onTap: () {
_launchInBrowser('https://xinlc.github.io');
},
);
}
Widget _buildGithubLink() {
return GestureDetector(
child: Container(
margin: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('GitHub:'),
Text('https://github.com/xinlc', style: textStyle,),
],
),
),
onTap: () {
_launchInBrowser('https://github.com/xinlc');
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('关于', style: new TextStyle(color: Colors.white)),
),
body: Center(
child: Column(
children: <Widget>[
Container(
width: 1.0,
height: 50.0,
color: Colors.transparent,
),
_buildAuthorLink(),
_buildGithubLink(),
Container(
margin: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
child: Text('基于Google Flutter的高仿煎蛋客户端'),
),
Container(
margin: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
child: Text('本项目仅供学习使用', style: TextStyle(fontSize: 12.0))
)
],
),
));
}
}
| 26.470588 | 72 | 0.541333 |
900700141b1a353fbc14b647305492b9bbe1224e | 130 | sql | SQL | src/test/resources/sql/create_table/33bc08d6.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/create_table/33bc08d6.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/create_table/33bc08d6.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:stats_ext.sql ln:71 expect:true
CREATE TABLE tststats.pt1 PARTITION OF tststats.pt FOR VALUES FROM (-10, -10) TO (10, 10)
| 43.333333 | 89 | 0.738462 |
46524018e72a1eb248fe88f87dbfe8d4f384f1f3 | 1,256 | php | PHP | routes/web.php | HectorEdgar/practicasUnam | 8dca68bad6b0275fd62c09d7de4297cbb01adac7 | [
"MIT"
] | null | null | null | routes/web.php | HectorEdgar/practicasUnam | 8dca68bad6b0275fd62c09d7de4297cbb01adac7 | [
"MIT"
] | null | null | null | routes/web.php | HectorEdgar/practicasUnam | 8dca68bad6b0275fd62c09d7de4297cbb01adac7 | [
"MIT"
] | null | null | null | <?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!
|
*/
//EDGAR
Route::resource('autor','AutorController')->middleware('auth');
Route::resource('tema', 'TemaController')->middleware('auth');
Route::resource('eje', 'EjeController')->middleware('auth');
//Routh::auth();
Route::get('/', function () {
return view('index');
});
Route::get('logout', 'auth\LoginController@logout');
//YU
Route::resource('editor','EditorController')->middleware('auth');
Route::resource('paises', 'PaisesController')->middleware('auth');
Route::resource('institucion', 'InstitucionController')->middleware('auth');
//Jair
Route::resource('ponencia', 'PonenciaController')->middleware('auth');
Route::resource('categoriaDocumento', 'CategoriaDocumentoController')->middleware('auth');;
Route::resource('documento', 'DocumentoController')->middleware('auth');;
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
| 33.052632 | 91 | 0.628981 |
0043d664d0b87aeece0ffff88bd2245517afb5c0 | 838 | swift | Swift | Sources/SwiftSCAD/Operations/Duplication/Symmetry.swift | tomasf/SwiftSCAD | ed4bd50ae3bd21e4fc295963aba83400ca0d4f43 | [
"MIT"
] | 2 | 2021-09-25T07:52:15.000Z | 2022-01-02T23:37:25.000Z | Sources/SwiftSCAD/Operations/Duplication/Symmetry.swift | tomasf/SwiftSCAD | ed4bd50ae3bd21e4fc295963aba83400ca0d4f43 | [
"MIT"
] | null | null | null | Sources/SwiftSCAD/Operations/Duplication/Symmetry.swift | tomasf/SwiftSCAD | ed4bd50ae3bd21e4fc295963aba83400ca0d4f43 | [
"MIT"
] | null | null | null | import Foundation
public extension Geometry3D {
/// Repeat this geometry mirrored across the provided axes
/// - Parameter axes: The axes to use
@UnionBuilder func symmetry(over axes: Axes3D) -> Geometry3D {
for xs in axes.contains(.x) ? [1.0, -1.0] : [1.0] {
for ys in axes.contains(.y) ? [1.0, -1.0] : [1.0] {
for zs in axes.contains(.z) ? [1.0, -1.0] : [1.0] {
scaled(x: xs, y: ys, z: zs)
}
}
}
}
}
public extension Geometry2D {
/// Repeat this geometry mirrored across the provided axes
/// - Parameter axes: The axes to use
@UnionBuilder func symmetry(over axes: Axes2D) -> Geometry2D {
for xs in axes.contains(.x) ? [1.0, -1.0] : [1.0] {
for ys in axes.contains(.y) ? [1.0, -1.0] : [1.0] {
scaled(x: xs, y: ys)
}
}
}
}
| 27.933333 | 66 | 0.552506 |
24a81d05038bba44e724274a5114d5a5db37b16d | 9,515 | php | PHP | Test/Unit/Block/GroupedProduct/Product/View/Type/GroupedTest.php | DivanteLtd/magento2-module-groupped-products-manager | ad9217603d3dc04a4ad5a66cba93997d000bde56 | [
"MIT"
] | 19 | 2017-07-20T06:22:43.000Z | 2022-01-19T21:42:40.000Z | Test/Unit/Block/GroupedProduct/Product/View/Type/GroupedTest.php | DivanteLtd/magento2-module-groupped-products-manager | ad9217603d3dc04a4ad5a66cba93997d000bde56 | [
"MIT"
] | 2 | 2018-07-05T15:28:47.000Z | 2020-06-19T09:08:40.000Z | Test/Unit/Block/GroupedProduct/Product/View/Type/GroupedTest.php | DivanteLtd/magento2-module-groupped-products-manager | ad9217603d3dc04a4ad5a66cba93997d000bde56 | [
"MIT"
] | 6 | 2017-07-25T07:10:35.000Z | 2022-02-15T23:14:05.000Z | <?php
/**
* @package Divante\GroupedProductsManager
* @author Marek Mularczyk <[email protected]>
* @copyright 2017 Divante Sp. z o.o.
* @license See LICENSE_DIVANTE.txt for license details.
*/
namespace Divante\GroupedProductsManager\Test\Unit\Block\GroupedProduct\Product\View\Type;
use Divante\GroupedProductsManager\Block\GroupedProduct\Product\View\Type\Grouped;
use Magento\Catalog\Model\Product;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use \PHPUnit_Framework_MockObject_MockObject as MockObject;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
use Divante\GroupedProductsManager\Helper\OutOfStock;
use Magento\Catalog\Model\Product\Attribute\Repository as ProductAttributeRepository;
use Magento\Catalog\Block\Product\Context;
use Magento\Framework\Stdlib\ArrayUtils;
use Magento\Framework\Api\SearchCriteriaBuilderFactory;
use Magento\Catalog\Helper\Output;
use Magento\Directory\Model\PriceCurrency;
use Magento\Catalog\Model\ProductFactory;
use Divante\GroupedProductsManager\Helper\Config;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
/**
* Class GroupedTest.
*/
class GroupedTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ObjectManagerHelper
*/
private $objectManagerHelper;
/**
* @var SearchCriteriaBuilderFactory|MockObject
*/
private $searchCriteriaBuilderFactoryMock;
/**
* @var ProductAttributeRepository|MockObject
*/
private $productAttributeRepositoryMock;
/**
* @var Output|MockObject
*/
private $outputHelperMock;
/**
* @var PriceCurrency|MockObject
*/
private $priceCurrencyMock;
/**
* @var ProductFactory|MockObject
*/
private $productFactoryMock;
/**
* @var Config|MockObject
*/
private $moduleConfigMock;
/**
* @var OutOfStock|MockObject
*/
private $outOfStockHelperMock;
/**
* @var Context|MockObject
*/
private $contextMock;
/**
* @var ArrayUtils|MockObject
*/
private $arrayUtilsMock;
/**
* @var Product|MockObject
*/
private $productMock;
/**
* @var SearchCriteriaBuilder|MockObject
*/
private $searchCriteriaBuilderMock;
/**
* @var SearchCriteria|MockObject
*/
private $searchCriteriaMock;
/**
* @var Grouped
*/
private $groupedModel;
/**
* {@inheritdoc}
*/
public function setUp()
{
$this->searchCriteriaBuilderFactoryMock = $this->getMockBuilder(
SearchCriteriaBuilderFactory::class
)->disableOriginalConstructor()->setMethods(['create'])->getMock();
$this->searchCriteriaBuilderMock = $this->getMockBuilder(
SearchCriteriaBuilder::class
)->disableOriginalConstructor()->getMock();
$this->searchCriteriaMock = $this->getMockBuilder(
SearchCriteria::class
)->disableOriginalConstructor()->getMock();
$this->searchCriteriaBuilderFactoryMock->method('create')
->willReturn($this->searchCriteriaBuilderMock);
$this->searchCriteriaBuilderMock->method('create')->willReturn($this->searchCriteriaMock);
$this->productAttributeRepositoryMock = $this->getMockBuilder(
ProductAttributeRepository::class
)->disableOriginalConstructor()->setMethods(
[
'getList',
'getItems',
]
)->getMock();
$this->outputHelperMock = $this->getMockBuilder(
Output::class
)->disableOriginalConstructor()->getMock();
$this->priceCurrencyMock = $this->getMockBuilder(
PriceCurrency::class
)->disableOriginalConstructor()->setMethods(['convertAndFormat'])->getMock();
$this->productFactoryMock = $this->getMockBuilder(
ProductFactory::class
)->disableOriginalConstructor()->setMethods(['create'])->getMock();
$this->productMock = $this->getMockBuilder(
Product::class
)->disableOriginalConstructor()->getMock();
$this->productFactoryMock->method('create')->willReturn($this->productMock);
$this->moduleConfigMock = $this->getMockBuilder(
Config::class
)->disableOriginalConstructor()->getMock();
$this->outOfStockHelperMock = $this->getMockBuilder(
OutOfStock::class
)->disableOriginalConstructor()->setMethods(['getProductAlertUrl'])->getMock();
$this->contextMock = $this->getMockBuilder(
Context::class
)->disableOriginalConstructor()->getMock();
$this->arrayUtilsMock = $this->getMockBuilder(
ArrayUtils::class
)->disableOriginalConstructor()->getMock();
$this->objectManagerHelper = new ObjectManagerHelper($this);
$this->groupedModel = $this->objectManagerHelper->getObject(
Grouped::class,
[
'searchCriteriaBuilderFactory' => $this->searchCriteriaBuilderFactoryMock,
'productAttributeRepository' => $this->productAttributeRepositoryMock,
'outputHelper' => $this->outputHelperMock,
'priceCurrency' => $this->priceCurrencyMock,
'productFactory' => $this->productFactoryMock,
'outOfStoryHelper' => $this->outOfStockHelperMock,
'moduleConfig' => $this->moduleConfigMock,
'context' => $this->contextMock,
'arrayUtils' => $this->arrayUtilsMock,
]
);
}
/**
* test getProductStockAlertUrl() method.
*/
public function testGetProductStockAlertUrl()
{
$this->outOfStockHelperMock->method('getProductAlertUrl')->with($this->productMock);
$this->groupedModel->getProductStockAlertUrl($this->productMock);
}
/**
* test getOutputHelper() method.
*/
public function testGetOutputHelper()
{
$this->assertSame($this->outputHelperMock, $this->groupedModel->getOutputHelper());
}
/**
* test getModuleConfigHelper() method.
*/
public function testGetModuleConfigHelper()
{
$this->assertSame($this->moduleConfigMock, $this->groupedModel->getModuleConfigHelper());
}
/**
* test resolveVisibleAttributes() method.
*
* @param $productId
*
* @dataProvider productIdProvider
*/
public function testResolveVisibleAttributes($productId)
{
$visibleAttributes = 'a:2:{i:1;s:23:"145,146,147,148,149,150";i:2;s:3:"149";}';
$attributesValues =
[
null,
'Żółty',
123.5,
'',
];
$productMock = $this->getMockBuilder(
Product::class
)->disableOriginalConstructor()->setMethods(['getProductsAttributesVisibility'])->getMock();
$productMock->expects($this->once())->method('getProductsAttributesVisibility')->willReturn($visibleAttributes);
$itemMock = $this->getMockBuilder(
Product::class
)->disableOriginalConstructor()->getMock();
$itemMock->id = $productId;
$productResourceMock = $this->getMockBuilder(
ProductResource::class
)->disableOriginalConstructor()->getMock();
$itemMock->expects($this->once())->method('getResource')->willReturn($productResourceMock);
$itemMock->expects($this->atLeastOnce())->method('getId')->willReturn($productId);
$productResourceMock->expects($this->once())->method('load')->with($this->productMock, $productId);
if (null !== $productId) {
$this->productAttributeRepositoryMock->expects($this->once())->method('getList')->willReturnSelf();
$this->productAttributeRepositoryMock->expects($this->once())
->method('getItems')
->willReturn(
$this->prepareAttributesCollection(
$attributesValues
)
);
$this->productMock->expects($this->exactly(count($attributesValues)))->method('hasData');
}
$this->groupedModel->resolveVisibleAttributes($productMock, $itemMock);
}
/**
* @return array
*/
public static function productIdProvider()
{
return [
[1],
[null],
];
}
/**
* @param $attributeValues
*
* @return array
*/
public function prepareAttributesCollection($attributeValues)
{
$result = [];
foreach ($attributeValues as $value) {
$attributeMock = $this->getMockBuilder(
Attribute::class
)->disableOriginalConstructor()->setMethods(
[
'getFrontend',
'getValue',
'getStoreLabel',
]
)->getMock();
$attributeMock->value = $value;
$attributeMock->expects($this->atLeastOnce())->method('getFrontend')->willReturnSelf();
$attributeMock->expects($this->atLeastOnce())->method('getValue')->willReturn($attributeMock->value);
$attributeMock->expects($this->atLeastOnce())->method('getStoreLabel')->willReturn('Label');
$result[] = $attributeMock;
}
return $result;
}
}
| 30.892857 | 120 | 0.618917 |
12a4c0ecca8f094ef6ec42187ea9311e35c06b67 | 290 | cs | C# | CoCore.Base/Interface/IBroadcast.cs | kvandake/CoCore | 2c390647493f048e48a0fbc22ff0ef231ceac9f6 | [
"Apache-2.0"
] | 1 | 2015-12-31T18:37:04.000Z | 2015-12-31T18:37:04.000Z | CoCore.Base/Interface/IBroadcast.cs | kvandake/CoCore | 2c390647493f048e48a0fbc22ff0ef231ceac9f6 | [
"Apache-2.0"
] | 16 | 2015-12-31T18:37:29.000Z | 2018-01-10T10:57:03.000Z | CoCore.Base/Interface/IBroadcast.cs | kvandake/CoCore | 2c390647493f048e48a0fbc22ff0ef231ceac9f6 | [
"Apache-2.0"
] | null | null | null | using System;
namespace CoCore.Base
{
public interface IBroadcast
{
void SubscribeOnBroadcast();
void UnscribeOnBroadcast();
void Register<T>(Action<T> action, string token = null);
void UnRegister<T>(string token = null);
void Send<T>(T obj, string token = null);
}
}
| 14.5 | 58 | 0.693103 |
05bb92dacd41ea41ab76afe93555fad51feee30d | 8,970 | py | Python | sysdfiles/network_file.py | ghuband/sysdfiles | eb13167b07b27351c3962a42b30dcd50ce551d71 | [
"MIT"
] | null | null | null | sysdfiles/network_file.py | ghuband/sysdfiles | eb13167b07b27351c3962a42b30dcd50ce551d71 | [
"MIT"
] | 1 | 2020-06-05T20:58:05.000Z | 2020-06-05T20:58:05.000Z | sysdfiles/network_file.py | ghuband/sysdfiles | eb13167b07b27351c3962a42b30dcd50ce551d71 | [
"MIT"
] | 1 | 2020-06-09T02:35:35.000Z | 2020-06-09T02:35:35.000Z | from .ini_file import IniFile
# =============================================================================
# NetworkFile
# =============================================================================
class NetworkFile(IniFile):
def __init__(self, file_name=''):
IniFile.__init__(self, file_name)
self.add_properties('match',
[['architecture'],
['driver', 'l'],
['host'],
['kernel_command_line'],
['kernel_version'],
['mac_address', 'l', ' ', 3],
['name', 'l'],
['path', 'l'],
['type', 'l'],
['virtualization']])
self.add_properties('link',
[['all_multicast', 'b'],
['arp', 'b'],
['mac_address'],
['mtu_bytes', 'nb'],
['multicast', 'b'],
['required_for_online', 'b'],
['unmanaged', 'b']])
self.add_properties('network',
[['active_slave', 'b'],
['address', 'l', ' ', 1],
['bind_carrier', 'l'],
['bond'],
['bridge'],
['configure_without_carrier', 'b'],
['description'],
['dhcp'],
['dhcp_server', 'b'],
['dns', 'l', ' ', 1],
['dns_over_tls'],
['dnssec'],
['dnssec_negative_trust_anchors', 'l'],
['domains', 'l'],
['emit_lldp'],
['gateway', 'l', ' ', 1],
['ip_forward'],
['ip_masquerade', 'b'],
['ipv4_ll_route', 'b'],
['ipv4_proxy_arp', 'b'],
['ipv6_accept_ra', 'b'],
['ipv6_duplicate_address_detection'],
['ipv6_hop_limit', 'i'],
['ipv6_mtu_bytes', 'nb'],
['ipv6_prefix_delegation'],
['ipv6_privacy_extensions'],
['ipv6_proxy_ndp', 'b'],
['ipv6_proxy_ndp_address', 'l', ' ', 1],
['ipv6_token'],
['link_local_addressing'],
['lldp'],
['llmnr'],
['mac_vlan', 'l', ' ', 1],
['multicast_dns'],
['ntp', 'l', ' ', 1],
['primary_slave', 'b'],
['tunnel', 'l', ' ', 1],
['vlan', 'l', ' ', 1],
['vrf'],
['vxlan', 'l', ' ', 1]])
self.add_properties('address',
[['auto_join', 'b'],
['address', 'l', ' ', 1],
['broadcast'],
['duplicate_address_detection', 'b'],
['home_address', 'b'],
['label'],
['manage_temporary_address', 'b'],
['peer', 'l', ' ', 1],
['preferred_lifetime'],
['prefix_route', 'b'],
['scope']])
self.add_properties('ipv6_address_label',
[['label', 'i'],
['prefix']])
self.add_properties('routing_policy_rule',
[['firewall_mark', 'i'],
['from'],
['incoming_interface'],
['outgoing_interface'],
['priority', 'i'],
['table', 'i'],
['to'],
['type_of_service', 'i']])
self.add_properties('route',
[['destination'],
['gateway', 'l', ' ', 1],
['gateway_on_link', 'b'],
['initial_advertised_receive_window', 'nb'],
['initial_congestion_window', 'nb'],
['ipv6_preference'],
['metric', 'i'],
['mtu_bytes', 'nb'],
['preferred_source'],
['protocol'],
['quick_ack', 'b'],
['scope'],
['source'],
['table', 'i'],
['type']])
self.add_properties('dhcp',
[['anonymize', 'b'],
['client_identifier'],
['critical_connection', 'b'],
['duid_raw_data'],
['duid_type'],
['host_name'],
['iad', 'i'],
['listen_port', 'i'],
['rapid_commit', 'b'],
['request_broadcast', 'b'],
['route_metric', 'i'],
['route_table', 'i'],
['send_host_name', 'b'],
['use_dns', 'b'],
['use_domains'],
['use_host_name', 'b'],
['use_mtu', 'b'],
['use_ntp', 'b'],
['use_routes', 'b'],
['use_timezone', 'b'],
['user_class', 'l'],
['vendor_class_identifier']])
self.add_properties('ipv6_accept_ra',
[['route_table', 'i'],
['use_domains'],
['use_dns', 'b']])
self.add_properties('dhcp_server',
[['default_lease_time_sec', 'ns'],
['dns', 'l'],
['emit_dns', 'b'],
['emit_ntp', 'b'],
['emit_router', 'b'],
['emit_time_zone', 'b'],
['max_lease_time_sec', 'ns'],
['ntp', 'l'],
['pool_offset', 'i'],
['pool_size', 'i'],
['router', 'l'],
['time_zone']])
self.add_properties('ipv6_prefix_delegation',
[['emit_dns', 'b'],
['emit_domains', 'b'],
['dns', 'l'],
['dns_lifetime_sec', 'ns'],
['domains', 'l'],
['managed', 'b'],
['other_information', 'b'],
['router_lifetime_sec', 'ns'],
['router_preference']])
self.add_properties('ipv6_prefix',
[['address_auto_configuration', 'b'],
['on_link', 'b'],
['preferred_lifetime_sec', 'ns'],
['prefix'],
['valid_lifetime_sec', 'ns']])
self.add_properties('bridge',
[['allow_port_to_be_root', 'b'],
['cost', 'i'],
['fast_leave', 'b'],
['hair_pin', 'b'],
['priority', 'i'],
['unicast_flood', 'b'],
['use_bpdu', 'b']])
self.add_properties('bridge_fdb',
[['mac_address'],
['vlan_id']])
self.add_properties('can',
[['bit_rate', 'bps'],
['restart_sec', 'ns'],
['sample_point']])
self.add_properties('bridge_vlan',
[['egress_untagged'],
['pv_id'],
['vlan']])
| 48.225806 | 79 | 0.273579 |
dde8f485661283dbf4d295bf89282f4726beff37 | 777 | java | Java | src/main/java/com/staten/capstone/service/IUserService.java | mstaten/capstone | e17b27f7e4e51d3a2a51e87a95b2ac7934ca116a | [
"MIT"
] | null | null | null | src/main/java/com/staten/capstone/service/IUserService.java | mstaten/capstone | e17b27f7e4e51d3a2a51e87a95b2ac7934ca116a | [
"MIT"
] | null | null | null | src/main/java/com/staten/capstone/service/IUserService.java | mstaten/capstone | e17b27f7e4e51d3a2a51e87a95b2ac7934ca116a | [
"MIT"
] | null | null | null | package com.staten.capstone.service;
import com.staten.capstone.errors.PasswordsMismatchException;
import com.staten.capstone.errors.UserAlreadyExistsException;
import com.staten.capstone.models.User;
import com.staten.capstone.models.data.UserDto;
public interface IUserService {
User registerNewUser(final UserDto userDto) throws UserAlreadyExistsException, PasswordsMismatchException;
User findUserByUsername(final String username);
User findUserById(final Integer id);
Boolean checkPasswords(final User user, final String oldPassword);
void changeUserPassword(final User user, final String password);
Boolean verifyNewUserPasswords(final String password, final String verify);
// getUser
// saveRegisteredUser
// deleteUser
}
| 27.75 | 110 | 0.795367 |
2a11871db8e679dcf69c6387a69c83108d46d092 | 293 | rs | Rust | src/test/ui/suggestions/const-pat-non-exaustive-let-new-var.rs | Timmmm/rust | e369d87b015a84653343032833d65d0545fd3f26 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 7 | 2020-09-23T01:43:19.000Z | 2022-03-17T09:18:56.000Z | src/test/ui/suggestions/const-pat-non-exaustive-let-new-var.rs | Timmmm/rust | e369d87b015a84653343032833d65d0545fd3f26 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 9 | 2019-08-14T16:32:51.000Z | 2021-07-20T23:38:07.000Z | src/test/ui/suggestions/const-pat-non-exaustive-let-new-var.rs | Timmmm/rust | e369d87b015a84653343032833d65d0545fd3f26 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 10 | 2020-06-03T23:08:12.000Z | 2021-03-23T17:53:42.000Z | fn main() {
let A = 3;
//~^ ERROR refutable pattern in local binding: `std::i32::MIN..=1i32` and
//~| interpreted as a constant pattern, not a new variable
//~| HELP introduce a variable instead
//~| SUGGESTION a_var
const A: i32 = 2;
//~^ constant defined here
}
| 26.636364 | 77 | 0.610922 |
33b80bbff1ea2b470efe39a637234e173b1e3208 | 786 | sql | SQL | src/main/resources/introdb/create-schema.sql | dbflute/dbflute-intro | eba78225cae6c27a36ae70172ae2009123631a7c | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2016-12-11T14:23:39.000Z | 2022-01-13T08:49:45.000Z | src/main/resources/introdb/create-schema.sql | dbflute/dbflute-intro | eba78225cae6c27a36ae70172ae2009123631a7c | [
"ECL-2.0",
"Apache-2.0"
] | 251 | 2016-04-16T08:41:49.000Z | 2022-03-24T14:42:54.000Z | src/main/resources/introdb/create-schema.sql | dbflute/dbflute-intro | eba78225cae6c27a36ae70172ae2009123631a7c | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-21T10:26:04.000Z | 2019-12-15T07:15:29.000Z |
create table CLS_TARGET_DATABASE(
DATABASE_CODE VARCHAR(10) NOT NULL PRIMARY KEY,
DATABASE_NAME VARCHAR(100) NOT NULL,
JDBC_DRIVER_FQCN VARCHAR(100) NOT NULL,
URL_TEMPLATE VARCHAR(100) NOT NULL,
DEFAULT_SCHEMA VARCHAR(10),
SCHEMA_REQUIRED_FLG INTEGER NOT NULL,
SCHEMA_UPPER_CASE_FLG INTEGER NOT NULL,
USER_INPUT_ASSIST_FLG INTEGER NOT NULL,
EMBEDDED_JAR_FLG INTEGER NOT NULL,
DISPLAY_ORDER INTEGER NOT NULL
);
create table CLS_TARGET_LANGUAGE(
LANGUAGE_CODE VARCHAR(10) NOT NULL PRIMARY KEY,
LANGUAGE_NAME VARCHAR(100) NOT NULL,
DISPLAY_ORDER INTEGER NOT NULL
);
create table CLS_TARGET_CONTAINER(
CONTAINER_CODE VARCHAR(10) NOT NULL PRIMARY KEY,
CONTAINER_NAME VARCHAR(100) NOT NULL,
DISPLAY_ORDER INTEGER NOT NULL
);
| 30.230769 | 52 | 0.762087 |
4cea66636174c62280f8b10c8fc1bfbd13a8974d | 2,055 | py | Python | views.py | tanminkwan/flask_appBuilder_pjt | 763c02b271288a0db67f1647f605836e98ac450e | [
"Unlicense"
] | null | null | null | views.py | tanminkwan/flask_appBuilder_pjt | 763c02b271288a0db67f1647f605836e98ac450e | [
"Unlicense"
] | null | null | null | views.py | tanminkwan/flask_appBuilder_pjt | 763c02b271288a0db67f1647f605836e98ac450e | [
"Unlicense"
] | null | null | null | from flask import render_template
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder import ModelView, ModelRestApi
from .models import ContactGroup, Contact
from . import appbuilder, db
"""
Create your Model based REST API::
class MyModelApi(ModelRestApi):
datamodel = SQLAInterface(MyModel)
appbuilder.add_api(MyModelApi)
Create your Views::
class MyModelView(ModelView):
datamodel = SQLAInterface(MyModel)
Next, register your Views::
appbuilder.add_view(
MyModelView,
"My View",
icon="fa-folder-open-o",
category="My Category",
category_icon='fa-envelope'
)
"""
"""
Application wide 404 error handler
"""
class ContactModelView(ModelView):
datamodel = SQLAInterface(Contact)
label_columns = {'contact_group':'Contacts Group','address':'주소'}
list_columns = ['name','personal_cellphone','gender', 'birthday','contact_group']
show_fieldsets = [
(
'Summary',
{'fields': ['name', 'address', 'contact_group']}
),
(
'Personal Info',
{'fields': ['birthday', 'personal_phone', 'personal_cellphone'], 'expanded': False}
),
]
class GroupModelView(ModelView):
datamodel = SQLAInterface(ContactGroup)
add_columns = ['id', 'name']
related_views = [ContactModelView]
@appbuilder.app.errorhandler(404)
def page_not_found(e):
return (
render_template(
"404.html", base_template=appbuilder.base_template, appbuilder=appbuilder
),
404,
)
class GroupModelApi(ModelRestApi):
resource_name = 'group'
datamodel = SQLAInterface(ContactGroup)
db.create_all()
appbuilder.add_view(
GroupModelView,
"List Groups",
icon = "fa-folder-open-o",
category = "Contacts",
category_icon = "fa-envelope"
)
appbuilder.add_view(
ContactModelView,
"List Contacts",
icon = "fa-envelope",
category = "Contacts"
)
appbuilder.add_api(GroupModelApi)
| 22.833333 | 95 | 0.654015 |
b62234cb05aae8354e0b8047bba699584ff7a583 | 281 | rb | Ruby | spec/utils_spec.rb | ngiger/softcover | 9350a14d1ead3538b6a307dc9cdf60e1f9b2267c | [
"MIT"
] | 331 | 2015-01-03T00:13:26.000Z | 2022-03-27T18:03:00.000Z | spec/utils_spec.rb | ngiger/softcover | 9350a14d1ead3538b6a307dc9cdf60e1f9b2267c | [
"MIT"
] | 111 | 2015-01-04T20:50:31.000Z | 2022-02-21T21:09:32.000Z | spec/utils_spec.rb | ngiger/softcover | 9350a14d1ead3538b6a307dc9cdf60e1f9b2267c | [
"MIT"
] | 49 | 2015-02-10T22:25:35.000Z | 2021-06-30T16:43:46.000Z | require 'spec_helper'
describe Softcover::Utils do
context "book_file_lines" do
let(:raw_lines) { ['foo.md', '# bar.tex'] }
subject { Softcover::Utils.non_comment_lines(raw_lines) }
it { should include 'foo.md' }
it { should_not include 'bar.tex' }
end
end | 28.1 | 61 | 0.66548 |
b734f0cd3f3cc7fa7d4671f172f94cf7d4a471b7 | 2,361 | cpp | C++ | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2022-03-16T14:31:36.000Z | 2022-03-16T14:31:36.000Z | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | null | null | null | Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp | aspose-tasks/Aspose.Tasks-for-C | acb3e2b75685f65cbe34dd739c7eae0dfc285aa1 | [
"MIT"
] | 1 | 2020-07-01T01:26:17.000Z | 2020-07-01T01:26:17.000Z | #include "GetResourceAssignmentOvertimes.h"
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object_ext.h>
#include <system/object.h>
#include <system/decimal.h>
#include <system/console.h>
#include <system/collections/ienumerator.h>
#include <ResourceAssignmentCollection.h>
#include <ResourceAssignment.h>
#include <Project.h>
#include <Key.h>
#include <enums/AsnKey.h>
#include <Duration.h>
#include <Asn.h>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithResourceAssignments {
RTTI_INFO_IMPL_HASH(3423715729u, ::Aspose::Tasks::Examples::CPP::WorkingWithResourceAssignments::GetResourceAssignmentOvertimes, ThisTypeBaseTypesInfo);
void GetResourceAssignmentOvertimes::Run()
{
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// ExStart:GetResourceAssignmentOvertimes
// Create project instance
System::SharedPtr<Project> project1 = System::MakeObject<Project>(dataDir + u"ResourceAssignmentOvertimes.mpp");
// Print assignment overtimes
{
auto ra_enumerator = (project1->get_ResourceAssignments())->GetEnumerator();
decltype(ra_enumerator->get_Current()) ra;
while (ra_enumerator->MoveNext() && (ra = ra_enumerator->get_Current(), true))
{
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::OvertimeCost()));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::OvertimeWork())));
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingCost()));
System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingOvertimeCost()));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork())));
System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork())));
}
}
// ExEnd:GetResourceAssignmentOvertimes
}
} // namespace WorkingWithResourceAssignments
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
| 35.772727 | 164 | 0.725964 |
cd218461b1b742554d230c85d20a8353993d1129 | 4,077 | cs | C# | src/BloomTests/ElementProxyTests.cs | StephenMcConnel/BloomDesktop | ef184acc3fcec5807bd79c4ef8f42ae06f529584 | [
"MIT"
] | null | null | null | src/BloomTests/ElementProxyTests.cs | StephenMcConnel/BloomDesktop | ef184acc3fcec5807bd79c4ef8f42ae06f529584 | [
"MIT"
] | null | null | null | src/BloomTests/ElementProxyTests.cs | StephenMcConnel/BloomDesktop | ef184acc3fcec5807bd79c4ef8f42ae06f529584 | [
"MIT"
] | null | null | null | // Copyright (c) 2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System.Xml;
using Bloom;
using NUnit.Framework;
namespace BloomTests
{
[TestFixture]
public class ElementProxyTests
{
/* Note, the whole purpose of the ElementProxy class is to work around the difficulty of producing
GeckoHtmlElements in unit tests. So we're not going to test those code paths here, either, sigh. */
[Test]
public void GetString_XmlElementHasAttribute()
{
Assert.AreEqual("foo", MakeElement("<div id='foo'/>").GetAttribute("id"));
}
[Test]
public void GetString_XmlElementMissingAttribute_GivesEmptyString()
{
Assert.AreEqual("", MakeElement("<div id='foo'/>").GetAttribute("blah"));
}
[Test]
public void SetString_CanReturnIt()
{
var e = MakeElement("<div id='foo'/>");
e.SetAttribute("id", XmlString.FromUnencoded("blah"));
Assert.AreEqual("blah", e.GetAttribute("id"));
MakeElement("<div/>");
e.SetAttribute("id", XmlString.FromUnencoded("blah"));
Assert.AreEqual("blah", e.GetAttribute("id"));
}
[Test]
public void Class_ReturnsSameCase()
{
Assert.AreEqual("Img", MakeElement("<Img id='foo'/>").Name,"should be same case because that's what XmlElement.Name does.");
}
private ElementProxy MakeElement(string xml)
{
var dom = new XmlDocument();
dom.LoadXml(xml);
return new ElementProxy(dom.DocumentElement);
}
[Test]
public void EqualsNull_ReturnsFalse()
{
var elementProxy = MakeElement("<div id='foo'/>");
Assert.That(elementProxy == null, Is.False);
Assert.That(elementProxy.Equals(null), Is.False);
ElementProxy proxy2 = null;
// proxy2.Equals(elementProxy) has to fail.
Assert.That(proxy2 == elementProxy, Is.False);
}
[Test]
public void EqualsSelf_ReturnsTrue()
{
var elementProxy = MakeElement("<div id='foo'/>");
Assert.That(elementProxy == elementProxy, Is.True);
Assert.That(elementProxy.Equals(elementProxy), Is.True);
}
[Test]
public void EqualsProxyForSameThing_ReturnsTrue()
{
var dom = new XmlDocument();
dom.LoadXml("<div id='foo'/>");
var elementProxy = new ElementProxy(dom.DocumentElement);
var proxy2 = new ElementProxy(dom.DocumentElement);
Assert.That(elementProxy == proxy2, Is.True);
Assert.That(elementProxy.Equals(proxy2), Is.True);
}
[Test]
public void EqualsProxyForDifferentThing_ReturnsFalse()
{
var elementProxy = MakeElement("<div id='foo'/>");
var proxy2 = MakeElement("<div id='foo'/>");
Assert.That(elementProxy == proxy2, Is.False);
Assert.That(elementProxy.Equals(proxy2), Is.False);
}
[Test]
public void EqualsNonProxy_ReturnsFalse()
{
var elementProxy = MakeElement("<div id='foo'/>");
Assert.That(elementProxy == new object(), Is.False); // won't exercise current == code, but I think still worth checking.
Assert.That(elementProxy.Equals(new object()), Is.False);
}
[Test]
public void SelfOrAncestorHasClass_MatchesSelf()
{
var elementProxy = MakeElement("<div class='blueberry pie'/>");
Assert.That(elementProxy.SelfOrAncestorHasClass("blueberry"), Is.True);
Assert.That(elementProxy.SelfOrAncestorHasClass("berry"), Is.False);
Assert.That(elementProxy.SelfOrAncestorHasClass("pie"), Is.True);
Assert.That(elementProxy.SelfOrAncestorHasClass("pieplate"), Is.False);
}
[Test]
public void SelfOrAncestorHasClass_MatchesAncestor()
{
var dom = new XmlDocument();
dom.LoadXml("<div class='blueberry pie'><div id='foo' class='foolish'/></div>");
var fooDiv = (XmlElement)dom.SelectSingleNode("//div[@id='foo']");
var elementProxy = new ElementProxy(fooDiv);
Assert.That(elementProxy.SelfOrAncestorHasClass("foolish"), Is.True);
Assert.That(elementProxy.SelfOrAncestorHasClass("blueberry"), Is.True);
Assert.That(elementProxy.SelfOrAncestorHasClass("berry"), Is.False);
Assert.That(elementProxy.SelfOrAncestorHasClass("pie"), Is.True);
Assert.That(elementProxy.SelfOrAncestorHasClass("pieplate"), Is.False);
}
}
}
| 32.102362 | 127 | 0.70493 |
1683ab3afaec0026a7f91136434007f3e5f136c1 | 310 | swift | Swift | MVVMKit/Base/CollectionItemViewModel.swift | IsaAliev/MVVMKit | dda68f83ace779d13b0238a77b6f2777a3497f61 | [
"MIT"
] | null | null | null | MVVMKit/Base/CollectionItemViewModel.swift | IsaAliev/MVVMKit | dda68f83ace779d13b0238a77b6f2777a3497f61 | [
"MIT"
] | null | null | null | MVVMKit/Base/CollectionItemViewModel.swift | IsaAliev/MVVMKit | dda68f83ace779d13b0238a77b6f2777a3497f61 | [
"MIT"
] | null | null | null | //
// CollectionItemViewModel.swift
//
// Created by Isa Aliev on 17/09/2020.
// Copyright © 2020. All rights reserved.
//
public protocol CollectionItemViewModel: ViewModel {
var identityIdentifier: Any? { get }
}
public extension CollectionItemViewModel {
var identityIdentifier: Any? { nil }
}
| 20.666667 | 52 | 0.719355 |
a3b85560fcfc0293685bde2588bb82ce8f0e2428 | 567 | java | Java | src/main/java/org/snomed/snowstorm/rest/pojo/CreateBranchRequest.java | kparmar1/snowstorm | 651d27bc857ef6ede0be15a09570f0ef370d9bd4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/snomed/snowstorm/rest/pojo/CreateBranchRequest.java | kparmar1/snowstorm | 651d27bc857ef6ede0be15a09570f0ef370d9bd4 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/snomed/snowstorm/rest/pojo/CreateBranchRequest.java | kparmar1/snowstorm | 651d27bc857ef6ede0be15a09570f0ef370d9bd4 | [
"Apache-2.0"
] | null | null | null | package org.snomed.snowstorm.rest.pojo;
import java.util.Map;
public class CreateBranchRequest {
private String parent;
private String name;
private Map<String, Object> metadata;
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
}
| 16.2 | 56 | 0.712522 |
dda1730d97418cd53699e9c9f334f2ac3a4e157b | 2,286 | java | Java | src/main/java/com/blurengine/blur/events/players/BlurPlayerEvent.java | Xorgon/Blur | 0790f54feb039bbc87ffa6f880e03721d5d85041 | [
"Apache-2.0"
] | 35 | 2016-01-01T16:54:58.000Z | 2021-12-25T13:20:25.000Z | src/main/java/com/blurengine/blur/events/players/BlurPlayerEvent.java | Xorgon/Blur | 0790f54feb039bbc87ffa6f880e03721d5d85041 | [
"Apache-2.0"
] | 6 | 2016-01-05T03:22:10.000Z | 2019-08-18T19:59:21.000Z | src/main/java/com/blurengine/blur/events/players/BlurPlayerEvent.java | Xorgon/Blur | 0790f54feb039bbc87ffa6f880e03721d5d85041 | [
"Apache-2.0"
] | 8 | 2016-01-01T13:35:52.000Z | 2021-06-17T21:07:19.000Z | /*
* Copyright 2016 Ali Moghnieh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blurengine.blur.events.players;
import com.google.common.base.Preconditions;
import com.blurengine.blur.events.session.BlurSessionEvent;
import com.blurengine.blur.session.BlurPlayer;
import com.blurengine.blur.session.BlurSession;
import javax.annotation.Nonnull;
/**
* Represents a {@link BlurPlayer} event.
*/
public abstract class BlurPlayerEvent extends BlurSessionEvent {
protected final BlurPlayer blurPlayer;
public BlurPlayerEvent(@Nonnull BlurPlayer blurPlayer) {
this(Preconditions.checkNotNull(blurPlayer, "blurPlayer cannot be null."), blurPlayer.getSession());
}
public BlurPlayerEvent(@Nonnull BlurPlayer blurPlayer, boolean isAsync) {
this(Preconditions.checkNotNull(blurPlayer, "blurPlayer cannot be null."), blurPlayer.getSession(), isAsync);
}
public BlurPlayerEvent(BlurPlayer blurPlayer, @Nonnull BlurSession session) {
super(Preconditions.checkNotNull(session, "session cannot be null."));
this.blurPlayer = blurPlayer;
}
public BlurPlayerEvent(BlurPlayer blurPlayer, @Nonnull BlurSession session, boolean isAsync) {
super(Preconditions.checkNotNull(session, "session cannot be null."), isAsync);
this.blurPlayer = blurPlayer;
}
/**
* Returns the primary {@link BlurPlayer} involved in this event. Subclass events will have delegate methods that represent what this primary
* player is.
* <p />
* E.g. {@link PlayerDamagePlayerEvent} returns the damager. {@link PlayerKilledEvent} returns the player that was killed.
* @return primary blur player
*/
public BlurPlayer getBlurPlayer() {
return blurPlayer;
}
}
| 36.285714 | 145 | 0.733596 |
4cd2e490b89c48819e40a2fc1ffbdb417f56c65e | 1,683 | py | Python | nesi/devices/softbox/api/schemas/logport_schemas.py | inexio/NESi | 920b23ccaf293733b4b571e4df27929c036257f7 | [
"BSD-2-Clause"
] | 30 | 2020-09-03T06:02:38.000Z | 2022-03-11T16:34:18.000Z | nesi/devices/softbox/api/schemas/logport_schemas.py | inexio/NESi | 920b23ccaf293733b4b571e4df27929c036257f7 | [
"BSD-2-Clause"
] | 2 | 2021-01-15T10:33:23.000Z | 2021-02-21T21:04:37.000Z | nesi/devices/softbox/api/schemas/logport_schemas.py | inexio/NESi | 920b23ccaf293733b4b571e4df27929c036257f7 | [
"BSD-2-Clause"
] | 3 | 2020-12-19T09:11:19.000Z | 2022-02-07T22:15:34.000Z | # This file is part of the NESi software.
#
# Copyright (c) 2020
# Original Software Design by Ilya Etingof <https://github.com/etingof>.
#
# Software adapted by inexio <https://github.com/inexio>.
# - Janis Groß <https://github.com/unkn0wn-user>
# - Philip Konrath <https://github.com/Connyko65>
# - Alexander Dincher <https://github.com/Dinker1996>
#
# License: https://github.com/inexio/NESi/LICENSE.rst
from nesi.devices.softbox.api import ma
from .interface_schemas import InterfacesSchema
from ..models.logport_models import LogPort
class LogPortSchema(ma.Schema):
class Meta:
model = LogPort
fields = ('id', 'box_id', 'box', 'card_id', 'name', 'ports', 'interfaces', 'description', 'admin_state',
'operational_state', 'label1', 'label2', 'profile',
'_links')
interfaces = ma.Nested(InterfacesSchema.InterfaceSchema, many=True)
box = ma.Hyperlinks(
{'_links': {
'self': ma.URLFor('show_box', id='<box_id>')}})
_links = ma.Hyperlinks(
{'self': ma.URLFor('show_logport', box_id='<box_id>', id='<id>'),
'collection': ma.URLFor('show_logports', box_id='<box_id>')})
class LogPortsSchema(ma.Schema):
class Meta:
fields = ('members', 'count', '_links')
class LogPortSchema(ma.Schema):
class Meta:
model = LogPort
fields = ('id', 'name', '_links')
_links = ma.Hyperlinks(
{'self': ma.URLFor(
'show_logport', box_id='<box_id>', id='<id>')})
members = ma.Nested(LogPortSchema, many=True)
_links = ma.Hyperlinks(
{'self': ma.URLFor('show_logports', box_id='<box_id>')})
| 31.754717 | 112 | 0.619727 |
6daefe3ec9e5b2703e766b14726c8339f68927b3 | 348 | swift | Swift | ReCaptcha/Classes/Rx/SPM_exported.swift | GhostGroup/ReCaptcha | fd8dc565d4a580d989e8b141952fbbd3c1a8ff34 | [
"MIT"
] | 1 | 2021-08-08T14:47:51.000Z | 2021-08-08T14:47:51.000Z | ReCaptcha/Classes/Rx/SPM_exported.swift | GhostGroup/ReCaptcha | fd8dc565d4a580d989e8b141952fbbd3c1a8ff34 | [
"MIT"
] | null | null | null | ReCaptcha/Classes/Rx/SPM_exported.swift | GhostGroup/ReCaptcha | fd8dc565d4a580d989e8b141952fbbd3c1a8ff34 | [
"MIT"
] | 1 | 2021-11-08T19:43:43.000Z | 2021-11-08T19:43:43.000Z | //
// SPM_exported.swift
//
//
// Created by Jakub Mazur on 15/07/2021.
//
/*
Since Swift Package Manager have directory structure and folders cannot override
this module import is needed to use internal dependency in ReCaptcha+Rx.swift file.
This file should NOT be included in Cocoapods and Carthage build
*/
@_exported import ReCaptcha
| 19.333333 | 83 | 0.755747 |
06f8ac08667c65025f52bba5713b804a3c9e426e | 2,079 | py | Python | Gathered CTF writeups/ptr-yudai-writeups/2019/UTCTF_2019/Encryption_Service/solve.py | mihaid-b/CyberSakura | f60e6b6bfd6898c69b84424b080090ae98f8076c | [
"MIT"
] | 1 | 2022-03-27T06:00:41.000Z | 2022-03-27T06:00:41.000Z | Gathered CTF writeups/ptr-yudai-writeups/2019/UTCTF_2019/Encryption_Service/solve.py | mihaid-b/CyberSakura | f60e6b6bfd6898c69b84424b080090ae98f8076c | [
"MIT"
] | null | null | null | Gathered CTF writeups/ptr-yudai-writeups/2019/UTCTF_2019/Encryption_Service/solve.py | mihaid-b/CyberSakura | f60e6b6bfd6898c69b84424b080090ae98f8076c | [
"MIT"
] | 1 | 2022-03-27T06:01:42.000Z | 2022-03-27T06:01:42.000Z | from ptrlib import *
def encrypt_message(mode, size, message):
sock.recvuntil(">")
sock.sendline("1")
sock.recvuntil(">")
sock.sendline(str(mode))
if 1 <= mode <= 2:
sock.recvuntil(">")
sock.sendline(str(size))
sock.recvuntil("message: ")
sock.sendline(message)
sock.recvuntil("message is: ")
return sock.recvline().rstrip()
else:
return None
def remove_encrypted_message(index):
sock.recvuntil(">")
sock.sendline("2")
sock.recvuntil("remove: ")
sock.sendline(str(index))
def view_encrypted_message(index):
sock.recvuntil(">")
sock.sendline("3")
sock.recvuntil("Message #" + str(index) + "\n")
sock.recvuntil("Plaintext: ")
plaintext = sock.recvline().rstrip()
sock.recvuntil("Ciphertext: ")
ciphertext = sock.recvline().rstrip()
return plaintext, ciphertext
def edit_encrypted_message(index, message):
sock.recvuntil(">")
sock.sendline("4")
sock.recvuntil("edit\n")
sock.sendline(str(index))
sock.recvuntil("message\n")
sock.sendline(message)
elf = ELF("./pwnable")
plt_puts = 0x004006e0
libc = ELF("./libc-2.17.so")
sock = Socket("127.0.0.1", 9001)
_ = input()
sock.recvline()
sock.sendline("0")
# libc leak
payload = b''
payload += p64(elf.got("puts"))
payload += p64(elf.got("puts"))
payload += p64(plt_puts)
payload += p64(plt_puts)
payload += p64(0)
encrypt_message(2, 0x200, "A") # 0
remove_encrypted_message(0)
encrypt_message(3, 0, '') # 0
encrypt_message(3, 0, '') # 1
edit_encrypted_message(0, payload)
edit_encrypted_message(1, '')
addr_puts = u64(sock.recvline().rstrip())
libc_base = addr_puts - libc.symbol("puts")
addr_system = libc_base + libc.symbol("system")
addr_binsh = libc_base + next(libc.search("/bin/sh"))
dump("libc_base = " + hex(libc_base))
# get the shell!
payload = b''
payload += p64(addr_binsh)
payload += p64(addr_binsh)
payload += p64(addr_system)
payload += p64(addr_system)
payload += p64(0)
edit_encrypted_message(0, payload)
edit_encrypted_message(1, '')
sock.interactive()
| 24.174419 | 53 | 0.660414 |
1c12e6e221390583c383ab1cdd4564096898af22 | 526 | sql | SQL | javawork/shorturl/src/main/resources/shorturl_sql_init.sql | velnewang/undefined-f3 | 7e18b6214349aa72caee6e4bb52ee6455a4ecacf | [
"Apache-2.0"
] | null | null | null | javawork/shorturl/src/main/resources/shorturl_sql_init.sql | velnewang/undefined-f3 | 7e18b6214349aa72caee6e4bb52ee6455a4ecacf | [
"Apache-2.0"
] | null | null | null | javawork/shorturl/src/main/resources/shorturl_sql_init.sql | velnewang/undefined-f3 | 7e18b6214349aa72caee6e4bb52ee6455a4ecacf | [
"Apache-2.0"
] | null | null | null | -- create table
CREATE TABLE IF NOT EXISTS `shorturl`(
`id` BIGINT(1) UNSIGNED NOT NULL,
`url` VARCHAR(2048) NOT NULL,
`counts` INT(1) NOT NULL,
`create_time` TIMESTAMP(0) NOT NULL,
`last_time` TIMESTAMP(0) NOT NULL,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- insert data
INSERT INTO `shorturl`
(id, url, counts, create_time, last_time)
VALUES
(0, 'http://min/0UPPW/', 42, '1971-01-01 00:00:00', '2037-12-31 12:34:56'),
(134217727, 'http://max/9ZZZZ/', 42, '1971-01-01 00:00:00', '2037-12-31 12:34:56');
| 30.941176 | 83 | 0.686312 |
ae2884c50e693ce07fc4d044d51ab1d9d87291c1 | 3,891 | cs | C# | Sources/EPiServer.Reference.Commerce.Site/Features/Cart/Controllers/CartController.cs | barrychampion/Quicksilver-Promotions | 3a684368724bdcf36659c76dbf7779d620f18e46 | [
"Apache-2.0"
] | 96 | 2015-05-06T13:46:51.000Z | 2022-01-18T09:57:59.000Z | Sources/EPiServer.Reference.Commerce.Site/Features/Cart/Controllers/CartController.cs | barrychampion/Quicksilver-Promotions | 3a684368724bdcf36659c76dbf7779d620f18e46 | [
"Apache-2.0"
] | 41 | 2015-05-24T10:35:16.000Z | 2021-08-17T14:39:40.000Z | Sources/EPiServer.Reference.Commerce.Site/Features/Cart/Controllers/CartController.cs | barrychampion/Quicksilver-Promotions | 3a684368724bdcf36659c76dbf7779d620f18e46 | [
"Apache-2.0"
] | 142 | 2015-05-07T17:37:58.000Z | 2022-03-25T15:37:51.000Z | using EPiServer.Commerce.Order;
using EPiServer.Reference.Commerce.Site.Features.Cart.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModelFactories;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Recommendations.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Attributes;
using EPiServer.Tracking.Commerce;
using EPiServer.Tracking.Commerce.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace EPiServer.Reference.Commerce.Site.Features.Cart.Controllers
{
public class CartController : Controller
{
private readonly ICartService _cartService;
private ICart _cart;
private readonly IOrderRepository _orderRepository;
private readonly IRecommendationService _recommendationService;
private readonly CartViewModelFactory _cartViewModelFactory;
public CartController(
ICartService cartService,
IOrderRepository orderRepository,
IRecommendationService recommendationService,
CartViewModelFactory cartViewModelFactory)
{
_cartService = cartService;
_orderRepository = orderRepository;
_recommendationService = recommendationService;
_cartViewModelFactory = cartViewModelFactory;
}
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult MiniCartDetails()
{
var viewModel = _cartViewModelFactory.CreateMiniCartViewModel(Cart);
return PartialView("_MiniCartDetails", viewModel);
}
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult LargeCart()
{
var viewModel = _cartViewModelFactory.CreateLargeCartViewModel(Cart);
return PartialView("LargeCart", viewModel);
}
[HttpPost]
public async Task<ActionResult> AddToCart(string code)
{
ModelState.Clear();
if (Cart == null)
{
_cart = _cartService.LoadOrCreateCart(_cartService.DefaultCartName);
}
var result = _cartService.AddToCart(Cart, code, 1);
if (result.EntriesAddedToCart)
{
_orderRepository.Save(Cart);
var change = new CartChangeData(CartChangeType.ItemAdded, code);
await _recommendationService.TrackCartAsync(HttpContext, new List<CartChangeData>{ change });
return MiniCartDetails();
}
return new HttpStatusCodeResult(500, result.GetComposedValidationMessage());
}
[HttpPost]
public async Task<ActionResult> ChangeCartItem(int shipmentId, string code, decimal quantity, string size, string newSize, string displayName)
{
ModelState.Clear();
var cartChange = _cartService.ChangeCartItem(Cart, shipmentId, code, quantity, size, newSize, displayName);
_orderRepository.Save(Cart);
var changes = new List<CartChangeData>();
if (cartChange != null)
{
changes.Add(cartChange);
}
await _recommendationService.TrackCartAsync(HttpContext, changes);
return MiniCartDetails();
}
[HttpPost]
public ActionResult UpdateShippingMethod(UpdateShippingMethodViewModel viewModel)
{
ModelState.Clear();
_cartService.UpdateShippingMethod(Cart, viewModel.ShipmentId, viewModel.ShippingMethodId);
_orderRepository.Save(Cart);
return LargeCart();
}
private ICart Cart
{
get { return _cart ?? (_cart = _cartService.LoadCart(_cartService.DefaultCartName)); }
}
}
} | 36.707547 | 150 | 0.655616 |
0ef8d2be0121a5cde9c47ea2ed9a07d1579527ae | 511 | swift | Swift | Demo/SimpleCollectionViewCell.swift | jayway/TableViewCompatible | a5ae1c3696752bcb52df9d5e7d4ebfee2c69483f | [
"Apache-2.0"
] | 36 | 2017-02-23T08:25:10.000Z | 2022-03-29T07:38:45.000Z | Demo/SimpleCollectionViewCell.swift | jayway/TableViewCompatible | a5ae1c3696752bcb52df9d5e7d4ebfee2c69483f | [
"Apache-2.0"
] | 2 | 2017-11-10T04:02:45.000Z | 2018-08-23T09:30:13.000Z | Demo/SimpleCollectionViewCell.swift | jayway/TableViewCompatible | a5ae1c3696752bcb52df9d5e7d4ebfee2c69483f | [
"Apache-2.0"
] | 6 | 2017-05-27T13:04:56.000Z | 2020-05-01T16:23:42.000Z | //
// SimpleCollectionViewCell.swift
// TableViewCompatible
//
// Created by Fredrik Nannestad on 31/01/2017.
// Copyright © 2017 Fredrik Nannestad. All rights reserved.
//
import UIKit
import CollectionAndTableViewCompatible
class SimpleCollectionViewCell: UICollectionViewCell, Configurable {
@IBOutlet weak var label: UILabel!
var model: SimpleCellModel?
func configure(withModel model: SimpleCellModel) {
self.model = model
label.text = model.string
}
}
| 22.217391 | 68 | 0.714286 |
3863c915f4e8d92ff0e449d44dd0856260ce3851 | 1,428 | php | PHP | resources/views/downloadpage40.blade.php | GrayChu/PlayExceller | ac6d5560f16b6e32f4fdb4f4e52c70c535b87fc3 | [
"MIT"
] | null | null | null | resources/views/downloadpage40.blade.php | GrayChu/PlayExceller | ac6d5560f16b6e32f4fdb4f4e52c70c535b87fc3 | [
"MIT"
] | null | null | null | resources/views/downloadpage40.blade.php | GrayChu/PlayExceller | ac6d5560f16b6e32f4fdb4f4e52c70c535b87fc3 | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('content')
<div class="container container-fruid">
<div class="form-group page-header">
<h2>
<label class="control-label">Download</label>
</h2>
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label>Requirement1</label>
<button onclick="window.location.href='{{url('/40/export1')}}'" class="btn brn-primary">下載</button>
</div>
<div class="col-md-4 mb-3">
<label>Requirement2</label>
<button onclick="window.location.href='{{url('/40/export2')}}'" class="btn brn-primary">下載</button>
</div>
<div class="col-md-4 mb-3">
<label>Requirement3</label>
<button onclick="window.location.href='{{url('/40/export3')}}'" class="btn brn-primary">下載</button>
</div>
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label>Requirement4-R</label>
<button onclick="window.location.href='{{url('/40/export4R')}}'" class="btn brn-primary">下載</button>
</div>
<div class="col-md-4 mb-3">
<label>Requirement4-G</label>
<button onclick="window.location.href='{{url('/40/export4G')}}'" class="btn brn-primary">下載</button>
</div>
<div class="col-md-4 mb-3">
<label>Requirement4-B</label>
<button onclick="window.location.href='{{url('/40/export4B')}}'" class="btn brn-primary">下載</button>
</div>
</div>
</div>
@endsection
@section('script')
@endsection
| 31.043478 | 106 | 0.607143 |
cc722ae4bb7310f4a0dfad34eb80a8c69b884ff9 | 1,923 | rb | Ruby | spec/ver/undo/record_sanitize.rb | manveru/ver | e3d6d18264686a7321be393435176368e08c9cf0 | [
"MIT"
] | 12 | 2015-01-08T10:59:21.000Z | 2021-07-02T16:59:54.000Z | spec/ver/undo/record_sanitize.rb | manveru/ver | e3d6d18264686a7321be393435176368e08c9cf0 | [
"MIT"
] | 2 | 2016-03-31T03:18:37.000Z | 2017-09-18T21:53:04.000Z | spec/ver/undo/record_sanitize.rb | manveru/ver | e3d6d18264686a7321be393435176368e08c9cf0 | [
"MIT"
] | null | null | null | require_relative '../../../lib/ver/undo'
require 'ffi-tk'
class Text < Tk::Text
class Index < Struct.new(:text, :position)
include Comparable
def <=>(other)
if text.compare(position, '>', other.position)
1
elsif text.compare(position, '<', other.position)
-1
elsif text.compare(position, '==', other.position)
0
end
end
def inspect
position.inspect
end
end
def index(index)
Index.new(self, super(index))
end
end
require 'bacon'
Bacon.summary_at_exit
describe 'VER::Undo::Record.sanitize' do
@text = Text.new
@text.value = <<-TEXT
this is the line one
this is the line two
this is the line three
this is the line four
this is the line six
TEXT
@tree = VER::Undo::Tree.new(@text)
def sanitize(*given)
record = VER::Undo::Record.new(@tree, @text)
results = record.sanitize(*given)
results.map{|result| result.map{|index| index.position }}
end
should 'sanitize two indices' do
sanitize('1.0', '1.0').should == [%w[1.0 1.0]]
end
should 'fail on odd number' do
i = '1.0'
lambda{ sanitize(i, i, i) }.should.raise(ArgumentError)
lambda{ sanitize(i, i, i, i, i) }.should.raise(ArgumentError)
end
should 'sanitize ordered non-overlapping' do
sanitize(*%w[1.0 1.5 1.6 1.10]).should == [%w[1.6 1.10], %w[1.0 1.5]]
end
should 'sanitize unordered non-overlapping' do
sanitize(*%w[1.6 1.10 1.0 1.5]).should == [%w[1.6 1.10], %w[1.0 1.5]]
end
should 'sanitize unordered overlapping' do
sanitize(*%w[1.6 1.10 1.0 1.7]).should == [%w[1.0 1.10]]
end
should 'sanitize ordered overlapping' do
sanitize(*%w[1.0 1.7 1.5 1.8]).should == [%w[1.0 1.8]]
end
should 'sanitize a lot' do
indices = %w[
1.0 2.0
1.3 2.1
2.2 3.4
3.6 3.8
3.7 4.0
]
sanitize(*indices).should == [%w[3.6 4.0], %w[2.2 3.4], %w[1.0 2.1]]
end
end
| 22.360465 | 73 | 0.599584 |
a3d6d649b9f5649b9a0915c5483bb2462cea7749 | 1,111 | java | Java | java/Atividades/04 - Vetor/src/vetor/exe01ordemInversa.java | Ebony-Full-Stack/Bloco_1 | 06bfbd3d85192b5582c6edda2882810ac2e1e59f | [
"Apache-2.0"
] | 1 | 2021-12-29T01:44:21.000Z | 2021-12-29T01:44:21.000Z | java/Atividades/04 - Vetor/src/vetor/exe01ordemInversa.java | Ebony-Generation/Bloco_1 | 06bfbd3d85192b5582c6edda2882810ac2e1e59f | [
"Apache-2.0"
] | null | null | null | java/Atividades/04 - Vetor/src/vetor/exe01ordemInversa.java | Ebony-Generation/Bloco_1 | 06bfbd3d85192b5582c6edda2882810ac2e1e59f | [
"Apache-2.0"
] | null | null | null | package vetor;
import java.util.Scanner;
/*
Faça um Programa com um vetor de 5 números reais
e mostre-os na ordem inversa.
Autor Leonardo Alves
*/
public class exe01ordemInversa {
public static void main(String[] args) {
try (Scanner ler = new Scanner (System.in)) {
double[] vetor = new double[5];
int cont;
// populando o vetor
for (cont=0; cont < vetor.length; cont++) {
System.out.printf("Digite um valor: ");
vetor[cont] = ler.nextDouble();
}
// Mostrando na ordem que foi inserido
System.out.printf("\nValores em ordem normal.: ");
for (cont=0; cont < vetor.length; cont++) {
if (cont == 4) {
System.out.printf(vetor[cont] + ", ".replace(", ", " "));
} else {
System.out.printf(vetor[cont] + ", ");
}
}
// Mostrando em ordem inversa
System.out.printf("\nValores em ordem inversa: ");
for (cont=(vetor.length)-1; cont >= 0; cont--) {
if (cont == 0) {
System.out.printf(vetor[cont] + ", ".replace(", ", " "));
} else {
System.out.printf(vetor[cont] + ", ");
}
}
ler.close();
}
}
}
| 23.638298 | 62 | 0.578758 |
ccce0647df63c7121dbf446040b68256890a65ee | 3,102 | rb | Ruby | app/controllers/spree/checkout_controller_decorator.rb | przekogo/spree_przelewy24_integration | 9222e4d05ae458092d7fe36e2f2c97e930dbbc65 | [
"MIT"
] | null | null | null | app/controllers/spree/checkout_controller_decorator.rb | przekogo/spree_przelewy24_integration | 9222e4d05ae458092d7fe36e2f2c97e930dbbc65 | [
"MIT"
] | 8 | 2020-06-24T18:43:16.000Z | 2022-03-08T21:42:23.000Z | app/controllers/spree/checkout_controller_decorator.rb | przekogo/spree_przelewy24_integration | 9222e4d05ae458092d7fe36e2f2c97e930dbbc65 | [
"MIT"
] | null | null | null | module Spree
module CheckoutControllerDecorator
def self.prepended(base)
base.before_action :pay_with_przelewy24, only: :update
end
private
def pay_with_przelewy24
begin
return unless params[:state] == 'payment'
return if params[:order].blank? || params[:order][:payments_attributes].blank?
pm_id = params[:order][:payments_attributes].first[:payment_method_id]
payment_method = Spree::PaymentMethod.find(pm_id)
if payment_method && payment_method.kind_of?(Spree::PaymentMethod::Przelewy24)
p24_params = prepare_register_transaction_przelewy24_params(payment_method)
register_transaction_response = register_transaction_przelewy24(payment_method, p24_params)
@order.save
logger.info("Przelewy24 transaction registration params: #{p24_params}")
if register_transaction_response['error']=='0'
logger.info("Token recived: #{register_transaction_response['token']}. Redirecting user to Przelewy24 for payment")
redirect_to "#{payment_method.payment_url}/#{register_transaction_response['token']}"
else
logger.error "Registering transaction with Przelewy24 FAILED. Error code: #{register_transaction_response['error']}. Error message: #{register_transaction_response['errorMessage']}"
@order.destroy
redirect_to root_path, alert: I18n.t("spree.register_transaction_error")
end
end
rescue Timeout::Error
logger.error "Registering transaction with Przelewy24 FAILED. Connection timed out"
@order.destroy
redirect_to root_path, alert: I18n.t("spree.przelewy24_timeout")
end
end
def prepare_register_transaction_przelewy24_params(payment_method)
p24_params = {
p24_merchant_id: payment_method.preferences[:p24_id_sprzedawcy],
p24_pos_id: payment_method.preferences[:p24_id_sprzedawcy],
p24_session_id: @order.number,
p24_amount: (@order.total*100).to_i, # conversion to przelewy24 required integer format
p24_currency: @order.currency,
p24_description: "Zamowienie nr #{@order.number}",
p24_email: @order.email,
p24_country: 'PL',
p24_url_return: order_url(@order, {checkout_complete: true, order_token: @order.token}), notice: I18n.t("spree.order_completed"),
p24_url_status: przelewy24_confirm_transaction_url(payment_method.id, @order.id),
p24_api_version: '3.2'
}
p24_params.merge!(p24_sign: Digest::MD5.hexdigest("#{p24_params[:p24_session_id]}|#{payment_method.preferences[:p24_id_sprzedawcy]}|#{p24_params[:p24_amount]}|#{p24_params[:p24_currency]}|#{payment_method.crc_key}"))
end
def register_transaction_przelewy24(payment_method, p24_params)
uri = URI(payment_method.register_url)
Net::HTTP.post_form(uri, p24_params).body.split('&',2).map{|r| r.split('=')}.to_h # handle http-like response attributes
end
end
end
::Spree::CheckoutController.prepend ::Spree::CheckoutControllerDecorator | 48.46875 | 222 | 0.706963 |
6ddcfd0812abb0d60f50fd0b3a54d4b60ec2617a | 1,076 | ts | TypeScript | features/interfaces.ts | stacyburris/typescript-guide | 6683d4fc4560303ea32c48609d1025200ac5d881 | [
"MIT"
] | null | null | null | features/interfaces.ts | stacyburris/typescript-guide | 6683d4fc4560303ea32c48609d1025200ac5d881 | [
"MIT"
] | null | null | null | features/interfaces.ts | stacyburris/typescript-guide | 6683d4fc4560303ea32c48609d1025200ac5d881 | [
"MIT"
] | null | null | null | const oldCivic = {
name: 'civic',
year: 2000,
broken: true
};
const printVehicle = (vehicle: { name: string; year: number; broken: boolean }): void => { // void equals function returns nothing
console.log(`Name: ${vehicle.name}`);
console.log(`Year: ${vehicle.year}`);
console.log(`Broken? ${vehicle.broken}`);
};
printVehicle(oldCivic);
// Improve above code with an interface:
interface Reportable {
// name: string;
// year: Date;
// broken: boolean;
summary(): string;
}
const oldCivic2 = {
name: 'civic',
year: new Date(),
broken: true,
summary(): string {
return `Name: ${this.name}`;
}
};
// Another Interface example:
const drink2 = {
color: 'brown',
carbonated: true,
sugar: 40,
summary(): string {
return `My drink has ${this.sugar} grams of sugar`;
}
};
const printSummary = (item: Reportable): void => {
// console.log(`Name: ${item.name}`);
// console.log(`Year: ${item.year}`);
// console.log(`Broken? ${item.broken}`);
console.log(item.summary());
};
printSummary(oldCivic2);
printSummary(drink2);
| 21.098039 | 130 | 0.6329 |
0d5db206d885a0cda54b29e2b50b61523b5b7034 | 3,326 | h | C | include/GafferScene/Private/IECoreGLPreview/AttributeVisualiser.h | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 561 | 2016-10-18T04:30:48.000Z | 2022-03-30T06:52:04.000Z | include/GafferScene/Private/IECoreGLPreview/AttributeVisualiser.h | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 1,828 | 2016-10-14T19:01:46.000Z | 2022-03-30T16:07:19.000Z | include/GafferScene/Private/IECoreGLPreview/AttributeVisualiser.h | ddesmond/gaffer | 4f25df88103b7893df75865ea919fb035f92bac0 | [
"BSD-3-Clause"
] | 120 | 2016-10-18T15:19:13.000Z | 2021-12-20T16:28:23.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Image Engine. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECOREGLPREVIEW_ATTRIBUTEVISUALISER_H
#define IECOREGLPREVIEW_ATTRIBUTEVISUALISER_H
#include "GafferScene/Export.h"
#include "GafferScene/Private/IECoreGLPreview/Visualiser.h"
#include "IECoreGL/Renderable.h"
#include "IECore/CompoundObject.h"
namespace IECoreGLPreview
{
IE_CORE_FORWARDDECLARE( AttributeVisualiser )
class GAFFERSCENE_API AttributeVisualiser : public IECore::RefCounted
{
public :
IE_CORE_DECLAREMEMBERPTR( AttributeVisualiser )
~AttributeVisualiser() override;
virtual Visualisations visualise(
const IECore::CompoundObject *attributes,
IECoreGL::ConstStatePtr &state
) const = 0;
/// Registers an attribute visualiser
static void registerVisualiser( ConstAttributeVisualiserPtr visualiser );
/// Get all registered visualisations for the given attributes, by
/// returning a map of renderable groups and some extra state. The
/// return value may be left empty and/or the state may left null if no
/// registered visualisers do anything with these attributes.
static Visualisations allVisualisations(
const IECore::CompoundObject *attributes,
IECoreGL::ConstStatePtr &state
);
protected :
AttributeVisualiser();
template<typename VisualiserType>
struct AttributeVisualiserDescription
{
AttributeVisualiserDescription()
{
registerVisualiser( new VisualiserType );
}
};
};
IE_CORE_DECLAREPTR( AttributeVisualiser )
} // namespace IECoreGLPreview
#endif // IECOREGLPREVIEW_ATTRIBUTEVISUALISER_H
| 33.59596 | 78 | 0.720385 |
e4035c1c615363b41884972a075eb3cc20b06c3c | 1,426 | cs | C# | NVIDIA.PhysX/Wrapper/PxOverlapHit.cs | zjhlogo/UnityPhysXPlugin | 0a84c892f87a5dedad7a07f8de09580ea4fa8354 | [
"BSD-3-Clause"
] | 62 | 2021-06-15T15:55:21.000Z | 2022-03-26T03:45:18.000Z | NVIDIA.PhysX/Wrapper/PxOverlapHit.cs | zjhlogo/UnityPhysXPlugin | 0a84c892f87a5dedad7a07f8de09580ea4fa8354 | [
"BSD-3-Clause"
] | 3 | 2021-06-18T09:20:09.000Z | 2022-03-26T02:02:03.000Z | NVIDIA.PhysX/Wrapper/PxOverlapHit.cs | zjhlogo/UnityPhysXPlugin | 0a84c892f87a5dedad7a07f8de09580ea4fa8354 | [
"BSD-3-Clause"
] | 15 | 2021-06-17T15:25:56.000Z | 2022-03-27T00:16:55.000Z | //------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 4.0.2
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace NVIDIA.PhysX {
public partial class PxOverlapHit : PxQueryHit {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal PxOverlapHit(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NativePINVOKE.PxOverlapHit_SWIGUpcast(cPtr), cMemoryOwn) {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(PxOverlapHit obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
public override void destroy() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
NativePINVOKE.delete_PxOverlapHit(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
base.destroy();
}
}
}
}
| 34.780488 | 134 | 0.626227 |
ddaa3855b50d25aabed5bab6e5b0491513e090bf | 5,950 | java | Java | LearningEnhancementSystem/src/java/Database/EvaluationDb.java | vegardalvsaker/BrukerfeilLES | 7efcf44b422752d2ce5d24a691130a8c82a90f32 | [
"MIT"
] | null | null | null | LearningEnhancementSystem/src/java/Database/EvaluationDb.java | vegardalvsaker/BrukerfeilLES | 7efcf44b422752d2ce5d24a691130a8c82a90f32 | [
"MIT"
] | 11 | 2018-08-30T19:40:16.000Z | 2018-11-19T22:07:04.000Z | LearningEnhancementSystem/src/java/Database/EvaluationDb.java | vegardalvsaker/BrukerfeilLES | 7efcf44b422752d2ce5d24a691130a8c82a90f32 | [
"MIT"
] | 3 | 2019-10-08T19:36:16.000Z | 2021-01-18T13:26:01.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Database;
import java.sql.*;
import Classes.Evaluation;
import Classes.Score;
/**
*
* @author Vegard
*/
public class EvaluationDb extends Database{
private static final String ADD_EVALUATION = "insert into Evaluation values (default, ?, ?, '', false)";
private static final String SELECT_ONE = "select evaluation_id from Evaluation where delivery_id = ?";
private static final String SELECT_EVALUATION_WITH_SCORE = "select * from Evaluation e inner join Score s on e.evaluation_id = s.evaluation_id where e.delivery_id = ?";
private static final String UPDATE_ISPUBLISHED = "update Evaluation set evaluation_isPublished = ? where evaluation_id = ?";
private static final String DELETE_EVALUATION = "delete from Evaluation where evaluation_id = ?";
private static final String UPDATE_COMMENT = "update Evaluation set evaluation_comment = ? where delivery_id = ?";
public EvaluationDb(){
init();
}
public boolean addEvaluation(String teacher_id, String delivery_id){
if (evaluationExists(delivery_id)) {
return false;
} else {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(ADD_EVALUATION);
) {
ps.setString(1, teacher_id);
ps.setString(2, delivery_id);
ps.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println(ex);
}
}
return false;
}
public boolean evaluationExists(String delivery_id) {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(SELECT_ONE);
) {
ps.setString(1, delivery_id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return true;
}
} catch (SQLException ex) {
System.out.println("Some error with the database" + ex);
}
return false;
}
/**
* Adds a comment to an evaluation
* @param deliveryid
* @param comment
* @return
*/
public boolean addComment(String deliveryid, String comment) {
try (Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(UPDATE_COMMENT);) {
ps.setString(1, comment);
ps.setString(2, deliveryid);
ps.executeUpdate();
return true;
}
catch (SQLException ex) {
System.out.println(ex);
return false;
}
}
public String getEvaluationId(String deliveryId) {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(SELECT_ONE);
) {
ps.setString(1, deliveryId);
ResultSet rs = ps.executeQuery();
rs.first();
return rs.getString("evaluation_id");
} catch (SQLException ex) {
System.out.println("Method: getEvaluationId(), error" + ex);
}
return null;
}
public Evaluation getEvaluationWithScore(String deliveryId) {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(SELECT_EVALUATION_WITH_SCORE);
) {
ps.setString(1, deliveryId);
try (ResultSet rset = ps.executeQuery()) {
rset.next();
Evaluation eval = new Evaluation();
eval.setEvaluationid(rset.getString("evaluation_id"));
eval.setComment(rset.getString("evaluation_comment"));
eval.setIsPublished(rset.getBoolean("evaluation_isPublished"));
eval.setDeliveryid(rset.getString("delivery_id"));
Score s1 = new Score();
s1.setEvaluation_id(rset.getString("evaluation_id"));
s1.setId(rset.getString("score_id"));
s1.setLearn_goal_id(rset.getString("learn_goal_id"));
s1.setPoints(rset.getInt("score_points"));
eval.addScoreToList(s1);
while (rset.next()) {
Score s2 = new Score();
s2.setEvaluation_id("evaluation_id");
s2.setId(rset.getString("score_id"));
s2.setLearn_goal_id(rset.getString("learn_goal_id"));
s2.setPoints(rset.getInt("score_points"));
eval.addScoreToList(s2);
}
return eval;
}
}
catch (SQLException ex) {
System.out.println("method: getEvaluationWithScore" + ex);
}
return null;
}
public void publish(boolean publish, String evaluationid) {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(UPDATE_ISPUBLISHED);
) {
ps.setBoolean(1, publish);
ps.setString(2, evaluationid);
ps.executeUpdate();
}catch (SQLException ex) {
System.out.println(ex);
}
}
public void deleteEvaluation(String evaluationid) {
try (
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(DELETE_EVALUATION)) {
ps.setString(1, evaluationid);
ps.executeUpdate();
} catch (SQLException ex) {
System.out.println(ex);
}
}
} | 35.416667 | 172 | 0.556471 |
91505d32d934ddb528e8fc019e04fdb399aa2753 | 147 | sql | SQL | Exams/Databases MSSQL Server Exam - 20 Oct 2019/06. Reports & Categories.sql | drapperr/Databases-Basics---MS-SQL-Server | e36c3c88d03bdd0a203e33d43e0c24c4bf83f108 | [
"MIT"
] | null | null | null | Exams/Databases MSSQL Server Exam - 20 Oct 2019/06. Reports & Categories.sql | drapperr/Databases-Basics---MS-SQL-Server | e36c3c88d03bdd0a203e33d43e0c24c4bf83f108 | [
"MIT"
] | null | null | null | Exams/Databases MSSQL Server Exam - 20 Oct 2019/06. Reports & Categories.sql | drapperr/Databases-Basics---MS-SQL-Server | e36c3c88d03bdd0a203e33d43e0c24c4bf83f108 | [
"MIT"
] | null | null | null | SELECT [Description], C.[Name] AS [CategoryName] FROM Reports AS R
JOIN Categories AS C ON C.Id = R.CategoryId
ORDER BY [Description], CategoryName | 49 | 66 | 0.768707 |
0265073d7d027ddf6b110e4b666d7335b05f929b | 106 | lua | Lua | InGameAvatarEditor/src/ServerScriptService/AvatarEditorInGameSetup/AvatarEditorInGame/Modules/Packages/Localization/LocalizationKey.lua | MirayXS/avatar | 7c78513fbe9587915700a0a5fd3c15d5f23596d2 | [
"RSA-MD"
] | 41 | 2021-04-30T18:27:45.000Z | 2022-03-23T21:12:57.000Z | InGameAvatarEditor/src/ServerScriptService/AvatarEditorInGameSetup/AvatarEditorInGame/Modules/Packages/Localization/LocalizationKey.lua | MirayXS/avatar | 7c78513fbe9587915700a0a5fd3c15d5f23596d2 | [
"RSA-MD"
] | 3 | 2021-08-24T20:07:47.000Z | 2022-02-15T19:40:13.000Z | InGameAvatarEditor/src/ServerScriptService/AvatarEditorInGameSetup/AvatarEditorInGame/Modules/Packages/Localization/LocalizationKey.lua | MirayXS/avatar | 7c78513fbe9587915700a0a5fd3c15d5f23596d2 | [
"RSA-MD"
] | 25 | 2021-05-02T14:33:04.000Z | 2022-03-17T20:28:07.000Z | local Root = script.Parent.Parent
local Symbol = require(Root.Symbol)
return Symbol.named("Localization") | 26.5 | 35 | 0.792453 |
0a86cf1886b485613463393b9a9b31312fc5e321 | 9,019 | cs | C# | AutoStop/AutoStopSettings.cs | ghotm/HearthbuddyPlugins | f5f03256197db9ccb0113610c55c34a820bf4fd3 | [
"MIT"
] | 2 | 2020-06-16T03:07:32.000Z | 2020-07-06T04:39:21.000Z | AutoStop/AutoStopSettings.cs | ghotm/HearthbuddyPlugins | f5f03256197db9ccb0113610c55c34a820bf4fd3 | [
"MIT"
] | null | null | null | AutoStop/AutoStopSettings.cs | ghotm/HearthbuddyPlugins | f5f03256197db9ccb0113610c55c34a820bf4fd3 | [
"MIT"
] | 2 | 2020-05-21T03:37:26.000Z | 2020-07-11T09:14:59.000Z | using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using log4net;
using Newtonsoft.Json;
using Triton.Bot.Logic.Bots.DefaultBot;
using Triton.Bot.Settings;
using Triton.Common;
using Triton.Game;
using Triton.Game.Mapping;
using Triton.Game.Mono;
using Logger = Triton.Common.LogUtilities.Logger;
namespace AutoStop
{
/// <summary>Settings for the Stats plugin. </summary>
public class AutoStopSettings : JsonSettings
{
private static readonly ILog Log = Logger.GetLoggerInstanceForType();
private static AutoStopSettings _instance;
/// <summary>The current instance for this class. </summary>
public static AutoStopSettings Instance
{
get { return _instance ?? (_instance = new AutoStopSettings()); }
}
/// <summary>The default ctor. Will use the settings path "Stats".</summary>
public AutoStopSettings()
: base(GetSettingsFilePath(Configuration.Instance.Name, string.Format("{0}.json", "AutoStop")))
{
}
private bool _stopAfterXGames;
private bool _stopAfterXWins;
private bool _stopAfterXLosses;
private bool _stopAfterXConcedes;
private int _stopGameCount;
private int _stopWinCount;
private int _stopLossCount;
private int _stopConcedeCount;
private bool _stopAtRank;
private int _rankToStopAt;
private int _wins;
private int _losses;
private int _concedes;
private int _rank;
public void Reset()
{
Wins = 0;
Losses = 0;
Concedes = 0;
bool useWildMedal = DefaultBotSettings.Instance.ConstructedMode.Equals("狂野模式");
int currentRank = SimpleRankMgr.Get().GetLocalPlayerMedalInfo().GetCurrentMedal(useWildMedal).GetLegacyRankNumber();
Rank = currentRank;
}
/// <summary>
/// Should the bot stop when a certain rank is reached?
/// </summary>
[DefaultValue(false)]
public bool StopAtRank
{
get { return _stopAtRank; }
set
{
if (!value.Equals(_stopAtRank))
{
_stopAtRank = value;
NotifyPropertyChanged(() => StopAtRank);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至天梯等级 = {0}.", _stopAtRank);
}
}
/// <summary>The rank to stop at.</summary>
[DefaultValue(20)]
public int RankToStopAt
{
get { return _rankToStopAt; }
set
{
if (!value.Equals(_rankToStopAt))
{
_rankToStopAt = value;
NotifyPropertyChanged(() => RankToStopAt);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至天梯等级 = {0}.", _rankToStopAt);
}
}
/// <summary>Current stored rank.</summary>
[DefaultValue(-1)]
public int Rank
{
get { return _rank; }
set
{
if (value.Equals(_rank))
{
return;
}
_rank = value;
NotifyPropertyChanged(() => Rank);
}
}
/// <summary>Current stored wins.</summary>
[DefaultValue(0)]
public int Wins
{
get { return _wins; }
set
{
if (value.Equals(_wins))
{
return;
}
_wins = value;
NotifyPropertyChanged(() => Wins);
}
}
/// <summary>Current stored losses.</summary>
[DefaultValue(0)]
public int Losses
{
get { return _losses; }
set
{
if (value.Equals(_losses))
{
return;
}
_losses = value;
NotifyPropertyChanged(() => Losses);
}
}
/// <summary>Current stored concedes.</summary>
[DefaultValue(0)]
public int Concedes
{
get { return _concedes; }
set
{
if (value.Equals(_concedes))
{
return;
}
_concedes = value;
NotifyPropertyChanged(() => Concedes);
}
}
/// <summary>
/// How many games should the bot play before stopping?
/// </summary>
[DefaultValue(1)]
public int StopGameCount
{
get { return _stopGameCount; }
set
{
if (!value.Equals(_stopGameCount))
{
_stopGameCount = value;
NotifyPropertyChanged(() => StopGameCount);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至对局数 = {0}.", _stopGameCount);
}
}
/// <summary>
/// How many games should the bot win before stopping?
/// </summary>
[DefaultValue(1)]
public int StopWinCount
{
get { return _stopWinCount; }
set
{
if (!value.Equals(_stopWinCount))
{
_stopWinCount = value;
NotifyPropertyChanged(() => StopWinCount);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至胜局 = {0}.", _stopWinCount);
}
}
/// <summary>
/// How many games should the bot lose before stopping?
/// </summary>
[DefaultValue(1)]
public int StopLossCount
{
get { return _stopLossCount; }
set
{
if (!value.Equals(_stopLossCount))
{
_stopLossCount = value;
NotifyPropertyChanged(() => StopLossCount);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至败局 = {0}.", _stopLossCount);
}
}
/// <summary>
/// How many games should the bot concede before stopping?
/// </summary>
[DefaultValue(1)]
public int StopConcedeCount
{
get { return _stopConcedeCount; }
set
{
if (!value.Equals(_stopConcedeCount))
{
_stopConcedeCount = value;
NotifyPropertyChanged(() => StopConcedeCount);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至投降局数 = {0}.", _stopConcedeCount);
}
}
/// <summary>
/// Should the bot stop after each game played?
/// </summary>
[DefaultValue(false)]
public bool StopAfterXGames
{
get { return _stopAfterXGames; }
set
{
if (!value.Equals(_stopAfterXGames))
{
_stopAfterXGames = value;
NotifyPropertyChanged(() => StopAfterXGames);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至完成的对局数 = {0}.", _stopAfterXGames);
}
}
/// <summary>
/// Should the bot stop after each win?
/// </summary>
[DefaultValue(false)]
public bool StopAfterXWins
{
get { return _stopAfterXWins; }
set
{
if (!value.Equals(_stopAfterXWins))
{
_stopAfterXWins = value;
NotifyPropertyChanged(() => StopAfterXWins);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至完成的胜局数 = {0}.", _stopAfterXWins);
}
}
/// <summary>
/// Should the bot stop after each loss?
/// </summary>
[DefaultValue(false)]
public bool StopAfterXLosses
{
get { return _stopAfterXLosses; }
set
{
if (!value.Equals(_stopAfterXLosses))
{
_stopAfterXLosses = value;
NotifyPropertyChanged(() => StopAfterXLosses);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至完成的败局数 = {0}.", _stopAfterXLosses);
}
}
/// <summary>
/// Should the bot stop after each concede?
/// </summary>
[DefaultValue(false)]
public bool StopAfterXConcedes
{
get { return _stopAfterXConcedes; }
set
{
if (!value.Equals(_stopAfterXConcedes))
{
_stopAfterXConcedes = value;
NotifyPropertyChanged(() => StopAfterXConcedes);
}
Log.InfoFormat("[自动停止插件设置] 自动停止至完成投降的局数 = {0}.", _stopAfterXConcedes);
}
}
}
}
| 29.473856 | 128 | 0.475995 |
8ecefaab926f7ad8b6a73799d32d40a1d1aed8ac | 1,077 | js | JavaScript | egg-upload-file/app/public/js/main.js | wuzhengyan2015/egg-common-example | 8b7afbce0cfed0c9fc27e885ae83760b18147e07 | [
"MIT"
] | null | null | null | egg-upload-file/app/public/js/main.js | wuzhengyan2015/egg-common-example | 8b7afbce0cfed0c9fc27e885ae83760b18147e07 | [
"MIT"
] | null | null | null | egg-upload-file/app/public/js/main.js | wuzhengyan2015/egg-common-example | 8b7afbce0cfed0c9fc27e885ae83760b18147e07 | [
"MIT"
] | null | null | null | 'use strict';
const form = document.querySelector('.ajax-form');
form.addEventListener('submit', e => {
e.preventDefault();
const formData = new FormData();
formData.append('file', form.elements.file.files[0]);
const _csrf = form.elements._csrf.value;
// fetch(`/upload?_csrf=${_csrf}`, {
// method: 'POST',
// body: formData,
// });
window.axios(`/ajax?_csrf=${_csrf}`, {
method: 'POST',
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
});
const multiForm = document.querySelector('.ajax-multiple');
multiForm.addEventListener('submit', e => {
e.preventDefault();
const formData = new FormData();
for (const file of multiForm.elements.file.files) {
formData.append(file.name, file);
}
const _csrf = multiForm.elements._csrf.value;
// fetch(`/upload?_csrf=${_csrf}`, {
// method: 'POST',
// body: formData,
// });
window.axios(`/multiple?_csrf=${_csrf}`, {
method: 'POST',
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
},
});
});
| 24.477273 | 59 | 0.612813 |
d1f1ebef8f1ef586625db1ec19820a8ee2264134 | 69 | sql | SQL | db/schema.sql | Chris-Franklin-1701/CAN-Do-Translations | d8d00ed8876e7b14805f0440547762a4400ff5c3 | [
"MIT"
] | null | null | null | db/schema.sql | Chris-Franklin-1701/CAN-Do-Translations | d8d00ed8876e7b14805f0440547762a4400ff5c3 | [
"MIT"
] | 2 | 2021-11-09T16:49:09.000Z | 2021-11-12T02:13:01.000Z | db/schema.sql | Chris-Franklin-1701/CAN-Do-Translations | d8d00ed8876e7b14805f0440547762a4400ff5c3 | [
"MIT"
] | 1 | 2021-11-10T23:11:20.000Z | 2021-11-10T23:11:20.000Z | DROP DATABASE IF EXISTS translator_db;
CREATE DATABASE translator_db; | 34.5 | 38 | 0.869565 |
d302fe811a4bf04d29552f8962316ca60284458a | 469 | cs | C# | MasterDetailsDataEntry.Demo.Database/Model/Client.cs | euklad/MasterDetailsDataEntry | 27643313bbf9758f1dccf41bf5c99648609f4c26 | [
"MIT"
] | 22 | 2020-10-25T18:52:41.000Z | 2021-11-25T09:27:31.000Z | MasterDetailsDataEntry.Demo.Database/Model/Client.cs | evolvencemsm/MasterDetailsDataEntry | 5d2420f4f98965446f486833105ae851623022bc | [
"MIT"
] | 84 | 2020-10-24T07:22:22.000Z | 2021-11-06T04:04:29.000Z | MasterDetailsDataEntry.Demo.Database/Model/Client.cs | euklad/MasterDetailsDataEntry | 27643313bbf9758f1dccf41bf5c99648609f4c26 | [
"MIT"
] | 8 | 2021-01-04T16:05:07.000Z | 2021-12-09T02:25:43.000Z | using System;
using System.Collections.Generic;
namespace MasterDetailsDataEntry.Demo.Database.Model
{
public partial class Client
{
public Client()
{
Order = new HashSet<Order>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get; set; }
public virtual ICollection<Order> Order { get; set; }
}
}
| 22.333333 | 61 | 0.588486 |
f8a688aff91e252eb668f8518c44fa0464bf13dd | 804 | c | C | pyhand/kinematics/hind_arm_middle_inter_bend_3.c | jsupancic/libhand-public | da9b92fa5440d06fdd4ba72c2327c50c88a1d469 | [
"CC-BY-3.0"
] | 19 | 2015-11-28T03:49:10.000Z | 2021-04-12T13:19:26.000Z | pyhand/kinematics/hind_arm_middle_inter_bend_3.c | jsupancic/libhand-public | da9b92fa5440d06fdd4ba72c2327c50c88a1d469 | [
"CC-BY-3.0"
] | 4 | 2015-12-24T08:53:10.000Z | 2017-11-08T10:58:16.000Z | pyhand/kinematics/hind_arm_middle_inter_bend_3.c | jsupancic/libhand-public | da9b92fa5440d06fdd4ba72c2327c50c88a1d469 | [
"CC-BY-3.0"
] | 7 | 2015-12-16T05:27:22.000Z | 2020-08-24T07:59:29.000Z | /******************************************************************************
* Code generated with sympy 0.7.6 *
* *
* See http://www.sympy.org/ for more information. *
* *
* This file is part of 'project' *
******************************************************************************/
#include "hind_arm_middle_inter_bend_3.h"
#include <math.h>
double hind_arm_middle_inter_bend_3() {
double hind_arm_middle_inter_bend_3_result;
hind_arm_middle_inter_bend_3_result = 0;
return hind_arm_middle_inter_bend_3_result;
}
| 44.666667 | 80 | 0.353234 |
74bb8f99e1cea352ef9f39ff7de8fa6af00959b5 | 4,775 | css | CSS | src/assets/css/Animations.css | TitoGrine/Ascoldata | 31aabd3c9da0d2977049ffca998aa7e2afa921b7 | [
"MIT"
] | 13 | 2020-09-22T14:07:57.000Z | 2021-11-04T15:48:58.000Z | src/assets/css/Animations.css | TitoGrine/Ascoldata | 31aabd3c9da0d2977049ffca998aa7e2afa921b7 | [
"MIT"
] | 1 | 2020-09-16T19:23:31.000Z | 2020-09-25T18:48:38.000Z | src/assets/css/Animations.css | TitoGrine/Ascoldata | 31aabd3c9da0d2977049ffca998aa7e2afa921b7 | [
"MIT"
] | null | null | null | /* Animations */
.slide-in-right {
-webkit-animation: slide-in-right 1s cubic-bezier(0.455, 0.030, 0.515, 0.955) both;
animation: slide-in-right 1s cubic-bezier(0.455, 0.030, 0.515, 0.955) both;
}
.heartbeat {
-webkit-animation: heartbeat 2s cubic-bezier(0.550, 0.085, 0.680, 0.530) infinite both;
animation: heartbeat 2s cubic-bezier(0.550, 0.085, 0.680, 0.530) infinite both;
}
@-webkit-keyframes rotation {
0% {
-webkit-transform: rotate(0);
transform: rotate(0);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes rotation {
0% {
-webkit-transform: rotate(0);
transform: rotate(0);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-webkit-keyframes fadeIn {
0% {
filter: brightness(1);
}
100% {
filter: brightness(1.2);
}
}
@keyframes fadeIn {
0% {
filter: brightness(1);
}
100% {
filter: brightness(1.2);
}
}
@-webkit-keyframes focusIn {
0% {
filter: opacity(0.6);
}
100% {
filter: opacity(1);
}
}
@keyframes focusIn {
0% {
filter: opacity(0.6);
}
100% {
filter: opacity(1);
}
}
@-webkit-keyframes focusOut {
0% {
filter: opacity(1);
}
100% {
filter: opacity(0.6);
}
}
@keyframes focusOut {
0% {
filter: opacity(1);
}
100% {
filter: opacity(0.6);
}
}
/* ----------------------------------------------
* Generated by Animista on 2020-7-21 16:26:58
* Licensed under FreeBSD License.
* See http://animista.net/license for more info.
* w: http://animista.net, t: @cssanimista
* ---------------------------------------------- */
/**
* ----------------------------------------
* animation slide-in-left
* ----------------------------------------
*/
@-webkit-keyframes slide-in-left {
0% {
-webkit-transform: translateX(-1000px);
transform: translateX(-1000px);
opacity: 0.5;
}
100% {
-webkit-transform: translateX(0);
transform: translateX(0);
opacity: 1;
}
}
@keyframes slide-in-left {
0% {
-webkit-transform: translateX(-1000px);
transform: translateX(-1000px);
opacity: 0.5;
}
100% {
-webkit-transform: translateX(0);
transform: translateX(0);
opacity: 1;
}
}
@-webkit-keyframes slide-in-right {
0% {
-webkit-transform: translateX(1500px);
transform: translateX(1500px);
opacity: 0;
}
100% {
-webkit-transform: translateX(0);
transform: translateX(0);
opacity: 1;
}
}
@keyframes slide-in-right {
0% {
-webkit-transform: translateX(1500px);
transform: translateX(1500px);
opacity: 0;
}
100% {
-webkit-transform: translateX(0);
transform: translateX(0);
opacity: 1;
}
}
@-webkit-keyframes slide-in-down {
0% {
-webkit-transform: translateY(1000px);
transform: translateY(1000px);
opacity: 0;
}
100% {
-webkit-transform: translateY(0);
transform: translateY(0);
opacity: 1;
}
}
@keyframes slide-in-down {
0% {
-webkit-transform: translateY(1000px);
transform: translateY(1000px);
opacity: 0;
}
100% {
-webkit-transform: translateY(0);
transform: translateY(0);
opacity: 1;
}
}
@-webkit-keyframes heartbeat {
from {
-webkit-transform: scale(1);
transform: scale(1);
-webkit-transform-origin: center center;
transform-origin: center center;
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
10% {
-webkit-transform: scale(0.91);
transform: scale(0.91);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
17% {
-webkit-transform: scale(0.98);
transform: scale(0.98);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
33% {
-webkit-transform: scale(0.87);
transform: scale(0.87);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
45% {
-webkit-transform: scale(1);
transform: scale(1);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
}
@keyframes heartbeat {
from {
-webkit-transform: scale(1);
transform: scale(1);
-webkit-transform-origin: center center;
transform-origin: center center;
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
10% {
-webkit-transform: scale(1.14);
transform: scale(1.14);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
17% {
-webkit-transform: scale(1.04);
transform: scale(1.04);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
33% {
-webkit-transform: scale(1.14);
transform: scale(1.14);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
45% {
-webkit-transform: scale(1);
transform: scale(1);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
}
| 19.895833 | 88 | 0.639581 |
ecb109f1d93476e3b10b1ac0bcdaac2dc1276997 | 10,251 | swift | Swift | YooKassaPayments/Private/Modules/Sberbank/Presenter/SberbankPresenter.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 14 | 2020-12-17T14:38:16.000Z | 2022-02-18T11:01:50.000Z | YooKassaPayments/Private/Modules/Sberbank/Presenter/SberbankPresenter.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 54 | 2020-12-09T14:52:15.000Z | 2022-03-30T08:16:36.000Z | YooKassaPayments/Private/Modules/Sberbank/Presenter/SberbankPresenter.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 16 | 2021-01-26T09:28:31.000Z | 2022-01-25T01:08:48.000Z | import UIKit
final class SberbankPresenter {
// MARK: - VIPER
weak var moduleOutput: SberbankModuleOutput?
weak var view: SberbankViewInput?
var interactor: SberbankInteractorInput!
var router: SberbankRouterInput!
// MARK: - Module inputs
weak var phoneNumberModuleInput: PhoneNumberInputModuleInput?
// MARK: - Init
private let shopName: String
private let purchaseDescription: String
private let priceViewModel: PriceViewModel
private let feeViewModel: PriceViewModel?
private let termsOfService: NSAttributedString
private let userPhoneNumber: String?
private let isBackBarButtonHidden: Bool
private let isSafeDeal: Bool
private let clientSavePaymentMethod: SavePaymentMethod
private var recurrencySectionSwitchValue: Bool?
private let isSavePaymentMethodAllowed: Bool
private let config: Config
init(
shopName: String,
purchaseDescription: String,
priceViewModel: PriceViewModel,
feeViewModel: PriceViewModel?,
termsOfService: NSAttributedString,
userPhoneNumber: String?,
isBackBarButtonHidden: Bool,
isSafeDeal: Bool,
clientSavePaymentMethod: SavePaymentMethod,
isSavePaymentMethodAllowed: Bool,
config: Config
) {
self.shopName = shopName
self.purchaseDescription = purchaseDescription
self.priceViewModel = priceViewModel
self.feeViewModel = feeViewModel
self.termsOfService = termsOfService
self.userPhoneNumber = userPhoneNumber
self.isBackBarButtonHidden = isBackBarButtonHidden
self.isSafeDeal = isSafeDeal
self.clientSavePaymentMethod = clientSavePaymentMethod
self.isSavePaymentMethodAllowed = isSavePaymentMethodAllowed
self.config = config
}
// MARK: - Stored properties
private var phoneNumber: String = ""
}
// MARK: - SberbankViewOutput
extension SberbankPresenter: SberbankViewOutput {
func setupView() {
guard let view = view else { return }
let priceValue = makePrice(priceViewModel)
var feeValue: String?
if let feeViewModel = feeViewModel {
feeValue = "\(CommonLocalized.Contract.fee) " + makePrice(feeViewModel)
}
let termsOfServiceValue = termsOfService
var section: PaymentRecurrencyAndDataSavingSection?
if isSavePaymentMethodAllowed {
switch clientSavePaymentMethod {
case .userSelects:
section = PaymentRecurrencyAndDataSavingSectionFactory.make(
mode: .allowRecurring,
texts: config.savePaymentMethodOptionTexts,
output: self
)
recurrencySectionSwitchValue = section?.switchValue
case .on:
section = PaymentRecurrencyAndDataSavingSectionFactory.make(
mode: .requiredRecurring,
texts: config.savePaymentMethodOptionTexts,
output: self
)
recurrencySectionSwitchValue = true
case .off:
section = nil
}
}
let viewModel = SberbankViewModel(
shopName: shopName,
description: purchaseDescription,
priceValue: priceValue,
feeValue: feeValue,
termsOfService: termsOfServiceValue,
safeDealText: isSafeDeal ? PaymentMethodResources.Localized.safeDealInfoLink : nil,
recurrencyAndDataSavingSection: section,
paymentOptionTitle: config.paymentMethods.first { $0.kind == .sberbank }?.title
)
view.setViewModel(viewModel)
let title = Localized.phoneInputTitle
phoneNumberModuleInput?.setTitle(title.uppercased())
phoneNumberModuleInput?.setPlaceholder(Localized.phoneInputPlaceholder)
phoneNumberModuleInput?.setSubtitle(Localized.phoneInputBottomHint)
if let userPhoneNumber = userPhoneNumber {
phoneNumberModuleInput?.setValue(userPhoneNumber)
}
view.setBackBarButtonHidden(isBackBarButtonHidden)
DispatchQueue.global().async { [weak self] in
guard let self = self else { return }
self.interactor.track(event:
.screenPaymentContract(
scheme: .smsSbol,
currentAuthType: self.interactor.analyticsAuthType()
)
)
}
}
func didPressSubmitButton() {
guard let view = view else { return }
view.endEditing(true)
view.showActivity()
DispatchQueue.global().async { [weak self] in
guard let self = self,
let interactor = self.interactor else { return }
interactor.tokenizeSberbank(
phoneNumber: self.phoneNumber,
savePaymentMethod: self.recurrencySectionSwitchValue ?? false
)
}
}
func didPressTermsOfService(_ url: URL) {
router.presentTermsOfServiceModule(url)
}
func didTapSafeDealInfo(_ url: URL) {
router.presentSafeDealInfo(
title: PaymentMethodResources.Localized.safeDealInfoTitle,
body: PaymentMethodResources.Localized.safeDealInfoBody
)
}
}
// MARK: - SberbankInteractorOutput
extension SberbankPresenter: SberbankInteractorOutput {
func didTokenize(_ data: Tokens) {
interactor.track(event:
.actionTokenize(
scheme: .smsSbol,
currentAuthType: interactor.analyticsAuthType()
)
)
moduleOutput?.sberbankModule(self, didTokenize: data, paymentMethodType: .sberbank)
}
func didFailTokenize(_ error: Error) {
interactor.track(
event: .screenErrorContract(scheme: .smsSbol, currentAuthType: interactor.analyticsAuthType())
)
let message = makeMessage(error)
DispatchQueue.main.async { [weak self] in
guard let view = self?.view else { return }
view.hideActivity()
view.showPlaceholder(with: message)
}
}
}
// MARK: - ActionTitleTextDialogDelegate
extension SberbankPresenter: ActionTitleTextDialogDelegate {
func didPressButton(
in actionTitleTextDialog: ActionTitleTextDialog
) {
guard let view = view else { return }
view.hidePlaceholder()
view.showActivity()
DispatchQueue.global().async { [weak self] in
guard let self = self, let interactor = self.interactor else { return }
interactor.track(
event: .actionTryTokenize(scheme: .smsSbol, currentAuthType: interactor.analyticsAuthType())
)
interactor.tokenizeSberbank(
phoneNumber: self.phoneNumber,
savePaymentMethod: self.recurrencySectionSwitchValue ?? false
)
}
}
}
// MARK: - PhoneNumberInputModuleOutput
extension SberbankPresenter: PhoneNumberInputModuleOutput {
func didChangePhoneNumber(_ phoneNumber: String) {
self.phoneNumber = phoneNumber
view?.setSubmitButtonEnabled(!phoneNumber.isEmpty)
}
}
// MARK: - PaymentRecurrencyAndDataSavingSectionOutput
extension SberbankPresenter: PaymentRecurrencyAndDataSavingSectionOutput {
func didChangeSwitchValue(newValue: Bool, mode: PaymentRecurrencyAndDataSavingSection.Mode) {
recurrencySectionSwitchValue = newValue
}
func didTapInfoLink(mode: PaymentRecurrencyAndDataSavingSection.Mode) {
switch mode {
case .allowRecurring, .requiredRecurring:
router.presentSafeDealInfo(
title: CommonLocalized.CardSettingsDetails.autopayInfoTitle,
body: CommonLocalized.CardSettingsDetails.autopayInfoDetails
)
case .savePaymentData, .requiredSaveData:
router.presentSafeDealInfo(
title: CommonLocalized.RecurrencyAndSavePaymentData.saveDataInfoTitle,
body: CommonLocalized.RecurrencyAndSavePaymentData.saveDataInfoMessage
)
case .allowRecurringAndSaveData, .requiredRecurringAndSaveData:
router.presentSafeDealInfo(
title: CommonLocalized.RecurrencyAndSavePaymentData.saveDataAndAutopaymentsInfoTitle,
body: CommonLocalized.RecurrencyAndSavePaymentData.saveDataAndAutopaymentsInfoMessage
)
default:
break
}
}
}
// MARK: - SberbankModuleInput
extension SberbankPresenter: SberbankModuleInput {}
// MARK: - Private helpers
private extension SberbankPresenter {
func makePrice(
_ priceViewModel: PriceViewModel
) -> String {
priceViewModel.integerPart
+ priceViewModel.decimalSeparator
+ priceViewModel.fractionalPart
+ priceViewModel.currency
}
func makeMessage(
_ error: Error
) -> String {
let message: String
switch error {
case let error as PresentableError:
message = error.message
default:
message = CommonLocalized.Error.unknown
}
return message
}
}
// MARK: - Localized
private extension SberbankPresenter {
enum Localized {
static let phoneInputTitle = NSLocalizedString(
"Contract.Sberbank.PhoneInput.Title",
bundle: Bundle.framework,
value: "Номер в Сбербанк Онлайн",
comment: "Текст `Номер в Сбербанк Онлайн` https://yadi.sk/i/T-XQGU9NaPMgKA"
)
static let phoneInputPlaceholder = NSLocalizedString(
"Contract.Sberbank.PhoneInput.Placeholder",
bundle: Bundle.framework,
value: "+ 7 987 654 32 10",
comment: "Текст `+ 7 987 654 32 10` https://yadi.sk/i/T-XQGU9NaPMgKA"
)
static let phoneInputBottomHint = NSLocalizedString(
"Contract.Sberbank.PhoneInput.BottomHint",
bundle: Bundle.framework,
value: "Для смс от Сбербанка с кодом для оплаты",
comment: "Текст `Для смс от Сбербанка с кодом для оплаты` https://yadi.sk/i/T-XQGU9NaPMgKA"
)
}
}
| 33.831683 | 108 | 0.648034 |
5808ac4930c51fd090863ec14636e03d78d723c4 | 495 | css | CSS | web/src/styles/pages/confirm.css | marceloambarc/ProjectHabil | d3e36b7db0825bd0422a6c7cea17e3a443ea7cd3 | [
"RSA-MD"
] | null | null | null | web/src/styles/pages/confirm.css | marceloambarc/ProjectHabil | d3e36b7db0825bd0422a6c7cea17e3a443ea7cd3 | [
"RSA-MD"
] | null | null | null | web/src/styles/pages/confirm.css | marceloambarc/ProjectHabil | d3e36b7db0825bd0422a6c7cea17e3a443ea7cd3 | [
"RSA-MD"
] | null | null | null | #confirm-container {
width: 100vw;
max-width: 100%;
background: linear-gradient(329.54deg, #ffff 0%, #ffff 100%);
display: flex;
justify-content: center;
align-items: center;
overflow-y: scroll;
overflow-x: hidden;
padding-top: 10%;
padding-bottom: 10%;
}
#page-landing .content-wrapper {
position: relative;
width: 100%;
max-width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
overflow-x: hidden;
} | 20.625 | 65 | 0.626263 |
12e92102a8f0536d819269347c59eb2197408be6 | 176 | cs | C# | BooLangCompiler/Boo/Lang/Compiler/TypeSystem/Reflection/IAssemblyReference.cs | Spoiledpay/Newboo | bab26f1977d8396f8758eb3cbc4bcf17d6f64203 | [
"MIT"
] | 3 | 2021-08-23T13:21:55.000Z | 2021-11-30T10:34:43.000Z | BooLangCompiler/Boo/Lang/Compiler/TypeSystem/Reflection/IAssemblyReference.cs | Spoiledpay/Newboo | bab26f1977d8396f8758eb3cbc4bcf17d6f64203 | [
"MIT"
] | null | null | null | BooLangCompiler/Boo/Lang/Compiler/TypeSystem/Reflection/IAssemblyReference.cs | Spoiledpay/Newboo | bab26f1977d8396f8758eb3cbc4bcf17d6f64203 | [
"MIT"
] | null | null | null | using System.Reflection;
namespace Boo.Lang.Compiler.TypeSystem.Reflection
{
public interface IAssemblyReference : ICompileUnit, IEntity
{
Assembly Assembly { get; }
}
}
| 17.6 | 60 | 0.772727 |
25a2b0e716fa13443537a143a5ca2fd85b2e94fb | 2,565 | js | JavaScript | SayonaraAdmin/app/scripts/services/adminnotify.js | torch2424/SayonaraJS | 287dd67725cdeca6ce2adbb9a00f6acc7701f4ed | [
"Apache-2.0"
] | 3 | 2017-04-28T00:13:45.000Z | 2019-12-09T04:39:59.000Z | SayonaraAdmin/app/scripts/services/adminnotify.js | torch2424/SayonaraJS | 287dd67725cdeca6ce2adbb9a00f6acc7701f4ed | [
"Apache-2.0"
] | 27 | 2016-10-26T00:48:35.000Z | 2016-12-27T08:16:55.000Z | SayonaraAdmin/app/scripts/services/adminnotify.js | SayonaraJS/SayonaraJS | 287dd67725cdeca6ce2adbb9a00f6acc7701f4ed | [
"Apache-2.0"
] | null | null | null | 'use strict';
angular.module('sayonaraAdminApp')
.service('adminNotify', function($mdToast, $location, sayonaraAuthService) {
//Function to show notifications to the user
var showAlert = function(text, callback) {
//Show the alert in a toast
$mdToast.show(
$mdToast.simple()
.textContent(text)
.toastClass('appToast')
.position('top right'));
//Call the callback
if (callback) callback();
};
//Functions to be returned to the user
return {
showAlert: function(alertText, callback) {
//Show a custom alert
showAlert(alertText, callback);
},
error: function(response, customHandlers) {
//Our status that we are handling
var status = -1;
//Search through our response handlers if we got a specific
//error we wanted to Handle
if (customHandlers) {
for (var i = 0; i < customHandlers.length; i++) {
//Check if our response Handler is for our status
if (response.status == customHandlers[i].status) {
//Make the handled status this status
status = response.status;
//Create the alert
if (customHandlers[i].callback) showAlert(customHandlers[i].text, customHandlers[i].callback(response));
else showAlert(customHandlers[i].text);
}
}
}
//Check if we handled any statuses, if we did not
//Go through default error handling
if (status < 0) {
if (response.status == 401) {
//401 error
//Show alert
showAlert("Authentication error. Please log back in!");
//Logout the user
sayonaraAuthService.logout();
} else if (response.status == 402) {
//402 Error
} else if (response.status == 404) {
//404 error
//Show alert
showAlert("Not Found, Something could not be found. Please contact your developers, or try again");
} else if (response.status == -1) {
//No Internet Connection
//Show alert
showAlert("No Connection, Internet Connection is required to use this app. Please connect to the internet with your device, and restart the app.");
} else if (response.status == 500) {
//500 error
//Show alert
showAlert("Server Error, Your connection may be bad, or the server is being problematic. Please contact your developer, or try again later.");
} else {
//General Error
//An unexpected error has occured
//Show alert
showAlert("Error Status: " + response.status + ", Unexpected Error. Please re-open the app, or try again later!");
}
}
}
}
});
| 27.880435 | 153 | 0.639376 |
3147fa37963fd7f029b9de83d655c7e03b61c69f | 246 | rs | Rust | mempool/src/tests/common.rs | novifinancial/research | cc2ec64d8028f2540e70ca9f9e7891c4ba72113f | [
"Apache-2.0",
"CC-BY-4.0"
] | 33 | 2019-09-26T23:11:17.000Z | 2020-05-20T03:46:28.000Z | mempool/src/tests/common.rs | novifinancial/research | cc2ec64d8028f2540e70ca9f9e7891c4ba72113f | [
"Apache-2.0",
"CC-BY-4.0"
] | 5 | 2021-05-19T04:23:18.000Z | 2021-07-14T15:13:55.000Z | mempool/src/tests/common.rs | novifinancial/research | cc2ec64d8028f2540e70ca9f9e7891c4ba72113f | [
"Apache-2.0",
"CC-BY-4.0"
] | 6 | 2020-10-16T15:33:31.000Z | 2021-08-19T23:32:16.000Z | // Copyright (c) Facebook, Inc. and its affiliates.
use crate::batch_maker::{Batch, Transaction};
// Fixture
pub fn transaction() -> Transaction {
vec![0; 100]
}
// Fixture
pub fn batch() -> Batch {
vec![transaction(), transaction()]
}
| 18.923077 | 51 | 0.650407 |
032066bb6e14e080cec06252a9d45fd6f9ce66dc | 2,383 | rb | Ruby | config/routes.rb | edgeryders/annotator_store-gem | 983a49812a9707bc014b6f6d21f4e6ec39f560d2 | [
"MIT"
] | 3 | 2019-06-28T21:32:49.000Z | 2020-05-31T16:35:53.000Z | config/routes.rb | edgeryders/annotator_store-gem | 983a49812a9707bc014b6f6d21f4e6ec39f560d2 | [
"MIT"
] | 216 | 2019-09-04T14:44:08.000Z | 2021-12-15T22:01:37.000Z | config/routes.rb | edgeryders/annotator_store-gem | 983a49812a9707bc014b6f6d21f4e6ec39f560d2 | [
"MIT"
] | null | null | null | require_dependency "annotator_constraint"
Rails.application.routes.draw do
get '/annotator/codes', to: 'annotator/annotator_store/tags#index', format: :json,
constraints: lambda { |req| AnnotatorStore::Setting.instance.public_codes_list_api_endpoint? }
namespace :annotator, constraints: AnnotatorConstraint.new do
root to: 'application#front'
resources :topics, only: [:index, :show]
resources :videos, only: [:show]
namespace :annotator_store, path: '' do
resources :tags, path: 'codes'do
collection do
post :update_parent
end
member do
get :merge
put :merge_into
put :copy
end
end
match 'localized_codes', to: 'localized_tags#index', via: [:get], defaults: {format: :json}, constraints: {format: :json}
match 'mergeable_codes', to: 'localized_tags#mergeable', via: [:get], defaults: {format: :json}, constraints: {format: :json}
match 'autosuggest_codes', to: 'localized_tags#autosuggest_codes', via: [:get], defaults: {format: :json}, constraints: {format: :json}
resources :localized_tags, only: [:show]
resources :tag_names
resources :languages
resources :user_settings
resource :setting, only: [:show, :edit, :update], path: 'settings'
# Search
match 'search', to: 'pages#search', via: [:get], defaults: {format: :json}, constraints: {format: :json}
match 'search', to: 'annotations#options', via: [:options], defaults: {format: :json}, constraints: {format: :json}
# Annotations Endpoint
resources :annotations, only: [:index, :show], defaults: {format: :html}, constraints: {format: :html} do
collection do
post :update_tag
delete :bulk_destroy
end
end
resources :annotations, only: [:index, :create, :show, :edit, :update, :destroy], defaults: {format: :json}, constraints: {format: :json} do
match '/', to: 'annotations#options', via: [:options], on: :collection
match '/', to: 'annotations#options', via: [:options], on: :member
end
resources :text_annotations, only: [:index, :show, :edit, :update, :destroy]
resources :video_annotations, only: [:index, :show, :edit, :update, :destroy]
resources :image_annotations, only: [:index, :show, :edit, :update, :destroy]
end
end
end
| 41.086207 | 146 | 0.644146 |
79362a057e2dc8de3fc3ca75fe3379e7164bf3ca | 2,681 | rb | Ruby | app/models/address.rb | fpsvogel/doctorlookup | 63afacf595fda828a8838bf5d9161450f6c3ef08 | [
"PostgreSQL",
"Ruby",
"MIT"
] | null | null | null | app/models/address.rb | fpsvogel/doctorlookup | 63afacf595fda828a8838bf5d9161450f6c3ef08 | [
"PostgreSQL",
"Ruby",
"MIT"
] | null | null | null | app/models/address.rb | fpsvogel/doctorlookup | 63afacf595fda828a8838bf5d9161450f6c3ef08 | [
"PostgreSQL",
"Ruby",
"MIT"
] | null | null | null | # Stores an address taken from an API response.
class Address
include ActiveModel::Model
include ActiveModel::Attributes
include StringAttributes
add_string_attributes(
required: [:line_1,
:city,
:state],
optional: [:line_2])
define_titleizing_setters([:line_1, :line_2, :city])
attribute :phone_numbers, array: true, default: []
# Makes Addresses from an API response.
# @param [Hash] response_result a raw result from an API response in JSON format
# @return [Array<Address>] addresses from each result in the response
def self.addresses_from_api_result(response_result, query)
return [] unless response_result
main_location = response_result["addresses"].find do |address|
address["address_purpose"] == "LOCATION"
end
practice_locations = response_result["practiceLocations"] || []
([main_location] + practice_locations).map do |location|
city, state = location["city"], location["state"]
next unless city_and_state_match_if_present(city, state, query)
new(
line_1: location["address_1"],
line_2: location["address_2"],
city:,
state:,
phone_numbers: [location["telephone_number"]])
end.compact.then do |addresses|
merge_duplicates(addresses)
end
end
def line_1=(new_line_1)
new_line_1 = titleize(new_line_1)&.gsub(/[\.,]/, "")
write_attribute(:line_1, new_line_1)
end
def line_2=(new_line_2)
new_line_2 = titleize(new_line_2)&.gsub(/[\.,]/, "")
write_attribute(:line_2, new_line_2)
end
private_class_method def self.city_and_state_match_if_present(city, state, query)
(city.downcase == query.city&.downcase) == (query.city.present?) &&
(state.downcase == query.state&.downcase) == (query.state.present?)
end
private_class_method def self.merge_duplicates(addresses)
unique_address_groups = addresses.group_by do |address|
first_3_words = address.line_1.split.take(3).join(" ")
[first_3_words, address.city, address.state]
end
duplicate_groups = unique_address_groups.values.select { |addresses| addresses.count > 1 }
duplicate_groups.each do |duplicates|
address_to_keep = duplicates.max_by do |address|
[address.line_2&.length ||0, address.line_1.length]
end
addresses_to_discard = duplicates - [address_to_keep]
addresses_to_discard.each do |to_discard|
unless address_to_keep.phone_numbers.include?(to_discard.phone_numbers.first)
address_to_keep.phone_numbers << to_discard.phone_numbers.first
end
addresses = addresses - [to_discard]
end
end
addresses
end
end | 36.726027 | 94 | 0.695636 |
565c48c6de1d7a171a892b54b0bdf88de0a661c1 | 2,382 | sh | Shell | prepare.sh | ginkgo-project/gitlab-hpc-ci-cb | 2ddd609ffa7244ce84bfde22a4cfbf1e702fb2e9 | [
"BSD-3-Clause"
] | 7 | 2021-11-02T10:56:08.000Z | 2022-03-28T14:39:23.000Z | prepare.sh | ginkgo-project/gitlab-hpc-ci-cb | 2ddd609ffa7244ce84bfde22a4cfbf1e702fb2e9 | [
"BSD-3-Clause"
] | 7 | 2021-10-30T11:28:39.000Z | 2021-12-08T12:31:15.000Z | prepare.sh | ginkgo-project/gitlab-hpc-ci-cb | 2ddd609ffa7244ce84bfde22a4cfbf1e702fb2e9 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/bash
# https://docs.gitlab.com/runner/executors/custom.html#prepare
# shellcheck source=./include.sh
source "${BASH_SOURCE[0]%/*}/include.sh"
ensure_executable_available enroot
ensure_executable_available flock
ensure_executable_available grep
# Create CI WorkSpace paths if they don't exist
if [[ ! -d "${ENROOT_CACHE_PATH}" ]]; then
mkdir -p "${ENROOT_CACHE_PATH}"
fi
if [[ ! -d "${ENROOT_DATA_PATH}" ]]; then
mkdir -p "${ENROOT_DATA_PATH}"
fi
if [[ ! -d "${SLURM_IDS_PATH}" ]]; then
mkdir -p "${SLURM_IDS_PATH}"
fi
# Reuse a container if it exists
# shellcheck disable=SC2143
if ! [[ $(enroot list | grep "${CONTAINER_NAME}") ]]; then
echo -e "Preparing the container ${CONTAINER_NAME}."
# Check if CI job image: is set
if [[ -z "${CUSTOM_ENV_CI_JOB_IMAGE}" ]]; then
die "No CI job image specified"
fi
# Import a container image from a specific location to enroot image dir
# Scheme: docker://[USER@][REGISTRY#]IMAGE[:TAG]
IMAGE_DIR="${ENROOT_DATA_PATH}"
URL="docker://${CUSTOM_ENV_CI_JOB_IMAGE}"
IMAGE_NAME="${CUSTOM_ENV_CI_JOB_IMAGE//[:@#.\/]/-}"
# Utility timestamp and lock files
IMAGE_TIMESTAMP_FILE=${IMAGE_DIR}/TIMESTAMP_${IMAGE_NAME}
IMAGE_LOCK_FILE=${IMAGE_DIR}/LOCK_${IMAGE_NAME}
# Update the image once every 3 hours. Use a lock to prevent conflicts
exec 100<>"${IMAGE_LOCK_FILE}"
flock -w 120 100
if [[ ! -f ${IMAGE_TIMESTAMP_FILE} ||
($(cat "${IMAGE_TIMESTAMP_FILE}") -le $(date +%s -d '-3 hours')) ]]; then
IMAGE_FILE="${IMAGE_DIR}/${IMAGE_NAME}.sqsh"
if [[ -f ${IMAGE_FILE} ]]; then
rm "${IMAGE_DIR}/${IMAGE_NAME}.sqsh"
fi
COMMAND=(enroot import \
--output "${IMAGE_DIR}/${IMAGE_NAME}.sqsh" \
-- "${URL}")
"${COMMAND[@]}" || die "Command: ${COMMAND[*]} failed with exit code ${?}"
date +%s > "${IMAGE_TIMESTAMP_FILE}"
fi
flock -u 100
# Create a container root filesystem from a container image
COMMAND=(
enroot create \
--name "${CONTAINER_NAME}" \
-- "${IMAGE_DIR}/${IMAGE_NAME}.sqsh"
)
"${COMMAND[@]}" || die "Command: ${COMMAND[*]} failed with exit code ${?}"
else
echo -e "Reusing container ${CONTAINER_NAME}"
fi
# List all the container root filesystems on the system.
enroot list --fancy
| 30.151899 | 87 | 0.625945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.