identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/Kasuromi/MTFO/blob/master/MTFO/Utilities/Extensions.cs
Github Open Source
Open Source
MIT
2,021
MTFO
Kasuromi
C#
Code
128
306
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MTFO.Utilities { public static class DataDumperExtensions { /// <summary> /// Hashes the given string in a persistent, platform independent way /// </summary> /// Thanks to https://stackoverflow.com/a/36845864 for this /// <param name="str">The string to hash</param> /// <returns>The hash of the string</returns> public static int GetStableHashCode(this string str) { unchecked { int hash1 = 5381; int hash2 = hash1; for (int i = 0; i < str.Length && str[i] != '\0'; i += 2) { hash1 = ((hash1 << 5) + hash1) ^ str[i]; if (i == str.Length - 1 || str[i + 1] == '\0') break; hash2 = ((hash2 << 5) + hash2) ^ str[i + 1]; } return hash1 + (hash2 * 1566083941); } } } }
6,880
https://github.com/sweverett/Balrog-GalSim/blob/master/plots/vinicius_plots.py
Github Open Source
Open Source
MIT
2,022
Balrog-GalSim
sweverett
Python
Code
1,023
6,300
#!/usr/bin/env python # encoding: UTF8 # from __future__ import print_function import numpy as np import pyfits as pf import matplotlib.pyplot as plt from matplotlib import cm import os def make_plots(realizations,tiles,bands,INPUT_DIR,OUT_DIR,OBJECT,RADIUS_MATCH,REMOVE_FLAGGED): for real in realizations: for tile in tiles: # truth catalogs of injections of galaxies cat_true = pf.open(INPUT_DIR+"/"+real+"/"+tile+"/"+tile+"_"+real+"_balrog_truth_cat_gals.fits") cat_true.info() tab_true = cat_true[1].data my_format_true = tab_true.formats ra_t = tab_true['ra'] dec_t = tab_true['dec'] mag_t = tab_true['cm_mag'] # truth catalogs of injections of stars cat_trues = pf.open(INPUT_DIR+"/"+real+"/"+tile+"/"+tile+"_"+real+"_balrog_truth_cat_stars.fits") cat_trues.info() tab_trues = cat_trues[1].data my_format_trues = tab_trues.formats ra_ts = tab_trues['RA_new'] dec_ts = tab_trues['DEC_new'] mag_gs = tab_trues['g_Corr'] mag_rs = tab_trues['g_Corr'] - tab_trues['gr_Corr'] mag_is = tab_trues['g_Corr'] - tab_trues['gr_Corr'] - tab_trues['ri_Corr'] mag_zs = tab_trues['g_Corr'] - tab_trues['gr_Corr'] - tab_trues['ri_Corr'] - tab_trues['iz_Corr'] # data plus injections cat_inj = pf.open(INPUT_DIR+"/"+real+"/"+tile+"/"+tile+"_mof.fits") cat_inj.info() tab_inj = cat_inj[1].data my_format_inj = tab_inj.formats ra_i = tab_inj['ra'] dec_i = tab_inj['dec'] mag_i = tab_inj['cm_mag'] flags = tab_inj['flags'] cm_flags = tab_inj['cm_flags'] if(REMOVE_FLAGGED == True): mask = (flags == 0)*(cm_flags == 0) ra_i = ra_i[mask] dec_i = dec_i[mask] mag_i = mag_i[mask] flag_match_all = [[] for _ in range(len(bands))] mag_all = [[] for _ in range(len(bands))] for band in bands: # check if there is a folder for the results, if not create it path = OUT_DIR+'/'+real+'/'+tile+'/'+band if not os.path.isdir(path): os.makedirs(path) if(band == 'g'): ind_band = 0 mag_star = mag_gs elif(band == 'r'): ind_band = 1 mag_star = mag_rs elif(band == 'i'): ind_band = 2 mag_star = mag_is else: ind_band = 3 mag_star = mag_zs mag_t_band = mag_t[:,ind_band] mag_i_band = mag_i[:,ind_band] if(OBJECT == 'stars'): ra_t = ra_ts dec_t = dec_ts mag_t_band = mag_star min_mag = np.min(mag_t_band) max_mag = np.max(mag_t_band) mag_bins = np.linspace(min_mag-0.01,max_mag+0.01,np.rint((max_mag-min_mag+0.02)/0.25)+1) flag_match = np.zeros(len(ra_t)) flag_blend = np.zeros(len(ra_t)) matched_elements_all = [[] for _ in range(len(ra_t))] matched_elements_min = [[] for _ in range(len(ra_t))] for i in range(len(ra_t)): mini_mask = (np.abs(ra_i-ra_t[i]) < 0.01)*(np.abs(dec_i-dec_t[i])<0.01) ra_temp = ra_i[mini_mask] dec_temp = dec_i[mini_mask] mag_temp = mag_i_band[mini_mask] for j in range(len(ra_temp)): cos_theta = np.sin(np.pi*dec_t[i]/180.)*np.sin(np.pi*dec_temp[j]/180.) + np.cos(np.pi*dec_t[i]/180.)*np.cos(np.pi*dec_temp[j]/180.)*np.cos(np.pi*(ra_t[i]-ra_temp[j])/180.) theta = 206300.*np.arccos(cos_theta) if(theta < RADIUS_MATCH): flag_match[i] = 1 matched_elements_all[i].append([mag_temp[j],theta]) if(flag_match[i] == 0): matched_elements_min[i].append([-999,-999]) else: flag_blend[i] = 1 z = np.array([matched_elements_all[i][k][1] for k in range(len(matched_elements_all[i]))]) ind_min, = np.where(z == np.min(z)) matched_elements_min[i].append(matched_elements_all[i][ind_min[0]]) flag_match_all[ind_band].append(flag_match) mean_mag_bin = np.zeros(len(mag_bins)-1) frac_bin = np.zeros(len(mag_bins)-1) mask_zero = np.zeros(len(mag_bins)-1) for i in range(len(mag_bins)-1): mask_mag = (mag_t_band >= mag_bins[i])*(mag_t_band < mag_bins[i+1]) mag_temp = mag_t_band[mask_mag] flag_temp = flag_match[mask_mag] mean_mag_bin[i] = np.mean(mag_temp) if(len(flag_temp) > 0): frac_bin[i] = np.sum(flag_temp)/np.float(len(flag_temp)) mask_zero[i] = 1 else: frac_bin[i] = 2 mask = (mask_zero == 1) mean_mag_bin = mean_mag_bin[mask] frac_bin = frac_bin[mask] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(mean_mag_bin,frac_bin) plt.title('Magnitude versus the fraction of recovered '+OBJECT,size=16) plt.xlabel(band+' [mag]',size=16) plt.ylabel('Fraction',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/'+band+'/mag_'+band+'_vs_fraction.png') plt.close() np.savetxt(OUT_DIR+'/'+real+'/'+tile+'/'+band+'/mag_fraction.txt',np.array([mean_mag_bin,frac_bin]).T) mag_t_band = np.array(mag_t_band)[flag_match == 1] mag_inj = [matched_elements_min[i][0][0] for i in range(len(matched_elements_min))] mag_all[ind_band].append(mag_inj) mag_inj = np.array(mag_inj) mag_inj = mag_inj[flag_match == 1] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(mag_t_band,mag_t_band - mag_inj,s=0.2) plt.title('Magnitude versus Offset of Recovered Magnitudes',size=16) plt.xlabel(band+' [mag]',size=16) plt.ylabel('$\Delta m$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/'+band+'/mag_'+band+'_vs_deltamag.png') plt.close() np.savetxt(OUT_DIR+'/'+real+'/'+tile+'/'+band+'/mag_deltamag.txt',np.array([mag_t_band,mag_t_band - mag_inj]).T) delta_m = mag_t_band - mag_inj mask_d = (delta_m > -2.)*(delta_m < 2) delta_m = delta_m[mask_d] mean_dm = np.mean(delta_m) std_dm = np.std(delta_m) print(mean_dm,std_dm) np.savetxt(OUT_DIR+'/'+real+'/'+tile+'/'+band+'/mag_deltamag.txt',np.array([mean_dm,std_dm])) if(OBJECT == 'galaxies'): # g-r color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[0][0][i] == 1 and flag_match_all[1][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[0][0][i] - mag_all[1][0][i] gmr_t[i] = mag_t[i][0] - mag_t[i][1] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] # check if there is a folder for the results, if not create it path = OUT_DIR+'/'+real+'/'+tile+'/colors' if not os.path.isdir(path): os.makedirs(path) fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('g-r color',size=16) plt.xlabel('g-r true',size=16) plt.ylabel('$\Delta_{g-r}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/gmr.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('g-r color',size=16) plt.xlabel('g-r true',size=16) plt.ylabel('$\Delta_{g-r}$',size=16) plt.xlim(-0.5,2) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/gmr_zoom.png') plt.close() # r-i color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[1][0][i] == 1 and flag_match_all[2][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[1][0][i] - mag_all[2][0][i] gmr_t[i] = mag_t[i][1] - mag_t[i][2] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.20) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('r-i color',size=16) plt.xlabel('r-i true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/rmi.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.gcf().subplots_adjust(left=0.20) plt.title('r-i color',size=16) plt.xlabel('r-i true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.xlim(-0.5,1.5) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/rmi_zoom.png') plt.close() # i-z color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[2][0][i] == 1 and flag_match_all[3][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[2][0][i] - mag_all[3][0][i] gmr_t[i] = mag_t[i][2] - mag_t[i][3] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.20) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('i-z color',size=16) plt.xlabel('i-z true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/imz.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.20) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('i-z color',size=16) plt.xlabel('i-z true',size=16) plt.ylabel('$\Delta_{i-z}$',size=16) plt.xlim(-0.5,1.5) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/imz_zoom.png') plt.close() else: # g-r color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[0][0][i] == 1 and flag_match_all[1][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[0][0][i] - mag_all[1][0][i] gmr_t[i] = mag_gs[i] - mag_rs[i] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] # check if there is a folder for the results, if not create it path = OUT_DIR+'/'+real+'/'+tile+'/colors' if not os.path.isdir(path): os.makedirs(path) fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.gcf().subplots_adjust(left=0.15) plt.title('g-r color',size=16) plt.xlabel('g-r true',size=16) plt.ylabel('$\Delta_{g-r}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/gmr.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('g-r color',size=16) plt.xlabel('g-r true',size=16) plt.ylabel('$\Delta_{g-r}$',size=16) plt.xlim(-0.5,2) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/gmr_zoom.png') plt.close() # r-i color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[1][0][i] == 1 and flag_match_all[2][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[1][0][i] - mag_all[2][0][i] gmr_t[i] = mag_rs[i] - mag_is[i] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('r-i color',size=16) plt.xlabel('r-i true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/rmi.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('r-i color',size=16) plt.xlabel('r-i true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.xlim(-0.5,2) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/rmi_zoom.png') plt.close() # i-z color_det = np.zeros(len(ra_t)) gmr = np.zeros(len(ra_t)) gmr_t = np.zeros(len(ra_t)) for i in range(len(ra_t)): if(flag_match_all[2][0][i] == 1 and flag_match_all[3][0][i] == 1): color_det[i] = 1 gmr[i] = mag_all[2][0][i] - mag_all[3][0][i] gmr_t[i] = mag_is[i] - mag_zs[i] mask_c = (color_det == 1) gmr = gmr[mask_c] gmr_t = gmr_t[mask_c] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('i-z color',size=16) plt.xlabel('i-z true',size=16) plt.ylabel('$\Delta_{r-i}$',size=16) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/imz.png') plt.close() fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.gcf().subplots_adjust(left=0.15) plt.scatter(gmr_t,gmr_t-gmr,s=0.4) plt.title('i-z color',size=16) plt.xlabel('i-z true',size=16) plt.ylabel('$\Delta_{i-z}$',size=16) plt.xlim(-0.5,1) plt.ylim(-4,4) plt.savefig(OUT_DIR+'/'+real+'/'+tile+'/colors/imz_zoom.png') plt.close() if __name__=="__main__": realizations = ['0','1','2'] bands = ['g','r','i','z'] tiles = ['DES0347-5540','DES2329-5622','DES2357-6456'] INPUT_DIR = '/home/vinicius/Documents/balrog/fraction_recovered/data/blank_test' OUT_DIR = '/home/vinicius/Documents/balrog/fraction_recovered/results/blank_test/flags_removed/stars2' OBJECT = 'stars' # 'galaxies' or 'stars' RADIUS_MATCH = 0.1 make_plots(realizations=realizations,tiles=tiles,bands=bands,INPUT_DIR=INPUT_DIR,OUT_DIR=OUT_DIR,OBJECT=OBJECT,RADIUS_MATCH=RADIUS_MATCH,REMOVE_FLAGGED=True)
26,622
https://github.com/mirakels/pandevice/blob/master/examples/userid.py
Github Open Source
Open Source
0BSD
2,020
pandevice
mirakels
Python
Code
508
1,298
#!/usr/bin/env python # Copyright (c) 2014, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: Brian Torres-Gil <btorres-gil@paloaltonetworks.com> """ userid.py ========= Update User-ID by adding or removing a user-to-ip mapping on the firewall **Usage**:: userid.py [-h] [-v] [-q] hostname username password action user ip **Examples**: Send a User-ID login event to a firewall at 10.0.0.1:: $ python userid.py 10.0.0.1 admin password login exampledomain/user1 4.4.4.4 Send a User-ID logout event to a firewall at 172.16.4.4:: $ python userid.py 172.16.4.4 admin password logout user2 5.1.2.2 """ __author__ = 'btorres-gil' import sys import os import argparse import logging curpath = os.path.dirname(os.path.abspath(__file__)) sys.path[:0] = [os.path.join(curpath, os.pardir)] from pandevice.base import PanDevice from pandevice.panorama import Panorama def main(): # Get command line arguments parser = argparse.ArgumentParser(description="Update User-ID by adding or removing a user-to-ip mapping") parser.add_argument('-v', '--verbose', action='count', help="Verbose (-vv for extra verbose)") parser.add_argument('-q', '--quiet', action='store_true', help="No output") # Palo Alto Networks related arguments fw_group = parser.add_argument_group('Palo Alto Networks Device') fw_group.add_argument('hostname', help="Hostname of Firewall") fw_group.add_argument('username', help="Username for Firewall") fw_group.add_argument('password', help="Password for Firewall") fw_group.add_argument('action', help="The action of the user. Must be 'login' or 'logout'.") fw_group.add_argument('user', help="The username of the user") fw_group.add_argument('ip', help="The IP address of the user") args = parser.parse_args() ### Set up logger # Logging Levels # WARNING is 30 # INFO is 20 # DEBUG is 10 if args.verbose is None: args.verbose = 0 if not args.quiet: logging_level = 20 - (args.verbose * 10) if logging_level <= logging.DEBUG: logging_format = '%(levelname)s:%(name)s:%(message)s' else: logging_format = '%(message)s' logging.basicConfig(format=logging_format, level=logging_level) # Connect to the device and determine its type (Firewall or Panorama). device = PanDevice.create_from_device(args.hostname, args.username, args.password, ) logging.debug("Detecting type of device") # Panorama does not have a userid API, so exit. # You can use the userid API on a firewall with the Panorama 'target' # parameter by creating a Panorama object first, then create a # Firewall object with the 'panorama' and 'serial' variables populated. if issubclass(type(device), Panorama): logging.error("Connected to a Panorama, but user-id API is not possible on Panorama. Exiting.") sys.exit(1) if args.action == "login": logging.debug("Login user %s at IP %s" % (args.user, args.ip)) device.userid.login(args.user, args.ip) elif args.action == "logout": logging.debug("Logout user %s at IP %s" % (args.user, args.ip)) device.userid.logout(args.user, args.ip) else: raise ValueError("Unknown action: %s. Must be 'login' or 'logout'." % args.action) logging.debug("Done") # Call the main() function to begin the program if not # loaded as a module. if __name__ == '__main__': main()
5,243
https://github.com/pocesar/DefinitelyTyped/blob/master/lodash-es/debounce/index.d.ts
Github Open Source
Open Source
MIT
2,016
DefinitelyTyped
pocesar
TypeScript
Code
14
31
import * as _ from "lodash"; declare const debounce: typeof _.debounce; export default debounce;
43,210
https://github.com/mulesoft/docs-connector-devk/blob/master/modules/ROOT/pages/setting-up-api-access.adoc
Github Open Source
Open Source
BSD-3-Clause
2,021
docs-connector-devk
mulesoft
AsciiDoc
Code
635
995
= Setting Up API Access ifndef::env-site,env-github[] include::_attributes.adoc[] endif::[] :keywords: devkit, api, access, connector, cloud, salesforce, twitter include::partial$devkit-important.adoc[] Before starting a connector project, research the API to which you wish to connect. Beyond collecting and reading any API documentation offered by the target's provider, prepare access to an instance so you can test against it. Sandbox access, supporting code and documentation, and other support required for building a connector to a local enterprise application or other Web service is usually provided by your local administrator or the application vendor. SaaS applications usually provide a self-service process for accessing the API, which varies from service to service. This document summarizes typical preparation steps you might need to perform, then presents examples for two cases: <<Salesforce Example>> and <<Twitter Example>>. == Prerequisites This document assumes you are familiar with your API, Web service or other resource, and that the documentation for your target's APIs or client library is publicly available. == Cloud APIs Cloud APIs, also known as Software as a Service (SaaS) or Web services, may require you to set up a test/developer account, sandbox environment and API access privileges with the application provider. Generally, these tasks require you to complete several steps; you must check your API provider's documentation for the correct procedure in each case. As a reference we've included two examples below: Salesforce and Twitter. [NOTE] The examples below are accurate at the time of writing this guide; however, bear in mind that the API owners may change their instructions over time. === Salesforce Example . http://www.developerforce.com/events/regular/registration.php[Register for a Salesforce account]. You need to provide an email address to receive a confirmation email. . After you've filled out the registration form, open the confirmation email and click the link provided to enable you to set a password and log in to Salesforce Developer Edition. . To enable remote applications to log in to Salesforce, you must reset your security token on Salesforce by completing the following steps: .. From the Salesforce UI, select _Your Name_ > *My Settings* in the upper right corner. .. Expand the *My Personal Information* on the left sidebar, then select *Reset My Security Token*. + image::reset-token.png[reset_token] + .. On the *Reset Security Token* page, click the *Reset Security Token* button. Salesforce emails a new Security Token. . Record your *security token*, *username* and *password* as these items are required to complete the example below. === Twitter Example Twitter is a good example of a relatively simple API to access from a connector as many Web applications or services follow a similar model. . To access the Twitter API, you must first http://twitter.com/signup[obtain a Twitter account]. . To access Twitter APIs through the account you created, you need to create an empty Twitter application at Twitter's https://dev.twitter.com/docs[developer portal]. . To test the Twitter connector, obtain the following elements from Twitter: ** Access key ** Access secret ** Consumer key ** Consumer secret == SOAP-Based APIs For SOAP-based APIs, you need to obtain a WSDL file from the API provider. On top of this, SOAP-based services may have different authentication schemes such as persistent sessions, security headers included in each message, security tokens, or others. Each of these require specific attention when implementing the connector. == Using Java Libraries If available, you can download any existing Java library for accessing the service. This may be a client library that are the only means of accessing the application, or they may be a wrapper for the application's publicly exposed web service. To use a library, you can include it as a Maven dependency in your project. [NOTE] For details on building applications with Maven, see http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html[Introduction to the Maven Build Cycle] in the official Maven documentation. == See Also *NEXT:* Continue to xref:creating-an-anypoint-connector-project.adoc[Creating an Anypoint Connector Project] to begin developing your connector.
38,800
https://github.com/carlbarrdahl/busstrams/blob/master/js/components/Common/Bubble.jsx
Github Open Source
Open Source
MIT
2,014
busstrams
carlbarrdahl
JavaScript
Code
19
74
var React = require('react/addons'); var Bubble = module.exports = React.createClass({ render: function() { return (<figure className="Bubble" style={this.props.style}><span>{this.props.text}</span></figure>); } });
16,584
https://github.com/jdm7dv/rosyln/blob/master/Src/Workspaces/VisualBasic/Formatting/Rules/AdjustSpaceFormattingRule.vb
Github Open Source
Open Source
Apache-2.0
null
rosyln
jdm7dv
Visual Basic
Code
985
4,017
' Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting #If MEF Then <ExportFormattingRule(AdjustSpaceFormattingRule.Name, LanguageNames.VisualBasic)> <ExtensionOrder(After:=ElasticTriviaFormattingRule.Name)> Friend Class AdjustSpaceFormattingRule #Else Friend Class AdjustSpaceFormattingRule #End If Inherits BaseFormattingRule Friend Const Name As String = "VisualBasic Adjust Space Formatting Rule" Public Sub New() End Sub Public Overrides Function GetAdjustSpacesOperation(previousToken As SyntaxToken, currentToken As SyntaxToken, optionSet As OptionSet, nextFunc As NextOperation(Of AdjustSpacesOperation)) As AdjustSpacesOperation ' * <end of file token> If currentToken.VisualBasicKind = SyntaxKind.EndOfFileToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' () If previousToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso currentToken.VisualBasicKind = SyntaxKind.CloseParenToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' ,, If previousToken.VisualBasicKind = SyntaxKind.CommaToken AndAlso currentToken.VisualBasicKind = SyntaxKind.CommaToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' ( < case If previousToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso FormattingHelpers.IsLessThanInAttribute(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' < * * > in attribute If FormattingHelpers.IsLessThanInAttribute(previousToken) OrElse FormattingHelpers.IsGreaterThanInAttribute(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * < > * in attribute If FormattingHelpers.IsGreaterThanInAttribute(previousToken) OrElse FormattingHelpers.IsLessThanInAttribute(currentToken) Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' <? * If previousToken.VisualBasicKind = SyntaxKind.LessThanQuestionToken AndAlso FormattingHelpers.IsXmlTokenInXmlDeclaration(previousToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * ?> case If currentToken.VisualBasicKind = SyntaxKind.QuestionGreaterThanToken AndAlso FormattingHelpers.IsXmlTokenInXmlDeclaration(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' except <%= [xml token] or [xml token] %> case If (previousToken.VisualBasicKind <> SyntaxKind.LessThanPercentEqualsToken AndAlso FormattingHelpers.IsXmlToken(currentToken)) AndAlso (FormattingHelpers.IsXmlToken(previousToken) AndAlso currentToken.VisualBasicKind <> SyntaxKind.PercentGreaterThanToken) Then ' [xml token] [xml token] If FormattingHelpers.IsXmlToken(previousToken) AndAlso FormattingHelpers.IsXmlToken(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If End If ' %> [xml name token] If previousToken.VisualBasicKind = SyntaxKind.PercentGreaterThanToken AndAlso currentToken.VisualBasicKind = SyntaxKind.XmlNameToken Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [xml token] [xml name token] If FormattingHelpers.IsXmlToken(previousToken) AndAlso currentToken.VisualBasicKind = SyntaxKind.XmlNameToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [xml name token] <%= If previousToken.VisualBasicKind = SyntaxKind.XmlNameToken AndAlso currentToken.VisualBasicKind = SyntaxKind.LessThanPercentEqualsToken Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [xml name token] %> If previousToken.VisualBasicKind = SyntaxKind.XmlNameToken AndAlso currentToken.VisualBasicKind = SyntaxKind.PercentGreaterThanToken Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [xml name token] [xml token] If previousToken.VisualBasicKind = SyntaxKind.XmlNameToken AndAlso FormattingHelpers.IsXmlToken(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [xml name token] = If previousToken.VisualBasicKind = SyntaxKind.XmlNameToken AndAlso currentToken.VisualBasicKind = SyntaxKind.EqualsToken Then ' [XmlAttributeAccessExpression] = If TypeOf currentToken.Parent Is BinaryExpressionSyntax AndAlso DirectCast(currentToken.Parent, BinaryExpressionSyntax).Left.IsKind(SyntaxKind.XmlAttributeAccessExpression) Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' = ' [xml string] If previousToken.VisualBasicKind = SyntaxKind.EqualsToken AndAlso FormattingHelpers.IsQuoteInXmlString(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' " * * " or ' * * ' or "" or '' in xml string If (FormattingHelpers.IsQuoteInXmlString(previousToken) AndAlso FormattingHelpers.IsContentInXmlString(currentToken)) OrElse (FormattingHelpers.IsQuoteInXmlString(currentToken) AndAlso (FormattingHelpers.IsContentInXmlString(previousToken) OrElse FormattingHelpers.IsQuoteInXmlString(previousToken))) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' xml text literal If (previousToken.VisualBasicKind = SyntaxKind.XmlTextLiteralToken AndAlso currentToken.VisualBasicKind <> SyntaxKind.XmlNameToken) OrElse (previousToken.VisualBasicKind <> SyntaxKind.XmlNameToken AndAlso currentToken.VisualBasicKind = SyntaxKind.XmlTextLiteralToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' xml entity literal If previousToken.VisualBasicKind = SyntaxKind.XmlEntityLiteralToken OrElse currentToken.VisualBasicKind = SyntaxKind.XmlEntityLiteralToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces) End If ' (( case If previousToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso currentToken.VisualBasicKind = SyntaxKind.OpenParenToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [identifier] ( case If previousToken.VisualBasicKind = SyntaxKind.IdentifierToken AndAlso currentToken.VisualBasicKind = SyntaxKind.OpenParenToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [some keywords] ( case If currentToken.VisualBasicKind = SyntaxKind.OpenParenToken Then Select Case previousToken.VisualBasicKind Case SyntaxKind.NewKeyword, SyntaxKind.FunctionKeyword, SyntaxKind.SubKeyword, SyntaxKind.SetKeyword, SyntaxKind.AddHandlerKeyword, SyntaxKind.RemoveHandlerKeyword, SyntaxKind.RaiseEventKeyword, SyntaxKind.GetTypeKeyword, SyntaxKind.CTypeKeyword, SyntaxKind.TryCastKeyword, SyntaxKind.DirectCastKeyword, SyntaxKind.GetXmlNamespaceKeyword Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End Select If SyntaxFacts.IsPredefinedCastExpressionKeyword(previousToken.VisualBasicKind) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If End If ' [parent in argument list] ( case If FormattingHelpers.IsParenInArgumentList(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [binary condition] ( case If FormattingHelpers.IsParenInBinaryCondition(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [ternary condition] ( case If FormattingHelpers.IsParenInTernaryCondition(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' array rank specifier ( case If currentToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso TypeOf currentToken.Parent Is ArrayRankSpecifierSyntax Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [overloadable operator] ( case If currentToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso FormattingHelpers.IsOverloadableOperator(previousToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' [type parameter list] [parameter list] )( case If previousToken.VisualBasicKind = SyntaxKind.CloseParenToken AndAlso TypeOf previousToken.Parent Is TypeParameterListSyntax AndAlso currentToken.VisualBasicKind = SyntaxKind.OpenParenToken AndAlso TypeOf currentToken.Parent Is ParameterListSyntax Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' , [named field initializer dot] If previousToken.VisualBasicKind = SyntaxKind.CommaToken AndAlso FormattingHelpers.IsNamedFieldInitializerDot(currentToken) Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * [member access dot without expression] If previousToken.VisualBasicKind <> SyntaxKind.OpenParenToken AndAlso FormattingHelpers.IsMemberAccessDotWithoutExpression(currentToken) Then Return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * } ' * ) ' * , ' * . ' * := Select Case currentToken.VisualBasicKind Case SyntaxKind.CloseBraceToken, SyntaxKind.CloseParenToken, SyntaxKind.CommaToken, SyntaxKind.ColonEqualsToken Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) Case SyntaxKind.DotToken Dim space = If(previousToken.VisualBasicKind = SyntaxKind.CallKeyword OrElse previousToken.VisualBasicKind = SyntaxKind.KeyKeyword, 1, 0) Return CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End Select ' { * ' ( * ' ) * ' . * ' := * Select Case previousToken.VisualBasicKind Case SyntaxKind.OpenBraceToken, SyntaxKind.OpenParenToken, SyntaxKind.DotToken, SyntaxKind.ColonEqualsToken Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) Case SyntaxKind.CloseParenToken Dim space = If(previousToken.VisualBasicKind = currentToken.VisualBasicKind, 0, 1) Return CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End Select ' dictionary member access ! case If IsExclamationInDictionaryAccess(previousToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If If IsExclamationInDictionaryAccess(currentToken) Then If Not currentToken.TrailingTrivia.Any(SyntaxKind.LineContinuationTrivia) AndAlso previousToken.VisualBasicKind <> SyntaxKind.WithKeyword AndAlso previousToken.VisualBasicKind <> SyntaxKind.EqualsToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If End If ' * </ If currentToken.VisualBasicKind = SyntaxKind.LessThanSlashToken AndAlso FormattingHelpers.IsXmlToken(previousToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * /> If currentToken.VisualBasicKind = SyntaxKind.SlashGreaterThanToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' * > in xml literal If (currentToken.VisualBasicKind = SyntaxKind.GreaterThanToken AndAlso FormattingHelpers.IsXmlToken(currentToken)) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' +1 or -1 If (previousToken.VisualBasicKind = SyntaxKind.PlusToken OrElse previousToken.VisualBasicKind = SyntaxKind.MinusToken) AndAlso TypeOf previousToken.Parent Is UnaryExpressionSyntax Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' nullable ? case If FormattingHelpers.IsQuestionInNullableType(currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' <AttributeTarget : case If FormattingHelpers.IsColonAfterAttributeTarget(previousToken, currentToken) Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If If previousToken.VisualBasicKind = SyntaxKind.EmptyToken OrElse currentToken.VisualBasicKind = SyntaxKind.EmptyToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces) End If ' Else If If previousToken.VisualBasicKind = SyntaxKind.ElseKeyword AndAlso currentToken.VisualBasicKind = SyntaxKind.IfKeyword AndAlso previousToken.Parent Is currentToken.Parent Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If ' label Dim labelStatement = TryCast(previousToken.Parent, LabelStatementSyntax) If labelStatement IsNot Nothing AndAlso labelStatement.LabelToken = previousToken AndAlso currentToken.VisualBasicKind = SyntaxKind.ColonToken Then Return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine) End If Return nextFunc.Invoke() End Function End Class End Namespace
35,061
https://github.com/TugasMburi/TugasAkhir/blob/master/application/controllers/Admin.php
Github Open Source
Open Source
MIT
null
TugasAkhir
TugasMburi
PHP
Code
135
848
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('admin_model'); if($this->session->userdata('logged_in')){ $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $data['level'] = $session_data['level']; $current_controller = $this->router->fetch_class(); $this->load->library('acl'); if (! $this->acl->is_public($current_controller)) { if (! $this->acl->is_allowed($current_controller, $data['level'])) { echo '<script>alert("Anda Tidak Memiliki Hak Akses")</script>'; redirect('home','refresh'); } } }else{ redirect('login','refresh'); } } public function Index() { $session_data=$this->session->userdata('logged_in'); $data['username']= $session_data['username']; $data['list_user'] = $this->admin_model->tampilUser(); $this->load->view('loginAdmin',$data); } public function register() { $this->load->library('form_validation'); $this->form_validation->set_rules('username','Username','trim|required'); $this->form_validation->set_rules('fullname','Full Name','trim|required'); $this->form_validation->set_rules('email', 'E-mail', 'trim|required'); $this->form_validation->set_rules('password','Password','trim|required'); $this->form_validation->set_rules('level','Level','trim|required'); if ($this->form_validation->run() == FALSE) { $session_data=$this->session->userdata('logged_in'); $data['username']= $session_data['username']; $this->load->view('tambah_user_admin_view', $data); } else { $this->load->model('user'); $this->user->insert(); echo '<script>alert("Data berhasil disimpan")</script>'; redirect('admin','refresh'); } } public function delete($id) { $this->load->helper("url"); $this->load->model("admin_model"); $this->admin_model->delete($id); redirect('admin'); } public function update($id) { $session_data=$this->session->userdata('logged_in'); $data['username']= $session_data['username']; $data['list_user'] = $this->admin_model->tampilUser(); $this->load->view('editAdmin',$data); } } /* End of file Pegawai.php */ /* Location: ./application/controllers/Pegawai.php */ ?>
24,547
https://github.com/tlk00/BitMagic/blob/master/tests/stress/run_all_tests.sh
Github Open Source
Open Source
Apache-2.0
2,023
BitMagic
tlk00
Shell
Code
35
102
#!/bin/bash # run_all_tests.sh # # run all tests in parallel # ./run_all_parallel.sh sse42 || exit 1 ./run_all_parallel.sh || exit 1 ./run_all_parallel.sh avx2 || exit 1 ./run_all_parallel.sh gcc || exit 1 ./run_all_parallel.sh sse2 || exit 1
50,109
https://github.com/HudsonSchumaker/Game-Development-Patterns/blob/master/Prototype/Enemy.cs
Github Open Source
Open Source
MIT
null
Game-Development-Patterns
HudsonSchumaker
C#
Code
18
41
// Hudson Schumaker public class Enemy : ICopyable { public ICopyable Copy() { return new (this); } }
32,729
https://github.com/bonedaddy/shartnet_startkit/blob/master/scripts/compile.sh
Github Open Source
Open Source
Apache-2.0
2,022
shartnet_startkit
bonedaddy
Shell
Code
44
156
#! /bin/bash CAIRO_FILE="$1" OUTPUT="$2" if [[ "$CAIRO_FILE" == "" ]]; then echo "[ERROR] invalid invocation" echo "[ERROR] usage: compile.sh /path/to/file/cairo <output>" exit 1 fi if [[ "$OUTPUT" == "" ]]; then echo "$CAIRO_FILE" OUTPUT="$(echo $CAIRO_FILE | sed -e 's/\.cairo//g').compiled.json" fi cairo-compile "$CAIRO_FILE" --output "$OUTPUT"
32,855
https://github.com/simondel/core/blob/master/packages/date/index.ts
Github Open Source
Open Source
MIT
2,019
core
simondel
TypeScript
Code
96
236
// Export public API export * from './src/Date'; export * from './src/DateFields'; export * from './src/DateTime'; export * from './src/DateTimeFields'; export * from './src/DateTimeFormat'; export * from './src/DateTimeLayout'; export * from './src/DayOfMonth'; export * from './src/DayOfWeek'; export * from './src/DayOfYear'; export * from './src/Duration'; export * from './src/Hours'; export * from './src/InvariantDateTimeFormat'; export * from './src/Milliseconds'; export * from './src/Minutes'; export * from './src/Month'; export * from './src/NativeDate'; export * from './src/Seconds'; export * from './src/Time'; export * from './src/TimeFields'; export * from './src/TimeSpan'; export * from './src/TimeZone'; export * from './src/TimeZoneOffset'; export * from './src/Year';
11,076
https://github.com/protofire/burner-wallet/blob/master/src/components/Vendors.js
Github Open Source
Open Source
MIT
2,019
burner-wallet
protofire
JavaScript
Code
647
2,135
import React from 'react' import { Scaler } from 'dapparatus' import Blockies from 'react-blockies' const QRCode = require('qrcode.react') let interval export default class Advanced extends React.Component { constructor(props) { super(props) let vendor = false if (window.location.pathname.indexOf('/vendors;') === 0) { vendor = window.location.pathname.replace('/vendors;', '') window.history.pushState({}, '', '/') } this.state = { vendor: vendor, vendorObject: false, loading: false, showQR: {} } } componentDidMount() { interval = setInterval(this.poll.bind(this), 3000) setTimeout(this.poll.bind(this), 444) } componentWillUnmount() { clearInterval(interval) } async poll() { let id = 0 if (this.state.vendor) { if (!this.state.vendorObject) { let vendorData = await this.props.contracts[this.props.ERC20VENDOR].vendors(this.state.vendor).call() console.log('vendorData', vendorData) vendorData.name = this.props.web3.utils.hexToUtf8(vendorData.name) this.setState({ vendorObject: vendorData }) } console.log('Looking up products for vendor ', this.state.vendor) let products = [] //this.state.products if (!products) { products = [] } let found = true while (found) { let nextProduct = await this.props.contracts[this.props.ERC20VENDOR].products(this.state.vendor, id).call() if (nextProduct.exists) { products[id++] = nextProduct } else { found = false } } this.setState({ products, loading: false }) } else { this.setState({ loading: false }) } } render() { let { mainStyle, web3, vendors, dollarDisplay, vendorObject } = this.props let { vendor } = this.state let url = window.location.protocol + '//' + window.location.hostname if (window.location.port && window.location.port !== 80 && window.location.port !== 443) { url = url + ':' + window.location.port } let correctVendorObject = this.state.vendorObject if (!correctVendorObject) correctVendorObject = vendorObject let products = [] let vendorDisplay = [] if (vendor) { if (correctVendorObject) { products.push( <div className="nav-card card"> <div className="row"> <div style={{ position: 'absolute', left: 10, fontSize: 42, top: 0, cursor: 'pointer', zIndex: 1, padding: 3 }} onClick={() => { this.setState({ vendor: false }) }} > <i className="fas fa-arrow-left" /> </div> <div style={{ textAlign: 'center', width: '100%', fontSize: 22 }}> <Scaler config={{ startZoomAt: 500, origin: '80% 50%', adjustedZoom: 1 }}> {correctVendorObject.name} </Scaler> </div> </div> </div> ) } let qrSize = Math.min(document.documentElement.clientWidth, 512) - 90 let correctProducts = this.state.products if (!correctProducts) correctProducts = this.props.products for (let p in correctProducts) { let prod = correctProducts[p] if (prod.exists && prod.isAvailable) { let extraQR = '' let theName = web3.utils.hexToUtf8(prod.name) let theAmount = web3.utils.fromWei(prod.cost, 'ether') let productLocation = '/' + vendor + ';' + theAmount + ';' + theName .replaceAll('#', '%23') .replaceAll(';', '%3B') .replaceAll(':', '%3A') .replaceAll('/', '%2F') + ';' + correctVendorObject.name + ':' productLocation = encodeURI(productLocation) let qrValue = url + productLocation let toggleQR = () => { let { showQR } = this.state showQR[p] = !showQR[p] this.setState({ showQR }) } if (this.state.showQR[p]) { extraQR = ( <div className="main-card card w-100" style={{ paddingTop: 40 }} onClick={toggleQR}> <div className="content qr row"> <QRCode value={qrValue} size={qrSize} /> <div style={{ width: '100%', textAlign: 'center' }}> <div>{correctVendorObject.name}</div> {theName}: {dollarDisplay(theAmount)} </div> </div> </div> ) } products.push( <div className="content bridge row" style={{ borderBottom: '1px solid #dddddd', paddingTop: 15, paddingBottom: 10 }} > <div className="col-1 p-1" onClick={toggleQR}> <i className="fas fa-qrcode"></i> </div> <div className="col-4 p-1">{theName}</div> <div className="col-3 p-1">{dollarDisplay(theAmount)}</div> <div className="col-4 p-1"> <button className="btn btn-large w-100" style={{ backgroundColor: mainStyle.mainColor, whiteSpace: 'nowrap', marginTop: -8 }} onClick={() => { this.setState({ loading: true, products: false, vendor: false }, () => { window.location = productLocation }) }} > <Scaler config={{ startZoomAt: 500, origin: '40% 50%' }}>Purchase</Scaler> </button> </div> {extraQR} </div> ) } } let qrValue = url + '/vendors;' + this.state.vendor if (vendorObject) { products.push( <div className="main-card card w-100" style={{ paddingTop: 40 }}> <div className="content qr row"> <QRCode value={qrValue} size={qrSize} /> <div style={{ width: '100%', textAlign: 'center' }}>{vendorObject.name}</div> </div> </div> ) } } else { for (let v in vendors) { if (vendors[v].isAllowed && vendors[v].isActive) { let vendorButton = ( <button disabled={!vendors[v].isActive} className="btn btn-large w-100" style={{ backgroundColor: mainStyle.mainColor, whiteSpace: 'nowrap' }} onClick={() => { this.setState({ loading: true, vendor: vendors[v].vendor, vendorObject: vendors[v] }, () => { this.poll() }) }} > <Scaler config={{ startZoomAt: 600, origin: '10% 50%' }}>{vendors[v].name}</Scaler> </button> ) vendorDisplay.push( <div key={v} className="content bridge row"> <div className="col-2 p-1" style={{ textAlign: 'center' }}> <Blockies seed={vendors[v].vendor.toLowerCase()} scale={5} /> </div> <div className="col-10 p-1" style={{ textAlign: 'center' }}> {vendorButton} </div> </div> ) } } } return ( <div> {vendorDisplay} {products} </div> ) } }
39,999
https://github.com/HereSinceres/atlaskit-mk-2/blob/master/packages/editor/adf-schema/src/schema/nodes/block-card.ts
Github Open Source
Open Source
Apache-2.0
2,020
atlaskit-mk-2
HereSinceres
TypeScript
Code
176
493
import { NodeSpec, Node as PMNode } from 'prosemirror-model'; export interface UrlType { url: string; } export interface DataType { /** * @additionalProperties true */ data: object; } export type CardAttributes = UrlType | DataType; /** * @name blockCard_node */ export interface BlockCardDefinition { type: 'blockCard'; attrs: CardAttributes; } export const blockCard: NodeSpec = { inline: false, group: 'block', draggable: true, selectable: true, attrs: { url: { default: null }, data: { default: null }, }, parseDOM: [ { tag: 'a[data-block-card]', // bump priority higher than hyperlink priority: 100, getAttrs: dom => { const anchor = dom as HTMLAnchorElement; const data = anchor.getAttribute('data-card-data'); return { url: anchor.getAttribute('href') || null, data: data ? JSON.parse(data) : null, }; }, }, { tag: 'div[data-block-card]', getAttrs: dom => { const anchor = dom as HTMLDivElement; const data = anchor.getAttribute('data-card-data'); return { url: anchor.getAttribute('data-card-url') || null, data: data ? JSON.parse(data) : null, }; }, }, ], toDOM(node: PMNode) { const attrs = { 'data-block-card': '', href: node.attrs.url || '', 'data-card-data': node.attrs.data ? JSON.stringify(node.attrs.data) : '', }; return ['a', attrs]; }, };
33,194
https://github.com/SornDev/sit_app_vue/blob/master/resources/js/components/transection/Transection.vue
Github Open Source
Open Source
MIT
null
sit_app_vue
SornDev
Vue
Code
36
138
<template> <section class="content"> <div class="row"> <div class="col-lg-12"> <h1>Transection</h1> </div> </div> </section> </template> <script> export default { name: "transection", components: {}, directives: {}, data() { return {}; }, mounted() {}, methods: {} }; </script> <style lang="scss" scoped></style>
15,503
https://github.com/i-Cell-Mobilsoft-Open-Source/swagger-jaxb/blob/master/README.adoc
Github Open Source
Open Source
Apache-2.0
2,020
swagger-jaxb
i-Cell-Mobilsoft-Open-Source
AsciiDoc
Code
430
2,334
= swagger-jaxb //A README.adoc-ot az index.adoc-ból generáljuk preprocessor scripttel, ami kicseréli az include-okat a tényleges adoc szövegre //mivel a github egyelőre nem képes include-olni csak linkelni //script: https://github.com/asciidoctor/asciidoctor-extensions-lab/blob/master/scripts/asciidoc-coalescer.rb script //futtatás: ruby ~/Work/iCell/Util/asciidoctor/scripts/asciidoc-coalescer.rb -o README.adoc index.adoc It was created form `be.redlab.jaxb:swagger-jaxb`, since the original GitHub project seems abandoned, this fork is developed independently from its parents. Original project: https://github.com/redlab/swagger-jaxb The modification is based on the following fork: https://github.com/peneksglazami/swagger-jaxb == Summary This project is a refactored version of the forks mentioned above, its purpose was to make the project more extendable, namely allowing to override the generated annotations and their targets. === Maven central This project is available in maven central as: [source, xml] ---- <dependency> <groupId>hu.icellmobilsoft.jaxb</groupId> <artifactId>swagger-jaxb</artifactId> <version>1.1.0</version> </dependency> ---- == Original README :leveloffset: 2 = swagger-jaxb JAXB XJC Plugin for automatically adding annotations from Swagger to generated classes from an XSD Tests run in separate project, see here for the code https://github.com/redlab/swagger-jaxb-tck[https://github.com/redlab/swagger-jaxb-tck] == Usage * REQUIRE Java 8 or higher! * build the plugin with maven * install it in your local repo * add the plugin to your classpath and use -swaggify on your jaxb command line or configure it i your pom or * add sonatype snapshot repository to your repo manager. ( post an issue if you really want dev version in Maven Central ) === Use with org.jvnet.jaxb2.maven2 maven-jaxb2-plugin [source, xml] ---- <build> <plugins> <plugin> <groupId>org.jvnet.jaxb2.maven2</groupId> <artifactId>maven-jaxb2-plugin</artifactId> <version>0.13.2</version> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <schemaIncludes> <schemaInclude>**/*.xsd</schemaInclude> </schemaIncludes> <strict>true</strict> <verbose>true</verbose> <extension>true</extension> <removeOldOutput>true</removeOldOutput> <args> <arguments>-swaggerify</arguments> </args> <plugins> <plugin> <groupId>be.redlab.jaxb</groupId> <artifactId>swagger-jaxb</artifactId> <version>1.5</version> </plugin> </plugins> <dependencies> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.12</version> </dependency> </dependencies> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.12</version> </dependency> </dependencies> ---- === Use with org.codehaus.mojo jaxb2-maven-plugin [source, xml] ---- <build> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>2.3</version> <dependencies> <dependency> <groupId>be.redlab.jaxb</groupId> <artifactId>swagger-jaxb</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>javax.xml.parsers</groupId> <artifactId>jaxp-api</artifactId> <version>1.4.5</version> </dependency> <dependency> <groupId>com.sun.xml.parsers</groupId> <artifactId>jaxp-ri</artifactId> <version>1.4.5</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-xjc</artifactId> <version>2.2.11</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.2.11</version> </dependency> </dependencies> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>2.3</version> <executions> <execution> <id>internal.generate</id> <goals> <goal>xjc</goal> </goals> <configuration> <arguments>-swaggerify</arguments> <clearOutputDir>true</clearOutputDir> <packageName>be.redlab.jaxb.swagger.generated.model</packageName> <sources> <source>${project.basedir}/src/main/xsd/schema</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> <dependencies> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.12</version> </dependency> </dependencies> ---- Also you can use plugin with Gradle [source, groovy] ---- configurations { xjcConf } dependencies { xjcConf 'com.sun.xml.bind:jaxb-xjc:2.2.6' xjcConf 'com.sun.xml.bind:jaxb-impl:2.2.6' xjcConf 'javax.xml.bind:jaxb-api:2.2.6' xjcConf 'org.jvnet.jaxb2_commons:jaxb2-basics:1.11.1' xjcConf 'org.jvnet.jaxb2_commons:jaxb2-basics-runtime:1.11.1' xjcConf 'org.jvnet.jaxb2_commons:jaxb2-basics-tools:1.11.1' xjcConf 'org.jvnet.jaxb2_commons:jaxb2-basics-ant:1.11.1' xjcConf 'org.jvnet.jaxb2_commons:jaxb2-basics-annotate:1.0.3' xjcConf('be.redlab.jaxb:swagger-jaxb:1.5') { exclude group: 'com.sun.xml.bind' exclude group: 'javax.xml.bind' } } task generateClassesFromXsd { doLast { ant.taskdef( name: 'antXjc', classname: 'org.jvnet.jaxb2_commons.xjc.XJC2Task', classpath: configurations.xjcConf.asPath ) System.setProperty('javax.xml.accessExternalSchema', 'file') ant.antXjc( destdir: 'src/main/java', binding: 'src/main/resources/xsd/binding.xjb', extension: 'true') { arg(value: '-swaggerify') schema(dir: 'src/main/resources/xsd') { include(name: '*.xsd') } } } } ---- :leveloffset!:
6,199
https://github.com/rampopat/social-network/blob/master/testsuite/socialnetwork/TestSuite.java
Github Open Source
Open Source
MIT
null
social-network
rampopat
Java
Code
487
1,662
package socialnetwork; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.collect.Multimap; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test; import socialnetwork.domain.Backlog; import socialnetwork.domain.Board; import socialnetwork.domain.LinkedBacklog; import socialnetwork.domain.LinkedBoard; import socialnetwork.domain.Message; import socialnetwork.domain.Worker; public class TestSuite { @Test public void testSmallParams() { ExperimentSettings settings = new ExperimentSettings(1, 5, 50, 3, 123456); runExperiment(settings); } @Test public void testMediumParams() { ExperimentSettings settings = new ExperimentSettings(3, 10, 50, 10, 123456); runExperiment(settings); } @Test public void testSlightlyLargerParams() { ExperimentSettings settings = new ExperimentSettings(5, 40, 75, 15, 123456); runExperiment(settings); } @Test public void testLargeParams() { ExperimentSettings settings = new ExperimentSettings(10, 100, 100, 20, 123456); runExperiment(settings); } static class ExperimentSettings { int nWorkers; int nUsers; int maxActions; int maxRecipients; int seed; public ExperimentSettings(int nWorkers, int nUsers, int maxActions, int maxRecipients, int seed) { this.nWorkers = nWorkers; this.nUsers = nUsers; this.maxActions = maxActions; this.maxRecipients = maxRecipients; this.seed = seed; } } private void runExperiment(ExperimentSettings settings) { Backlog backlog = new LinkedBacklog(); SocialNetwork socialNetwork = new SocialNetwork(backlog); Worker[] workers = new Worker[settings.nWorkers]; Arrays.setAll(workers, i -> new Worker(backlog)); Arrays.stream(workers).forEach(Thread::start); TestUser.maxActions = settings.maxActions; TestUser.maxRecipients = settings.maxRecipients; TestUser[] userThreads = new TestUser[settings.nUsers]; Arrays.setAll(userThreads, i -> { TestUser user = new TestUser("user" + i, socialNetwork); user.getRandom().setSeed(settings.seed++); //use distinct seeds for each user return user; }); Arrays.stream(userThreads).forEach(u -> { socialNetwork.register(u, new LinkedBoard()); u.start(); }); Arrays.stream(userThreads).forEach(u -> { try { u.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); while (backlog.numberOfTasksInTheBacklog() != 0) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } Arrays.stream(workers).forEach(w -> w.interrupt()); Arrays.stream(workers).forEach(w -> { try { w.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); assertEquals(0, backlog.numberOfTasksInTheBacklog()); System.out.println("Work's done, checking for consistency..."); Map<User, Set<Integer>> userToReceivedMessages = new HashMap<>(); for (Map.Entry<User, Board> entry : socialNetwork.getBoards().entrySet()) { Board board = entry.getValue(); User user = entry.getKey(); // check if all messages in a board are ordered checkBoardOrdering(board); Set<Integer> messageIds = board.getBoardSnapshot().stream() .map(Message::getMessageId) .collect(Collectors.toSet()); userToReceivedMessages.put(user, messageIds); } Map<User, Integer> expectedMessageCount = new HashMap<>(); // check that all messages sent by an user were received properly for (TestUser tUser : userThreads) { Multimap<User, Message> userMessages = tUser.getSentMessages(); //System.out.println(tUser + " ---> " + userMessages); for (Map.Entry<User, Collection<Message>> entry : userMessages.asMap().entrySet()) { User recipient = entry.getKey(); List<Integer> sentMessageIds = entry.getValue().stream() .map(Message::getMessageId) .collect(Collectors.toList()); Set<Integer> recipientBoard = userToReceivedMessages.get(recipient); sentMessageIds.forEach(e -> { if(!recipientBoard.contains(e)) { System.out.println(e); } }); assertTrue(recipientBoard.containsAll(sentMessageIds)); int count = expectedMessageCount.getOrDefault(recipient,0); expectedMessageCount.put(recipient, count + sentMessageIds.size()); } } //check that the number of messages delivered and received is consistent for (TestUser tUser : userThreads) { Board userBoard = socialNetwork.userBoard(tUser); int expectedCount = expectedMessageCount.getOrDefault(tUser,0); int actualCount = userBoard.size(); assertEquals("count for user " + tUser + " doesn't match!",expectedCount,actualCount); } } private void checkBoardOrdering(Board b) { List<Message> messages = b.getBoardSnapshot(); if (messages.isEmpty()) { return; } Iterator<Message> it = messages.iterator(); Message current = it.next(); while (it.hasNext()) { Message next = it.next(); int cId = current.getMessageId(); int nId = next.getMessageId(); if(cId <= nId) { System.out.println(cId + " " + nId); } assertTrue(cId > nId); current = next; } } }
17,711
https://github.com/labzen/cells/blob/master/core/src/test/java/cn/labzen/cells/core/utils/BytesTest.java
Github Open Source
Open Source
Apache-2.0
null
cells
labzen
Java
Code
215
749
package cn.labzen.cells.core.utils; import com.google.common.collect.Maps; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.Serializable; import java.math.BigInteger; import java.util.Map; import static cn.labzen.cells.core.utils.Bytes.*; public class BytesTest { @Test void testHex() { String original = "410f1b"; byte[] bytes = hexStringToBytes(original); String hex = bytesToHexString(bytes, false); Assertions.assertEquals(original, hex); String binary = hexStringToBinaryString("03"); Assertions.assertEquals("00000011", binary); } @Test void testAscii() { String original = "ascii0123"; byte[] bytes = asciiStringToBytes(original); String ascii = bytesToAsciiString(bytes); Assertions.assertEquals(original, ascii); } @Test void testInt() { int original = 12498761; byte[] bytes = intToBytes(original); int integer = bytesToInt(bytes); Assertions.assertEquals(original, integer); } @Test void testBigInt() { BigInteger original = new BigInteger("4546928818324112"); byte[] bytes = bigIntToBytes(original); BigInteger integer = bytesToBigInt(bytes); Assertions.assertEquals(original, integer); } @Test void testByteArray() { long number = Randoms.longNumber(Long.MAX_VALUE); byte[] bytes = longToBytes(number); long recovered = bytesToLong(bytes); Assertions.assertEquals(number, recovered); } @Test void testObjectArray() { Map<String, Integer> params = Maps.newHashMap(); params.put("a", 1); params.put("b", 2); byte[] bytes = objectToBytes(params); Object restored = bytesToObject(bytes); Assertions.assertEquals(params, restored); Bean bean = new Bean("Dean", 18); byte[] beanBytes = objectToBytes(bean); Object restoredBean = bytesToObject(beanBytes); Assertions.assertNotNull(restoredBean); Assertions.assertEquals(Bean.class, restoredBean.getClass()); Bean rb = (Bean) restoredBean; Assertions.assertEquals(bean.age, rb.age); } static class Bean implements Serializable { private final String name; private final int age; public Bean(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } }
44,241
https://github.com/SincerelyUnique/grimm-backend/blob/master/grimm/utils/vrfcode.py
Github Open Source
Open Source
MIT
2,021
grimm-backend
SincerelyUnique
Python
Code
281
885
# # File: vrfcode.py # Copyright: Grimm Project, Ren Pin NGO, all rights reserved. # License: MIT # ------------------------------------------------------------------------- # Authors: Ming Li(adagio.ming@gmail.com) # # Description: generate transaction ID and verification code, # keeping them unique. # # To-Dos: # 1. make other supplements if needed. # # Issues: # No issue so far. # # Revision History (Date, Editor, Description): # 1. 2019/09/19, Ming, create first revision. # import uuid import time import random import string from itsdangerous import URLSafeTimedSerializer from grimm import logger from grimm import GrimmConfig from grimm.utils.misctools import get_host_ip, is_ipv4_addr from grimm.utils.constants import HOST, PORT from grimm.utils.constants import DEFAULT_SERIAL_NO_BYTES, DEFAULT_VRFCODE_BYTES, DEFAULT_PROTOCOL VRFCODE_POOL = {} def new_serial_number(_bytes=DEFAULT_SERIAL_NO_BYTES): '''generate new serial number''' return uuid.uuid1().hex[0:_bytes] def new_vrfcode(_bytes=DEFAULT_VRFCODE_BYTES): '''generate new verification code''' global VRFCODE_POOL code = ''.join(random.choices(string.digits, k=_bytes)) if code in VRFCODE_POOL: return new_vrfcode() else: start = int(time.time()) VRFCODE_POOL[code] = start return code def check_vrfcode_expiry(code, limit=600): '''check code expiry, return True if not expired, otherwise False''' global VRFCODE_POOL if isinstance(code, bytes): code = code.decode('utf8') if isinstance(code, int): code = '%06d' % (code) if isinstance(code, str): if code in VRFCODE_POOL: start = VRFCODE_POOL[code] else: logger.error('invalid verification code: %s', code) return False else: err = TypeError('invalid type for parameter: code') logger.error(err.message) raise err duration = time.time() - start if duration > limit: del VRFCODE_POOL[code] return False return True def new_vrfurl(email): '''generate new confirm verification email url''' serializer = URLSafeTimedSerializer(GrimmConfig.SECRET_KEY) token = serializer.dumps(email, salt=GrimmConfig.SECURITY_PASSWORD_SALT) server_port = PORT server_host = get_host_ip() if is_ipv4_addr(HOST) or HOST == 'localhost' else HOST vrfurl = DEFAULT_PROTOCOL + '://' + 'rp-i.net' + '/admin-email?verify_token=' + token return vrfurl def parse_vrftoken(token): '''confirm email token with certain expiration time''' serializer = URLSafeTimedSerializer(GrimmConfig.SECRET_KEY) try: addr = serializer.loads( token, salt=GrimmConfig.SECURITY_PASSWORD_SALT) except: return None return addr
20,314
https://github.com/LER0ever/Presentations/blob/master/template/js/hovercraft.js
Github Open Source
Open Source
Apache-2.0
2,021
Presentations
LER0ever
JavaScript
Code
110
331
// Initialize impress.js impress().init(); // Set up the help-box var helpdiv = window.document.getElementById('hovercraft-help'); if (window.top!=window.self) { // This is inside an iframe, so don't show the help. helpdiv.className = "disabled"; } else { // Install a funtion to toggle help on and off. var help = function() { if(helpdiv.className == 'hide') helpdiv.className = 'show'; else helpdiv.className = 'hide'; }; impressConsole().registerKeyEvent([72], help, window); // The help is by default shown. Hide it after five seconds. setTimeout(function () { var helpdiv = window.document.getElementById('hovercraft-help'); if(helpdiv.className != 'show') helpdiv.className = 'hide'; }, 5000); } if (impressConsole) { impressConsole().init(cssFile='css/impressConsole.css'); var impressattrs = document.getElementById('impress').attributes if (impressattrs.hasOwnProperty('auto-console') && impressattrs['auto-console'].value.toLowerCase() === 'true') { consoleWindow = console().open(); } }
27,508
https://github.com/Camaradotspace/camara-native/blob/master/src/components/Phone/icons/HomeIndicator.tsx
Github Open Source
Open Source
MIT
null
camara-native
Camaradotspace
TypeScript
Code
54
148
import React from "react"; import Svg, { Rect } from "react-native-svg"; interface IHomeIndicator { theme?: "light" | "dark"; } export const HomeIndicator = ({ theme }: IHomeIndicator) => { return ( <Svg width="134" height="5" viewBox="0 0 134 5" fill="none"> <Rect width="134" height="5" rx="2.5" fill={theme === "dark" ? "white" : "black"} /> </Svg> ); };
13,536
https://github.com/strawsyz/straw/blob/master/ProgrammingQuestions/Others/Com-L-intern-2021.py
Github Open Source
Open Source
MIT
2,023
straw
strawsyz
Python
Code
86
386
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/06/21 3:04 # @Author : strawsyz # @File : line2021.py # @desc: import numpy as np import math te = -0.3+0.53+0.46-0.77+0.9-0.4 print(te) te = 0.46-0.39-0.75+0.3-0.56+0.55 print(te) te = -0.77+0.51-0.44-0.42+0.2+0.51 print(te) te = -0.97+0.49-0.86-0.17+0.22+0.13 print(te) te = np.sqrt((0.6+0.41)**2 + (1.46)**2) print(te) # if first <x : # first = x # second = first # elif second < x: # second = x te = 2.5**2 + 1.5**2 + 0.5**2 print(te/3) def main(x): print((1+2*x+3*x**2+4*x**3+5*x**4+6*x**5+7*x**6+8*x**7+9*x**8+10*x**9)*(1-x)) main(0.2) # print(2.4244172799999997/1.25)
3,505
https://github.com/andrew-m/map-battle/blob/master/model/GameEngine.js
Github Open Source
Open Source
Apache-2.0
null
map-battle
andrew-m
JavaScript
Code
273
751
//external events are: //Turn submissions // - firing angles // - movements //keyboard presses //Which result in changes to the game state //Such as angles/collisions being worked out // With lives lost if hit. //or blobs moving //No loop really needed, but could detect keyboard events, as more fun than using a form. //Game engine does NOT contain game state. //It acts upon an event, and a game state, to create a new game state. //Still sounds about right //Immutable or mutable game state? I think mutable will be fine. Vector = require('./Vector.js').Vector; VectorCalculator = require('./VectorFromAngleCalculator.js') function getCurrentBlob(gameState) { return gameState.Blobs[gameState.currentTurnIndex]; } function keyLeft(gameState) { let currentBlob = getCurrentBlob(gameState); if (currentBlob.x > 1) { (moveLeft(currentBlob)) } return gameState } function keyRight(gameState) { let currentBlob = getCurrentBlob(gameState); if (currentBlob.x < gameState.gridWidth) { (moveRight(getCurrentBlob(gameState))) } return gameState } function keyDown(gameState) { let currentBlob = getCurrentBlob(gameState); if(currentBlob.y > 1) { (moveDown(currentBlob)) } return gameState } function keyUp(gameState) { let currentBlob = getCurrentBlob(gameState); if (currentBlob.y < gameState.gridHeight) { (moveUp(currentBlob)) } return gameState } function nextPlayer (gameState) { var currentBlob = getCurrentBlob(gameState) currentBlob.oldx = currentBlob.x currentBlob.oldy = currentBlob.y gameState.currentTurnIndex += 1 if (gameState.currentTurnIndex >= gameState.Blobs.length) { gameState.currentTurnIndex = 0 } return gameState } function bearingFired (bearing, gameState, distance) { let currentBlob = getCurrentBlob(gameState); let vector = VectorCalculator.calculateVector(bearing, distance); currentBlob.vector = vector return gameState } function moveUp(blob) { blob.y += 1 //OS grid references start in South West corner. return blob } function moveDown(blob) { blob.y -= 1 return blob } function moveLeft(blob) { blob.x -= 1 return blob } function moveRight(blob) { blob.x += 1 return blob } module.exports = { keyLeft, keyRight, keyDown, keyUp, nextPlayer, bearingFired }
12,048
https://github.com/sweetysweets/Sports/blob/master/controller/Friend/addFriend.php
Github Open Source
Open Source
Apache-2.0
2,017
Sports
sweetysweets
PHP
Code
33
162
<?php /** * Created by PhpStorm. * User: sweets_ling * Date: 2016/12/1 * Time: 下午2:45 */ include('../../model/Friend.php'); $friendid=$_POST['fid']; $id = $_POST['uid']; $account=new Friend("sqlite:../../mydatabase.sqlite"); $res=$account->addFriend($id,$friendid); if($res) { echo json_encode(true); //$.ajax已经指定了服务器返回的数据为json格式 }else{ echo json_encode(false); }
18,522
https://github.com/NilmaPeiris/nodecloud/blob/master/packages/azure-plugin/storage/azure-blockStorage.js
Github Open Source
Open Source
MIT
2,020
nodecloud
NilmaPeiris
JavaScript
Code
444
1,520
const { ComputeManagementClient } = require("@azure/arm-compute"); /*This is an auto generated class, please do not change.*/ /** * Class to create a BlockStorage object * @category Azure */ class Azure_BlockStorage { /** * * @param {module} azureRestSdk Azure Rest SDK */ constructor(azureRestSdk) { this._azureRestSdk = azureRestSdk; } /** * Trigers the createOrUpdate function of compute * @param {StringKeyword} resourceGroupName - Mandatory parameter * @param {StringKeyword} diskName - Mandatory parameter * @param {TypeReference} disk - Mandatory parameter * @param {TypeReference} [options] - Optional parameter * @returns {Promise<createOrUpdateResponse>} */ create(resourceGroupName, diskName, disk, options = undefined) { return new Promise((resolve, reject) => { this._azureRestSdk .loginWithServicePrincipalSecretWithAuthResponse( process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET, process.env.AZURE_TENANT_ID ) .then(authres => { const client = new ComputeManagementClient( authres.credentials, process.env.AZURE_SUBSCRIPTION_ID ); client.disks .createOrUpdate(resourceGroupName, diskName, disk, options) .then(result => { resolve(result); }); }) .catch(err => { reject(err); }); }); } /** * Trigers the deleteMethod function of compute * @param {StringKeyword} resourceGroupName - Mandatory parameter * @param {StringKeyword} diskName - Mandatory parameter * @param {TypeReference} [options] - Optional parameter * @returns {Promise<deleteMethodResponse>} */ delete(resourceGroupName, diskName, options = undefined) { return new Promise((resolve, reject) => { this._azureRestSdk .loginWithServicePrincipalSecretWithAuthResponse( process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET, process.env.AZURE_TENANT_ID ) .then(authres => { const client = new ComputeManagementClient( authres.credentials, process.env.AZURE_SUBSCRIPTION_ID ); client.disks .deleteMethod(resourceGroupName, diskName, options) .then(result => { resolve(result); }); }) .catch(err => { reject(err); }); }); } /** * Trigers the get function of compute * @param {StringKeyword} resourceGroupName - Mandatory parameter * @param {StringKeyword} diskName - Mandatory parameter * @param {TypeReference} [options] - Optional parameter * @returns {Promise<getResponse>} */ describe(resourceGroupName, diskName, options = undefined) { return new Promise((resolve, reject) => { this._azureRestSdk .loginWithServicePrincipalSecretWithAuthResponse( process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET, process.env.AZURE_TENANT_ID ) .then(authres => { const client = new ComputeManagementClient( authres.credentials, process.env.AZURE_SUBSCRIPTION_ID ); client.disks .get(resourceGroupName, diskName, options) .then(result => { resolve(result); }); }) .catch(err => { reject(err); }); }); } /** * Trigers the list function of compute * @param {TypeReference} [options] - Optional parameter * @returns {Promise<listResponse>} */ list(options = undefined) { return new Promise((resolve, reject) => { this._azureRestSdk .loginWithServicePrincipalSecretWithAuthResponse( process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET, process.env.AZURE_TENANT_ID ) .then(authres => { const client = new ComputeManagementClient( authres.credentials, process.env.AZURE_SUBSCRIPTION_ID ); client.disks.list(options).then(result => { resolve(result); }); }) .catch(err => { reject(err); }); }); } /** * Trigers the update function of compute * @param {StringKeyword} resourceGroupName - Mandatory parameter * @param {StringKeyword} diskName - Mandatory parameter * @param {TypeReference} disk - Mandatory parameter * @param {TypeReference} [options] - Optional parameter * @returns {Promise<updateResponse>} */ update(resourceGroupName, diskName, disk, options = undefined) { return new Promise((resolve, reject) => { this._azureRestSdk .loginWithServicePrincipalSecretWithAuthResponse( process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET, process.env.AZURE_TENANT_ID ) .then(authres => { const client = new ComputeManagementClient( authres.credentials, process.env.AZURE_SUBSCRIPTION_ID ); client.disks .update(resourceGroupName, diskName, disk, options) .then(result => { resolve(result); }); }) .catch(err => { reject(err); }); }); } } module.exports = Azure_BlockStorage;
40,107
https://github.com/rvedam/cl-data-structures/blob/master/src/algorithms/common.lisp
Github Open Source
Open Source
MIT
2,018
cl-data-structures
rvedam
Common Lisp
Code
602
2,165
(in-package #:cl-data-structures.algorithms) (defclass proxy-range () ((%original-range :initarg :original-range :reader read-original-range))) (defmethod cl-ds:reset! ((range proxy-range)) (cl-ds:reset! (read-original-range range)) range) (defmethod cl-ds:clone ((range proxy-range)) (make (type-of range) :original-range (cl-ds:clone (read-original-range range)))) (defmethod cl-ds:traverse (function (range proxy-range)) (cl-ds:traverse function (read-original-range range))) (defmethod cl-ds:across (function (range proxy-range)) (cl-ds:across function (read-original-range range))) (defgeneric proxy-range-aggregator-outer-fn (range key function outer-fn arguments) (:method ((range proxy-range) key function outer-fn arguments) (or outer-fn (if (typep function 'cl-ds.alg.meta:multi-aggregation-function) (lambda () (cl-ds.alg.meta:make-multi-stage-linear-aggregator arguments key (apply #'cl-ds.alg.meta:multi-aggregation-stages function arguments))) (lambda () (cl-ds.alg.meta:make-linear-aggregator function arguments key)))))) (defmethod cl-ds.alg.meta:construct-aggregator ((range proxy-range) key function outer-fn (arguments list)) (cl-ds.alg.meta:construct-aggregator (read-original-range range) key function (proxy-range-aggregator-outer-fn range key function outer-fn arguments) arguments)) (defmethod cl-ds.alg.meta:apply-aggregation-function-with-aggregator ((aggregator cl-ds.alg.meta:fundamental-aggregator) (range proxy-range) function &rest all) (apply #'cl-ds.alg.meta:apply-aggregation-function-with-aggregator aggregator (read-original-range range) function all)) (defclass forward-proxy-range (proxy-range fundamental-forward-range) ()) (defclass bidirectional-proxy-range (proxy-range fundamental-bidirectional-range) ()) (defclass random-access-proxy-range (proxy-range fundamental-random-access-range) ()) (defgeneric make-proxy (range class &rest all &key &allow-other-keys) (:method ((range fundamental-range) class &rest all &key &allow-other-keys) (apply #'make-instance class :original-range range all))) (defclass hash-table-range (fundamental-random-access-range key-value-range) ((%hash-table :initarg :hash-table :reader read-hash-table) (%keys :initarg :keys :reader read-keys) (%begin :initarg :begin :type fixnum :accessor access-begin) (%end :initarg :end :type fixnum :accessor access-end))) (defmethod print-object ((obj hash-table-range) stream) (format stream "<HT-range:~%") (let ((count 10)) (block map-block (maphash (lambda (key value) (format stream " {~a} ~%" key) (decf count) (when (zerop count) (return-from map-block))) (read-hash-table obj))) (when (> (hash-table-count (read-hash-table obj)) 3) (format stream " ~a~%" "...")) (format stream ">") obj)) (defmethod cl-ds:traverse (function (range hash-table-range)) (let ((keys (read-keys range)) (table (read-hash-table range))) (iterate (for i from (access-begin range) below (access-end range)) (for key = (aref keys i)) (funcall function (list* key (gethash key table)))))) (defmethod clone ((range hash-table-range)) (make 'hash-table-range :keys (read-keys range) :begin (access-begin range) :end (access-end range) :hash-table (read-hash-table range))) (defmethod consume-front ((range forward-proxy-range)) (consume-front (read-original-range range))) (defmethod consume-back ((range bidirectional-proxy-range)) (consume-back (read-original-range range))) (defmethod peek-front ((range forward-proxy-range)) (peek-front (read-original-range range))) (defmethod peek-back ((range bidirectional-proxy-range)) (peek-back (read-original-range))) (defmethod at ((range random-access-proxy-range) location &rest more) (apply #'at (read-original-range range) location more)) (defmethod consume-front ((range hash-table-range)) (bind (((:slots (begin %begin) (end %end) (ht %hash-table) (keys %keys)) range) ((:lazy key result) (prog1 (aref keys begin) (incf begin)) (list* key (gethash key ht)))) (if (eql begin end) (values nil nil) (values result t)))) (defmethod consume-back ((range hash-table-range)) (bind (((:slots (begin %begin) (end %end) (ht %hash-table) (keys %keys)) range) ((:lazy key result) (aref keys (decf end)) (list* key (gethash key ht)))) (if (eql begin end) (values nil nil) (values result t)))) (defmethod peek-front ((range hash-table-range)) (bind (((:slots (begin %begin) (end %end) (ht %hash-table) (keys %keys)) range) ((:lazy key result) (aref keys begin) (list* key (gethash key ht)))) (if (eql begin end) (values nil nil) (values result t)))) (defmethod peek-back ((range hash-table-range)) (bind (((:slots (begin %begin) (end %end) (ht %hash-table) (keys %keys)) range) ((:lazy key result) (aref keys end) (list* key (gethash key ht)))) (if (eql begin end) (values nil nil) (values result t)))) (defmethod drop-front ((range hash-table-range) count) (bind (((:slots (begin %begin) (end %end)) range) (count (min end (+ begin count)))) (setf begin count)) range) (defmethod drop-back ((range hash-table-range) count) (with-slots ((begin %begin) (end %end)) range (setf end (max begin (- end count)))) range) (defmethod at ((range hash-table-range) location &rest more) (assert (null more)) (bind (((:slots (ht %hash-table)) range) ((:hash-table (result location)) ht) (test (hash-table-test ht)) (begin (access-begin range)) (end (access-end range)) (keys (read-keys range))) (if (iterate (for i from begin below end) (for l = (aref keys i)) (finding t such-that (funcall test l location))) (values result t) (values nil nil)))) (defmethod size ((range hash-table-range)) (bind (((:slots %end %begin) range)) (- %end %begin))) (defun make-hash-table-range (hash-table) (let ((keys (coerce (hash-table-keys hash-table) 'vector))) (make-instance 'hash-table-range :hash-table hash-table :keys keys :begin 0 :end (length keys))))
5,147
https://github.com/git-the-cpan/MooseX-InsideOut/blob/master/t/sub.t
Github Open Source
Open Source
Artistic-1.0
null
MooseX-InsideOut
git-the-cpan
Perl
Code
165
478
use strict; use warnings; use Test::More tests => 56; use lib 't/lib'; my @classes = qw(IO Array Hash Moose); for my $c (@classes) { my $base = "InsideOut::Base$c"; my $sub = "InsideOut::Sub$c"; eval "require $base;1" or die $@; eval "require $sub;1" or die $@; my $obj = eval { $sub->new(base_foo => 17) }; is($@, "", "$c: no errors creating object"); my $get = eval { $obj->base_foo }; is($@, "", "$c: no errors getting attribute"); { local $TODO = "don't clobber superclass' meta's create_instance" if $c eq 'Moose'; is($get, 17, "$c: base_foo is 17"); } my $set_base = eval { $obj->base_foo(18); $obj->base_foo; }; is($@, "", "$c: no errors setting base class attribute"); is($set_base, 18, "$c: base_foo is 18"); my $set_sub = eval { $obj->sub_foo(23); $obj->sub_foo; }; is($@, "", "$c: no errors setting attribute"); is($set_sub, 23, "$c: sub_foo is 23"); # diag MooseX::InsideOut::Meta::Instance->__dump($obj); # use Data::Dumper; # diag Dumper($obj); $sub->meta->make_immutable( allow_mutable_ancestors => 1, inline_constructor => ($c ne 'Hash' and $c ne 'Array') ), redo if $sub->meta->is_mutable; }
8,037
https://github.com/mtorromeo/vue-patternfly/blob/master/apps/docs/src/stories/Components/Modal.story.vue
Github Open Source
Open Source
MIT
2,023
vue-patternfly
mtorromeo
Vue
Code
246
716
<template> <doc-page title="Modal"> <component-title name="pf-modal" /> <story-canvas title="Default"> <pf-button @click="open1 = !open1">Toggle Modal</pf-button> <pf-modal v-model:open="open1" title="Simple modal header"> {{ sample_content }} </pf-modal> </story-canvas> <story-canvas title="With description"> <pf-button @click="open2 = !open2">Toggle Modal</pf-button> <pf-modal v-model:open="open2" title="Simple modal header"> {{ sample_content }} <template #description> A description is used when you want to provide more info about the modal than the title is able to describe. The content in the description is static and will not scroll with the rest of the modal body. </template> <template #footer> <pf-button variant="primary" @click="open2 = !open2"> Confirm </pf-button> <pf-button variant="link" @click="open2 = !open2"> Cancel </pf-button> </template> </pf-modal> </story-canvas> <story-canvas title="With help"> <pf-button @click="open3 = !open3">Toggle Modal</pf-button> <pf-modal v-model:open="open3" title="Simple modal header"> {{ sample_content }} <template #help> <pf-tooltip> <pf-button variant="plain"> <help-icon /> </pf-button> <template #content> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam id feugiat augue, nec fringilla turpis. </template> </pf-tooltip> </template> </pf-modal> </story-canvas> </doc-page> </template> <script lang="ts" setup> import HelpIcon from "@vue-patternfly/icons/help-icon"; import { ref } from "vue"; const open1 = ref(false); const open2 = ref(false); const open3 = ref(false); const sample_content = ref(`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`); </script>
33,623
https://github.com/luwenchang/dataflux-func/blob/master/client/src/components/Management/SysStats.vue
Github Open Source
Open Source
Apache-2.0
2,022
dataflux-func
luwenchang
Vue
Code
1,206
4,453
<template> <transition name="fade"> <el-container direction="vertical" v-if="$store.state.isLoaded"> <!-- 标题区 --> <el-header height="60px"> <h1> 系统指标 </h1> </el-header> <el-main> <el-divider content-position="left"><h1>Server</h1></el-divider> <div id="serverCPUPercent" class="chart"></div> <div id="serverMemoryRSS" class="chart"></div> <div id="serverMemoryHeapTotal" class="chart"></div> <div id="serverMemoryHeapUsed" class="chart"></div> <div id="serverMemoryHeapExternal" class="chart"></div> <el-divider content-position="left"><h1>Worker</h1></el-divider> <div id="workerCPUPercent" class="chart"></div> <div id="workerMemoryPSS" class="chart"></div> <div id="workerQueueLength" class="chart"></div> <el-divider content-position="left"><h1>Database/Cache</h1></el-divider> <div id="dbDiskUsed" class="chart"></div> <div id="cacheDBMemoryUsed" class="chart"></div> <div id="cacheDBKeyUsed" class="chart"></div> <div id="cacheDBKeyCountByPrefix" class="chart"></div> <el-divider content-position="left"><h1>API</h1></el-divider> <div id="matchedRouteCount" class="chart"></div> </el-main> </el-container> </transition> </template> <script> import echarts from 'echarts' export default { name: 'SysStats', components: { }, watch: { $route: { immediate: true, async handler(to, from) { await this.loadData(); } }, '$store.getters.uiColorSchema': function(to, from) { let textStyle = this.T.getEchartTextStyle(); let splitLineStyle = this.T.getEchartSplitLineStyle(); for (let chartId in this.charts) { let chart = this.charts[chartId]; chart.setOption({ textStyle: textStyle, title : { textStyle: textStyle }, xAxis : { splitLine: { lineStyle: splitLineStyle } }, yAxis : { splitLine: { lineStyle: splitLineStyle } }, }); } }, }, methods: { async loadData() { this.$store.commit('updateLoadStatus', true); }, genSeries(tsDataMap, opt) { let series = []; for (let name in tsDataMap) { let s = { name : name, data : tsDataMap[name], showSymbol: false, }; if (!this.T.isNothing(opt.seriesOptions)) { Object.assign(s, opt.seriesOptions); } switch(s.type) { case 'bar': s.label = s.label || {}; s.label.normal = s.label.normal || { show : true, position: 'right', }; break; case 'pie': s.label = s.label || {}; s.label.formatter = s.label.formatter || '{b}: {c} ({d}%)'; break; } s.data.forEach(dp => { switch(opt.dataConvert) { case 'xyTranspose': dp.reverse(); break; } }); series.push(s); } series.sort((a, b) => { let a_dp = a.data.slice(-1)[0]; let b_dp = b.data.slice(-1)[0]; if (opt.dataConvert === 'xyTranspose') { return b_dp[0] - a_dp[0]; } else { return b_dp[1] - a_dp[1]; } }); return series; }, resizeBarChart(chart) { let chartSeries = chart.getOption().series; let dataLength = 0; chartSeries.forEach(s => { dataLength = Math.max(dataLength, s.data.length); }); let height = dataLength * 25 * chartSeries.length + (chartSeries.length - 1) * 5 + 60 + 80 chart.getDom().style.height = `${height}px`; chart.resize(); }, async updateChart() { let apiRes = await this.T.callAPI_get('/api/v1/monitor/sys-stats/do/get'); if (!apiRes.ok) return; let hostname = apiRes.data.hostname; let sysStats = apiRes.data.sysStats; for (let metric in sysStats) { let chart = this.charts[metric]; if (!chart) continue; let tsDataMap = sysStats[metric]; if (this.T.isNothing(tsDataMap)) continue; if (Array.isArray(tsDataMap)) { tsDataMap = { '': tsDataMap }; } // Prepare Series let series = null; switch(metric) { case 'matchedRouteCount': series = this.genSeries(tsDataMap, { dataConvert : 'xyTranspose', seriesOptions: { type: 'bar' }, }); break; case 'workerQueueLength': series = this.genSeries(tsDataMap, { seriesOptions: { type: 'line' }, }); series.forEach(s => { s.name = '#' + s.name; }); break; default: series = this.genSeries(tsDataMap, { seriesOptions: { type: 'line' }, }); break; } // Set Series chart.setOption({ series: series }); // Resize Chart switch(metric) { case 'matchedRouteCount': this.resizeBarChart(chart); break; } }; }, createTitleOpt(title) { return { text : title, left : 100, textStyle: this.T.getEchartTextStyle(), }; }, createCommonTooltipOpt() { return { trigger: 'axis', axisPointer: { animation: false } }; }, createTSTooltipOpt(opt) { opt = opt || {}; return { trigger: 'axis', axisPointer: { animation: false }, formatter: params => { let sortedParams = this.T.jsonCopy(params); sortedParams.sort((a, b) => { let valueDiff = b.data[1] - a.data[1]; if (valueDiff > 0) { return 1; } else if (valueDiff < 0) { return -1; } else { if (b.seriesName < a.seriesName) { return 1; } else { return -1; } } }); let tooltipHTML = this.T.getDateTimeString(params[0].data[0]); tooltipHTML += '<br>'; tooltipHTML += '<table>'; for (let i = 0; i < sortedParams.length; i++) { if (i >= 10) { tooltipHTML += '<tr><td colspan="100%" align="right">只展示Top10</td></tr>'; break; } let p = sortedParams[i]; let unit = opt.unit || ''; if (Array.isArray(unit)) { unit = p.data[1] > 1 ? unit[0] : unit[1]; } tooltipHTML += '<tr>'; tooltipHTML += '<td style="font-size: 12px">' + p.marker + '</td>'; if (p.seriesName) { tooltipHTML += '<td style="font-size: 12px">' + p.seriesName + '</td>'; tooltipHTML += '<td style="font-size: 12px">:</td>'; } tooltipHTML += '<td style="font-size: 12px" align="right">' + p.data[1] + '</td>'; tooltipHTML += '<td style="font-size: 12px">' + unit + '</td>'; tooltipHTML += '</tr>'; } tooltipHTML += '</table>'; return tooltipHTML; } }; }, createCommonGridOpt() { return { left : 80, right : 50, containLabel: true, }; }, createCountGridOpt() { return { left: 50, right: '35%', containLabel: true }; }, createTimeXAxisOpt() { return { type : 'time', offset: 10, splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, axisLabel: { formatter: (value, index) => { return this.T.getDateTimeString(value, 'YYYY-MM-DD HH:mm'); } } }; }, createCountXAxisOpt() { return { type: 'value', splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, max: (value) => Math.ceil(value.max * 1.1), }; }, createPercentYAxisOpt() { return { type : 'value', offset : 10, max : 100, min : 0, boundaryGap: ['20%', '20%'], splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, axisLabel: { formatter: (value, index) => { return value + '%'; } } }; }, createVolumnYAxisOpt(opt) { opt = opt || {}; return { type : 'value', offset: 10, min : 0, max : opt.max, splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, axisLabel: { formatter: (value, index) => { return value + ' MB'; } } }; }, createCateYAxisOpt() { return { type : 'category', position : 'right', offset : 50, inverse : true, axisLabel: { interval: 0 }, splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, }; }, createCountYAxisOpt() { return { type : 'value', offset : 10, min : 0, minInterval: 1, splitLine: { lineStyle: this.T.getEchartSplitLineStyle(), }, }; }, }, computed: { CHART_CONFIGS() { let textStyle = this.T.getEchartTextStyle(); return { serverCPUPercent: { textStyle: textStyle, title : this.createTitleOpt('Server CPU 使用率'), tooltip: this.createTSTooltipOpt({ unit: '%'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createPercentYAxisOpt(), }, serverMemoryRSS: { textStyle: textStyle, title : this.createTitleOpt('Server 内存RSS'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, serverMemoryHeapTotal: { textStyle: textStyle, title : this.createTitleOpt('Server 内存Heap总量'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, serverMemoryHeapUsed: { textStyle: textStyle, title : this.createTitleOpt('Server 内存Heap用量'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, serverMemoryHeapExternal: { textStyle: textStyle, title : this.createTitleOpt('Server 内存Heap外部对象用量'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, workerCPUPercent: { textStyle: textStyle, title : this.createTitleOpt('Worker CPU 使用率'), tooltip: this.createTSTooltipOpt({ unit: '%'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createPercentYAxisOpt(), }, workerMemoryPSS: { textStyle: textStyle, title : this.createTitleOpt('Worker 内存PSS'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, workerQueueLength: { textStyle: textStyle, title : this.createTitleOpt('工作队列长度'), tooltip: this.createTSTooltipOpt({ unit: ['Tasks', 'Task']}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createCountYAxisOpt(), }, dbDiskUsed: { textStyle: textStyle, title : this.createTitleOpt('数据库磁盘用量'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, cacheDBMemoryUsed: { textStyle: textStyle, title : this.createTitleOpt('缓存数据库内存用量'), tooltip: this.createTSTooltipOpt({ unit: 'MB'}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createVolumnYAxisOpt(), }, cacheDBKeyUsed: { textStyle: textStyle, title : this.createTitleOpt('缓存数据库Key数量'), tooltip: this.createTSTooltipOpt({ unit: ['Keys', 'Key']}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createCountYAxisOpt(), }, cacheDBKeyCountByPrefix: { textStyle: textStyle, title : this.createTitleOpt('缓存数据库Key数量(按前缀区分)'), tooltip: this.createTSTooltipOpt({ unit: ['Keys', 'Key']}), grid : this.createCommonGridOpt(), xAxis : this.createTimeXAxisOpt(), yAxis : this.createCountYAxisOpt(), }, matchedRouteCount: { textStyle: textStyle, title : this.createTitleOpt('接口访问次数(按路由区分)'), tooltip: this.createCommonTooltipOpt(), grid : this.createCountGridOpt(), xAxis : this.createCountXAxisOpt(), yAxis : this.createCateYAxisOpt(), }, } }, }, mounted() { setImmediate(() => { // 初始化Echarts for (let chartId in this.CHART_CONFIGS) { this.charts[chartId] = echarts.init(document.getElementById(chartId)); this.charts[chartId].setOption(this.CHART_CONFIGS[chartId]); } // 更新图表数据 this.updateChart(); setInterval(() => { this.updateChart(); }, 30 * 1000); }); }, props: { }, data() { return { charts: {}, } }, } </script> <style scoped> .chart { width : 1300px; height: 350px; } </style>
39,782
https://github.com/uwase-diane/password_locker/blob/master/passwordLocker_test.py
Github Open Source
Open Source
Unlicense
null
password_locker
uwase-diane
Python
Code
330
1,199
#!/usr/bin/env python3.6 import pyperclip import unittest from passwordLocker import User, Credential class TestClassUser(unittest.TestCase): """ A Test class that defines test cases for the User class. """ def setUp(self): self.new_user = User("uwase-diane","@August2016") """ Method that runs before each individual test methods run. """ def test_init(self): """ test case to chek if the object has been initialized correctly """ self.assertEqual(self.new_user.userName,'uwase-diane') self.assertEqual(self.new_user.password,'@August2016') def test_save_user(self): """ test case to test if a new user instance has been saved into the User list """ self.new_user.save_user() self.assertEqual(len(User.user_list),1) class TestClassCredentials(unittest.TestCase): """ A test class that defines test cases for credentials class """ def setUp(self): """ Method that runs before each individual credentials test methods run. """ self.new_credential = Credential('Instagram','uwas-dian','@August2016') def test_init(self): """ Test case to check if a new Credentials instance has been initialized correctly """ self.assertEqual(self.new_credential.accountName,'Instagram') self.assertEqual(self.new_credential.username,'uwas-dian') self.assertEqual(self.new_credential.password,'@August2016') def test_save_credentials(self): """ test case to test if the crential object is saved into the credentials list. """ self.new_credential.save_credentials() self.assertEqual(len(Credential.credential_list),1) def tearDown(self): ''' method that does clean up after each test case has run. ''' Credential.credential_list = [] def test_save_many_accounts(self): ''' test to check if we can save multiple credentials objects to our credentials list ''' self.new_credential.save_credentials() test_credential = Credential("Yahoo","RahelBrhane","Rahel45xs") test_credential.save_credentials() self.assertEqual(len(Credential.credential_list),2) def test_detele_credential(self): """ test method to test if we can remove an account credentials from our credentials_list """ self.new_credential.save_credentials() test_credential = Credential("Yahoo","RaheBrhane","Rahel45xs") test_credential.save_credentials() self.new_credential.delete_credentials() self.assertEqual(len(Credential.credential_list),1) def test_find_credential(self): """ test to check if we can find a credential entry by username and display the details of the credential """ self.new_credential.save_credentials() test_credential = Credential("Yahoo","RaheBrhane","Rahel45xs") test_credential.save_credentials() username_credential = Credential.find_credential("RaheBrhane") self.assertEqual(username_credential.username,test_credential.username) def test_copy_password(self): ''' Test to confirm that we are copying the email address from a found contact ''' self.new_credential.save_credentials() Credential.copy_password("uwas-dian") self.assertEqual(self.new_credential.password, pyperclip.paste()) def test_credential_exist(self): """ test to check if we can return a true or false based on whether we find or can't find the credential. """ self.new_credential.save_credentials() username_credential = Credential("Yahoo","RaheBrhane","Rahel45xs") username_credential.save_credentials() found_user = Credential.credential_exist("RaheBrhane") self.assertTrue(found_user) def test_display_credential(self): ''' method that displays all the credentials that has been saved by the user ''' self.assertEqual(Credential.display_credentials(),Credential.credential_list) if __name__ == '__main__': unittest.main()
3,939
https://github.com/linked/django-mediagenerator/blob/master/mediagenerator/filters/clevercss.py
Github Open Source
Open Source
BSD-3-Clause
2,018
django-mediagenerator
linked
Python
Code
69
252
from mediagenerator.generators.bundles.base import Filter from clevercss import convert class CleverCSS(Filter): def __init__(self, **kwargs): super(CleverCSS, self).__init__(**kwargs) assert self.filetype == 'css', ( 'CleverCSS only supports compilation to css. ' 'The parent filter expects "%s".' % self.filetype) self.input_filetype = 'clevercss' def should_use_default_filter(self, ext): if ext == 'ccss': return False return super(CleverCSS, self).should_use_default_filter(ext) def get_output(self, variation): for input in self.get_input(variation): yield convert(input) def get_dev_output(self, name, variation): content = super(CleverCSS, self).get_dev_output(name, variation) return convert(content)
28,468
https://github.com/ashrhmn/FMS-Laravel/blob/master/app/Http/Controllers/AuthController.php
Github Open Source
Open Source
MIT
null
FMS-Laravel
ashrhmn
PHP
Code
262
1,043
<?php namespace App\Http\Controllers; use App\Models\City; use App\Models\Token; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; class AuthController extends Controller { public function signin(Request $req) { $token = $req->session()->get('token'); $userToken = Token::where('value', $token)->first(); if ($userToken) { switch ($userToken->user->role) { case 'User': //return redirect()->route('index'); return redirect()->route('user.index'); break; case 'Manager': return redirect()->route('manager.home'); break; case 'FlightManager': return redirect()->route('fmgr.dashboard'); break; case 'Admin': return redirect()->route('admin.index'); break; default: return redirect()->route('auth.signin'); break; } } $req->session()->put('token', null); return view('auth.signin'); } public function signup(Request $req) { $token = $req->session()->get('token'); $userToken = Token::where('value', $token)->first(); if ($userToken) { return redirect()->route('auth.signin'); } $req->session()->put('token', null); $cities = City::all(); return view('auth.signup')->with('cities', $cities); } public function signupPost(Request $req) { $req->validate([ 'username' => 'required|unique:users,username|min:3', 'name' => 'required|min:5', 'password' => 'required|min:6', 'password2' => 'required|same:password', 'email' => 'required|email', 'dob' => 'required' ], [ 'password2.required' => '', 'password2.same' => 'Both passwords must match', ]); $existingUser = User::where('username', $req->username)->first(); if ($existingUser) { throw ValidationException::withMessages(['username' => 'User already exist with the username']); } $user = new User(); $user->username = $req->username; $user->name = $req->name; $user->email = $req->email; $user->address = $req->address; $user->phone = $req->phone; $user->date_of_birth = $req->dob; $user->password = md5($req->password); $user->save(); // $tokenGen = bin2hex(random_bytes(37)); // $token = new Token(); // $token->value = $tokenGen; // $token->user_id = $user->id; // $token->save(); // $req->session()->put('token', $tokenGen); return redirect()->route('auth.signin'); } public function logoutPost(Request $req) { $token = $req->session()->get('token'); Token::where('value', $token)->delete(); $req->session()->put('user', null); return redirect()->route('auth.signin'); } public function signinPost(Request $req) { $user = User::where('username', $req->username)->where('password', md5($req->password))->first(); if ($user) { $tokenGen = bin2hex(random_bytes(37)); $token = new Token(); $token->value = $tokenGen; $token->user_id = $user->id; $token->save(); $req->session()->put('token', $tokenGen); } else { $req->session()->put('user', null); throw ValidationException::withMessages(['password' => 'Username or password is incorrect']); } return redirect()->route('auth.signin'); } }
30,667
https://github.com/remore/gemstat/blob/master/lib/gemstat/cache/gemfiles/g/git_remote_branch:0.3.8/Gemfile
Github Open Source
Open Source
MIT
2,015
gemstat
remore
Ruby
Code
14
46
gem 'rake' gem 'rdoc' gem 'test-unit' gem 'shoulda' gem 'mocha' gem 'pry' gem 'pry-nav'
29,614
https://github.com/AlexanderWert/kibana/blob/master/x-pack/plugins/infra/server/services/log_entries/types.ts
Github Open Source
Open Source
Apache-2.0
null
kibana
AlexanderWert
TypeScript
Code
71
162
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { PluginSetup as DataPluginSetup, PluginStart as DataPluginStart, } from '../../../../../../src/plugins/data/server'; import { InfraSources } from '../../lib/sources'; export interface LogEntriesServiceSetupDeps { data: DataPluginSetup; sources: InfraSources; } export interface LogEntriesServiceStartDeps { data: DataPluginStart; }
37,313
https://github.com/yuyasugano/defi-test/blob/master/defipulse_api.py
Github Open Source
Open Source
MIT
2,021
defi-test
yuyasugano
Python
Code
170
622
#!/usr/bin/python import json import boto3 import decimal import pprint import datetime import requests TABLE_NAME = 'Tokens' headers = {'Content-Type': 'application/json'} api_url_base = "https://public.defipulse.com/api/GetProjects" api_url = '{}'.format(api_url_base) dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-1') table = dynamodb.Table(TABLE_NAME) # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if abs(o) % 1 > 0: return float(o) else: return int(o) return super(DecicmalEncoder, self).default(o) # Helper function to convert dict to json format with decimal parse def float_to_decimal(value): return json.loads(json.dumps(value), parse_float=decimal.Decimal) def defipulse(): try: response = requests.get(api_url, headers=headers) except Exception as e: print("An error occurred:", e.args) if response.status_code == 200: res = json.loads(response.content.decode('utf-8')) return res else: return None def main(): response = defipulse() # pprint.pprint(response, width=40) if response is None: print("Calling API did not succeed") quit() for res in response: dt = datetime.datetime.fromtimestamp(res['timestamp']) try: response = table.put_item( Item={ 'name': res['name'], 'datetime': dt.strftime("%Y/%m/%d %H:%M:%S"), 'tvl': float_to_decimal(res['value']['tvl']), 'total': float_to_decimal(res['value']['total']), 'balance': float_to_decimal(res['value']['balance']) } ) print("PutItem succeeded:") print(json.dumps(res, indent=4, cls=DecimalEncoder)) except Exception as e: print("PutItem failed:", e.args) continue if __name__ == '__main__': main()
30,232
https://github.com/xcfcode/DataLab/blob/master/src/datalabs/operations/featurize/summarization.py
Github Open Source
Open Source
Apache-2.0
null
DataLab
xcfcode
Python
Code
864
3,617
from typing import Dict, List, Any, Optional from .featurizing import Featurizing, featurizing # from ..operation import DatasetOperation, dataset_operation from typing import Callable, Mapping from .plugins.summarization.sum_attribute import * from .plugins.summarization.extractive_methods import _ext_oracle from .plugins.summarization.extractive_methods import _lead_k from .plugins.summarization.extractive_methods import _compute_rouge # store all featurizing class import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from operation import DatasetOperation, dataset_operation from .general import get_features_sample_level as get_features_sample_level_general class SummarizationFeaturizing(Featurizing, DatasetOperation): def __init__(self, name:str = None, func:Callable[...,Any] = None, resources: Optional[Mapping[str, Any]] = None, contributor: str = None, processed_fields: List = ["text"], generated_field: str = None, task = "summarization", description = None, ): super().__init__(name = name, func = func, resources = resources, contributor = contributor, description= description) self._type = 'SummarizationFeaturizing' self.processed_fields = processed_fields self.generated_field = generated_field self._data_type = "Dataset" self.task = task class summarization_featurizing(featurizing, dataset_operation): def __init__(self, name: Optional[str] = None, resources: Optional[Mapping[str, Any]] = None, contributor: str = None, processed_fields:List = None, generated_field:str = None, task = "summarization", description = None, ): super().__init__(name = name, resources = resources, contributor = contributor, task = task, description=description) self.processed_fields = processed_fields self.generated_field = generated_field def __call__(self, *param_arg): if callable(self.name): tf_class = SummarizationFeaturizing(name = self.name.__name__, func=self.name) return tf_class(*param_arg) else: f = param_arg[0] name = self.name or f.__name__ tf_cls = SummarizationFeaturizing(name=name, func = f, resources = self.resources, contributor = self.contributor, processed_fields = self.processed_fields, generated_field = self.generated_field, task = self.task, description=self.description) return tf_cls @summarization_featurizing(name = "get_density", contributor="datalab", task = "summarization", description="This function measures to what extent a summary covers the content in the source text.") def get_density(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"density":attribute_info["attr_density"]} @summarization_featurizing(name = "get_coverage", contributor="datalab", task = "summarization", description="This function measures to what extent a summary covers the content in the source text.") def get_coverage(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"coverage":attribute_info["attr_coverage"]} @summarization_featurizing(name = "get_compression", contributor="datalab", task = "summarization", description="This function measures the compression ratio from the source text to the generated summary.") def get_compression(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"compression":attribute_info["attr_compression"]} @summarization_featurizing(name = "get_repetition", contributor="datalab", task = "summarization", description="This function measures the rate of repeated segments in summaries. The segments are instantiated as trigrams.") def get_repetition(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"repetition":attribute_info["attr_repetition"]} @summarization_featurizing(name = "get_novelty", contributor="datalab", task = "summarization", description="This measures the proportion of segments in the summaries that haven’t appeared in source documents. The segments are instantiated as bigrams.") def get_novelty(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"novelty":attribute_info["attr_novelty"]} @summarization_featurizing(name = "get_copy_len", contributor="datalab", task = "summarization", description="Measures the average length of segments in summary copied from source document.") def get_copy_len(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return {"copy_len":attribute_info["attr_copy_len"]} @summarization_featurizing(name = "get_all_features", contributor="datalab", task = "summarization", description="Calculate all features for summarization datasets (density, coverage, compression, repetition, novelty, copy lenght)") def get_all_features(sample:dict): summary_attribute = SUMAttribute() attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['summary']) return { "density":attribute_info["attr_density"], "coverage":attribute_info["attr_coverage"], "compression": attribute_info["attr_compression"], "repetition": attribute_info["attr_repetition"], "novelty": attribute_info["attr_novelty"], "copy_len": attribute_info["attr_copy_len"], } @summarization_featurizing(name = "get_oracle_summary", contributor="datalab", task = "summarization", description="This function extract the oracle summaries for text summarization") def get_oracle_summary(sample:dict) -> Dict: """ Input: SummarizationDataset: dict Output: return {"source":src, "reference":ref, "oracle_summary":oracle, "oracle_labels":labels, "oracle_score":max_score} """ document = sent_tokenize(sample["text"]) # List summary = sample['summary'] oracle_info = _ext_oracle(document, summary, _compute_rouge, max_sent=3) return oracle_info # # # @summarization_featurizing(name = "get_lead_k_summary", contributor="datalab", task = "summarization", description="This function extract the lead k summary for text summarization datasets") def get_lead_k_summary(sample:dict) -> Dict: """ Input: SummarizationDataset: dict Output: return {"source":src, "reference":ref, "lead_k_summary":src, "lead_k_score":score} """ document = sent_tokenize(sample["text"]) # List summary = sample['summary'] lead_k_info = _lead_k(document, summary, _compute_rouge, k = 3) return lead_k_info def get_schema_of_sample_level_features(): return { "text_length":1, "text_lexical_richness":0.2, "text_basic_words":0.2, "text_gender_bias_word_male":1, "text_gender_bias_word_female":2, "text_gender_bias_single_name_male":1, "text_gender_bias_single_name_female":1, "summary_length": 1, "summary_lexical_richness": 0.2, "summary_basic_words": 0.2, "summary_gender_bias_word_male": 1, "summary_gender_bias_word_female": 2, "summary_gender_bias_single_name_male": 1, "summary_gender_bias_single_name_female": 1, "density": 0.1, "coverage": 0.1, "compression": 0.1, "repetition": 0.1, "novelty": 0.1, "copy_len": 0.1, } @summarization_featurizing(name = "get_features_sample_level", contributor= "datalab", processed_fields= "text", task="summarization", description="This function is used to calculate the text length") def get_features_sample_level(sample:dict): text = sample["text"] summary = sample["summary"] res_info_general = get_features_sample_level_general.func(text) res_info_general_new = {} for k,v in res_info_general.items(): res_info_general_new["text" + "_" + k] =v res_info_general = get_features_sample_level_general.func(summary) for k,v in res_info_general.items(): res_info_general_new["summary" + "_" + k] =v # get task-dependent features summary_features = get_all_features.func(sample) # update the res_info_general_new res_info_general_new.update(summary_features) # res_info_general_new.update({"answer_length":answer_length, # "option1_length":option1_length, # "option2_length":option2_length, # # "option_index":int(option_index), # }) return res_info_general_new def get_schema_of_sample_level_features_asap(): return { "text_length":1, # "text_lexical_richness":0.2, # "text_basic_words":0.2, # "text_gender_bias_word_male":1, # "text_gender_bias_word_female":2, # "text_gender_bias_single_name_male":1, # "text_gender_bias_single_name_female":1, "summary_length": 1, "summary_lexical_richness": 0.2, "summary_basic_words": 0.2, "summary_gender_bias_word_male": 1, "summary_gender_bias_word_female": 2, "summary_gender_bias_single_name_male": 1, "summary_gender_bias_single_name_female": 1, # "density": 0.1, # "coverage": 0.1, # "compression": 0.1, # "repetition": 0.1, # "novelty": 0.1, # "copy_len": 0.1, "n_aspects":0.0, } @summarization_featurizing(name = "get_features_sample_level_asap", contributor= "datalab", processed_fields= "text", task="summarization", description="This function is used to calculate the text length") def get_features_sample_level_asap(sample:dict): text = sample["text"] summary = sample["review"] aspects = sample["aspects"] # res_info_general = get_features_sample_level_general.func(text) res_info_general_new = {} # for k,v in res_info_general.items(): # res_info_general_new["text" + "_" + k] =v res_info_general_new["text" + "_" + "length"] = len(text.split(" ")) res_info_general = get_features_sample_level_general.func(summary) for k,v in res_info_general.items(): res_info_general_new["summary" + "_" + k] =v # get task-dependent features # summary_attribute = SUMAttribute() # attribute_info = summary_attribute.cal_attributes_each(sample['text'], sample['review']) # summary_features = { # "density":attribute_info["attr_density"], # "coverage":attribute_info["attr_coverage"], # "compression": attribute_info["attr_compression"], # "repetition": attribute_info["attr_repetition"], # "novelty": attribute_info["attr_novelty"], # "copy_len": attribute_info["attr_copy_len"], # } # res_info_general_new.update(summary_features) # print(aspects) # exit() n_aspects = len(aspects) res_info_general_new.update({"n_aspects":n_aspects}) # update the res_info_general_new # res_info_general_new.update({"answer_length":answer_length, # "option1_length":option1_length, # "option2_length":option2_length, # # "option_index":int(option_index), # }) return res_info_general_new
36,841
https://github.com/guibrancopc/vue-dynamic-height/blob/master/src/main.js
Github Open Source
Open Source
MIT
2,021
vue-dynamic-height
guibrancopc
JavaScript
Code
90
232
import dynamicHeight from './dynamic-height/dynamicHeight'; // Declare install function executed by Vue.use() export function installVueDynamicHeight(Vue) { if (installVueDynamicHeight.installed) return; installVueDynamicHeight.installed = true; Vue.directive('DynamicHeight', dynamicHeight); } // Create module definition for Vue.use() const plugin = { installVueDynamicHeight, }; // Auto-install when vue is found (eg. in browser via <script> tag) let GlobalVue = null; if (typeof window !== 'undefined') { GlobalVue = window.Vue; } else if (typeof global !== 'undefined') { GlobalVue = global.Vue; } if (GlobalVue) { GlobalVue.use(plugin); } // To allow use as module (npm/webpack/etc.) export component export default dynamicHeight;
5,579
https://github.com/iliyaST/TelerikAcademy/blob/master/OOP/7-Exams/11-July-2016-Evening/01.Dealership/Dealership-Skeleton/Dealership/Models/User.cs
Github Open Source
Open Source
MIT
2,017
TelerikAcademy
iliyaST
C#
Code
482
1,662
using Dealership.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Dealership.Common.Enums; using Dealership.Common; using Dealership.Engine; namespace Dealership.Models { public class User : IUser { private string firstName; private string lastName; private string username; private string password; private const string UsernamePattern = "^[A-Za-z0-9]+$"; private const string PasswordPattern = "^[A-Za-z0-9@*_-]+$"; private const int MinNameLength = 2; private const int MaxNameLength = 20; private const int MinPasswordLength = 5; private const int MaxPasswordLength = 30; private const string InvalidPassword = "Password contains invalid symbols!"; private const string StringMustBeBetweenMinAndMaxA = "{0} must be between {1} and {2} characters long!"; private IList<IVehicle> vehicles; private const int VehicleCapacityForNonVips = 5; public User(string username, string firstName, string lastName, string password, string role) { this.Username = username; this.FirstName = firstName; this.LastName = lastName; this.Password = password; this.Role = (Role)Enum.Parse(typeof(Role), role); this.vehicles = new List<IVehicle>(); } public string FirstName { get { return this.firstName; } set { Validator.ValidateIntRange(value.Length, MinNameLength, MaxNameLength, String.Format(Constants.StringMustBeBetweenMinAndMax, "Firstname" , Constants.MinNameLength, Constants.MaxNameLength)); this.firstName = value; } } public string LastName { get { return this.lastName; } set { Validator.ValidateIntRange(value.Length, MinNameLength, MaxNameLength, String.Format(Constants.StringMustBeBetweenMinAndMax, "Lastname" , Constants.MinNameLength, MaxNameLength)); this.lastName = value; } } public string Password { get { return this.password; } set { Validator.ValidateIntRange(value.Length, MinPasswordLength, MaxPasswordLength , String.Format(StringMustBeBetweenMinAndMaxA, nameof(Password), MinPasswordLength, MaxPasswordLength)); Validator.ValidateSymbols(value, PasswordPattern, InvalidPassword); this.password = value; } } public string Username { get { return this.username; } set { Validator.ValidateIntRange(value.Length, MinNameLength, MaxNameLength, "Username must be between 2 and 20 characters long!"); Validator.ValidateSymbols(value, UsernamePattern, "Username contains invalid symbols!"); this.username = value; } } public Role Role { get; } public IList<IVehicle> Vehicles { get { return this.vehicles; } } public void AddComment(IComment commentToAdd, IVehicle vehicleToAddComment) { vehicleToAddComment.Comments.Add(commentToAdd); } public void AddVehicle(IVehicle vehicle) { if (this.Role == Role.Admin) { throw new ArgumentException(Constants.AdminCannotAddVehicles); } else if (this.Role != Role.VIP) { if (vehicles.Count == 5) { throw new ArgumentException(String.Format(Constants.NotAnVipUserVehiclesAdd , Constants.MaxVehiclesToAdd)); } else { vehicles.Add(vehicle); } } else { vehicles.Add(vehicle); } } public string PrintVehicles() { var sb = new StringBuilder(); var indexer = 0; sb.AppendLine(String.Format("--USER {0}--", this.Username)); var index = vehicles.Count; if (vehicles.Count != 0) { foreach (var vehicle in vehicles) { indexer += 1; index--; string vehicleType = vehicle.Type.ToString(); sb.AppendLine(string.Format("{0}. {1}:", indexer, vehicleType)); sb.Append(vehicle.ToString()); if (index == 0) { if (vehicle.Comments.Count == 0) { sb.Append(" --NO COMMENTS--"); } else { sb.Append(" --COMMENTS--"); } } else { if (vehicle.Comments.Count == 0) { sb.AppendLine(" --NO COMMENTS--"); } else { sb.AppendLine(" --COMMENTS--"); foreach (var comment in vehicle.Comments) { sb.AppendLine(" ----------"); sb.AppendLine(" " + comment.Content); sb.AppendLine(" User: " + comment.Author); sb.AppendLine(" ----------"); } sb.AppendLine(" --COMMENTS--"); } } } } else { sb.Append("--NO VEHICLES--"); } return sb.ToString().TrimEnd(); } public void RemoveComment(IComment commentToRemove, IVehicle vehicleToRemoveComment) { if (this.username != commentToRemove.Author) { throw new ArgumentException(Constants.YouAreNotTheAuthor); } else { vehicleToRemoveComment.Comments.Remove(commentToRemove); } } public void RemoveVehicle(IVehicle vehicle) { vehicles.Remove(vehicle); } public override string ToString() { var sb = new StringBuilder(); sb.Append(String.Format("Username: {0}, FullName: {1} {2}, Role: {3}", this.Username, this.FirstName, this.LastName, this.Role)); return sb.ToString(); } } }
32,448
https://github.com/bd2019us/accumulo-wikisearch/blob/master/query/src/main/java/org/apache/accumulo/examples/wikisearch/iterator/UniqFieldNameValueIterator.java
Github Open Source
Open Source
Apache-2.0
2,021
accumulo-wikisearch
bd2019us
Java
Code
1,186
3,250
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.examples.wikisearch.iterator; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.PartialKey; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.IteratorEnvironment; import org.apache.accumulo.core.iterators.SortedKeyValueIterator; import org.apache.accumulo.core.iterators.WrappingIterator; import org.apache.accumulo.examples.wikisearch.util.FieldIndexKeyParser; import org.apache.hadoop.io.Text; import org.apache.log4j.Level; import org.apache.log4j.Logger; public class UniqFieldNameValueIterator extends WrappingIterator { protected static final Logger log = Logger.getLogger(UniqFieldNameValueIterator.class); // Wrapping iterator only accesses its private source in setSource and getSource // Since this class overrides these methods, it's safest to keep the source declaration here private SortedKeyValueIterator<Key,Value> source; private FieldIndexKeyParser keyParser; private Key topKey = null; private Value topValue = null; private Range overallRange = null; private Range currentSubRange; private Text fieldName = null; private Text fieldValueLowerBound = null; private Text fieldValueUpperBound = null; private static final Collection<ByteSequence> EMPTY_COL_FAMS = new ArrayList<ByteSequence>(); private static final String ONE_BYTE = "\1"; private boolean multiRow = false; private boolean seekInclusive = false; // ------------------------------------------------------------------------- // ------------- Static Methods public static void setLogLevel(Level l) { log.setLevel(l); } // ------------------------------------------------------------------------- // ------------- Constructors public UniqFieldNameValueIterator(Text fName, Text fValLower, Text fValUpper) { this.fieldName = fName; this.fieldValueLowerBound = fValLower; this.fieldValueUpperBound = fValUpper; keyParser = createDefaultKeyParser(); } public UniqFieldNameValueIterator(UniqFieldNameValueIterator other, IteratorEnvironment env) { source = other.getSource().deepCopy(env); // Set a default KeyParser keyParser = createDefaultKeyParser(); } // ------------------------------------------------------------------------- // ------------- Overrides @Override public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env) throws IOException { super.init(source, options, env); source = super.getSource(); } @Override protected void setSource(SortedKeyValueIterator<Key,Value> source) { this.source = source; } @Override protected SortedKeyValueIterator<Key,Value> getSource() { return source; } @Override public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) { return new UniqFieldNameValueIterator(this, env); } @Override public Key getTopKey() { return this.topKey; } @Override public Value getTopValue() { return this.topValue; } @Override public boolean hasTop() { return (topKey != null); } @Override public void next() throws IOException { if (log.isDebugEnabled()) { log.debug("next()"); } if (!source.hasTop()) { topKey = null; topValue = null; return; } Key currentKey = topKey; keyParser.parse(topKey); String fValue = keyParser.getFieldValue(); Text currentRow = currentKey.getRow(); Text currentFam = currentKey.getColumnFamily(); if (overallRange.getEndKey() != null && overallRange.getEndKey().getRow().compareTo(currentRow) < 0) { if (log.isDebugEnabled()) { log.debug("next, overall endRow: " + overallRange.getEndKey().getRow() + " currentRow: " + currentRow); } topKey = null; topValue = null; return; } if (fValue.compareTo(this.fieldValueUpperBound.toString()) > 0) { topKey = null; topValue = null; return; } Key followingKey = new Key(currentKey.getRow(), this.fieldName, new Text(fValue + ONE_BYTE)); if (log.isDebugEnabled()) { log.debug("next, followingKey to seek on: " + followingKey); } Range r = new Range(followingKey, followingKey); source.seek(r, EMPTY_COL_FAMS, false); while (true) { if (!source.hasTop()) { topKey = null; topValue = null; return; } Key k = source.getTopKey(); if (!overallRange.contains(k)) { topKey = null; topValue = null; return; } if (log.isDebugEnabled()) { log.debug("next(), key: " + k + " subrange: " + this.currentSubRange); } // if (this.currentSubRange.contains(k)) { keyParser.parse(k); Text currentVal = new Text(keyParser.getFieldValue()); if (k.getRow().equals(currentRow) && k.getColumnFamily().equals(currentFam) && currentVal.compareTo(fieldValueUpperBound) <= 0) { topKey = k; topValue = source.getTopValue(); return; } else { // need to move to next row. if (this.overallRange.contains(k) && this.multiRow) { // need to find the next sub range // STEPS // 1. check if you moved past your current row on last call to next // 2. figure out next row // 3. build new start key with lowerbound fvalue // 4. seek the source // 5. test the subrange. if (k.getRow().equals(currentRow)) { // get next row currentRow = getNextRow(); if (currentRow == null) { topKey = null; topValue = null; return; } } else { // i'm already in the next row currentRow = source.getTopKey().getRow(); } // build new startKey Key sKey = new Key(currentRow, fieldName, fieldValueLowerBound); Key eKey = new Key(currentRow, fieldName, fieldValueUpperBound); currentSubRange = new Range(sKey, eKey); source.seek(currentSubRange, EMPTY_COL_FAMS, seekInclusive); } else { // not multi-row or outside overall range, we're done topKey = null; topValue = null; return; } } } } @Override public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) throws IOException { if (log.isDebugEnabled()) { log.debug("seek, range: " + range); } this.overallRange = range; this.seekInclusive = inclusive; source.seek(range, EMPTY_COL_FAMS, inclusive); topKey = null; topValue = null; Key sKey; Key eKey; if (range.isInfiniteStartKey()) { sKey = source.getTopKey(); if (sKey == null) { return; } } else { sKey = range.getStartKey(); } if (range.isInfiniteStopKey()) { eKey = null; this.multiRow = true; // assume we will go to the end of the tablet. } else { eKey = range.getEndKey(); if (sKey.getRow().equals(eKey.getRow())) { this.multiRow = false; } else { this.multiRow = true; } } if (log.isDebugEnabled()) { log.debug("seek, multiRow:" + multiRow + " range:" + range); } /* * NOTE: If the seek range spans multiple rows, we are only interested in the fieldName:fieldValue subranges in each row. Keys will exist in the * overallRange that we will want to skip over so we need to create subranges per row so we don't have to examine every key in between. */ Text sRow = sKey.getRow(); Key ssKey = new Key(sRow, this.fieldName, this.fieldValueLowerBound); Key eeKey = new Key(sRow, this.fieldName, this.fieldValueUpperBound); this.currentSubRange = new Range(ssKey, eeKey); if (log.isDebugEnabled()) { log.debug("seek, currentSubRange: " + currentSubRange); } source.seek(this.currentSubRange, columnFamilies, inclusive); // cycle until we find a valid topKey, or we get ejected b/c we hit the // end of the tablet or exceeded the overallRange. while (topKey == null) { if (source.hasTop()) { Key k = source.getTopKey(); if (log.isDebugEnabled()) { log.debug("seek, source.topKey: " + k); } if (currentSubRange.contains(k)) { topKey = k; topValue = source.getTopValue(); if (log.isDebugEnabled()) { log.debug("seek, source has top in valid range"); } } else { // outside of subRange. // if multiRow mode, get the next row and seek to it if (multiRow && overallRange.contains(k)) { Key fKey = sKey.followingKey(PartialKey.ROW); Range fRange = new Range(fKey, eKey); source.seek(fRange, columnFamilies, inclusive); if (source.hasTop()) { Text row = source.getTopKey().getRow(); Key nKey = new Key(row, this.fieldName, this.fieldValueLowerBound); this.currentSubRange = new Range(nKey, eKey); sKey = this.currentSubRange.getStartKey(); Range nextRange = new Range(sKey, eKey); source.seek(nextRange, columnFamilies, inclusive); } else { topKey = null; topValue = null; return; } } else { // not multi row & outside range, we're done. topKey = null; topValue = null; return; } } } else { // source does not have top, we're done topKey = null; topValue = null; return; } } } // ------------------------------------------------------------------------- // ------------- Internal Methods private FieldIndexKeyParser createDefaultKeyParser() { FieldIndexKeyParser parser = new FieldIndexKeyParser(); return parser; } private Text getNextRow() throws IOException { if (log.isDebugEnabled()) { log.debug("getNextRow()"); } Key fakeKey = new Key(source.getTopKey().followingKey(PartialKey.ROW)); Range fakeRange = new Range(fakeKey, fakeKey); source.seek(fakeRange, EMPTY_COL_FAMS, false); if (source.hasTop()) { return source.getTopKey().getRow(); } else { return null; } } }
39,420
https://github.com/l1ahim/test/blob/master/store/datastore/ddl/mysql/files/009_create_table_config.sql
Github Open Source
Open Source
Apache-2.0
2,022
test
l1ahim
SQL
Code
24
86
-- name: create-table-config CREATE TABLE IF NOT EXISTS config ( config_id INTEGER PRIMARY KEY AUTO_INCREMENT ,config_repo_id INTEGER ,config_hash VARCHAR(250) ,config_data MEDIUMBLOB ,UNIQUE(config_hash, config_repo_id) );
35,582
https://github.com/antvis/GWebGPUEngine/blob/master/packages/compiler/src/ast/glsl-ast-node-types.ts
Github Open Source
Open Source
MIT
2,022
GWebGPUEngine
antvis
TypeScript
Code
14
71
import { AST_NODE_TYPES, AST_TOKEN_TYPES, STORAGE_CLASS, } from '@antv/g-webgpu-core'; export { AST_TOKEN_TYPES, AST_NODE_TYPES, STORAGE_CLASS };
48,529
https://github.com/sungyeon/drake/blob/master/source/machine-pc-freebsd/s-stomap.adb
Github Open Source
Open Source
MIT
2,020
drake
sungyeon
Ada
Code
72
287
with System.Address_To_Named_Access_Conversions; with C.dlfcn; with C.sys.link_elf; package body System.Storage_Map is pragma Suppress (All_Checks); use type C.signed_int; package char_ptr_Conv is new Address_To_Named_Access_Conversions (C.char, C.char_ptr); -- implementation function Load_Address return Address is type Link_map_ptr is access all C.sys.link_elf.Link_map with Convention => C; for Link_map_ptr'Storage_Size use 0; Map : aliased Link_map_ptr; begin if C.dlfcn.dlinfo ( C.dlfcn.RTLD_SELF, C.dlfcn.RTLD_DI_LINKMAP, C.void_ptr (Map'Address)) < 0 then return Null_Address; -- ??? end if; return char_ptr_Conv.To_Address (Map.l_addr); end Load_Address; end System.Storage_Map;
29,070
https://github.com/hibernate/hibernate-validator/blob/master/engine/src/test/java/org/hibernate/validator/test/internal/constraintvalidators/bv/SignValidatorForNumberTest.java
Github Open Source
Open Source
LicenseRef-scancode-dco-1.1, Apache-2.0
2,023
hibernate-validator
hibernate
Java
Code
1,186
4,552
/* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.test.internal.constraintvalidators.bv; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.math.BigDecimal; import java.math.BigInteger; import jakarta.validation.ConstraintValidator; import jakarta.validation.constraints.Negative; import jakarta.validation.constraints.NegativeOrZero; import jakarta.validation.constraints.Positive; import jakarta.validation.constraints.PositiveOrZero; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForBigDecimal; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForBigInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForByte; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForDouble; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForFloat; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForLong; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForNumber; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeOrZeroValidatorForShort; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForBigDecimal; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForBigInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForByte; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForDouble; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForFloat; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForLong; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForNumber; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.NegativeValidatorForShort; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForBigDecimal; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForBigInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForByte; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForDouble; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForFloat; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForLong; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForNumber; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveOrZeroValidatorForShort; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForBigDecimal; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForBigInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForByte; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForDouble; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForFloat; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForInteger; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForLong; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForNumber; import org.hibernate.validator.internal.constraintvalidators.bv.number.sign.PositiveValidatorForShort; import org.hibernate.validator.internal.util.annotation.ConstraintAnnotationDescriptor; import org.testng.annotations.Test; /** * @author Marko Bekhta * @author Guillaume Smet */ public class SignValidatorForNumberTest { @Test public void testPositiveValidator() { testPositive( new ConstraintAnnotationDescriptor.Builder<>( Positive.class ).build().getAnnotation() ); } @Test public void testPositiveOrZeroValidator() { testPositiveOrZero( new ConstraintAnnotationDescriptor.Builder<>( PositiveOrZero.class ).build().getAnnotation() ); } @Test public void testNegativeValidator() { testNegative( new ConstraintAnnotationDescriptor.Builder<>( Negative.class ).build().getAnnotation() ); } @Test public void testNegativeOrZeroValidator() { testNegativeOrZero( new ConstraintAnnotationDescriptor.Builder<>( NegativeOrZero.class ).build().getAnnotation() ); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void testNegative(Negative m) { ConstraintValidator validator = new NegativeValidatorForNumber(); validator.initialize( m ); testSignNumber( validator, true, false ); validator = new NegativeValidatorForBigDecimal(); validator.initialize( m ); testSignBigDecimal( validator, true, false ); validator = new NegativeValidatorForBigInteger(); validator.initialize( m ); testSignBigInteger( validator, true, false ); validator = new NegativeValidatorForLong(); validator.initialize( m ); testSignLong( validator, true, false ); validator = new NegativeValidatorForFloat(); validator.initialize( m ); testSignFloat( validator, true, false ); validator = new NegativeValidatorForDouble(); validator.initialize( m ); testSignDouble( validator, true, false ); validator = new NegativeValidatorForShort(); validator.initialize( m ); testSignShort( validator, true, false ); validator = new NegativeValidatorForByte(); validator.initialize( m ); testSignByte( validator, true, false ); validator = new NegativeValidatorForInteger(); validator.initialize( m ); testSignInteger( validator, true, false ); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void testNegativeOrZero(NegativeOrZero m) { ConstraintValidator validator = new NegativeOrZeroValidatorForNumber(); validator.initialize( m ); testSignNumber( validator, false, false ); validator = new NegativeOrZeroValidatorForBigDecimal(); validator.initialize( m ); testSignBigDecimal( validator, false, false ); validator = new NegativeOrZeroValidatorForBigInteger(); validator.initialize( m ); testSignBigInteger( validator, false, false ); validator = new NegativeOrZeroValidatorForLong(); validator.initialize( m ); testSignLong( validator, false, false ); validator = new NegativeOrZeroValidatorForFloat(); validator.initialize( m ); testSignFloat( validator, false, false ); validator = new NegativeOrZeroValidatorForDouble(); validator.initialize( m ); testSignDouble( validator, false, false ); validator = new NegativeOrZeroValidatorForShort(); validator.initialize( m ); testSignShort( validator, false, false ); validator = new NegativeOrZeroValidatorForByte(); validator.initialize( m ); testSignByte( validator, false, false ); validator = new NegativeOrZeroValidatorForInteger(); validator.initialize( m ); testSignInteger( validator, false, false ); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void testPositive(Positive m) { ConstraintValidator validator = new PositiveValidatorForNumber(); validator.initialize( m ); testSignNumber( validator, true, true ); validator = new PositiveValidatorForBigDecimal(); validator.initialize( m ); testSignBigDecimal( validator, true, true ); validator = new PositiveValidatorForBigInteger(); validator.initialize( m ); testSignBigInteger( validator, true, true ); validator = new PositiveValidatorForLong(); validator.initialize( m ); testSignLong( validator, true, true ); validator = new PositiveValidatorForFloat(); validator.initialize( m ); testSignFloat( validator, true, true ); validator = new PositiveValidatorForDouble(); validator.initialize( m ); testSignDouble( validator, true, true ); validator = new PositiveValidatorForShort(); validator.initialize( m ); testSignShort( validator, true, true ); validator = new PositiveValidatorForByte(); validator.initialize( m ); testSignByte( validator, true, true ); validator = new PositiveValidatorForInteger(); validator.initialize( m ); testSignInteger( validator, true, true ); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void testPositiveOrZero(PositiveOrZero m) { ConstraintValidator validator = new PositiveOrZeroValidatorForNumber(); validator.initialize( m ); testSignNumber( validator, false, true ); validator = new PositiveOrZeroValidatorForBigDecimal(); validator.initialize( m ); testSignBigDecimal( validator, false, true ); validator = new PositiveOrZeroValidatorForBigInteger(); validator.initialize( m ); testSignBigInteger( validator, false, true ); validator = new PositiveOrZeroValidatorForLong(); validator.initialize( m ); testSignLong( validator, false, true ); validator = new PositiveOrZeroValidatorForFloat(); validator.initialize( m ); testSignFloat( validator, false, true ); validator = new PositiveOrZeroValidatorForDouble(); validator.initialize( m ); testSignDouble( validator, false, true ); validator = new PositiveOrZeroValidatorForShort(); validator.initialize( m ); testSignShort( validator, false, true ); validator = new PositiveOrZeroValidatorForByte(); validator.initialize( m ); testSignByte( validator, false, true ); validator = new PositiveOrZeroValidatorForInteger(); validator.initialize( m ); testSignInteger( validator, false, true ); } private void testSignShort(ConstraintValidator<?, Number> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( (short) 0, null ), !strict ); assertEquals( validator.isValid( (short) 1, null ), positive ); assertEquals( validator.isValid( (short) -1, null ), !positive ); assertEquals( validator.isValid( (short) 10.0, null ), positive ); assertEquals( validator.isValid( (short) -10.0, null ), !positive ); } private void testSignByte(ConstraintValidator<?, Number> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( (byte) 0, null ), !strict ); assertEquals( validator.isValid( (byte) 1, null ), positive ); assertEquals( validator.isValid( (byte) -1, null ), !positive ); assertEquals( validator.isValid( (byte) 10.0, null ), positive ); assertEquals( validator.isValid( (byte) -10.0, null ), !positive ); } private void testSignInteger(ConstraintValidator<?, Number> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( 0, null ), !strict ); assertEquals( validator.isValid( 1, null ), positive ); assertEquals( validator.isValid( -1, null ), !positive ); assertEquals( validator.isValid( 10, null ), positive ); assertEquals( validator.isValid( -10, null ), !positive ); } private void testSignNumber(ConstraintValidator<?, Number> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( 0, null ), !strict ); assertEquals( validator.isValid( 1, null ), positive ); assertEquals( validator.isValid( -1, null ), !positive ); assertEquals( validator.isValid( 10.0, null ), positive ); assertEquals( validator.isValid( -10.0, null ), !positive ); } private void testSignBigDecimal(ConstraintValidator<?, BigDecimal> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( BigDecimal.ZERO, null ), !strict ); assertEquals( validator.isValid( BigDecimal.ONE, null ), positive ); assertEquals( validator.isValid( BigDecimal.ONE.negate(), null ), !positive ); assertEquals( validator.isValid( BigDecimal.TEN, null ), positive ); assertEquals( validator.isValid( BigDecimal.TEN.negate(), null ), !positive ); } private void testSignBigInteger(ConstraintValidator<?, BigInteger> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( BigInteger.ZERO, null ), !strict ); assertEquals( validator.isValid( BigInteger.ONE, null ), positive ); assertEquals( validator.isValid( BigInteger.ONE.negate(), null ), !positive ); assertEquals( validator.isValid( BigInteger.TEN, null ), positive ); assertEquals( validator.isValid( BigInteger.TEN.negate(), null ), !positive ); } private void testSignLong(ConstraintValidator<?, Long> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( 0L, null ), !strict ); assertEquals( validator.isValid( 1L, null ), positive ); assertEquals( validator.isValid( -1L, null ), !positive ); assertEquals( validator.isValid( 10L, null ), positive ); assertEquals( validator.isValid( -10L, null ), !positive ); } private void testSignDouble(ConstraintValidator<?, Double> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( 0D, null ), !strict ); assertEquals( validator.isValid( 1D, null ), positive ); assertEquals( validator.isValid( -1D, null ), !positive ); assertEquals( validator.isValid( 10D, null ), positive ); assertEquals( validator.isValid( -10D, null ), !positive ); assertEquals( validator.isValid( Double.POSITIVE_INFINITY, null ), positive ); assertEquals( validator.isValid( Double.NEGATIVE_INFINITY, null ), !positive ); assertFalse( validator.isValid( Double.NaN, null ) ); } private void testSignFloat(ConstraintValidator<?, Float> validator, boolean strict, boolean positive) { assertTrue( validator.isValid( null, null ) ); assertEquals( validator.isValid( 0F, null ), !strict ); assertEquals( validator.isValid( 1F, null ), positive ); assertEquals( validator.isValid( -1F, null ), !positive ); assertEquals( validator.isValid( 10F, null ), positive ); assertEquals( validator.isValid( -10F, null ), !positive ); assertEquals( validator.isValid( Float.POSITIVE_INFINITY, null ), positive ); assertEquals( validator.isValid( Float.NEGATIVE_INFINITY, null ), !positive ); assertFalse( validator.isValid( Float.NaN, null ) ); } }
4,007
https://github.com/ECSLab/ES_IoT_Cloud/blob/master/iot_ssm/src/main/java/com/wust/iot/dto/DeviceDto.java
Github Open Source
Open Source
Apache-2.0
2,022
ES_IoT_Cloud
ECSLab
Java
Code
186
574
package com.wust.iot.dto; import io.swagger.annotations.ApiModelProperty; public class DeviceDto { @ApiModelProperty(value = "项目id") private Integer projectId; @ApiModelProperty(value = "协议id")//TODO 需要添加获取接口 private Integer protocolId; @ApiModelProperty(value = "数据类型id") private Integer dataType; @ApiModelProperty(value = "设备名字") private String name; @ApiModelProperty(value = "设备编号",notes = "仅允许数字及字母") private String number; @ApiModelProperty(value = "设备保密性",notes = "0公开 1私有",hidden = true) private Integer privacy; public DeviceDto() { } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getProtocolId() { return protocolId; } public void setProtocolId(Integer protocolId) { this.protocolId = protocolId; } public Integer getDataType() { return dataType; } public void setDataType(Integer dataType) { this.dataType = dataType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Integer getPrivacy() { return privacy; } public void setPrivacy(Integer privacy) { this.privacy = privacy; } public DeviceDto(Integer projectId, Integer protocolId, Integer dataType, String name, String number, Integer privacy) { this.projectId = projectId; this.protocolId = protocolId; this.dataType = dataType; this.name = name; this.number = number; this.privacy = privacy; } }
46,940
https://github.com/vincent-pradeilles/KeyPathTesting/blob/master/Sources/KeyPathTesting/Assert/AssertionBuilder.swift
Github Open Source
Open Source
MIT
2,021
KeyPathTesting
vincent-pradeilles
Swift
Code
68
179
// // AssertionBuilder.swift // KeyPathTesting // // Created by Vincent on 12/06/2019. // Copyright © 2019 Vincent. All rights reserved. // import Foundation @resultBuilder public struct AssertionBuilder<Type> { public static func buildExpression( _ expression: @escaping RawAssertion<Type>, _ file: StaticString = #file, _ line: UInt = #line) -> Assertion<Type> { Assertion(assertion: expression, file: file, line: line) } public static func buildBlock(_ children: Assertion<Type>...) -> [Assertion<Type>] { children } }
34,934
https://github.com/DanielSantiagoCardenas/TruckFlet/blob/master/app/Models/Iniciar_Sesion.php
Github Open Source
Open Source
MIT
null
TruckFlet
DanielSantiagoCardenas
PHP
Code
43
178
<?php namespace app\Models; use CodeIgniter\Model; class Iniciar_Sesion extends Model { protected $table = 'registro'; protected $primaryKey = 'id_registro'; protected $useAutoIncrement = true; protected $returnType = 'array'; protected $useSoftDeletes = false; protected $allowedFields = ['nombres','apellidos','identificacion','email','telefono','contrasena','licencia_categoria','estado','tipo']; public function getUser($columna,$valor) { return $this->where($columna, $valor)->first(); } }
45,728
https://github.com/callzhang/AFIncrementalStore/blob/master/Examples/CheckIns Example/Classes/CheckInsAPIClient.m
Github Open Source
Open Source
MIT
2,021
AFIncrementalStore
callzhang
Objective-C
Code
439
1,420
// CheckInsAPIClient.m // // Copyright (c) 2012 Mattt Thompson (http://mattt.me) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import "CheckInsAPIClient.h" static NSString * const kAFIncrementalStoreExampleAPIBaseURLString = @"https://api.parse.com/1/"; @implementation CheckInsAPIClient + (CheckInsAPIClient *)sharedClient { static CheckInsAPIClient *_sharedClient = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:kAFIncrementalStoreExampleAPIBaseURLString]]; }); return _sharedClient; } - (id)initWithBaseURL:(NSURL *)url { self = [super initWithBaseURL:url]; if (!self) { return nil; } self.parameterEncoding = AFJSONParameterEncoding; [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; [self setDefaultHeader:@"Accept" value:@"application/json"]; [self setDefaultHeader:@"Content-Type" value:@"application/json"]; [self setDefaultHeader:@"X-Parse-Application-Id" value:@"FWleLi5CkEfziHZTb2RlZ1RFgZVEa7cdsjt4HpLT"]; [self setDefaultHeader:@"X-Parse-REST-API-Key" value:@"2jAwSuO0tmh3cFA3jNaYXV4KSJnKUc9JJpMA9m7y"]; //[self setAuthorizationHeaderWithUsername:@"aISrB65XT4oj46hvQywSx4YnYtf9DZZLEojLsAaX" // password:@"SpEldL5yLzysNZoZAQJkZZS3dwJSolzYzemKuzZ5"]; [self setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { self.operationQueue.suspended = (status == AFNetworkReachabilityStatusNotReachable); }]; return self; } - (NSString *)pathForEntity:(NSEntityDescription *)entity{ NSString *className = entity.name; NSString *path = [NSString stringWithFormat:@"classes/%@", className]; return path; } - (NSString *)pathForObject:(NSManagedObject *)object{ NSString *resourceIdentifier = AFResourceIdentifierFromReferenceObject([(NSIncrementalStore *)object.objectID.persistentStore referenceObjectForObjectID:object.objectID]); NSString *path = [[self pathForEntity:object.entity] stringByAppendingPathComponent:[resourceIdentifier lastPathComponent]]; return path; } #pragma - - (id)representationOrArrayOfRepresentationsOfEntity:(NSEntityDescription *)entity fromResponseObject:(id)responseObject{ if ([responseObject isKindOfClass:[NSArray class]]) { return responseObject; } else if ([responseObject isKindOfClass:[NSDictionary class]]) { if (!responseObject[@"results"]) { return nil; } NSDictionary *responseDict = responseObject[@"results"]; NSMutableArray *arrayOfRepresentation = [[NSMutableArray alloc] init]; for (NSDictionary *dict in responseDict) { arrayOfRepresentation[arrayOfRepresentation.count] = dict; } return arrayOfRepresentation; } return nil; } - (NSDictionary *)attributesForRepresentation:(NSDictionary *)representation ofEntity:(NSEntityDescription *)entity fromResponse:(NSHTTPURLResponse *)response { NSMutableDictionary *mutablePropertyValues = [[super attributesForRepresentation:representation ofEntity:entity fromResponse:response] mutableCopy]; if ([entity.name isEqualToString:@"CheckIn"]) { } return mutablePropertyValues; } - (NSString *)resourceIdentifierForRepresentation:(NSDictionary *)representation ofEntity:(NSEntityDescription *)entity fromResponse:(NSHTTPURLResponse *)response{ static NSArray *_candidateKeys = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _candidateKeys = [[NSArray alloc] initWithObjects:@"objectId", nil]; }); NSString *key = [[representation allKeys] firstObjectCommonWithArray:_candidateKeys]; if (key) { id value = [representation valueForKey:key]; if (value) { return [value description]; } } return nil; } @end
25,460
https://github.com/CraigMacomber/FluidFramework/blob/master/examples/data-objects/primitives/src/main.tsx
Github Open Source
Open Source
MIT
null
FluidFramework
CraigMacomber
TypeScript
Code
257
641
/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ import { DataObject, } from "@fluidframework/aqueduct"; import { IFluidHTMLView } from "@fluidframework/view-interfaces"; import React from "react"; import ReactDOM from "react-dom"; import { SharedMap, IDirectory, IDirectoryValueChanged } from "@fluidframework/map"; import { DdsCollectionComponent } from "./ddsCollection"; export const PrimitivesName = "PrimitivesCollection"; /** * Basic DDS examples using view interfaces and stock component classes. */ export class PrimitivesCollection extends DataObject implements IFluidHTMLView { public get IFluidHTMLView() { return this; } private internalMapDir: IDirectory | undefined; protected get mapDir(): IDirectory { return this.tryGetDds(this.internalMapDir, "mapDir"); } /** * ComponentInitializingFirstTime is called only once, it is executed only by the first client to open the * component and all work will resolve before the view is presented to any user. * * This method is used to perform component setup, which can include setting an initial schema or initial values. */ protected async initializingFirstTime() { this.internalMapDir = this.root.createSubDirectory("map"); } protected async initializingFromExisting() { this.internalMapDir = this.root.getSubDirectory("map"); } /** * Render the primitives. */ public render(div: HTMLElement) { const mapCreate = (name: string) => SharedMap.create(this.runtime, name); const mapListen = (listener: (changed: IDirectoryValueChanged) => void) => { this.root.on("valueChanged", (changed) => { if (changed.path !== this.mapDir.absolutePath) { return; } listener(changed); }); }; const rerender = () => { ReactDOM.render( <div> <DdsCollectionComponent mapDir={this.mapDir} mapCreate={mapCreate} listenValueChanged={mapListen}> </DdsCollectionComponent> </div>, div, ); }; rerender(); } private tryGetDds<T>(dds: T | undefined, id: string): T { if (dds === undefined) { throw Error(`${id} must be initialized before being accessed.`); } return dds; } }
1,928
https://github.com/wylwang/CodeSameples/blob/master/server/contactController.js
Github Open Source
Open Source
MIT
2,021
CodeSameples
wylwang
JavaScript
Code
346
1,211
const axios = require('axios'); const AccessToken = require('./accesstoken')('contact'); module.exports = function(router) { router.get('/user/get', async function (req, res, next) { const query = req.query || {}; const access_token = await AccessToken.getToken(); const { data } = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', { params: { access_token, userid: query.userid } }); res.send(data); }); router.get('/user/delete', async function (req, res, next) { const query = req.query || {}; const access_token = await AccessToken.getToken(); const { data } = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/user/delete', { params: { access_token, userid: query.userid } }); res.send(data); }); router.post('/user/create', async function(req, res) { const {department, name, mobile, email, userid} = req.body || {}; const access_token = await AccessToken.getToken(); const {data} = await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=${access_token}&debug=1`, { department, name, mobile, email, userid }); res.send(data); }); router.get('/department/list', async function (req, res, next) { const query = req.query || {}; if (!query.id) { query.id = 1; } const access_token = await AccessToken.getToken(); let final_data = []; let filter_users = []; let filter_departments = []; const { data:{department:departmentlist} } = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/department/list', { params: { access_token, id: query.id || '' } }); departmentlist.forEach(item => { if (item.parentid == query.id) { filter_departments.push({ id: item.id, name: item.name || '', order: item.order, type: 'department' }); } }); if(query.need_user == 1){ const { data:{userlist} } = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/user/simplelist', { params: { access_token, department_id: query.id || '', fetch_child: 0 } }); filter_users = userlist.map(user => { return { id:user.userid || '', name : user.name || '', leaf : true, type : 'user' }; }); } else{ if (filter_departments.length > 0) { for (let index = 0; index < filter_departments.length; index++) { let element = filter_departments[index]; if (departmentlist.some(item => { return item.parentid == element.id })) { element.leaf = false; } else { element.leaf = true; } } } } final_data = [].concat(filter_users,filter_departments); res.send(final_data); }); router.post('/department/create', async function(req, res) { const {parentid, name} = req.body || {}; const access_token = await AccessToken.getToken(); const {data} = await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=${access_token}`, { parentid, name }); res.send(data); }); router.get('/department/delete', async function(req, res) { const {query:form_params} = req || {}; const access_token = await AccessToken.getToken(); const {data} = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/department/delete`, { params: { id: form_params.id, access_token } }); res.send(data); }); };
16,613
https://github.com/JulesMoorhouse/Ideaspad/blob/master/CodeLibrary/SharewareProjs/CRCStamp/CRCStamp.vb
Github Open Source
Open Source
MIT
2,019
Ideaspad
JulesMoorhouse
Visual Basic
Code
375
1,075
Imports System.IO Module CRCStamp Sub Main() Main(Environment.GetCommandLineArgs()) End Sub Private Sub Main(ByVal args() As String) Dim lstrInputFile As String Dim lstrTestFile As String = "" If args Is Nothing OrElse args.Length > 6 Then Console.WriteLine("CRCSTAMP: Invalid argurments....") Else Start: On Error Resume Next lstrInputFile = args(1) lstrTestFile = args(2) On Error GoTo 0 If lstrTestFile = "" Then lstrTestFile = lstrInputFile Dim lCrc32Value As Integer 'On Error Resume Next 'Dim FileStr As String 'Dim lintFreeFile As Short = FreeFile() Dim llngFileLength As Integer Dim llngRestartCounter As Long Dim lstrCRCOutPut As String If lstrInputFile = "" Then Console.WriteLine("CRCSTAMP: No file specified... Exit...") Exit Sub End If lstrCRCOutPut = lstrInputFile & ".CRC.exe" File.Copy(lstrInputFile, lstrCRCOutPut, True) ''''Dim FullFile As String = GetFirstPartOfFile(lstrCRCOutPut, True) '''Dim FullFile As String = GetFirstPartOfFile(lstrTestFile, True) 'this is looking at the test file which has been pre strong named '''Sleep(2) ''''---- add crc block to file ---- '''lCrc32Value = InitCrc32() '''lCrc32Value = AddCrc32(FullFile, lCrc32Value) '''Dim RealCRC As String '''RealCRC = CStr(Hex$(GetCrc32(lCrc32Value))) Dim FullFile As String = lstrTestFile Dim c As New CRC32() Dim crc As Integer = 0 Dim f As FileStream = New FileStream(FullFile, FileMode.Open, FileAccess.Read, FileShare.Read, 8192) crc = c.GetCrc32(f, True) 'used with full file param f.Close() Dim RealCRC As String = String.Format("{0:X8}", crc) 'Debug.WriteLine(RealCRC) llngFileLength = FileLen(lstrCRCOutPut) Dim lintFreeFile2 As Integer = FreeFile() FileOpen(lintFreeFile2, lstrCRCOutPut, OpenMode.Binary, OpenAccess.Write, OpenShare.LockWrite) FilePut(lintFreeFile2, RealCRC, llngFileLength + 1) 'FilePut(lintFreeFile2, RealCRC, llngFileLength) FileClose() '---- add crc block to file ---- ''---- check to see if written correctly ---- ''GetWritteCRC = 1 = OK 'If GetWrittenCRC(lstrCRCOutPut, lstrTestFile) <> 1 Then ' 'fail ' If llngRestartCounter < 50 Then ' GoTo start ' llngRestartCounter = llngRestartCounter + 1 ' End If 'Else File.Copy(lstrCRCOutPut, lstrInputFile, True) File.Delete(lstrCRCOutPut) If lstrTestFile <> lstrInputFile Then File.Delete(lstrTestFile) End If ' If llngRestartCounter = 0 Then Console.WriteLine("CRCSTAMP: File (" & lstrInputFile & ", CRC=" & RealCRC & ") Stamped OK! ") ' Else ' Console.WriteLine("CRCSTAMP: File (" & lstrInputFile & ", CRC=" & RealCRC & ") OK! Attempts=" & llngRestartCounter) ' End If 'End If '' ---- check to see if written correctly ---- End If End Sub Sub Sleep(ByVal Seconds As Long) Dim Start As DateTime = Date.Now While Not DateDiff(DateInterval.Second, Start, Date.Now) >= Seconds ' do nothing End While End Sub End Module
19,395
https://github.com/MrAdamBoyd/I-Want-Tea/blob/master/I Want Tea/View Controllers/MapViewController.h
Github Open Source
Open Source
MIT
2,015
I-Want-Tea
MrAdamBoyd
C
Code
80
308
// // ViewController.h // I Want Coffee // // Created by Adam on 2015-09-24. // Copyright © 2015 Adam Boyd. All rights reserved. // #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import "EAIntroView.h" #import "IWCDataController.h" #import "IWCMapAnnotation.h" #import "IWCShopDetailViewController.h" #import "IWCNetworkRequestHandler.h" #import "MBProgressHUD.h" #import "IWCAboutPageBuilder.h" #import "CNPPopupController.h" #import "NYSegmentedControl.h" @interface MapViewController : UIViewController <EAIntroDelegate, IWCLocationListenerDelegate, IWCNetworkRequestDelegate, MKMapViewDelegate> @property (nonatomic, strong) MKMapView *mainMapView; @property (nonatomic, strong) UIToolbar *bottomToolbar; @property (nonatomic, strong) UIButton *searchAreaButton; @property (nonatomic, strong) CNPPopupController *popupController; @property (nonatomic, strong) NYSegmentedControl *segmentedControl; @end
45,827
https://github.com/yangxin1994/bridge/blob/master/bridge-console/src/main/webapp/bridge/src/App.vue
Github Open Source
Open Source
Apache-2.0
2,020
bridge
yangxin1994
Vue
Code
91
394
<template> <div id="app"> <transition name="slide-fade"> <router-view></router-view> </transition> </div> </template> <style> @import "../static/css/main.css"; @import "../static/css/color-dark.css"; /*深色主题*/ #nprogress .bar { background: #FF4949 !important; } </style> <style scoped> .slide-fade-enter-active { transition: all .3s ease; -webkit-transition: all .3s ease; -moz-transition: all .3s ease; -ms-transition: all .3s ease; -o-transition: all .3s ease; } .slide-fade-leave-active { transition: all .5s ease; -webkit-transition: all .5s ease; -moz-transition: all .5s ease; -ms-transition: all .5s ease; -o-transition: all .5s ease; } .slide-fade-enter{ transform: translateX(0px); -webkit-transform: translateX(0px); -moz-transform: translateX(0px); -ms-transform: translateX(0px); -o-transform: translateX(0px); opacity: 0; } .slide-fade-leave-active { opacity: 0; } </style>
36,142
https://github.com/PyColors/ng-potree/blob/master/src/app/cube/cube.component.ts
Github Open Source
Open Source
MIT
2,020
ng-potree
PyColors
TypeScript
Code
357
1,127
import { AfterViewInit, Component, ElementRef, Input, ViewChild } from "@angular/core"; import * as THREE from "three"; import { OrbitControls } from "three-orbitcontrols-ts"; @Component({ selector: "geometry-cube", templateUrl: "./cube.component.html", styleUrls: ["./cube.component.scss"] }) export class CubeComponent implements AfterViewInit { /* HELPER PROPERTIES (PRIVATE PROPERTIES) */ private camera: THREE.PerspectiveCamera; private get canvas(): HTMLCanvasElement { return this.canvasRef.nativeElement; } @ViewChild("canvas") private canvasRef: ElementRef; private cube: THREE.Mesh; private renderer: THREE.WebGLRenderer; private scene: THREE.Scene; /* CUBE PROPERTIES */ @Input() public rotationSpeedX: number = 0.005; @Input() public rotationSpeedY: number = 0.01; @Input() public size: number = 200; @Input() public texture: string = "../assets/textures/crate.gif"; /* STAGE PROPERTIES */ @Input() public cameraZ: number = 400; @Input() public fieldOfView: number = 70; @Input("nearClipping") public nearClippingPane: number = 1; @Input("farClipping") public farClippingPane: number = 1000; /* DEPENDENCY INJECTION (CONSTRUCTOR) */ constructor() {} /* STAGING, ANIMATION, AND RENDERING */ /** * Animate the cube */ private animateCube() { this.cube.rotation.x += this.rotationSpeedX; this.cube.rotation.y += this.rotationSpeedY; } /** * Create the cube */ private createCube() { let texture = new THREE.TextureLoader().load(this.texture); let material = new THREE.MeshBasicMaterial({ map: texture }); let geometry = new THREE.BoxBufferGeometry(this.size, this.size, this.size); this.cube = new THREE.Mesh(geometry, material); // Add cube to scene this.scene.add(this.cube); } /** * Create the scene */ private createScene() { /* Scene */ this.scene = new THREE.Scene(); /* Camera */ let aspectRatio = this.getAspectRatio(); this.camera = new THREE.PerspectiveCamera( this.fieldOfView, aspectRatio, this.nearClippingPane, this.farClippingPane ); this.camera.position.z = this.cameraZ; } private getAspectRatio() { return this.canvas.clientWidth / this.canvas.clientHeight; } /** * Start the rendering loop */ private startRenderingLoop() { /* Renderer */ // Use canvas element in template this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas }); this.renderer.setPixelRatio(devicePixelRatio); this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight); let component: CubeComponent = this; (function render() { requestAnimationFrame(render); component.animateCube(); component.renderer.render(component.scene, component.camera); })(); } /* EVENTS */ /** * Update scene after resizing. */ public onResize() { this.camera.aspect = this.getAspectRatio(); this.camera.updateProjectionMatrix(); this.renderer.setSize(this.canvas.clientWidth, this.canvas.clientHeight); } /* LIFECYCLE */ /** * We need to wait until template is bound to DOM, as we need the view * dimensions to create the scene. We could create the cube in a Init hook, * but we would be unable to add it to the scene until now. */ public ngAfterViewInit() { this.createScene(); this.createCube(); this.startRenderingLoop(); } }
16,602
https://github.com/eGangotri/eGangotri/blob/master/resources/logback.groovy
Github Open Source
Open Source
Unlicense
2,023
eGangotri
eGangotri
Groovy
Code
174
792
import ch.qos.logback.classic.AsyncAppender import ch.qos.logback.classic.PatternLayout import ch.qos.logback.classic.encoder.PatternLayoutEncoder import ch.qos.logback.core.ConsoleAppender import ch.qos.logback.core.FileAppender import ch.qos.logback.core.rolling.TimeBasedRollingPolicy import static ch.qos.logback.classic.Level.INFO String LOG_PATH = "target" String LOG_ARCHIVE = "${LOG_PATH}/archive" def USER_HOME = System.getProperty("user.home") def GOOGLE_DRIVE_PATH = "$USER_HOME/eGangotri/google_drive/archive_uploader/server_logs" def CURRENT_TIME = timestamp("yyyy-MM-dd HH-mm") String logPattern = "%msg%n" appender("Console-Appender", ConsoleAppender) { encoder(PatternLayoutEncoder) { //pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss} %c{1} - %msg%n" pattern = logPattern } } appender("File-Appender", FileAppender) { file = "${LOG_PATH}/egangotri.log" encoder(PatternLayoutEncoder) { //pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss} %c{1} - %msg%n" pattern = logPattern outputPatternAsHeader = false } } appender("RollingFile-Appender", RollingFileAppender) { file = "${LOG_PATH}/egangotri_rolling.log" rollingPolicy(TimeBasedRollingPolicy) { fileNamePattern = "${LOG_ARCHIVE}/rollingfile_%d{yyyy-MM-dd}.log" maxFileSize = "10MB" maxHistory = 30 } encoder(PatternLayoutEncoder) { pattern = logPattern } } //With this Setting your logs will end up in appender("Google-Drive-Appender", FileAppender) { file = "${GOOGLE_DRIVE_PATH}/egangotri_${CURRENT_TIME}.log" encoder(PatternLayoutEncoder) { //pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss} %c{1} - %msg%n" pattern = logPattern outputPatternAsHeader = false } } appender("Focused-Log-Appender", FileAppender) { file = "${GOOGLE_DRIVE_PATH}/egangotri_focus.log" encoder(PatternLayoutEncoder) { //pattern = "[%-5level] %d{yyyy-MM-dd HH:mm:ss} %c{1} - %msg%n" pattern = logPattern outputPatternAsHeader = false } } logger("com.egangotri", INFO, ["Console-Appender", "File-Appender","Google-Drive-Appender", "RollingFile-Appender", "Focused-Log-Appender" ], false) root(INFO, ["Console-Appender"])
34,945
https://github.com/spchal/pwntools-write-ups/blob/master/wargames/overthewire-vortex/level10/win.py
Github Open Source
Open Source
MIT
2,022
pwntools-write-ups
spchal
Python
Code
250
724
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * from ctypes import * context(arch='i386',os='linux') level = 10 host = 'vortex.labs.overthewire.org' user = 'vortex%i' % level chal = 'vortex%i' % level password = args['PASSWORD'] passfile = '/etc/vortex_pass/vortex%i' % (level+1) binary = '/vortex/%s' % chal shell = ssh(host=host, user=user, password=password) if not os.path.exists(chal): shell.download_file(binary) # Load up some ctypes wooo cdll.LoadLibrary("libc.so.6") libc = CDLL("libc.so.6") # Run our binary and get a good guess as to what the value might be shell.set_working_directory() shell.upload_file('ticks.c') shell['gcc -O3 ticks.c -o ticks'] # Run our binary and their binary at the same time # so that the times are closer. def find_the_seed(): sh = shell.run('(./ticks && %s)' % binary) exec(sh.recvline()) # seed exec(sh.recvline()) # ticks log.info("seed: %x" % seed) log.info("ticks: %x" % ticks) want = sh.recvline().strip() want = want.strip('[], ') want = want.split(',') want = [int('0x'+i.strip(), 16) for i in want] log.info("Needle: %s" % want) for seed in xrange(seed-0x10000, seed+0x10000): libc.srand(seed) match = 0 for i in xrange(0x100): rv = libc.rand() if rv == want[match]: match += 1 else: match = 0 if match > 15: log.success("Found seed: %x" % seed) sh.send(p32(seed)) return sh log.info("Didn't find the seed") return None # Search for the seed based off of our guess # When we find it, send it as a 4-byte packed integer sh = None while sh is None: sh = find_the_seed() # Win sh.sendline('export PS1=""') sh.clean(2) sh.sendline('id') log.success('id: ' + sh.recvline().strip()) sh.sendline('cat %s' % passfile) password = sh.recvline().strip() log.success('Password: %s' % password) print password
38,823
https://github.com/nik-sergeson/bsuir-informatics-labs/blob/master/5term/SP/Lab13.vs/Lab13.vs/Lab13.vs.cpp
Github Open Source
Open Source
Apache-2.0
null
bsuir-informatics-labs
nik-sergeson
C++
Code
786
3,375
// Lab13.vs.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "Lab13.vs.h" #include <string> #include <tchar.h> #include <iostream> #include <windows.h> #include <tlhelp32.h> #include <stdio.h> #include <vector> #include "Resource.h" #include <psapi.h> #include <windowsx.h> #include <winbase.h> std::vector<DWORD> processid; #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_LAB13VS, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LAB13VS)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LAB13VS)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 644, 375, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // void GetModuleList(HWND hwnd,int id){ bool exists = false; MODULEENTRY32 entry; entry.dwSize = sizeof(MODULEENTRY32); HANDLE const snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, processid[id]); Module32First(snapshot, &entry); if( !Module32First( snapshot, &entry ) ) { std::wstring str=L"64bit procces, cannot load modules"; SendDlgItemMessage(hwnd, ID_SECONDBOX, LB_ADDSTRING, 0, (LPARAM)str.c_str()); CloseHandle( snapshot ); // Must clean up the snapshot object! return; } do{ std::wstring str; str=entry.szModule; SendDlgItemMessage(hwnd, ID_SECONDBOX, LB_ADDSTRING, 0, (LPARAM)str.c_str()); SendDlgItemMessage(hwnd, ID_SECONDBOX, LB_SETHORIZONTALEXTENT, 8*str.length(),NULL); }while (Module32Next(snapshot, &entry)); CloseHandle(snapshot); } void GetProcessList(HWND hwnd) { bool exists = false; PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry)) while (Process32Next(snapshot, &entry)){ char *num=(char *)calloc(2,sizeof(char)); HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID ); int dwPriorityClass = GetPriorityClass( hProcess ); CloseHandle(hProcess); std::wstring wstr; wstr=entry.szExeFile; wstr+=L",priority: "; wstr+=std::to_wstring(dwPriorityClass); processid.push_back(entry.th32ProcessID); SendDlgItemMessage(hwnd, ID_FIRSTTBOX, LB_ADDSTRING, 0, (LPARAM)wstr.c_str()); SendDlgItemMessage(hwnd, ID_FIRSTTBOX, LB_SETHORIZONTALEXTENT, 8*wstr.length(),NULL); } CloseHandle(snapshot); } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; HWND hListBox=NULL; switch (message) { case WM_CREATE: { hListBox = CreateWindowEx(WS_EX_CLIENTEDGE,L"LISTBOX", NULL, WS_HSCROLL|LBS_NOTIFY|WS_VSCROLL|WS_CHILD|WS_VISIBLE, 10, 45, 300, 200, hWnd, (HMENU)ID_FIRSTTBOX, GetModuleHandle(NULL), NULL); HWND hListBox2 = CreateWindowEx(WS_EX_CLIENTEDGE,L"LISTBOX", NULL, WS_VSCROLL|WS_HSCROLL|WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL, 320, 45, 300, 200, hWnd, (HMENU)ID_SECONDBOX, GetModuleHandle(NULL), NULL); GetProcessList(hWnd); } case WM_COMMAND: { switch(LOWORD(wParam)) { case ID_FIRSTTBOX: { switch(HIWORD(wParam)) { case LBN_SELCHANGE: { HWND hList = GetDlgItem(hWnd, ID_FIRSTTBOX); int lcount = SendMessage(hList, LB_GETCURSEL, 0, 0); SendDlgItemMessage(hWnd, ID_SECONDBOX, LB_RESETCONTENT,NULL,NULL); GetModuleList(hWnd,lcount); } break; case LBN_DBLCLK: { HMENU hPopupMenu = LoadMenu(NULL,MAKEINTRESOURCE(ID_MENU)); hPopupMenu=GetSubMenu(hPopupMenu,0); POINT pt; GetCursorPos(&pt); int nind=TrackPopupMenu(hPopupMenu,TPM_LEFTALIGN,pt.x,pt.y,0,hWnd,0); } break; } } break; case ID_IDLE: { HWND hList = GetDlgItem(hWnd, ID_FIRSTTBOX); int lcount = SendMessage(hList, LB_GETCURSEL, 0, 0); HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processid[lcount] ); SetPriorityClass(hProcess,IDLE_PRIORITY_CLASS); CloseHandle(hProcess); SendDlgItemMessage(hWnd, ID_FIRSTTBOX, LB_RESETCONTENT,NULL,NULL); GetProcessList(hWnd); } break; case ID_NORMAL: { HWND hList = GetDlgItem(hWnd, ID_FIRSTTBOX); int lcount = SendMessage(hList, LB_GETCURSEL, 0, 0); HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processid[lcount] ); SetPriorityClass(hProcess,NORMAL_PRIORITY_CLASS); CloseHandle(hProcess); SendDlgItemMessage(hWnd, ID_FIRSTTBOX, LB_RESETCONTENT,NULL,NULL); GetProcessList(hWnd); } break; case ID_HIGH: { HWND hList = GetDlgItem(hWnd, ID_FIRSTTBOX); int lcount = SendMessage(hList, LB_GETCURSEL, 0, 0); HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processid[lcount] ); SetPriorityClass(hProcess,HIGH_PRIORITY_CLASS); CloseHandle(hProcess); SendDlgItemMessage(hWnd, ID_FIRSTTBOX, LB_RESETCONTENT,NULL,NULL); GetProcessList(hWnd); } break; case ID_REALTIME: { HWND hList = GetDlgItem(hWnd, ID_FIRSTTBOX); int lcount = SendMessage(hList, LB_GETCURSEL, 0, 0); HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, processid[lcount] ); SetPriorityClass(hProcess,REALTIME_PRIORITY_CLASS); CloseHandle(hProcess); SendDlgItemMessage(hWnd, ID_FIRSTTBOX, LB_RESETCONTENT,NULL,NULL); GetProcessList(hWnd); } break; } } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
29,161
https://github.com/hrvojevu/tailor-teaching-elements/blob/master/src/teaching-element/Image.vue
Github Open Source
Open Source
MIT
2,020
tailor-teaching-elements
hrvojevu
Vue
Code
41
127
<template> <div class="te-image"> <img :src="url"> </div> </template> <script> export default { name: 'te-image', props: { url: { type: String, required: true } } }; </script> <style lang="scss"> .te-image img { display: block; max-width: 100%; height: auto; margin: 0 auto; } </style>
16,567
https://github.com/CharlesBases/protoc-gen-doc/blob/master/utils/logger.go
Github Open Source
Open Source
MIT
2,020
protoc-gen-doc
CharlesBases
Go
Code
103
368
package utils import ( "fmt" "os" "strings" "time" ) const ( DBG = 36 INF = 38 WRN = 34 ERR = 31 ) var level = map[int]string{ DBG: "DBG", INF: "INF", WRN: "WRN", ERR: "ERR", } func ThrowCheck(err error) { if err != nil { Error(err) os.Exit(1) } } func Debug(vs ...interface{}) { print(DBG, vs) } func Info(vs ...interface{}) { print(INF, vs) } func Warn(vs ...interface{}) { print(WRN, vs) } func Error(vs ...interface{}) { print(ERR, vs) } func print(code int, vs interface{}) { os.Stderr.WriteString(fmt.Sprintf( "%c[%d;%d;%dm[%s][%s] ==> %s%c[0m\n", 0x1B, 0 /*字体*/, 0 /*背景*/, code /*前景*/, time.Now().Format("2006-01-02 15:04:05.000"), level[code], strings.Trim(fmt.Sprint(vs), "[]"), 0x1B), ) }
41,938
https://github.com/fornesarturo/santo-clos/blob/master/santo-clos-front/src/App.vue
Github Open Source
Open Source
MIT
2,018
santo-clos
fornesarturo
Vue
Code
344
1,843
/* eslint-disable */ <template> <div class="pageBG" id="main"> <div v-if='loggedIn'> <nav class="navbar sticky-top navbar-expand-sm navbar-dark bg-dark" v-bind:id="activeView" v-on:click.prevent> <a class="navbar-brand" v-on:click="setHubActive()"> <router-link to="/hub"> <img src="static/images/santo_clos.png" width="200" height="50" alt="Santo Clos"> </router-link> </a> <button class="navbar-toggler custom-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerSantoClos" aria-controls="navbarTogglerSantoClos" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerSantoClos"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a href="#" id="hub" v-on:click="setHubActive()"> <router-link to="/hub">Home</router-link> </a> </li> <li class="nav-item active"> <a href="#" id="create-event" v-on:click="setCreateEventActive()"> <router-link to="/create-event">Create Event</router-link> </a> </li> <li class="nav-item active"> <a href="#" id="settings" v-on:click="setSettingsActive()"> <router-link to="/settings">Settings</router-link> </a> </li> <button type="button" id="logoutButton" class="nav-item" v-on:click="logoutFunction()"> <a href="#"> Log Out </a> </button> </ul> </div> </nav> <Modal v-if="showModal" @close="showModalClose()" v-bind:gifteeList="eventModal.gifteeList" v-bind:name="eventModal.name" v-bind:date="eventModal.date" v-bind:location="eventModal.location" v-bind:hostName="eventModal.hostName" v-bind:userYouGive.sync="eventModal.userYouGive" v-bind:maxAmount="eventModal.maxAmount" v-bind:eventId="eventModal.eventId" v-bind:wishlist="eventModal.wishlist" v-bind:participants="eventModal.participants" v-bind:sortDone.sync="eventModal.sortDone" v-bind:parentComponent="eventModal.parentComponent" @delete="setHubActivePlz()"> </Modal> <ModalJoined v-if="showModalJoined" @close="showModalJoinedClose()" v-bind:gifteeList="eventModal.gifteeList" v-bind:name="eventModal.name" v-bind:date="eventModal.date" v-bind:location="eventModal.location" v-bind:hostName="eventModal.hostName" v-bind:userYouGive.sync="eventModal.userYouGive" v-bind:maxAmount="eventModal.maxAmount" v-bind:eventId="eventModal.eventId" v-bind:wishlist="eventModal.wishlist" v-bind:participants="eventModal.participants" v-bind:sortDone.sync="eventModal.sortDone" v-bind:parentComponent="eventModal.parentComponent"> </ModalJoined> </div> <router-view @login-setActive ="setLoginActive()" @login-event="setLogin()" @change-to-event="setCreateEventActive()" @change-to-hub="setHubActive()"></router-view> </div> </template> <script> /* eslint-disable */ import Modal from '@/components/Modal' import ModalJoined from '@/components/ModalJoined' import '@/assets/vendor/js-cookie/js-cookie.js' const request = require('./components/requests/requests_main') export default { name: "App", components: { Modal, ModalJoined }, data: () => { return { loggedIn: false, activeView: 'hub', adminedEvents: {}, n: 0, items: [], showModal: false, showModalJoined: false, eventModal: {} } }, methods: { setLogin: function() { this.loggedIn = true }, setLoginActive: function() { this.activeView = "login" this.$router.push('/') }, setHubActive: function() { this.activeView = "hub" this.$router.push('/hub') }, setHubActivePlz: function() { this.activeView = "create-event"; this.$router.push('/create-event'); let myThis = this; setTimeout(function(){ myThis.activeView = "hub"; myThis.$router.push('/hub'); }, 50); }, setCreateEventActive: function() { this.activeView = "create-event" this.$router.push('/create-event') }, setSettingsActive: function() { this.activeView = "settings" this.$router.push('/settings') }, setServicesActive: function() { this.activeView = "services" }, setEventInformationActive: function() { this.activeView = "eventInformation" location.href = "main#/eventInformation" }, modalData: function(data) { this.eventModal = data }, logoutFunction: function() { Cookies.remove("current_user"); Cookies.remove("token"); this.loggedIn = false; this.activeView = "login"; this.$router.push('/'); }, showModalClose: function() { this.showModal = false; }, showModalJoinedClose: function() { this.showModalJoined = false; }, }, mounted() { if(this.activeView != "login") { request.checkIfLoggedIn().then( (logged) => { if(logged) this.loggedIn = true; else { this.logoutFunction() } } ); } } }; </script> <style> @import 'bootstrap/dist/css/bootstrap.css'; @import './assets/vendor/animate/animate.css'; @import './assets/vendor/css-hamburgers/hamburgers.css'; @import './assets/css/main.css'; @import './assets/css/index.css'; @import './assets/css/modal.css'; @import './assets/css/setup.css'; </style>
9,520
https://github.com/pmqtt/pmq/blob/master/test/test_login_factory.cpp
Github Open Source
Open Source
Apache-2.0
2,019
pmq
pmqtt
C++
Code
55
296
// // Created by pmqtt on 2019-07-19. // #define BOOST_TEST_DYN_LINK 1 #define BOOST_TEST_MODULE test_login_factory #include <boost/test/included/unit_test.hpp> #include "lib/server/login/login_factory.hpp" #include "lib/server/login/login_handler.hpp" #include "lib/server/login/login_allow_anonymous_handler.hpp" template<typename Base, typename T> inline bool instanceof(const T *ptr) { return dynamic_cast<const Base*>(ptr) != nullptr; } BOOST_AUTO_TEST_CASE( CREATION_TEST ) { pmq::login_factory factory; std::shared_ptr<pmq::login_handler> need_login = factory.create(false); std::shared_ptr<pmq::login_handler> no_login_require = factory.create(true); BOOST_CHECK(instanceof<pmq::login_handler>(need_login.get())); BOOST_CHECK(instanceof<pmq::login_allow_anonymous_handler>(no_login_require.get())); }
28,052
https://github.com/lshowbiz/agnt_ht/blob/master/src/service/com/joymain/jecs/am/service/impl/AmMessageManagerImpl.java
Github Open Source
Open Source
Apache-2.0
null
agnt_ht
lshowbiz
Java
Code
495
2,334
package com.joymain.jecs.am.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import com.joymain.jecs.am.dao.AmMessageDao; import com.joymain.jecs.am.model.AmMessage; import com.joymain.jecs.am.service.AmMessageManager; import com.joymain.jecs.service.impl.BaseManager; import com.joymain.jecs.util.data.CommonRecord; import com.joymain.jecs.util.data.Pager; import com.joymain.jecs.util.string.StringUtil; public class AmMessageManagerImpl extends BaseManager implements AmMessageManager { public void saveAmMessageStatus(String uniNo, Integer status) { // TODO Auto-generated method stub AmMessage amMessage = dao.getAmMessage(uniNo); amMessage.setStatus(status); dao.saveAmMessage(amMessage); } private AmMessageDao dao; /** * Set the Dao for communication with the data layer. * @param dao */ public void setAmMessageDao(AmMessageDao dao) { this.dao = dao; } /** * @see com.joymain.jecs.am.service.AmMessageManager#getAmMessages(com.joymain.jecs.am.model.AmMessage) */ public List getAmMessages(final AmMessage amMessage) { return dao.getAmMessages(amMessage); } /** * @see com.joymain.jecs.am.service.AmMessageManager#getAmMessage(String uniNo) */ public AmMessage getAmMessage(final String uniNo) { return dao.getAmMessage(new String(uniNo)); } /** * @see com.joymain.jecs.am.service.AmMessageManager#saveAmMessage(AmMessage amMessage) */ public void saveAmMessage(AmMessage amMessage) { dao.saveAmMessage(amMessage); } /** * @see com.joymain.jecs.am.service.AmMessageManager#removeAmMessage(String uniNo) */ public void removeAmMessage(final String uniNo) { dao.removeAmMessage(new String(uniNo)); } //added for getAmMessagesByCrm public List getAmMessagesByCrm(CommonRecord crm, Pager pager){ List list = new ArrayList(); String searchFlag = crm.getString("searchFlag", ""); if("company".equals(searchFlag)){ list = dao.getCompanyAmMessages(crm,pager); }else if("control".equals(searchFlag)){ //list = dao.getAmMessagesByCrm(crm,pager); //add comment by lihao,查询条件里加上部门名称 //list = dao.getAmMessagesByCrm2(crm,pager); //add comment by lihao,查询条件里加上部门名称(需求变更) list = dao.getAmMessagesByCrm3(crm,pager); }else if("cs".equals(searchFlag)){ list = dao.getAmMessagesByCrm(crm,pager); }else if("agent".equals(searchFlag)){ list = dao.getAgentAmMessages(crm,pager); }else if("type".equals(searchFlag)){ String amMessageType=crm.getString("amMessageType", ""); if(!StringUtil.isEmpty(amMessageType)){ list = dao.getCompanyAmMessages(crm,pager); } }else{ list = dao.getAmMessagesByCrm(crm,pager); } /* String isAgent = crm.getString("isAgent",""); String agentNo = crm.getString("agentNo",""); if("1".equals(isAgent)){ list = dao.getAgentAmMessages(crm,pager); }else{ list = dao.getAmMessagesByCrm(crm, pager); } */ return list; // List list = dao.getAmMessagesByCrm(crm,pager); //// List ret = new ArrayList(); // // String isAgent = crm.getString("isAgent",""); // if("1".equals(isAgent)){ // return reBuildList(list); // }else{ // return list; // } } private List reBuildList(List list){ List ret = new ArrayList(); Iterator iterator=list.iterator(); if(iterator.hasNext()){ AmMessage amMessage = (AmMessage) iterator.next(); if(amMessage.getSendRoute().equals("0")){ if(amMessage.getStatus() >= 3){ ret.add(amMessage); } }else{ ret.add(amMessage); } } return ret; } public void readAmMessage(String uniNo) { // TODO Auto-generated method stub AmMessage amMessage = dao.getAmMessage(uniNo); amMessage.setStatus(9); saveAmMessage(amMessage); } public void checkAmMessage(String uniNo) {//,String checkUserNo // TODO Auto-generated method stub AmMessage amMessage = dao.getAmMessage(uniNo); //amMessage.setCheckUserNo(checkUserNo); //amMessage.setCheckMsgTime(new Date()); amMessage.setStatus(3); saveAmMessage(amMessage); } public int checkAmMessageBatch(String aanos){ return dao.checkAmMessageBatch(aanos); } public void agentSendMessage(String uniNo) { AmMessage amMessage = dao.getAmMessage(uniNo); amMessage.setStatus(0); saveAmMessage(amMessage); } public void saveAmMessageReceiver(String uniNo, String userNo, String userName, String ctrluser) { // TODO Auto-generated method stub AmMessage amMessage = dao.getAmMessage(uniNo); amMessage.setReceiverNo(userNo); amMessage.setReceiverName(userName); amMessage.setCheckUserNo(ctrluser); amMessage.setCheckMsgTime(new Date()); dao.saveAmMessage(amMessage); } public String getAmMessagesReplyNum(CommonRecord crm, String tag) { String num = "0"; if("reply".equals(tag)){ num = dao.getAmMessagesReplyNum(crm); }else if ("noreply".equals(tag)){ num = dao.getAmMessagesNoReplyNum(crm); }else if ("nocheck".equals(tag)){ num = dao.getAmMessagesNoCkeckNum(crm); } return num; } public String getAgentReplyNum(CommonRecord crm, String tag) { String num = "0"; if("reply".equals(tag)){ num = dao.getAgentReplyNum(crm); }else if ("noreply".equals(tag)){ num = dao.getAgentNoReplyNum(crm); }else if ("nocheck".equals(tag)){ num = dao.getAmMessagesNoCkeckNum(crm); }else if ("noread".equals(tag)){ num = dao.getAgentNoReadNum(crm); } return num; } public String getCompanyReplyNum(CommonRecord crm, String tag) { String num = "0"; if("reply".equals(tag)){ num = dao.getCompanyReplyNum(crm); }else if ("noreply".equals(tag)){ num = dao.getCompanyNoReplyNum(crm); }else if ("nocheck".equals(tag)){ //num = dao.getAmMessagesNoCkeckNum(crm); }else if ("noread".equals(tag)){ //num = dao.getAgentNoReadNum(crm); } return num; } public List getRecentlyAmMessage(String userCode,String companyCode) { return dao.getRecentlyAmMessage(userCode,companyCode); } public List getAmMessageByUserCode(String userCode, String msgClassNo) { return dao.getAmMessageByUserCode(userCode, msgClassNo); } }
41,958
https://github.com/bernardd/otp/blob/master/lib/erl_interface/src/legacy/erl_internal.h
Github Open Source
Open Source
Apache-2.0
2,021
otp
bernardd
C
Code
172
381
/* * %CopyrightBegin% * * Copyright Ericsson AB 1996-2016. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #ifndef _ERL_INTERNAL_H #define _ERL_INTERNAL_H /* * Function: Some useful stuff not to be exported to users. */ #define HEAD(ep) ep->uval.lval.head #define TAIL(ep) ep->uval.lval.tail #define ERL_NO_REF(x) (ERL_COUNT(x) == 0) #ifdef DEBUG #define ASSERT(e) \ if (e) { \ ; \ } else { \ erl_assert_error(#e, __FILE__, __LINE__); \ } extern void erl_assert_error(char* expr, char* file, int line) __attribute__ ((__noreturn__)); #else #define ASSERT(e) #endif #endif /* _ERL_INTERNAL_H */
10,105
https://github.com/dsandip/graphql-engine/blob/master/console/src/components/Common/utils/tsUtils.ts
Github Open Source
Open Source
Apache-2.0, MIT
2,020
graphql-engine
dsandip
TypeScript
Code
13
35
export const UNSAFE_keys = <T extends object>(source: T) => Object.keys(source) as Array<keyof T>;
3,485
https://github.com/MichaelShaw/hogger/blob/master/HoggerTests/ShrinkTests.swift
Github Open Source
Open Source
MIT
null
hogger
MichaelShaw
Swift
Code
120
454
// // ShrinkTests.swift // HoggerTests // // Created by Michael Shaw on 26/1/18. // Copyright © 2018 Michael Shaw. All rights reserved. // import XCTest @testable import Hogger class ShrinkTests: XCTestCase { func testTowards() { let a = Towards(from: 0, destination: 100) XCTAssert(a.collect() == [0,50,75,88,94,97,99], "towards(0,100) was \(a)") let b = Towards(from: 500, destination: 1000) XCTAssert(b.collect() == [500,750,875,938,969,985,993,997,999], "towards(500,1000) was \(b)") let c = Towards(from: -50, destination: -26) XCTAssert(c.collect() == [-50,-38,-32,-29,-27], "towards(-50,-26) was \(c)") } func testTowardsFrac() { let a = Array(TowardsFrac(from: 0.0, destination: 100.0).iter().prefix(7)) XCTAssert(a.count == 7 && Math.approxEqual(a.last!, 98.4375, epsilon: 0.01), "towards(0.0, 100.0, 7) was \(a)") let b = Array(TowardsFrac(from: 1.0, destination: 0.5).iter().prefix(7)) XCTAssert(b.count == 7 && Math.approxEqual(b.last!, 0.5078125, epsilon: 0.01), "towards(1.0, 0.5, 7) was \(b)") } }
8,120
https://github.com/Passarinho4/scala-commons/blob/master/commons-core/src/main/scala/com/avsystem/commons/rpc/RpcMetadataCompanion.scala
Github Open Source
Open Source
MIT
null
scala-commons
Passarinho4
Scala
Code
20
99
package com.avsystem.commons package rpc import com.avsystem.commons.macros.rpc.RpcMacros import com.avsystem.commons.meta.MetadataCompanion trait RpcMetadataCompanion[M[_]] extends MetadataCompanion[M] { def materialize[Real]: M[Real] = macro RpcMacros.rpcMetadata[Real] }
16,922
https://github.com/Thieum/Ark.Tools/blob/master/Ark.Tools.Authorization/IAuthorizationContextFactory.cs
Github Open Source
Open Source
MIT
2,022
Ark.Tools
Thieum
C#
Code
115
246
using System.Security.Claims; namespace Ark.Tools.Authorization { /// <summary> /// A factory used to provide a <see cref="AuthorizationContext"/> used by authorization handlers. /// Applications with custom handlers can implement a custom factory to provide handlers with additional context informations. /// </summary> public interface IAuthorizationContextFactory { /// <summary> /// Creates a <see cref="AuthorizationContext"/> used for authorization. /// </summary> /// <param name="policy">The policy to evaluate.</param> /// <param name="user">The user to evaluate the requirements against.</param> /// <param name="resource"> /// An optional resource the policy should be checked with. /// If a resource is not required for policy evaluation you may pass null as the value. /// </param> /// <returns>The <see cref="AuthorizationContext"/>.</returns> AuthorizationContext Create(IAuthorizationPolicy policy, ClaimsPrincipal user, object resource); } }
43,473
https://github.com/sathwikkannam/courses-HKR/blob/master/Database Technique/Exercises/join.sql
Github Open Source
Open Source
MIT
null
courses-HKR
sathwikkannam
SQL
Code
23
61
USE world; SHOW TABLES; SELECT * FROM country; SELECT * FROM countrylanguage; SELECT * FROM country INNER JOIN countrylanguage ON country.code = countrylanguage.CountryCode;
34,533
https://github.com/miguelvazq/HPCC-Platform/blob/master/ecl/regress/sqfilt.ecl
Github Open Source
Open Source
Apache-2.0
2,022
HPCC-Platform
miguelvazq
ECL
Code
374
1,211
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 sq; sq.DeclareCommon(); #option ('childQueries', true); // Test filtering at different levels, making sure parent fields are available in the child query. // Also tests scoping of sub expressions using within. udecimal8 todaysDate := 20040602D; unsigned4 age(udecimal8 dob) := ((todaysDate - dob) / 10000D); //MORE: books[1] ave(books) // Different child operators, all inline. house := sqHousePersonBookDs.persons; persons := sqHousePersonBookDs.persons; books := persons.books; booksDs := sqBookDs(personid = persons.id); personsDs := sqPersonDs(houseid = sqHousePersonBookDs.id); booksDsDs := sqBookDs(personid = personsDs.id); personsDsDs := sqPersonDs(houseid = sqHouseDs.id); booksDsDsDs := sqBookDs(personid = personsDsDs.id); //Who has a book worth more than their book limit? (nest, nest), (nest, ds) (ds, ds) output(sqHousePersonBookDs, { addr, max(persons,booklimit), max(persons.books,price), count(persons(exists(books(price>persons.booklimit)))); }, named('NumPeopleExceedBookLimit')); output(sqHousePersonBookDs, { addr, count(persons(exists(booksDs(price>persons.booklimit)))); }, named('NumPeopleExceedBookLimitDs')); output(sqHouseDs, { addr, count(personsDsDs(exists(booksDsDsDs(price>personsDs.booklimit)))); }, named('NumPeopleExceedBookLimitDsDs')); //The following currently give the wrong results because there is no differentiation between the two iterators on books //which means sizeof(row-of-books) is wrong, and the iterators etc. don't work correctly! // How many people have books worth more than twice their average book price output(sqHousePersonBookDs, { addr, count(persons(exists(books(price>ave(__ALIAS__(books), price)*2)))) }); output(sqHousePersonBookDs, { addr, count(persons(exists(booksDs(price>ave(books, price)*2)))) }); output(sqHousePersonBookDs, { addr, count(persons(exists(booksDs(price>ave(booksDs, price)*2)))) }); //output(sqHousePersonBookDs, { addr, count(personsDs(exists(booksDsDs(price>ave(booksDs, price)*2)))) }); output(sqHousePersonBookDs, { addr, count(personsDs(exists(booksDsDs(price>ave(booksDsDs, price)*2)))) }); output(sqHouseDs, { addr, count(personsDsDs(exists(booksDsDsDs(price>ave(booksDsDsDs, price)*2)))) }); /**** Within not supported yet ****** // How many people have books worth more than twice the average book price for the house output(sqHousePersonBookDs, { addr, count(persons(exists(books(price>ave(books(within house), price)*2)))) }); output(sqHousePersonBookDs, { addr, count(persons(exists(booksDs(price>ave(books(within house), price)*2)))) }); output(sqHousePersonBookDs, { addr, count(persons(exists(booksDs(price>ave(booksDs(within house), price)*2)))) }); //output(sqHousePersonBookDs, { addr, count(personsDs(exists(booksDsDs(price>ave(booksDs(within house), price)*2)))) }); output(sqHousePersonBookDs, { addr, count(personsDs(exists(booksDsDs(price>ave(booksDsDs(within house), price)*2)))) }); output(sqHouseDs, { addr, count(personsDsDs(exists(booksDsDsDs(price>ave(booksDsDsDs(within sqHouseDs), price)*2)))) }); ***** end within *****/ output(sqHouseDs, { addr, filename, count(personsDsDs(exists(booksDsDsDs(price>personsDs.booklimit)))); }, named('NumPeopleFilename')); output(sqHouseDs, { addr, count(personsDsDs(exists(booksDsDsDs(price>(integer)sqHouseDs.filename)))); }, named('NumPeopleFilenameChild'));
2,886
https://github.com/ularsth/contextual-help/blob/master/src/js/chFetch.js
Github Open Source
Open Source
MIT
2,020
contextual-help
ularsth
JavaScript
Code
134
365
import _fetch from 'isomorphic-fetch'; export const handleResponse = (response, requestData)=> { const valid = response.status >= 200 && response.status <= 399; if (!valid) { const responseData = { locLocation: 'Error during fetch request in ContextualHelp', status: response.status, statusText: response.statusText, url: response.url }; const error = { errorData: new Error('Error during fetch request in ContextualHelp'), requestData, responseData }; throw error; } return response.json(); }; const chFetch = (url) => { if (!url && typeof url !== 'string') { return } const requestData = { method: 'GET', headers: {} } return _fetch(url, requestData) .then((response) => handleResponse(response, requestData)) .catch((error) => { const errorObj = { logLocation: url, errorMessage: error.errorData && error.errorData.Message, errorStack: (error.errorData && error.errorData.stack) || 'No stack provided', errorStatus: (error.responseData && error.responseData.status) || 1, errorRequestData: requestData, errorResponseData: error.responseData }; throw errorObj; }); }; export default chFetch;
17,991
https://github.com/samskalicky/tvm/blob/master/src/runtime/contrib/tensorrt/tensorrt_module.cc
Github Open Source
Open Source
Apache-2.0
null
tvm
samskalicky
C++
Code
1,292
4,428
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file runtime/contrib/tensorrt/tensorrt_module.cc * \brief TensorRTModule is the runtime module for tensorrt backend. */ #include <stdlib.h> #include <tvm/node/serialization.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/type.h> #include <tvm/runtime/ndarray.h> #include <fstream> #include <string> #include <unordered_map> #include <vector> #include "../../file_util.h" #include "tensorrt_module.h" #ifdef TVM_GRAPH_RUNTIME_TENSORRT #include "NvInfer.h" #include "tensorrt_builder.h" #endif // TVM_GRAPH_RUNTIME_TENSORRT namespace tvm { namespace runtime { /*! \brief A module for TensorRT runtime. */ class TensorRTModule : public runtime::ModuleNode { public: explicit TensorRTModule( const std::unordered_map<std::string, std::string>& serialized_subgraphs) : serialized_subgraphs_(serialized_subgraphs) { max_workspace_size_ = dmlc::GetEnv("TVM_TENSORRT_MAX_WORKSPACE_SIZE", size_t(1) << 31); #if TVM_GRAPH_RUNTIME_TENSORRT GetCachedEnginesFromDisk(); #endif } ~TensorRTModule() { #if TVM_GRAPH_RUNTIME_TENSORRT for (auto& it : trt_engine_cache_) { it.second.context->destroy(); it.second.engine->destroy(); } #endif // TVM_GRAPH_RUNTIME_TENSORRT } PackedFunc GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) final { #if TVM_GRAPH_RUNTIME_TENSORRT // Returning nullptr tells TVM that the function is not in this module, so // it can look for the correct one. auto it_subgraph = serialized_subgraphs_.find(name); if (it_subgraph == serialized_subgraphs_.end()) { return PackedFunc(nullptr); } // Generate an external packed function return PackedFunc([this, name](tvm::TVMArgs args, tvm::TVMRetValue* rv) { auto it = trt_engine_cache_.find(name); if (it == trt_engine_cache_.end()) { // Build new trt engine and place in cache. LOG(INFO) << "Building new TensorRT engine for subgraph " << name; auto func = Downcast<relay::Function>( LoadJSON(this->serialized_subgraphs_[name])); auto inputs = ConvertInputs(args); std::string key = GetSubgraphKey(serialized_subgraphs_[name]); this->serialized_subgraphs_[name].clear(); relay::contrib::TensorRTBuilder builder(&logger_, inputs, max_workspace_size_); auto engine_and_context = builder.BuildEngine(func); CacheEngineToDisk(key, engine_and_context); LOG(INFO) << "Finished building TensorRT engine for subgraph " << name; this->trt_engine_cache_[name] = engine_and_context; this->ExecuteEngine(engine_and_context, args, rv); } else { this->ExecuteEngine(it->second, args, rv); } }); #else LOG(FATAL) << "TVM was not built with TensorRT runtime enabled. Build " << "with USE_TENSORRT=ON."; return PackedFunc(); #endif // TVM_GRAPH_RUNTIME_TENSORRT } const char* type_key() const { return "tensorrt"; } void SaveToFile(const std::string& file_name, const std::string& format) final { std::string fmt = runtime::GetFileFormat(file_name, format); CHECK_EQ(fmt, type_key()) << "Can only save to format=" << type_key(); SaveBinaryToFile(file_name, SerializeModuleToString()); } void SaveToBinary(dmlc::Stream* stream) final { stream->Write(SerializeModuleToString()); } static Module LoadFromFile(const std::string& path) { std::ifstream filep(path); filep.seekg(0, std::ios::end); size_t size = filep.tellg(); std::string serialized_module(size, ' '); filep.seekg(0); filep.read(&serialized_module[0], size); return CreateModuleFromString(serialized_module); } static Module LoadFromBinary(void* strm) { dmlc::Stream* stream = static_cast<dmlc::Stream*>(strm); std::string serialized_module; stream->Read(&serialized_module); return CreateModuleFromString(serialized_module); } private: /*! \brief Relay program serialized using SaveJSON */ std::unordered_map<std::string, std::string> serialized_subgraphs_; /*! \brief Max workspace size for TensorRT */ size_t max_workspace_size_; #if TVM_GRAPH_RUNTIME_TENSORRT /*! \brief Map of function name to TRT engine if built already. */ std::unordered_map<std::string, TrtEngineAndContext> trt_engine_cache_; /*! \brief TensorRT object used to log warnings and errors. */ TensorRTLogger logger_; /*! * \brief Convert TVMArgs to make compatible with VM or graph runtime. * \param args Inputs to the PackedFunc. * \return Inputs converted to vector of DLTensor* */ std::vector<DLTensor*> ConvertInputs(tvm::TVMArgs args) { std::vector<DLTensor*> inputs(args.size(), nullptr); for (size_t i = 0; i < args.size(); ++i) { if (args[i].type_code() == kTVMNDArrayHandle) { // Relay Debug/VM uses NDArray runtime::NDArray array = args[i]; inputs[i] = const_cast<DLTensor*>(array.operator->()); } else if (args[i].type_code() == kTVMDLTensorHandle) { // Graph runtime uses DLTensors inputs[i] = args[i]; } else { LOG(FATAL) << "Invalid TVMArgs type."; } } return inputs; } /*! * \brief Perform inference using TensorRT. * \param engine_and_context TRT engine from TrtBuilder::BuildEngine() * \param args Inputs to the PackedFunc. * \param rv Return value pointer for the PackedFunc. * \return Inputs converted to vector of DLTensor* */ void ExecuteEngine(const TrtEngineAndContext& engine_and_context, tvm::TVMArgs args, tvm::TVMRetValue* rv) { auto engine = engine_and_context.engine; auto context = engine_and_context.context; const int num_bindings = engine->getNbBindings(); std::vector<void*> bindings(num_bindings, nullptr); // Set inputs. auto inputs = ConvertInputs(args); const size_t num_outputs = engine_and_context.outputs.size(); CHECK_GT(inputs.size(), num_outputs); for (size_t i = 0; i < engine_and_context.inputs.size(); ++i) { // If an input was baked into the engine, skip. if (engine_and_context.input_is_baked[i]) continue; DLTensor* arg = inputs[i]; int binding_index = engine->getBindingIndex(engine_and_context.inputs[i].c_str()); CHECK_NE(binding_index, -1); if (!runtime::TypeMatch(arg->dtype, kDLFloat, 32)) { LOG(FATAL) << "Only float32 inputs are supported."; } bindings[binding_index] = reinterpret_cast<float*>(arg->data); #if TRT_VERSION_GE(6, 0, 1) // Set binding dimensions for INetworkV2 explicit batch mode engines. nvinfer1::Dims dims; dims.d[0] = 1; dims.nbDims = arg->ndim; for (int i = 0; i < arg->ndim; ++i) { dims.d[i] = arg->shape[i]; } context->setBindingDimensions(binding_index, dims); #endif } // Set outputs. for (size_t i = 0; i < num_outputs; ++i) { const int index_in_inputs = inputs.size() - num_outputs + i; DLTensor* out_arg = inputs[index_in_inputs]; int binding_index = engine->getBindingIndex(engine_and_context.outputs[i].c_str()); CHECK_NE(binding_index, -1); bindings[binding_index] = reinterpret_cast<float*>(out_arg->data); } #if TRT_VERSION_GE(6, 0, 1) CHECK(context->executeV2(bindings.data())) << "Running TensorRT failed."; #else // Use batch size from first input. const int batch_size = inputs[0]->shape[0]; CHECK(context->execute(batch_size, bindings.data())) << "Running TensorRT failed."; #endif *rv = bindings[num_bindings - num_outputs]; } std::string GetSubgraphKey(const std::string& serialized_subgraph) { if (dmlc::GetEnv("TVM_TENSORRT_CACHE_DIR", std::string("")).empty()) return ""; std::string key = std::to_string(std::hash<std::string>()(serialized_subgraph)); if (dmlc::GetEnv("TVM_TENSORRT_USE_FP16", false)) { key += "_fp16"; } return key; } /*! \brief If TVM_TENSORRT_CACHE_DIR is set, will check that directory for * already built TRT engines and load into trt_engine_cache_ so they don't * have to be built at first inference. */ void GetCachedEnginesFromDisk() { std::string cache_dir = dmlc::GetEnv("TVM_TENSORRT_CACHE_DIR", std::string("")); if (cache_dir.empty()) return; for (auto it : serialized_subgraphs_) { std::string key = GetSubgraphKey(it.second); std::string path = cache_dir + "/" + key + ".plan"; // Check if engine is in the cache. std::ifstream infile(path, std::ios::binary); if (!infile.good()) continue; LOG(INFO) << "Loading cached TensorRT engine from " << path; infile.close(); std::string serialized_engine; LoadBinaryFromFile(path, &serialized_engine); // Deserialize engine nvinfer1::IRuntime* runtime = nvinfer1::createInferRuntime(logger_); TrtEngineAndContext engine_and_context; engine_and_context.engine = runtime->deserializeCudaEngine( &serialized_engine[0], serialized_engine.size(), nullptr);; engine_and_context.context = engine_and_context.engine->createExecutionContext(); // Load metadata std::string meta_path = cache_dir + "/" + key + ".meta"; std::string serialized_meta; LoadBinaryFromFile(meta_path, &serialized_meta); std::istringstream is(serialized_meta); dmlc::JSONReader reader(&is); dmlc::JSONObjectReadHelper helper; helper.DeclareField("inputs", &engine_and_context.inputs); helper.DeclareField("input_is_baked", &engine_and_context.input_is_baked); helper.DeclareField("outputs", &engine_and_context.outputs); helper.ReadAllFields(&reader); trt_engine_cache_[it.first] = engine_and_context; } } /*! \brief If TVM_TENSORRT_CACHE_DIR is set, will save the engine to that * directory so it can be loaded later. A hash of the source relay function is * used as the key for the file name. * \param name Subgraph name * \param engine_and_context Engine to cache */ void CacheEngineToDisk(const std::string& key, const TrtEngineAndContext& engine_and_context) { std::string cache_dir = dmlc::GetEnv("TVM_TENSORRT_CACHE_DIR", std::string("")); if (cache_dir.empty()) return; std::string path = cache_dir + "/" + key + ".plan"; LOG(INFO) << "Caching TensorRT engine to " << path; // Serialize engine to disk nvinfer1::IHostMemory* serialized_engine = engine_and_context.engine->serialize(); SaveBinaryToFile(path, std::string(static_cast<const char*>(serialized_engine->data()), serialized_engine->size())); serialized_engine->destroy(); // Serialize metadata std::ostringstream os; dmlc::JSONWriter writer(&os); writer.BeginObject(); writer.WriteObjectKeyValue("inputs", engine_and_context.inputs); writer.WriteObjectKeyValue("input_is_baked", engine_and_context.input_is_baked); writer.WriteObjectKeyValue("outputs", engine_and_context.outputs); writer.EndObject(); std::string meta_path = cache_dir + "/" + key + ".meta"; SaveBinaryToFile(meta_path, os.str()); } #endif // TVM_GRAPH_RUNTIME_TENSORRT /*! \brief Serialize this module to a string. To be used during codegen. */ std::string SerializeModuleToString() { std::ostringstream os; dmlc::JSONWriter writer(&os); writer.BeginObject(); writer.WriteObjectKeyValue("subgraphs", serialized_subgraphs_); writer.WriteObjectKeyValue("max_workspace_size", max_workspace_size_); writer.EndObject(); return os.str(); } /*! \brief Load serialized module from string created by SerializeModuleToString. */ static Module CreateModuleFromString(const std::string& str) { std::unordered_map<std::string, std::string> serialized_subgraphs; size_t max_workspace_size = 0; std::istringstream is(str); dmlc::JSONReader reader(&is); dmlc::JSONObjectReadHelper helper; helper.DeclareField("subgraphs", &serialized_subgraphs); helper.DeclareOptionalField("max_workspace_size", &max_workspace_size); helper.ReadAllFields(&reader); auto n = make_object<TensorRTModule>(serialized_subgraphs); // Use max_workspace_size from artifact if it is set and it is not overriden by env var. if (max_workspace_size != 0 && dmlc::GetEnv("TVM_TENSORRT_MAX_WORKSPACE_SIZE", 0) != 0) { n->max_workspace_size_ = max_workspace_size; } return Module(n); } }; Module TensorRTModuleCreate( const std::unordered_map<std::string, std::string>& serialized_subgraphs) { auto n = make_object<TensorRTModule>(serialized_subgraphs); return Module(n); } TVM_REGISTER_GLOBAL("runtime.module.loadfile_tensorrt") .set_body([](TVMArgs args, TVMRetValue* rv) { *rv = TensorRTModule::LoadFromFile(args[0]); }); TVM_REGISTER_GLOBAL("runtime.module.loadbinary_tensorrt") .set_body_typed(TensorRTModule::LoadFromBinary); } // namespace runtime } // namespace tvm
13,248
https://github.com/awakun/LearningPython/blob/master/Python/PythonCrashCourse2ndEdition/3-1_names.py
Github Open Source
Open Source
MIT
null
LearningPython
awakun
Python
Code
31
103
names = ['Dave', 'Joe', 'Tucker', 'Julia', 'Amber', 'Equinox'] print(names[0]) print(names[1]) print(names[2]) print(names[3]) print(names[4]) print(names[5]) print('----') # If I'm not mistaken I can just for loop this- for name in names: print(name)
4,229
https://github.com/lourenco-cunha/woocommerce-orders-bot/blob/master/models/orders.js
Github Open Source
Open Source
MIT
2,018
woocommerce-orders-bot
lourenco-cunha
JavaScript
Code
139
485
'use strict'; const _ = require("lodash"); function Orders(response) { this.orders = _.map(response, o => new Order(o)); //TODO set pagination info? } function Order(wcOrder) { function Product(wcProduct) { this.id = wcProduct.variation_id || wcProduct.product_id; this.quantity = wcProduct.quantity; this.total = wcProduct.subtotal; this.metadata = _.map(wcProduct.meta_data, m => {return {key:m.key, val: m.value}}); } function vat(){ var m = _.find(wcOrder.meta_data, ['key', '_vat_number']); return m ? m.value : null; } this.number = wcOrder.number; this.date_gmt = wcOrder.date_created_gmt; this.status = wcOrder.status; this.addr = { shipping: wcOrder.shipping, billing: wcOrder.billing }; this.payment = { method: wcOrder.payment_method_title, total: wcOrder.total, shipping: wcOrder.shipping_total, date_gmt: wcOrder.date_paid_gmt, vat: vat() }; this.products = _.map(wcOrder.line_items, p => new Product(p)); this.coupons = _.map(c => c.code); this.fees = _.map(f => f.code); this.customer_note = wcOrder.customer_note; } module.exports.orders = function(response) { return new Orders(response); }; module.exports.detail = function(response) { return new Order(response); }; module.exports.notes = function(response) { //return new Notes(response); };
47,404
https://github.com/cytech/scheduler-InvoiceNinja/blob/master/Resources/views/categories/index.blade.php
Github Open Source
Open Source
Apache-2.0, MIT
2,021
scheduler-InvoiceNinja
cytech
PHP
Code
198
979
@extends('Scheduler::partials._master') @section('content') <div class="container col-lg-12"> <div class="row"> <div class="col-lg-12"> <a href="{!! route('scheduler.categories.create') !!}" class="btn btn-success"><i class="fa fa-fw fa-plus"></i> {{ trans('Scheduler::texts.create_category') }}</a> </div> </div> <br/> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-fw fa-table fa-fw"></i>{{ trans('Scheduler::texts.categories') }} </h3> </div> {{--@include('Scheduler::layouts._alerts')--}} <div class="panel-body"> <table id="dt-categoriestable" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>ID</th> <th>{{ trans('Scheduler::texts.category_name') }}</th> <th>{{ trans('Scheduler::texts.category_text_color') }}</th> <th>{{ trans('Scheduler::texts.category_bg_color') }}</th> <th>Actions</th> </tr> </thead> <tbody> @foreach($categories as $category) <tr id="{!! $category->id !!}"> <td>{!! $category->id !!}</td> <td>{!! $category->name !!}</td> <td>{!! $category->text_color !!}&nbsp;&nbsp;&nbsp;<i class="fa fa-square" style="color:{!! $category->text_color !!}"></i> </td> <td>{!! $category->bg_color !!}&nbsp;&nbsp;&nbsp;<i class="fa fa-square" style="color:{!! $category->bg_color !!}"></i> </td> <td> <a class="btn btn-primary iframe" href="{{ route('scheduler.categories.edit', [$category->id]) }}"><i class="fa fa-fw fa-edit"></i>{{ trans('Scheduler::texts.edit') }}</a> @if($category->id > 9) {!! Form::button('<i class="fa fa-fw fa-trash"></i>'.trans('Scheduler::texts.delete'), ['type' => 'button','class' => 'btn btn-danger delete-button', 'data-id'=> $category->id]) !!} @endif </td> </tr> @endforeach </tbody> </table> <script> $(function () { $('#dt-categoriestable').on('click','.delete-button',function () { var id = ($(this).data('id')); pconfirm_def.text = '{!! trans('Scheduler::texts.delete_warning') !!}'; new PNotify(pconfirm_def).get().on('pnotify.confirm', function () { $.post('{!! url('/scheduler/categories/delete/') !!}' + '/' + id, { }).done(function () { pnotify('{!! trans('Scheduler::texts.deleted_item_success') !!}', 'success'); $("#" + id).hide(); }).fail(function (data) { pnotify(data.responseJSON.error, 'error'); }); }).on('pnotify.cancel', function () { //Do Nothing }); }) }); </script> </div> </div> </div> </div> @stop @section('javascript') @stop
46,764
https://github.com/RahulMisra2000/auth0-angular-samples/blob/master/04-Authorization/src/app/auth/auth0-variables.ts
Github Open Source
Open Source
MIT
null
auth0-angular-samples
RahulMisra2000
TypeScript
Code
46
197
interface AuthConfig { clientID: string; domain: string; callbackURL: string; apiUrl: string; } //export const AUTH_CONFIG: AuthConfig = { // clientID: '{CLIENT_ID}', // domain: '{DOMAIN}', // callbackURL: 'http://localhost:3000/callback', // apiUrl: '{API_IDENTIFIER}' //}; export const AUTH_CONFIG: AuthConfig = { clientID: 'Qcq75xR4VjcLRzyUx0GjrMKDJE5dh7po', domain: 'rahulmisra2000.auth0.com', callbackURL: 'http://localhost:4200/callback', apiUrl: 'https://api-namespace1-on-portal' };
5,653
https://github.com/BorisMR/foundapi/blob/master/app.js
Github Open Source
Open Source
BSD-3-Clause
null
foundapi
BorisMR
JavaScript
Code
224
810
var bodyParser = require('body-parser'); var path = require('path'); var mongoose = require('mongoose'); var express = require('express'); var app = express(); mongoose.connect('mongodb://localhost/foundapidb'); /* === MODELOS === */ var Libro = require('./app/models/libro'); var Serie = require('./app/models/serie'); /* === MIDDLEWARE === */ app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static(path.join(__dirname, 'public'))); /* === ROUTES === */ var router = express.Router(); router.get('/', function (req, res) { console.log('mw used'); next(); }); //almacena un libro //POST http://localhost:8008/api/libros router.route('/libros').post(function (req, res) { var libro = new Libro(); libro.nombre = req.body.nombre; libro.publicacion = req.body.publicacion; libro.save(function (err) { if (err) res.send(err); res.json({message: 'Libro creado!'}); }); }); //obtiene todos los libros //GET http://localhost:8008/api/libros router.route('/libros').get(function (req, res) { Libro.find(function (err, libros) { if (err) res.send(err); res.json(libros); }); }); /* opera segun id http://localhost:8008/api/libros/:libro_id */ router.route('/libros/:libro_id') //get by id .get(function (req, res) { Libro.findById(req.params.libro_id, function (err, libro) { if (err) res.send(err); res.json(libro); }); }) //update by id .put(function (req, res) { Libro.findById(req.params.libro_id, function (err, libro) { if (err) res.send(err); libro.nombre = req.body.nombre; libro.publicacion = req.body.publicacion; libro.save(function (err) { if (err) res.send(err); res.json({ message: 'Libro actualizado!'}); }) }); }) //delete by id .delete(function (req, res) { Libro.remove({ _id: req.params.libro_id }, function (err, libro) { if (err) res.send(err); res.send({ message : 'Libro eliminado!'}); }); }); //prefix /api app.use('/api', router); /* === INICIAR SERVIDOR === */ var port = process.env.PORT || 8008; app.listen(port, function() { console.log('Server Started on port:'+ port); });
47,080
https://github.com/mtiendar/arconesycanastas.pe/blob/master/database/migrations/2020_03_05_161701_create_datos_fiscales_table.php
Github Open Source
Open Source
MIT
null
arconesycanastas.pe
mtiendar
PHP
Code
113
691
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateDatosFiscalesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('datos_fiscales', function (Blueprint $table) { $table->engine ='InnoDB'; $table->charset = 'utf8mb4'; $table->collation = 'utf8mb4_unicode_ci'; $table->bigIncrements('id'); $table->string('nom_o_raz_soc',60)->comment('Nombre o razón social'); $table->string('rfc',20)->comment('RFC'); $table->string('lad_fij',4)->nullable()->comment('Lada del teléfono fijo'); $table->string('tel_fij',15)->nullable()->comment('Teléfono fijo'); $table->string('ext',10)->nullable()->comment('Extensión'); $table->string('lad_mov',4)->comment('Lada del teléfono móvil'); $table->string('tel_mov',15)->comment('Teléfono móvil'); $table->string('calle',45)->comment('Calle'); $table->string('no_ext',8)->comment('Número exterior'); $table->string('no_int',30)->nullable()->comment('Número interior'); $table->string('pais',40)->comment('País'); $table->string('ciudad',50)->comment('Ciudad'); $table->string('col',40)->comment('Colonia'); $table->string('del_o_munic',50)->comment('Delegación o Municipio'); $table->string('cod_post',6)->comment('Código Postal'); $table->string('corr',75)->comment('Correo'); $table->unsignedBigInteger('user_id')->comment('Foreign Key de users'); $table->foreign('user_id')->references('id')->on('users')->onUpdate('restrict')->onDelete('cascade'); $table->string('created_at_dat_fisc',75)->nullable()->comment('Correo del usuario que realizo el registro'); $table->string('updated_at_dat_fisc',75)->nullable()->comment('Correo del usuario que realizo la última modificación'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('datos_fiscales'); } }
4,161
https://github.com/kalkin/wingo/blob/master/heads/doc.go
Github Open Source
Open Source
WTFPL
2,015
wingo
kalkin
Go
Code
34
46
/* package heads manages state and geometry information for each physical active head detected by Xinerama. This package is also responsible for tracking which workspaces are visible and which are hidden. */ package heads
18,800
https://github.com/kmadden84/techdegree-project-9/blob/master/db/index.js
Github Open Source
Open Source
MIT
null
techdegree-project-9
kmadden84
JavaScript
Code
163
467
'use strict'; var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var basename = path.basename(module.filename); const options = { dialect: 'sqlite', storage: 'fsjstd-restapi.db', operatorsAliases: false, sync: { force: false, alter: true } // define: { // timestamps: false, // }, }; const sequelize = new Sequelize(options); sequelize .authenticate() .then(() => { console.log('Synchronizing the models with the database...'); // return sequelize.sync(); }) .then(function(err) { console.log('Connection has been established successfully.'); }) .catch(function (err) { console.log('Unable to connect to the database:', err); }); /** * Create HTTP server. */ /** * Listen on provided port, on all network interfaces. */ const models = {}; // Import all of the models. fs .readdirSync(path.join(__dirname, 'models')) .forEach((file) => { console.info(`Importing database model from file: ${file}`); const model = sequelize.import(path.join(__dirname, 'models', file)); models[model.name] = model; }); // If available, call method to create associations. Object.keys(models).forEach((modelName) => { if (models[modelName].associate) { console.info(`Configuring the associations for the ${modelName} model...`); models[modelName].associate(models); } }); module.exports = { sequelize, Sequelize, models, };
33,311
https://github.com/scalajs-io/phaser/blob/master/src/main/scala/io/scalajs/dom/html/phaser/BitmapText.scala
Github Open Source
Open Source
Apache-2.0
2,021
phaser
scalajs-io
Scala
Code
469
889
package io.scalajs.dom.html.phaser import io.scalajs.dom.html.pixijs import scala.scalajs.js import scala.scalajs.js.annotation.JSGlobal /** * BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to * match the font structure. * * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability * to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by * processing the font texture in an image editor, applying fills and any other effects required. * * To create multi-line text insert \r, \n or \r\n escape codes into the text string. * * If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly * updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText. * @param game A reference to the currently running game. * @param x X coordinate to display the BitmapText object at. * @param y Y coordinate to display the BitmapText object at. * @param font The key of the BitmapText as stored in Phaser.Cache. * @param text The text that will be rendered. This can also be set later via BitmapText.text. * @param size The size the font will be rendered at in pixels. * @param align Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text. * @see https://phaser.io/docs/2.6.2/Phaser.BitmapText.html */ @js.native @JSGlobal("Phaser.BitmapText") class BitmapText(var game: Phaser.Game, override var x: Double, override var y: Double, val font: String, val text: String = js.native, val size: Double = js.native, val align: String = js.native) extends pixijs.DisplayObjectContainer with Phaser.Component.Core with Phaser.Component.Angle with Phaser.Component.AutoCull with Phaser.Component.Bounds with Phaser.Component.Destroy with Phaser.Component.FixedToCamera with Phaser.Component.InputEnabled with Phaser.Component.InWorld with Phaser.Component.LifeSpan with Phaser.Component.PhysicsBody with Phaser.Component.Reset { /** * The angle property is the rotation of the Game Object in degrees from its original orientation. * * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * * Values outside this range are added to or subtracted from 360 to obtain a value within the range. * For example, the statement player.angle = 450 is the same as player.angle = 90. * * If you wish to work in radians instead of degrees you can use the property rotation instead. * Working in radians is slightly faster as it doesn't have to perform any calculations. */ override var angle: Double = js.native /** * Base destroy method for generic display objects. */ override def destroy(): Unit = js.native /** * Base destroy method for generic display objects. */ override def destroy(destroyChildren: Boolean): Unit = js.native }
45,741
https://github.com/percussion/percussioncms/blob/master/deployer/src/test/java/com/percussion/deployer/objectstore/idtypes/PSApplicationIdContextTest.java
Github Open Source
Open Source
LicenseRef-scancode-dco-1.1, Apache-2.0, OFL-1.1, LGPL-2.0-or-later
2,023
percussioncms
percussion
Java
Code
629
3,117
/* * Copyright 1999-2023 Percussion Software, Inc. * * 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.percussion.deployer.objectstore.idtypes; import com.percussion.design.objectstore.PSConditional; import com.percussion.design.objectstore.PSDataMapping; import com.percussion.design.objectstore.PSDisplayMapper; import com.percussion.design.objectstore.PSDisplayText; import com.percussion.design.objectstore.PSEntry; import com.percussion.design.objectstore.PSExtensionCall; import com.percussion.design.objectstore.PSExtensionParamValue; import com.percussion.design.objectstore.PSHtmlParameter; import com.percussion.design.objectstore.PSParam; import com.percussion.design.objectstore.PSTextLiteral; import com.percussion.design.objectstore.PSUISet; import com.percussion.design.objectstore.PSUrlRequest; import com.percussion.design.objectstore.PSXmlField; import com.percussion.extension.PSExtensionRef; import com.percussion.util.PSCollection; import com.percussion.xml.PSXmlDocumentBuilder; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Unit test for the {@link PSApplicationIdContext} class. */ public class PSApplicationIdContextTest extends TestCase { /** * Construct this unit test * * @param name The name of this test. */ public PSApplicationIdContextTest(String name) { super(name); } /** * Test serializing to and from xml, as well as equals method. * * @throws Exception if there are any errors. */ public void testXml() throws Exception { PSAppCEItemIdContext ceItemctx; int[] fieldTypes = { PSAppCEItemIdContext.TYPE_APPLY_WHEN, PSAppCEItemIdContext.TYPE_CHOICES, PSAppCEItemIdContext.TYPE_DATA_LOCATOR, PSAppCEItemIdContext.TYPE_DEFAULT_UI, PSAppCEItemIdContext.TYPE_DEFAULT_VALUE, PSAppCEItemIdContext.TYPE_INPUT_TRANSLATION, PSAppCEItemIdContext.TYPE_OUTPUT_TRANSLATION, PSAppCEItemIdContext.TYPE_VALIDATION_RULE, PSAppCEItemIdContext.TYPE_VISIBILITY_RULE, PSAppCEItemIdContext.TYPE_READ_ONLY_RULES, PSAppCEItemIdContext.TYPE_CHOICE_FILTER }; for (int i = 0; i < fieldTypes.length; i++) { ceItemctx = new PSAppCEItemIdContext(fieldTypes[i]); assertTrue(ceItemctx.equals(testXml(ceItemctx))); } PSAppNamedItemIdContext namedItemIdCtx; int[] namedTypes = { PSAppNamedItemIdContext.TYPE_APP_FLOW, PSAppNamedItemIdContext.TYPE_CE_FIELD, PSAppNamedItemIdContext.TYPE_CHILD_ITEM, PSAppNamedItemIdContext.TYPE_CONTROL, PSAppNamedItemIdContext.TYPE_DISPLAY_MAPPING, PSAppNamedItemIdContext.TYPE_FIELD_SET, PSAppNamedItemIdContext.TYPE_FUNCTION_CALL, PSAppNamedItemIdContext.TYPE_ITEM_FIELD, PSAppNamedItemIdContext.TYPE_PARAM, PSAppNamedItemIdContext.TYPE_PROCESS_CHECK, PSAppNamedItemIdContext.TYPE_PSPROPERTY, PSAppNamedItemIdContext.TYPE_RESULT_PAGE, PSAppNamedItemIdContext.TYPE_SIMPLE_CHILD_VALUE, PSAppNamedItemIdContext.TYPE_STYLESHEET_SET, PSAppNamedItemIdContext.TYPE_SYS_DEF_INIT_PARAMS, PSAppNamedItemIdContext.TYPE_SYS_DEF_INPUT_DATA_EXITS, PSAppNamedItemIdContext.TYPE_SYS_DEF_RESULT_DATA_EXITS }; for (int i = 0; i < namedTypes.length; i++) { namedItemIdCtx = new PSAppNamedItemIdContext(namedTypes[i], "name" + i); assertTrue(namedItemIdCtx.equals(testXml(namedItemIdCtx))); } PSAppIndexedItemIdContext indexedItemIdCtx; int[] indexedTypes = { PSAppIndexedItemIdContext.TYPE_CONDITIONAL_EXIT, PSAppIndexedItemIdContext.TYPE_CONDITIONAL_REQUEST, PSAppIndexedItemIdContext.TYPE_CONDITIONAL_STYLESHEET, PSAppIndexedItemIdContext.TYPE_CUSTOM_ACTION_GROUP, PSAppIndexedItemIdContext.TYPE_RULE }; for (int i = 0; i < indexedTypes.length; i++) { indexedItemIdCtx = new PSAppIndexedItemIdContext(indexedTypes[i], i); assertTrue(indexedItemIdCtx.equals(testXml(indexedItemIdCtx))); } PSAppConditionalIdContext ceCondctx = new PSAppConditionalIdContext( new PSConditional(new PSTextLiteral("a"), PSConditional.OPTYPE_EQUALS, new PSHtmlParameter("b")), PSAppConditionalIdContext.TYPE_VALUE); assertTrue(ceCondctx.equals(testXml(ceCondctx))); PSExtensionParamValue[] params = new PSExtensionParamValue[2]; params[0] = new PSExtensionParamValue(new PSHtmlParameter("foo")); params[1] = new PSExtensionParamValue(new PSTextLiteral("bar")); PSExtensionRef ref = new PSExtensionRef("java", "myctx", "myExt"); PSExtensionCall call = new PSExtensionCall(ref, params); PSAppExtensionCallIdContext extCallCtx = new PSAppExtensionCallIdContext(call); assertTrue(extCallCtx.equals(testXml(extCallCtx))); PSAppExtensionCallIdContext extCallCtx2 = new PSAppExtensionCallIdContext(call, 3); assertTrue(extCallCtx2.equals(testXml(extCallCtx2))); PSAppExtensionParamIdContext extParamCtx = new PSAppExtensionParamIdContext(0, params[0]); assertTrue(extParamCtx.equals(testXml(extParamCtx))); PSAppExtensionParamIdContext extParamCtx2 = new PSAppExtensionParamIdContext(0, params[0]); assertEquals(extParamCtx, extParamCtx2); extParamCtx2.setParamName("paramName"); // name should be ignored in equals assertEquals(extParamCtx, extParamCtx2); assertEquals(extParamCtx2.getParamName(), "paramName"); assertTrue(extParamCtx2.equals(testXml(extParamCtx2))); PSUISet uiSet = new PSUISet(); PSAppUISetIdContext ceUISetCtx = new PSAppUISetIdContext(uiSet); assertTrue(ceUISetCtx.equals(testXml(ceUISetCtx))); uiSet.setName("test"); PSAppUISetIdContext ceUISetCtx2 = new PSAppUISetIdContext(uiSet); assertTrue(ceUISetCtx2.equals(testXml(ceUISetCtx2))); assertTrue(!ceUISetCtx.equals(testXml(ceUISetCtx2))); PSDisplayMapper dispMap = new PSDisplayMapper("test"); dispMap.setId(2); PSAppDisplayMapperIdContext ceDispMapCtx = new PSAppDisplayMapperIdContext(dispMap); assertTrue(ceDispMapCtx.equals(testXml(ceDispMapCtx))); PSEntry entry = new PSEntry("45", new PSDisplayText("label")); entry.setSequence(2); PSAppEntryIdContext entryCtx = new PSAppEntryIdContext(entry); assertTrue(entryCtx.equals(testXml(entryCtx))); PSCollection urlparams = new PSCollection(PSParam.class); PSUrlRequest req = new PSUrlRequest("foo", null, urlparams); PSAppUrlRequestIdContext urlCtx = new PSAppUrlRequestIdContext(req); assertTrue(urlCtx.equals(testXml(urlCtx))); req = new PSUrlRequest(null, "bar", urlparams); urlCtx = new PSAppUrlRequestIdContext(req); assertTrue(urlCtx.equals(testXml(urlCtx))); req = new PSUrlRequest((String) null, null, urlparams); urlCtx = new PSAppUrlRequestIdContext(req); assertTrue(urlCtx.equals(testXml(urlCtx))); PSDataMapping dataMapping = new PSDataMapping(new PSXmlField("testXml"), new PSTextLiteral("testLit")); PSAppDataMappingIdContext dataMappingCtx = new PSAppDataMappingIdContext( dataMapping, PSAppDataMappingIdContext.TYPE_BACK_END); assertTrue(dataMappingCtx.equals(testXml(dataMappingCtx))); PSAppDataMappingIdContext dataMappingCtx2 = new PSAppDataMappingIdContext( dataMapping, PSAppDataMappingIdContext.TYPE_XML); assertTrue(dataMappingCtx2.equals(testXml(dataMappingCtx2))); PSAppDataMappingIdContext dataMappingCtx3 = new PSAppDataMappingIdContext( dataMapping, PSAppDataMappingIdContext.TYPE_COND); assertTrue(dataMappingCtx3.equals(testXml(dataMappingCtx3))); // set parents extParamCtx.setParentCtx(extCallCtx); assertTrue(extParamCtx.equals(testXml(extParamCtx))); extCallCtx.setParentCtx(ceCondctx); assertTrue(extParamCtx.equals(testXml(extParamCtx))); assertTrue(extParamCtx.getNextRootCtx().equals(ceCondctx)); assertTrue(extParamCtx.getCurrentRootCtx().equals(ceCondctx)); assertTrue(extParamCtx.getNextRootCtx().equals(extCallCtx)); assertTrue(extParamCtx.getCurrentRootCtx().equals(extCallCtx)); assertTrue(extParamCtx.getNextRootCtx().equals(extParamCtx)); assertTrue(extParamCtx.getCurrentRootCtx().equals(extParamCtx)); extParamCtx.resetCurrentRootCtx(); assertTrue(extParamCtx.getNextRootCtx().equals(extParamCtx)); extParamCtx.resetCurrentRootCtx(); assertTrue(extParamCtx.getNextRootCtx().equals(extCallCtx)); extParamCtx.resetCurrentRootCtx(); assertTrue(extParamCtx.getNextRootCtx().equals(ceCondctx)); } /** * Test serializing to and from xml, as well as equals method. * * @param ctx The context to test, assumed not <code>null</code>. * * @return The serialized/deserialized context, never <code>null</code>. * * @throws Exception if there are any errors. */ private PSApplicationIdContext testXml(PSApplicationIdContext ctx) throws Exception { System.err.println("testing xml for ctx: " + ctx.getDisplayText()); Document doc = PSXmlDocumentBuilder.createXmlDocument(); Element el = ctx.toXml(doc); return PSApplicationIDContextFactory.fromXml(el); } // collect all tests into a TestSuite and return it public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new PSApplicationIdContextTest("testXml")); return suite; } }
28,347
https://github.com/maxreader/custom-map-colors/blob/master/data-updates.lua
Github Open Source
Open Source
MIT
null
custom-map-colors
maxreader
Lua
Code
3
35
require("code.entities-and-paths") require("code.fancy-trees") require("code.map-tiles-code")
15,319
https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Rendering/Rendering/SortKey.cs
Github Open Source
Open Source
MIT
2,023
FocusEngine
phr00t
C#
Code
76
191
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; namespace Xenko.Rendering { /// <summary> /// Sort key used /// </summary> public struct SortKey : IComparable<SortKey> { public ulong Value; public int Index; public int StableIndex; public int CompareTo(SortKey other) { var result = Value.CompareTo(other.Value); return result != 0 ? result : StableIndex.CompareTo(other.StableIndex); } } }
41,966
https://github.com/socialsky-io/offline-license-server/blob/master/main_extras.go
Github Open Source
Open Source
Apache-2.0
2,021
offline-license-server
socialsky-io
Go
Code
217
732
/* Copyright AppsCode Inc. 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. */ //nolint package main import ( "bytes" "fmt" "time" "github.com/appscodelabs/offline-license-server/pkg/server" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer/html" gdrive "gomodules.xyz/gdrive-utils" "gomodules.xyz/x/log" ) func main_MD_HTML() { source := `Hi Tamal, Thanks for your interest in stash. Here is the link to the license for Kubernetes cluster: xyz-abc https://appscode.com Regards, AppsCode Team ` md := goldmark.New( goldmark.WithExtensions(extension.GFM), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( html.WithHardWraps(), html.WithXHTML(), ), ) var buf bytes.Buffer if err := md.Convert([]byte(source), &buf); err != nil { panic(err) } fmt.Println(buf.String()) } func main_sheets() { si, err := gdrive.NewSpreadsheet("1evwv2ON94R38M-Lkrw8b6dpVSkRYHUWsNOuI7X0_-zA") // Share this sheet with the service account email if err != nil { log.Fatalf("Unable to retrieve Sheets client: %v", err) } info := server.LogEntry{ LicenseForm: server.LicenseForm{ Name: "Fahim Abrar", Email: "fahimabrar@appscode.com", Product: "Kubeform Community", Cluster: "bad94a42-0210-4c81-b07a-99bae529ec14", }, Timestamp: time.Now().UTC().Format(time.RFC3339), } err = server.LogLicense(si, info) if err != nil { log.Fatal(err) } }
41,394
https://github.com/oucsaw/silver/blob/master/silver/api/exceptions.py
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, Apache-2.0
2,016
silver
oucsaw
Python
Code
34
78
from rest_framework import status from rest_framework.exceptions import APIException class APIConflictException(APIException): status_code = status.HTTP_409_CONFLICT default_detail = 'The request could not be completed due to a conflict ' \ 'with the current state of the resource.'
28,553
https://github.com/restato/bunnybook/blob/master/backend/notification/models.py
Github Open Source
Open Source
MIT
2,022
bunnybook
restato
Python
Code
84
273
import datetime as dt from typing import Optional, Dict from uuid import UUID from pydantic import BaseModel from sqlalchemy import Column, Table, ForeignKey, Boolean from sqlalchemy.dialects.postgresql import JSON from database.core import metadata from database.utils import uuid_pk, created_at, PgUUID notification = Table( "notification", metadata, uuid_pk(), created_at(index=True), Column("profile_id", PgUUID, ForeignKey("profile.id", ondelete="CASCADE"), nullable=False), Column("data", JSON, nullable=False), Column("read", Boolean, server_default="false"), Column("visited", Boolean, server_default="false") ) class NotificationData(BaseModel): event: str payload: Dict class Notification(BaseModel): id: Optional[UUID] created_at: Optional[dt.datetime] profile_id: UUID data: NotificationData read: bool = False visited: bool = False
31,996
https://github.com/googleinterns/vectio/blob/master/homatransport/src/transport/HomaConfigDepot.h
Github Open Source
Open Source
Apache-2.0
2,020
vectio
googleinterns
C
Code
835
1,627
/* Copyright (c) 2015-2016 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __HOMA_CONFIG_DEPOT_H_ #define __HOMA_CONFIG_DEPOT_H_ #include "omnetpp.h" #include "common/Minimal.h" // This class is the ultimate place for storing all config parameters. All other // classes will get a pointer to this class and can read params from this class HomaConfigDepot { public: HomaConfigDepot(cComponent* ownerTransport); ~HomaConfigDepot(){} /** * Corresponding enum values for SenderScheme config param. */ enum SenderScheme { OBSERVE_PKT_PRIOS = 0, // Highest prio homa pkt first SRBF, // Pkt of shortest remaining mesg first UNDEFINED }; public: cComponent* ownerTransport; // Contains the parameters defined in the xml file config.xml in under // "/topologyConfig/hostConfig[@id=HostId]/transportConfig" section. cXMLElement* xmlConfig; // NIC link speed (in Gb/s) connected to this host. This parameter will be // read from the omnetpp.ini config file. int nicLinkSpeed; // RTT is computed as travel time of a full ethernet frame in one way and a // short grant packet in the other way, on the longest path in the topology. simtime_t rtt; // RTT in bytes for the topology, given as a configuration parameter. uint16_t rttBytes; // This parameter is read from the omnetpp.ini config file and provides an // upper bound on the total allowed outstanding bytes. It is necessary for // the rxScheduler to check that the total outstanding bytes is smaller than // this value every time a new grant is to be sent. uint32_t maxOutstandingRecvBytes; // udp ports assigned to this transprt int localPort; int destPort; // Maximum possible data bytes allowed in grant uint32_t grantMaxBytes; // Total number of available priorities uint16_t allPrio; // Total priority levels available for adaptive scheduling when adaptive // scheduling is enabled. uint16_t adaptiveSchedPrioLevels; // Number of senders that receiver tries to keeps granted cuncurrently to // avoid its bandwidth wasted in one or more of the these senders stops // sending. This number is at most as large as adaptiveSchedPrioLevels uint16_t numSendersToKeepGranted; // priod intervals at which the transport fires signals that are // collected by GlobalSignalListener. double signalEmitPeriod; // If true, network traffic bytes from grant packets will be accounted in // when computing CBF and unscheduled priority cutoff sizes. bool accountForGrantTraffic; // Total number of priorities that PrioResolver would use to resolve // priorities. uint16_t prioResolverPrioLevels; // Specifies which priority resolution mode should be used for unscheduled // packets. Resolution modes are defined in PrioResolver class. const char* unschedPrioResolutionMode; // Specifies for the unsched prio level, how many times prio p_i will be // used comparing to p_i-1 (p_i is higher prio). Cutoff weight are used // in PrioResolver class. double unschedPrioUsageWeight; // If unschedPrioResolutionMode is set to EXPLICIT, then this string defines // the priority cutoff points of unsched bytes for the remaining message // sizes. Example would be "100 1500 9000" std::vector<uint32_t> explicitUnschedPrioCutoff; // Defines the type of logic sender uses for transmitting messages and pkts const char* senderScheme; // Specifies the scheduler type. True, means round robin scheduler and false // is for SRBF scheduler. bool isRoundRobinScheduler; // If receiver inbound link is idle for longer than (link speed X // bwCheckInterval), while there are senders waiting for grants, we consider // receiver bw is wasted. -1 means don't check for the bw-waste. int linkCheckBytes; // Specifies that only first cbfCapMsgSize bytes of a message must be used // in computing the cbf function. uint32_t cbfCapMsgSize; // This value is in bytes and determines that this number of last scheduled // bytes of the message will be send at priority equal to unscheduled // priorites. The default is 0 bytes. uint32_t boostTailBytesPrio; // Number data bytes to be packed in request packet. uint32_t defaultReqBytes; // Maximum number of unscheduled data bytes that will be sent in unsched. // packets except the data bytes in request packet. uint32_t defaultUnschedBytes; // True means that scheduler would use // (1-avgUnscheduledRate)*maxOutstandingRecvBytes as the cap for number of // scheduled bytes allowed outstanding. bool useUnschRateInScheduler; // Only for simulation purpose, we allow the transport to be aware of // workload type. The value must be similar to WorkloadSynthesizer // workloadType. const char* workloadType; private: // Enum-ed corresponding value for SenderScheme param. Provided for doing // faster runtime checks based on SenderScheme values. SenderScheme sxScheme; public: /** * getter method for SenderScheme enum-ed param. */ const SenderScheme getSenderScheme() {return sxScheme;} private: void paramToEnum(); }; #endif
27,813
https://github.com/rmachielse/ember-data-paperclip/blob/master/tests/integration/helpers/file-url-test.js
Github Open Source
Open Source
MIT
2,017
ember-data-paperclip
rmachielse
JavaScript
Code
88
301
import { expect } from 'chai'; import { describe, it, beforeEach } from 'mocha'; import { setupComponentTest } from 'ember-mocha'; import hbs from 'htmlbars-inline-precompile'; import File from 'ember-data-paperclip/objects/file'; describe('Integration | Helper | file url', function() { setupComponentTest('file-url', { integration: true }); beforeEach(function() { this.set('file', File.create({ isEmpty: false, path: 'files/:style.jpg' })); }); describe('without a given style', () => { it('renders a file url', function() { this.render(hbs`{{file-url file}}`); expect(this.$().text().trim()).to.equal('files/original.jpg'); }); }); describe('with style thumbnail', () => { it('renders a file url', function() { this.render(hbs`{{file-url file 'thumbnail'}}`); expect(this.$().text().trim()).to.equal('files/thumbnail.jpg'); }); }); });
3,423
https://github.com/CaptainCaffeine/subdivision/blob/master/src/renderer/shaders/light_fragment_shader.glsl
Github Open Source
Open Source
MIT
null
subdivision
CaptainCaffeine
GLSL
Code
13
33
#version 430 core out vec4 colour; void main() { colour = vec4(1.0f); }
45,933
https://github.com/zhangminkefromflydish/RedisX/blob/master/src/main/java/redis/clients/jedis/client/JedisCmdExecutor.java
Github Open Source
Open Source
Apache-2.0
null
RedisX
zhangminkefromflydish
Java
Code
1,328
4,255
package redis.clients.jedis.client; import redis.clients.jedis.JedisSentinelPools; import redis.clients.jedis.ShardedJedisSentinel; import redis.clients.jedis.*; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; public class JedisCmdExecutor { private final Set<Method> methods; private final int scanParallelism; private final int flushParallelism; private final int flushBatch; private final JedisClientConfig jedisClientConfig; private final JedisSentinelPools pools; public JedisCmdExecutor(JedisClientConfig jedisClientConfig) { this.jedisClientConfig = jedisClientConfig; pools = jedisClientConfig.jedisSentinelPools(); methods = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ShardedJedis.class.getDeclaredMethods()))); scanParallelism = jedisClientConfig.prop.getInteger("scan.parallelism", 10); flushParallelism = jedisClientConfig.prop.getInteger("flush.parallelism", 10); flushBatch = jedisClientConfig.prop.getInteger("flush.batch", 10); } public Set<String> commands() { Set<String> set = methods.stream().map(Method::getName).collect(Collectors.toSet()); set.add("sentinels"); set.add("masters"); set.add("dbSize"); set.add("scan"); set.add("flushDB"); return set; } public void run(String[] words, PrintWriter writer) throws Throwable { String cmd = words[0]; LinkedList<String> params = new LinkedList<>(Arrays.asList(words)); params.removeFirst(); if ("sentinels".equalsIgnoreCase(cmd) && params.size() == 0) { doSentinels(writer); return; } if ("masters".equalsIgnoreCase(cmd) && params.size() == 0) { doMasters(writer); return; } if ("dbSize".equalsIgnoreCase(cmd) && params.size() == 0) { doDbSize(writer); return; } if ("scan".equalsIgnoreCase(cmd) && params.size() == 2) { doScan(params.get(0), Integer.parseInt(params.get(1)), writer); return; } if ("flushDB".equalsIgnoreCase(cmd) && params.size() == 1) { if ("Sure".equals(params.get(0))) { doFlushDB(writer); return; } } final Method method = chooseBest(cmd, params.size()); if (method == null) { throw new IllegalStateException("No such CMD: '" + cmd + "' with " + params.size() + " args"); } Class<?>[] pTypes = method.getParameterTypes(); final Object[] args = new Object[pTypes.length]; for (int i = 0; i < pTypes.length; i++) { if (pTypes[i].isArray()) { if (i != pTypes.length - 1 || !pTypes[i].getComponentType().isAssignableFrom(String.class)) { throw new IllegalStateException("Unsupported method: " + method); } String[] arr = new String[params.size() - i]; for (int j = 0; j < arr.length; j++) { arr[j] = params.get(i + j); } args[i] = arr; } else { args[i] = resolveValue(params.get(i), pTypes[i]); } } try (ShardedJedis shardedJedis = new ShardedJedisSentinel(jedisSentinelPools().getShards())) { formatPrint(method.invoke(shardedJedis, args), writer); } catch (InvocationTargetException e) { throw e.getTargetException(); } } private JedisSentinelPools jedisSentinelPools() { return pools; } private void doSentinels(PrintWriter printWriter) { List<String> lst = new LinkedList<>(); for (HostAndPort sentinel : jedisClientConfig.sentinels()) { String str; try (Jedis j = jedisClientConfig.sentinel(sentinel)) { str = sentinel + " " + j.sentinelMasters().size(); } catch (RuntimeException e) { str = sentinel + " " + e.getMessage(); } lst.add(str); } formatPrint(lst, printWriter); } private void doMasters(PrintWriter printWriter) { List<Map<String, String>> masters = null; for (HostAndPort sentinel : jedisClientConfig.sentinels()) { try (Jedis j = jedisClientConfig.sentinel(sentinel)) { masters = j.sentinelMasters(); break; } catch (RuntimeException ignored) { } } if (masters == null) { throw new IllegalStateException("All sentinels not available"); } Map<String, Map<String, String>> map = new HashMap<>(); for (Map<String, String> master : masters) { map.put(master.get("name"), master); } List<String> lst = new LinkedList<>(); for (String masterName : jedisClientConfig.masterNames()) { Map<String, String> master = map.get(masterName); if (master == null) { lst.add(masterName + " --> " + "Not Available"); } else { lst.add(masterName + " --> " + master.get("ip") + ":" + master.get("port") + " " + master.get("num-slaves")); } } formatPrint(lst, printWriter); } private void doDbSize(PrintWriter printWriter) { try (ShardedJedis shardedJedis = new ShardedJedisSentinel(jedisSentinelPools().getShards())) { List<String> lst = new LinkedList<>(); long total = 0; for (Jedis j : shardedJedis.getAllShards()) { String str; try { long size = j.dbSize(); total += size; str = resolveServer(j) + " " + size; } catch (RuntimeException e) { str = resolveServer(j) + " " + e.getMessage(); } lst.add(str); } formatPrint(lst, printWriter); printWriter.println("Total " + total); printWriter.flush(); } } private void doScan(String pattern, int limit, PrintWriter writer) throws InterruptedException { ScanParams scanParams = new ScanParams().match(pattern).count(Math.min(Math.max(1000, limit), 10000)); ExecutorService executorService = Executors.newWorkStealingPool(scanParallelism); try (ShardedJedis shardedJedis = new ShardedJedisSentinel(jedisSentinelPools().getShards())) { List<String> err = new LinkedList<>(); int seq = 0; CompletionService<ScanResult<String>> cs = new ExecutorCompletionService<>(executorService); Map<Future<ScanResult<String>>, Jedis> scanners = new HashMap<>(); long start = System.currentTimeMillis(); for (Jedis j : shardedJedis.getAllShards()) { scanners.put(cs.submit(() -> j.scan("0", scanParams)), j); } while (!scanners.isEmpty() && seq < limit) { Future<ScanResult<String>> future = cs.take(); Jedis j = scanners.remove(future); ScanResult<String> scanResult; try { scanResult = future.get(); } catch (ExecutionException ee) { err.add(resolveServer(j) + " " + ee.getCause().getMessage()); continue; } for (String key : scanResult.getResult()) { if (seq >= limit) { break; } writer.print("(" + (++seq) + ") "); writer.println(key); } writer.flush(); String cursor = scanResult.getCursor(); if (seq < limit && !"0".equals(cursor)) { scanners.put(cs.submit(() -> j.scan(cursor, scanParams)), j); } } long end = System.currentTimeMillis(); writer.println("Found " + seq + " in " + formatDuration(end - start)); writer.flush(); if (!err.isEmpty()) { writer.println("Error " + err.size()); writer.flush(); formatPrint(err, writer); } if (!scanners.isEmpty()) { writer.println("Waiting " + scanners.size() + " scanners to shutdown... "); writer.flush(); while (!scanners.isEmpty()) { scanners.remove(cs.take()); } writer.println("Done"); writer.flush(); } } finally { executorService.shutdownNow(); } } private void doFlushDB(PrintWriter writer) throws InterruptedException, ExecutionException { ScanParams scanParams = new ScanParams().match("*").count(Math.min(Math.max(1000, flushBatch), 10000)); ExecutorService executorService = Executors.newWorkStealingPool(flushParallelism); try (ShardedJedis shardedJedis = new ShardedJedisSentinel(jedisSentinelPools().getShards())) { writer.println("WARNING: flushDB(" + shardedJedis.getAllShards().size() + ") in progress..."); writer.flush(); AtomicLong cnt = new AtomicLong(); AtomicLong total = new AtomicLong(); CompletionService<String> cs = new ExecutorCompletionService<>(executorService); long start = System.currentTimeMillis(); for (Jedis j : shardedJedis.getAllShards()) { cs.submit(() -> { String str; try { long sum = 0; int err = 0; String cursor = "0"; do { ScanResult<String> scanResult = j.scan(cursor, scanParams); if (!scanResult.getResult().isEmpty()) { total.addAndGet(scanResult.getResult().size()); try { long del = j.del(scanResult.getResult().toArray(new String[0])); sum += del; cnt.addAndGet(del); } catch (RuntimeException e) { err++; } } cursor = scanResult.getCursor(); } while (!"0".equals(cursor)); str = resolveServer(j) + " " + sum + (err > 0 ? " (Error: " + err + " times)" : ""); } catch (RuntimeException e) { str = resolveServer(j) + " " + e.getMessage(); } return str; }); } int seq = 0; for (int i = 0; i < shardedJedis.getAllShards().size(); i++) { Future<String> future = cs.take(); writer.print("(" + (++seq) + ") "); writer.println(future.get()); writer.flush(); } long end = System.currentTimeMillis(); writer.println("Deleted " + cnt.get() + " / " + total.get() + " in " + formatDuration(end - start)); writer.flush(); } finally { executorService.shutdown(); } } private static String formatDuration(long millis) { StringBuilder sb = new StringBuilder(); sb.append("."); sb.append(new DecimalFormat("000").format(millis % 1000)); sb.append("s"); long seconds = millis / 1000; if (seconds < 60) { sb.insert(0, seconds); } else { sb.insert(0, new DecimalFormat("00").format(seconds % 60)); } long minutes = seconds / 60; if (minutes > 0) { sb.insert(0, ":"); if (minutes < 60) { sb.insert(0, minutes); } else { sb.insert(0, new DecimalFormat("00").format(minutes % 60)); } } long hours = minutes / 60; if (hours > 0) { sb.insert(0, ":"); sb.insert(0, hours); } return sb.toString(); } private Method chooseBest(String cmd, int paramNum) { Method candidate = null; for (Method method : methods) { if (!method.getName().equalsIgnoreCase(cmd)) { continue; } Class<?>[] pTypes = method.getParameterTypes(); boolean incompatible = false; for (Class<?> pType : pTypes) { if (Map.class.isAssignableFrom(pType)) { incompatible = true; break; } } if (incompatible) { continue; } if (pTypes.length == paramNum) { candidate = method; break; } if (pTypes.length > paramNum) { continue; } if (pTypes[pTypes.length - 1].isArray()) { candidate = method; break; } } return candidate; } private static void formatPrint(Object obj, PrintWriter writer) { if (obj instanceof Collection) { Collection<?> col = (Collection<?>) obj; if (col.isEmpty()) { writer.println("(EmptyCollection)"); } else { Iterator<?> it = col.iterator(); int i = 0; while (it.hasNext()) { writer.print("(" + (++i) + ") "); writer.println(showElement(it.next())); } } } else if (obj instanceof Map) { Map<?, ?> map = (Map<?, ?>) obj; if (map.isEmpty()) { writer.println("(EmptyMap)"); } else { int i = 0; for (Map.Entry<?, ?> entry : map.entrySet()) { writer.print("(" + (++i) + ") "); writer.print(entry.getKey()); writer.print(" --> "); writer.println(showElement(entry.getValue())); } } } else { writer.println(showElement(obj)); } writer.flush(); } private static String showElement(Object element) { if (element == null) { return "null"; } if (element instanceof Tuple) { Tuple tuple = (Tuple) element; DecimalFormat df = new DecimalFormat("#.###"); return df.format(tuple.getScore()) + ": " + tuple.getElement(); } return element.toString(); } private static Object resolveValue(String value, Class<?> clazz) { if (clazz.isAssignableFrom(String.class)) { return value; } if (clazz.isAssignableFrom(Long.class)) { return Long.valueOf(value); } if (clazz.isAssignableFrom(long.class)) { return Long.parseLong(value); } if (clazz.isAssignableFrom(Integer.class)) { return Integer.valueOf(value); } if (clazz.isAssignableFrom(int.class)) { return Integer.parseInt(value); } if (clazz.isAssignableFrom(Double.class)) { return Double.valueOf(value); } if (clazz.isAssignableFrom(double.class)) { return Double.parseDouble(value); } throw new IllegalStateException("Unsupported parameter type: " + clazz); } private static String resolveServer(Jedis jedis) { Client client = jedis.getClient(); return client.getHost() + ":" + client.getPort(); } }
31,218
https://github.com/kungfooman/pcui/blob/master/src/binding/history.js
Github Open Source
Open Source
MIT
2,021
pcui
kungfooman
JavaScript
Code
522
1,340
import Events from './events'; /** * @name HistoryAction * @class * @classdesc A history action * @property {string} name The name of the action * @property {Function} undo The undo function * @property {Function} redo The redo function * @property {boolean} combine Whether to combine with the previous action with the same name. * The effect of combining is merely changing the redo function to be the redo function of this action. * The original undo function is not modified. */ /** * @name History * @class * @classdesc Manages history actions for undo / redo operations. * @property {HistoryAction} currentAction Returns the current history action * @property {HistoryAction} lastAction Returns the last history action * @property {boolean} canUndo Whether we can undo at this time. * @property {boolean} canRedo Whether we can redo at this time. * @augments Events */ class History extends Events { /** * Creates a new pcui.History. */ constructor() { super(); this._actions = []; this._currentActionIndex = -1; this._canUndo = false; this._canRedo = false; } /** * @name History#add * @description Adds a new history action * @param {HistoryAction} action - The action */ add(action) { if (!action.name) { console.error('Trying to add history action without name'); return; } if (!action.undo) { console.error('Trying to add history action without undo method', action.name); return; } if (!action.redo) { console.error('Trying to add history action without redo method', action.name); return; } // if we are adding an action // but we have undone some actions in the meantime // then we should erase the actions that come after our // last action before adding this if (this._currentActionIndex !== this._actions.length - 1) { this._actions = this._actions.slice(0, this._currentActionIndex + 1); } // if combine is true then replace the redo of the current action // if it has the same name if (action.combine && this.currentAction && this.currentAction.name === action.name) { this.currentAction.redo = action.redo; } else { const length = this._actions.push(action); this._currentActionIndex = length - 1; } this.emit('add', action.name); this.canUndo = true; this.canRedo = false; } /** * @name History#undo * @description Undo the last history action */ undo() { if (!this.canUndo) return; const name = this.currentAction.name; try { this.currentAction.undo(); } catch (ex) { console.info('%c(pcui.History#undo)', 'color: #f00'); console.log(ex.stack); return; } this._currentActionIndex--; this.emit('undo', name); if (this._currentActionIndex < 0) { this.canUndo = false; } this.canRedo = true; } /** * @name History#redo * @description Redo the current history action */ redo() { if (!this.canRedo) return; this._currentActionIndex++; try { this.currentAction.redo(); } catch (ex) { console.info('%c(pcui.History#redo)', 'color: #f00'); console.log(ex.stack); return; } this.emit('redo', this.currentAction.name); this.canUndo = true; if (this._currentActionIndex === this._actions.length - 1) { this.canRedo = false; } } /** * @name History#clear * @description Clears all history actions. */ clear() { if (! this._actions.length) return; this._actions.length = 0; this._currentActionIndex = -1; this.canUndo = false; this.canRedo = false; } get currentAction() { return this._actions[this._currentActionIndex] || null; } get lastAction() { return this._actions[this._actions.length - 1] || null; } get canUndo() { return this._canUndo; } set canUndo(value) { if (this._canUndo === value) return; this._canUndo = value; this.emit('canUndo', value); } get canRedo() { return this._canRedo; } set canRedo(value) { if (this._canRedo === value) return; this._canRedo = value; this.emit('canRedo', value); } } export default History;
42,717
https://github.com/Lakshya-Saini/Restaurant-Webapp/blob/master/delete_store.php
Github Open Source
Open Source
MIT
2,021
Restaurant-Webapp
Lakshya-Saini
PHP
Code
27
96
<?php include 'auth/database.php'; if(isset($_GET['id'])) { $store_id = $_GET['id']; $query = "DELETE FROM store WHERE id = '" . $store_id . "'"; mysqli_query($connect, $query); header('Location: store.php'); } ?>
42,724
https://github.com/htdong/mdb-template/blob/master/src/app/ngrx/user/users.reducers.ts
Github Open Source
Open Source
Unlicense
null
mdb-template
htdong
TypeScript
Code
58
178
import { initialState } from '../initial.state'; import { UsersActionTypes } from './users.actions'; export function UsersReducers( state = initialState, { type, payload }) { switch (type) { case UsersActionTypes.GET_MANY_USERS: return Object.assign({}, state, {pending: true, error: null}); case UsersActionTypes.GET_MANY_USERS_SUCCESS: return Object.assign({}, state, {data: payload, pending: false}); case UsersActionTypes.GET_MANY_USERS_ERROR: return Object.assign({}, state, {pending: false, error: 'Error'}); default: return state; } }
11,459
https://github.com/timgates42/embox/blob/master/src/drivers/mmc/core/mmc_host.c
Github Open Source
Open Source
BSD-2-Clause
null
embox
timgates42
C
Code
675
2,628
/** * @file mmc_simple.h * @brief * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 18.10.2019 */ #include <errno.h> #include <limits.h> #include <drivers/block_dev.h> #include <drivers/block_dev/partition.h> #include <drivers/mmc/mmc.h> #include <drivers/mmc/mmc_core.h> #include <drivers/mmc/mmc_host.h> #include <mem/misc/pool.h> #include <util/indexator.h> #include <util/log.h> #define MMC_DEV_QUANTITY OPTION_GET(NUMBER, dev_quantity) #define MMC_DEFAULT_NAME "mmc#" /* Sharp symbol is used for enumeration */ POOL_DEF(mmc_dev_pool, struct mmc_host, MMC_DEV_QUANTITY); INDEX_DEF(mmc_idx, 0, MMC_DEV_QUANTITY); static int mmc_block_ioctl(struct block_dev *bdev, int cmd, void *args, size_t size) { log_debug("NIY"); return 0; } static int mmc_block_read(struct block_dev *bdev, char *buffer, size_t count, blkno_t blkno) { struct mmc_host *mmc; uint32_t arg; struct mmc_request req; log_debug("count %d blkno %d", count, blkno); assert(bdev); assert(buffer); mmc = bdev->privdata; assert(mmc); if (mmc->high_capacity) { arg = blkno; } else { arg = blkno * bdev->block_size; } memset(&req, 0, sizeof(req)); req.cmd.opcode = 17; req.cmd.arg = arg; req.cmd.flags = MMC_RSP_R1B | MMC_DATA_READ; req.data.addr = (uintptr_t) buffer; req.data.blksz = bdev->block_size; req.data.blocks = count / bdev->block_size; assert(mmc->ops); assert(mmc->ops->request); mmc->ops->request(mmc, &req); return bdev->block_size; } static int mmc_block_write(struct block_dev *bdev, char *buffer, size_t count, blkno_t blkno) { struct mmc_host *mmc; uint32_t arg; struct mmc_request req; log_debug("count %d blkno %d", count, blkno); assert(bdev); assert(buffer); mmc = bdev->privdata; assert(mmc); if (mmc->high_capacity) { arg = blkno; } else { arg = blkno * bdev->block_size; } memset(&req, 0, sizeof(req)); req.cmd.opcode = 24; req.cmd.arg = arg; req.cmd.flags = MMC_RSP_R1B | MMC_DATA_WRITE; req.data.addr = (uintptr_t) buffer; req.data.blksz = bdev->block_size; req.data.blocks = count / bdev->block_size; assert(mmc->ops); assert(mmc->ops->request); mmc->ops->request(mmc, &req); return bdev->block_size; } static int mmc_block_probe(void *args) { log_debug("NIY"); return 0; } static const struct block_dev_ops mmc_block_driver = { .name = "MMC driver", .ioctl = mmc_block_ioctl, .read = mmc_block_read, .write = mmc_block_write, .probe = mmc_block_probe, }; struct mmc_host *mmc_alloc_host(void) { struct mmc_host *mmc; char buf[PATH_MAX]; mmc = pool_alloc(&mmc_dev_pool); if (mmc == NULL) { log_error("Failed to alloc mmc_host from pool"); errno = ENOMEM; return NULL; } strncpy(buf, MMC_DEFAULT_NAME, sizeof(buf) - 1); mmc->idx = block_dev_named(buf, &mmc_idx); if (mmc->idx < 0) { log_error("Failed to alloc index for mmc_host"); errno = -mmc->idx; goto free_mmc; } mmc->bdev = block_dev_create(buf, (void *) &mmc_block_driver, mmc); if (mmc->bdev == NULL) { log_error("Failed to create block_device for mmc_host"); goto free_idx; } return mmc; free_idx: assert(mmc); assert(mmc->idx > 0); index_free(&mmc_idx, mmc->idx); free_mmc: assert(mmc); pool_free(&mmc_dev_pool, mmc); return NULL; } int mmc_dev_destroy(struct mmc_host *mmc) { if (mmc->bdev) { block_dev_destroy(mmc->bdev->dev_module); } index_free(&mmc_idx, mmc->idx); pool_free(&mmc_dev_pool, mmc); return 0; } /* Send simple command without data */ int mmc_send_cmd(struct mmc_host *host, int cmd, int arg, int flags, uint32_t *resp) { struct mmc_request req; assert(host); assert(host->ops); assert(host->ops->request); memset(&req, 0, sizeof(req)); req.cmd.opcode = cmd; req.cmd.arg = arg; req.cmd.flags = flags; host->ops->request(host, &req); if (resp) { memcpy(resp, req.cmd.resp, sizeof(uint32_t) * 4); } return 0; } int mmc_sw_reset(struct mmc_host *host) { log_debug("NIY"); return 0; } static void mmc_go_idle(struct mmc_host *host) { /* CMD0 sets card in an inactive state */ mmc_send_cmd(host, 0, 0, 0, NULL); } int mmc_scan(struct mmc_host *host) { assert(host); mmc_go_idle(host); /* The order is important! */ if (!mmc_try_sdio(host)) { log_debug("SDIO detected"); create_partitions(host->bdev); return 0; } mmc_go_idle(host); if (!mmc_try_sd(host)) { log_debug("SD detected"); create_partitions(host->bdev); return 0; } mmc_go_idle(host); if (!mmc_try_mmc(host)) { log_debug("MMC detected"); create_partitions(host->bdev); return 0; } log_debug("Failed to detect any memory card"); return -1; } void mmc_dump_cid(uint32_t *cid) { int man_year, man_mon; static const char mon_name[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; assert(cid); log_debug("MMC CID: %08x %08x %08x %08x", cid[0], cid[1], cid[2], cid[3]); log_debug("MMC info (parsed CID):"); log_debug("Manufacturer ID =0x%2x", cid[0] >> 24); log_debug("OEM/OID =0x%2x%2x", (cid[0] >> 16) & 0xFF, (cid[0] >> 8) & 0xFF); log_debug("Product name =%c%c%c%c%c", (char) (cid[0] & 0xFF), (char) ((cid[1] >> 24) & 0xFF), (char) ((cid[1] >> 16) & 0xFF), (char) ((cid[1] >> 8) & 0xFF), (char) (cid[1] & 0xFF)); log_debug("Revision =0x%02x", (cid[2] >> 24) & 0xFF); log_debug("Serial number =0x%2x%2x%2x%2x", (cid[2] >> 16) & 0xFF, (cid[2] >> 8) & 0xFF, cid[2] & 0xFF, (cid[3] >> 24) & 0xFF); man_year = 2000 + 10 * ((cid[3] >> 16) & 0xFF) + (((cid[3] >> 8) & 0xFF) >> 4); man_mon = (cid[3] >> 8) & 0xF; assert(man_mon < 12); log_debug("Date %s %d", mon_name[man_mon], man_year); /* Avoid warnings if log_level = 0 */ (void) man_year, (void) man_mon, (void) mon_name; }
26,959
https://github.com/bendraaisma-zz/gnuob-api/blob/master/src/main/java/br/com/netbrasoft/gnuob/api/order/PayPalExpressCheckOutWebServiceRepository.java
Github Open Source
Open Source
Apache-2.0
2,016
gnuob-api
bendraaisma-zz
Java
Code
328
1,667
/* * Copyright 2016 Netbrasoft * * 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 br.com.netbrasoft.gnuob.api.order; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.GNUOB_SOAP_ORDER_PAY_PAL_WEBSERVICE_WSDL; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.HTTP_LOCALHOST_8080_GNUOB_SOAP_ORDER_PAY_PAL_WEB_SERVICE_IMPL_WSDL; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.PAY_PAL_EXPRESS_CHECK_OUT_WEB_SERVICE_REPOSITORY_NAME; import static br.com.netbrasoft.gnuob.api.generic.NetbrasoftApiConstants.UNCHECKED_VALUE; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoCheckout; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoCheckoutDetails; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoCheckoutPayment; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoNotification; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoRefundTransaction; import static br.com.netbrasoft.gnuob.api.order.OrderWebserviceWrapperHelper.wrapToDoTransactionDetails; import static java.lang.System.getProperty; import static org.slf4j.LoggerFactory.getLogger; import java.net.MalformedURLException; import java.net.URL; import org.javasimon.aop.Monitored; import org.slf4j.Logger; import org.springframework.stereotype.Repository; import br.com.netbrasoft.gnuob.api.MetaData; import br.com.netbrasoft.gnuob.api.Order; import br.com.netbrasoft.gnuob.api.PayPalExpressCheckOutWebServiceImpl; import br.com.netbrasoft.gnuob.api.PayPalExpressCheckOutWebServiceImplService; @Monitored @Repository(PAY_PAL_EXPRESS_CHECK_OUT_WEB_SERVICE_REPOSITORY_NAME) public class PayPalExpressCheckOutWebServiceRepository<O extends Order> implements ICheckoutWebServiceRepository<O> { private static final Logger LOGGER = getLogger(PayPalExpressCheckOutWebServiceRepository.class); private static final URL WSDL_LOCATION; static { URL url = null; try { url = new URL(getProperty(GNUOB_SOAP_ORDER_PAY_PAL_WEBSERVICE_WSDL, HTTP_LOCALHOST_8080_GNUOB_SOAP_ORDER_PAY_PAL_WEB_SERVICE_IMPL_WSDL)); } catch (final MalformedURLException e) { LOGGER.info(CAN_NOT_INITIALIZE_THE_DEFAULT_WSDL_FROM_0, getProperty(GNUOB_SOAP_ORDER_PAY_PAL_WEBSERVICE_WSDL, HTTP_LOCALHOST_8080_GNUOB_SOAP_ORDER_PAY_PAL_WEB_SERVICE_IMPL_WSDL)); } WSDL_LOCATION = url; } private transient PayPalExpressCheckOutWebServiceImpl payPalExpressCheckOutWebServiceImpl = null; private PayPalExpressCheckOutWebServiceImpl getPayPalExpressCheckOutWebServiceImpl() { if (payPalExpressCheckOutWebServiceImpl == null) { payPalExpressCheckOutWebServiceImpl = new PayPalExpressCheckOutWebServiceImplService(WSDL_LOCATION).getPayPalExpressCheckOutWebServiceImplPort(); } return payPalExpressCheckOutWebServiceImpl; } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doCheckout(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl().doCheckout(wrapToDoCheckout(orderType), credentials) .getReturn(); } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doCheckoutDetails(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl() .doCheckoutDetails(wrapToDoCheckoutDetails(orderType), credentials).getReturn(); } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doCheckoutPayment(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl() .doCheckoutPayment(wrapToDoCheckoutPayment(orderType), credentials).getReturn(); } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doNotification(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl().doNotification(wrapToDoNotification(orderType), credentials) .getReturn(); } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doRefundTransaction(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl() .doRefundTransaction(wrapToDoRefundTransaction(orderType), credentials).getReturn(); } @SuppressWarnings(UNCHECKED_VALUE) @Override public O doTransactionDetails(final MetaData credentials, final O orderType) { return (O) getPayPalExpressCheckOutWebServiceImpl() .doTransactionDetails(wrapToDoTransactionDetails(orderType), credentials).getReturn(); } }
38,484
https://github.com/VitaliaPiliuhina/vividus/blob/master/vividus-plugin-azure-cosmos-db/src/test/java/org/vividus/azure/cosmos/CosmosDbStepsTests.java
Github Open Source
Open Source
Apache-2.0
null
vividus
VitaliaPiliuhina
Java
Code
338
1,142
/* * Copyright 2019-2021 the original author or authors. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vividus.azure.cosmos; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.vividus.azure.cosmos.model.CosmosDbContainer; import org.vividus.context.VariableContext; import org.vividus.softassert.SoftAssert; import org.vividus.util.property.PropertyMappedCollection; import org.vividus.variable.VariableScope; @ExtendWith(MockitoExtension.class) class CosmosDbStepsTests { private static final int CREATED = 201; private static final int NO_CONTENT = 204; private static final int OK = 200; private static final String PARTITION = "partition"; private static final String ID = "id"; private static final int UNAUTHORIZED = 401; private static final Set<VariableScope> SCOPES = Set.of(VariableScope.SCENARIO); private static final String RESULT_SET = "resultSet"; private static final String RESULT = "{}"; private static final String QUERY = "SELECT * FROM DEVS"; private static final String CONTAINER = "container"; private final CosmosDbContainer container = new CosmosDbContainer(); @Mock private VariableContext variableContext; @Mock private PropertyMappedCollection<CosmosDbContainer> containers; @Mock private CosmosDbService cosmosDbService; @Mock private SoftAssert softAssert; @InjectMocks private CosmosDbSteps dbSteps; @BeforeEach void beforeEach() { when(containers.get(CONTAINER, "Unable to find connetion details for Cosmos DB container: %s", CONTAINER)) .thenReturn(container); } @Test void shouldQueryCosmosDatabase() { when(cosmosDbService.executeQuery(container, QUERY)).thenReturn(RESULT); dbSteps.query(QUERY, CONTAINER, SCOPES, RESULT_SET); verify(variableContext).putVariable(SCOPES, RESULT_SET, RESULT); verifyNoInteractions(softAssert); } @Test void shouldInsertItem() { when(cosmosDbService.insert(container, RESULT)).thenReturn(UNAUTHORIZED); dbSteps.insert(RESULT, CONTAINER); verifyAssertion(CREATED); } @Test void shouldUpsertItem() { when(cosmosDbService.upsert(container, RESULT)).thenReturn(UNAUTHORIZED); dbSteps.upsert(RESULT, CONTAINER); verifyAssertion(OK); } @Test void shouldDeleteItem() { when(cosmosDbService.delete(container, RESULT)).thenReturn(UNAUTHORIZED); dbSteps.delete(RESULT, CONTAINER); verifyAssertion(NO_CONTENT); } @Test void shouldReadItemByIdAndPartition() { when(cosmosDbService.readById(container, ID, PARTITION)).thenReturn(RESULT); dbSteps.read(ID, PARTITION, CONTAINER, SCOPES, RESULT_SET); verify(variableContext).putVariable(SCOPES, RESULT_SET, RESULT); verifyNoInteractions(softAssert); } private void verifyAssertion(int expected) { verify(softAssert).assertEquals("Query status code", expected, UNAUTHORIZED); } }
9,405
https://github.com/EL20202/ultimate-crosscode-typedefs/blob/master/modules/game.feature.player.modifiers.d.ts
Github Open Source
Open Source
MIT
null
ultimate-crosscode-typedefs
EL20202
TypeScript
Code
120
622
// requires impact.base.game export {}; declare global { namespace sc { interface Modifier { icon: number; order: number; noPercent?: boolean; } interface MODIFIERS { AIM_SPEED: Modifier; AIM_STABILITY: Modifier; AIMING_MOVEMENT: Modifier; KNOCKBACK: Modifier; RANGED_DMG: Modifier; MELEE_DMG: Modifier; CRITICAL_DMG: Modifier; BREAK_DMG: Modifier; SPIKE_DMG: Modifier; ASSAULT: Modifier; CROSS_COUNTER: Modifier; BERSERK: Modifier; MOMENTUM: Modifier; DASH_INVINC: Modifier; DASH_STEP: Modifier; GUARD_STRENGTH: Modifier; GUARD_SP: Modifier; GUARD_AREA: Modifier; PERFECT_GUARD_WINDOW: Modifier; PERFECT_GUARD_RESET: Modifier; STUN_THRESHOLD: Modifier; OVERHEAT_REDUCTION: Modifier; HP_REGEN: Modifier; SP_REGEN: Modifier; ITEM_GUARD: Modifier; ONCE_MORE: Modifier; XP_PLUS: Modifier; DROP_CHANCE: Modifier; MONEY_PLUS: Modifier; XP_ZERO: Modifier; RANK_PLANTS: Modifier; ITEM_BOOST: Modifier; APPETITE: Modifier; COND_HEALING: Modifier; COND_EFFECT_HEAT: Modifier; COND_EFFECT_COLD: Modifier; COND_EFFECT_SHOCK: Modifier; COND_EFFECT_WAVE: Modifier; COND_EFFECT_ALL: Modifier; COND_GUARD_HEAT: Modifier; COND_GUARD_COLD: Modifier; COND_GUARD_SHOCK: Modifier; COND_GUARD_WAVE: Modifier; SPIDER_SLOW_DOWN_GUARD: Modifier; BEGONE_ICE: Modifier; } var MODIFIERS: MODIFIERS; } }
23,241
https://github.com/CiaccoDavide/DefinitelyTyped/blob/master/types/nginstack__web-framework/lib/dsv/VisualizationFilter.d.ts
Github Open Source
Open Source
MIT
2,022
DefinitelyTyped
CiaccoDavide
TypeScript
Code
42
112
export = VisualizationFilter; declare function VisualizationFilter(name: string, type: string, size: number): void; declare class VisualizationFilter { constructor(name: string, type: string, size: number); name: string; type: string; size: number; targets: any[]; private propertiesToAssign_; assignFrom(obj: { [x: string]: any }): void; getVisibleValue(): any; }
260
https://github.com/InnovateUKGitHub/innovation-funding-service/blob/master/ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/review/repository/ReviewRepository.java
Github Open Source
Open Source
MIT
2,022
innovation-funding-service
InnovateUKGitHub
Java
Code
169
653
package org.innovateuk.ifs.review.repository; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.review.domain.Review; import org.innovateuk.ifs.review.resource.ReviewState; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.workflow.repository.ProcessRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import java.util.List; /** * This interface is used to generate Spring Data Repositories. * For more info: * http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories */ public interface ReviewRepository extends ProcessRepository<Review>, PagingAndSortingRepository<Review, Long> { List<Review> findByTargetCompetitionIdAndActivityState(long competitionId, ReviewState state); boolean existsByParticipantUserIdAndTargetIdAndActivityStateNot(long userId, long targetId, ReviewState state); boolean existsByParticipantUserAndTargetAndActivityStateNot(User user, Application target, ReviewState state); boolean existsByTargetCompetitionIdAndActivityState(long competitionId, ReviewState backingState); @Query("SELECT CASE WHEN count(a.id)>0 THEN TRUE ELSE FALSE END " + "FROM Application a " + "INNER JOIN AssessmentParticipant ap ON ap.competition = a.competition " + "WHERE " + " a.competition.id = :competitionId AND a.inAssessmentReviewPanel=true " + "AND " + " ap.status = org.innovateuk.ifs.invite.domain.ParticipantStatus.ACCEPTED AND " + " ap.role=org.innovateuk.ifs.competition.domain.CompetitionParticipantRole.PANEL_ASSESSOR AND " + " NOT EXISTS (SELECT 1 FROM Review r " + " WHERE " + " r.target=a AND " + " r.participant.user = ap.user AND " + " r.activityState <> org.innovateuk.ifs.review.resource.ReviewState.WITHDRAWN) " ) boolean notifiable(@Param("competitionId") long competitionId); List<Review> findByTargetIdAndActivityStateNot(long applicationId, ReviewState withdrawnState); List<Review> findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(long userId, long competitionId); }
5,940
https://github.com/2sic/2sxc/blob/master/Src/Sxc.Tests/ToSic.Sxc.Tests/LinksAndImages/UrlHelperTests/Obj2UrlMerge.cs
Github Open Source
Open Source
MIT
2,023
2sxc
2sic
C#
Code
127
573
using Microsoft.VisualStudio.TestTools.UnitTesting; using ToSic.Sxc.Web.Url; using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert; namespace ToSic.Sxc.Tests.LinksAndImages.UrlHelperTests { [TestClass] public class Obj2UrlMerge { // Test accessor private string SerializeWithChild(object main, object child) => new ObjectToUrl().SerializeWithChild(main, child, prefix); private const string prefix = "prefix:"; [DataRow((string)null)] [DataRow("")] [DataRow("icon=hello")] [DataRow("icon=hello&value=2")] [TestMethod] public void FirstOnlyString(string ui) { AreEqual(ui, SerializeWithChild(ui, null)); } [DataRow(null, null)] [DataRow("", "")] [DataRow("prefix:icon=hello", "icon=hello")] [DataRow("prefix:icon=hello&prefix:value=2", "icon=hello&value=2")] [TestMethod] public void ChildOnlyString(string exp, string child) { AreEqual(exp, SerializeWithChild(null, child)); } [TestMethod] public void MainObjectChildString() => AreEqual("id=27&name=daniel&prefix:title=title2", SerializeWithChild(new { id = 27, name = "daniel" }, "title=title2")); [TestMethod] public void MainStringChildString() => AreEqual("id=27&name=daniel&prefix:title=title2", SerializeWithChild("id=27&name=daniel", "title=title2")); [TestMethod] public void MainStringChildObject() => AreEqual("id=27&name=daniel&prefix:title=title2", SerializeWithChild("id=27&name=daniel", new { title = "title2"})); [TestMethod] public void MainObjectChildObject() => AreEqual("id=27&name=daniel&prefix:title=title2", SerializeWithChild(new { id = 27, name = "daniel" }, new { title = "title2"})); } }
42,422
https://github.com/namjagbrawa/framework/blob/master/bingo-rpc/bingo-rpc-api/src/main/java/com/bingo/framework/rpc/filter/ExceptionFilter.java
Github Open Source
Open Source
Apache-2.0
2,018
framework
namjagbrawa
Java
Code
356
1,394
package com.bingo.framework.rpc.filter; import java.lang.reflect.Method; import com.bingo.framework.common.exception.BingoException; import com.bingo.framework.common.Constants; import com.bingo.framework.common.extension.Activate; import com.bingo.framework.common.logger.Logger; import com.bingo.framework.common.logger.LoggerFactory; import com.bingo.framework.common.utils.ReflectUtils; import com.bingo.framework.common.utils.StringUtils; import com.bingo.framework.rpc.Filter; import com.bingo.framework.rpc.Invocation; import com.bingo.framework.rpc.Invoker; import com.bingo.framework.rpc.Result; import com.bingo.framework.rpc.RpcContext; import com.bingo.framework.rpc.RpcException; import com.bingo.framework.rpc.RpcResult; import com.bingo.framework.rpc.service.GenericService; /** * ExceptionInvokerFilter * <p> * 功能: * <ol> * <li>不期望的异常打ERROR日志(Provider端)<br> * 不期望的日志即是,没有的接口上声明的Unchecked异常。 * <li>异常不在API包中,则Wrap一层RuntimeException。<br> * RPC对于第一层异常会直接序列化传输(Cause异常会String化),避免异常在Client出不能反序列化问题。 * </ol> * * @author william.liangf * @author ding.lid */ @Activate(group = Constants.PROVIDER) public class ExceptionFilter implements Filter { private final Logger logger; public ExceptionFilter() { this(LoggerFactory.getLogger(ExceptionFilter.class)); } public ExceptionFilter(Logger logger) { this.logger = logger; } public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { try { Result result = invoker.invoke(invocation); if (result.hasException() && GenericService.class != invoker.getInterface()) { try { Throwable exception = result.getException(); // 如果是checked异常,直接抛出 if (! (exception instanceof RuntimeException) && (exception instanceof Exception)) { return result; } // 在方法签名上有声明,直接抛出 try { Method method = invoker.getInterface().getMethod(invocation.getMethodName(), invocation.getParameterTypes()); Class<?>[] exceptionClassses = method.getExceptionTypes(); for (Class<?> exceptionClass : exceptionClassses) { if (exception.getClass().equals(exceptionClass)) { return result; } } } catch (NoSuchMethodException e) { return result; } // 未在方法签名上定义的异常,在服务器端打印ERROR日志 logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + exception.getClass().getName() + ": " + exception.getMessage(), exception); // 异常类和接口类在同一jar包里,直接抛出 String serviceFile = ReflectUtils.getCodeBase(invoker.getInterface()); String exceptionFile = ReflectUtils.getCodeBase(exception.getClass()); if (serviceFile == null || exceptionFile == null || serviceFile.equals(exceptionFile)){ return result; } // 是JDK自带的异常,直接抛出 String className = exception.getClass().getName(); if (className.startsWith("java.") || className.startsWith("javax.")) { return result; } // 是Bingo Framework本身的异常,直接抛出 if (exception instanceof RpcException) { return result; } // 是BingoException,直接抛出,不封装,Edit By ZhangGe if (exception instanceof BingoException) { return result; } // 否则,包装成RuntimeException抛给客户端 return new RpcResult(new RuntimeException(StringUtils.toString(exception))); } catch (Throwable e) { logger.warn("Fail to ExceptionFilter when called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); return result; } } return result; } catch (RuntimeException e) { logger.error("Got unchecked and undeclared exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: " + invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: " + e.getClass().getName() + ": " + e.getMessage(), e); throw e; } } }
1,526