code
stringlengths
46
37.2k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.91
max_line_length
int64
13
399
avg_line_length
float64
5.67
140
num_lines
int64
7
299
original_docstring
stringlengths
22
42.6k
source
stringclasses
2 values
[Fact] public static void MatchesTest114() { var xml = "books.xml"; var startingNodePath = "/bookstore/book/author"; var testExpression = @"(book/author)[last-name=(/bookstore/book/author/last-name)[1]]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); }
c#
12
0.609223
99
44.888889
9
/// <summary> /// Predicate within a predicate - Return all authors with a last-name equal to the first last-name node. /// (book/author)[last-name=(/bookstore/book/author)[1]/last-name] /// </summary>
function
private final void zzd(int r5, int r6) { /* r4 = this; r4.zzqk() com.google.android.gms.common.util.Clock r0 = com.google.android.gms.ads.internal.zzbv.zzer() long r0 = r0.currentTimeMillis() java.lang.Object r2 = r4.mLock monitor-enter(r2) int r3 = r4.zzcpx // Catch:{ all -> 0x0020 } if (r3 == r5) goto L_0x0014 monitor-exit(r2) // Catch:{ all -> 0x0020 } return L_0x0014: r4.zzcpx = r6 // Catch:{ all -> 0x0020 } int r5 = r4.zzcpx // Catch:{ all -> 0x0020 } int r6 = com.google.android.gms.internal.ads.zzajq.zzcqb // Catch:{ all -> 0x0020 } if (r5 != r6) goto L_0x001e r4.zzcpy = r0 // Catch:{ all -> 0x0020 } L_0x001e: monitor-exit(r2) // Catch:{ all -> 0x0020 } return L_0x0020: r5 = move-exception monitor-exit(r2) // Catch:{ all -> 0x0020 } throw r5 */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.ads.zzajp.zzd(int, int):void"); }
java
7
0.500824
135
42.392857
28
/* Code decompiled incorrectly, please refer to instructions dump. */
function
private void toggleCustomiseUI(bool enable) { if (enable) { customiseGrid.Opacity = 1; customiseGrid.IsEnabled = true; btnDelete.IsEnabled = true; } else { customiseGrid.Opacity = 0.33; customiseGrid.IsEnabled = false; btnDelete.IsEnabled = false; } }
c#
9
0.481203
48
32.333333
12
/// <summary> /// Hides or shows all of the UI elements that require a custom theme to be loaded first (which is most of them) /// </summary> /// <param name="enable">Whether or not to enable UI elements that require a loaded theme</param>
function
public static String determineContextPath(HttpServletRequest request) { String contextPath = request.getContextPath(); String proxyContextPath = request.getHeader(PROXY_CONTEXT_PATH_HTTP_HEADER); String forwardedContext = request.getHeader(FORWARDED_CONTEXT_HTTP_HEADER); logger.debug("Context path: " + contextPath); String determinedContextPath = ""; if (anyNotBlank(proxyContextPath, forwardedContext)) { logger.debug(String.format("On the request, the following context paths were parsed" + " from headers:\n\t X-ProxyContextPath: %s\n\tX-Forwarded-Context: %s", proxyContextPath, forwardedContext)); determinedContextPath = StringUtils.isNotBlank(proxyContextPath) ? proxyContextPath : forwardedContext; } logger.debug("Determined context path: " + determinedContextPath); return determinedContextPath; }
java
12
0.685475
115
62.866667
15
/** * Determines the context path if populated in {@code X-ProxyContextPath} or {@code X-ForwardContext} headers. If not populated, returns an empty string. * * @param request the HTTP request * @return the provided context path or an empty string */
function
createPlaceholderSystemNote({ formContent, uniqueId }) { const $tempNote = $( `<li id="${uniqueId}" class="note system-note timeline-entry being-posted fade-in-half"> <div class="timeline-entry-inner"> <div class="timeline-content"> <i>${formContent}</i> </div> </div> </li>` ); return $tempNote; }
javascript
8
0.550265
94
30.583333
12
/** * Create Placeholder System Note DOM element populated with quick action description */
function
private static Bitmap TryCaptureFullScreen() { int width = Screen.PrimaryScreen.Bounds.Width; int height = Screen.PrimaryScreen.Bounds.Height; if (width <= 0 || height <= 0) { return null; } var bitmap = new Bitmap(width, height); using (var graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen( sourceX: Screen.PrimaryScreen.Bounds.X, sourceY: Screen.PrimaryScreen.Bounds.Y, destinationX: 0, destinationY: 0, blockRegionSize: bitmap.Size, copyPixelOperation: CopyPixelOperation.SourceCopy); } return bitmap; }
c#
13
0.502469
71
37.619048
21
/// <summary> /// Captures the full screen to a <see cref="Bitmap"/>. /// </summary> /// <returns> /// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen /// capture can't be created. /// </returns>
function
static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct) { uint32_t pllfreq; assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_PLLInitStruct->PLLP)); assert_param(IS_LL_UTILS_FRACN_VALUE(UTILS_PLLInitStruct->FRACN)); pllfreq = LL_RCC_CalcPLLClockFreq(PLL_InputFrequency, UTILS_PLLInitStruct->PLLM, UTILS_PLLInitStruct->PLLN, UTILS_PLLInitStruct->FRACN, UTILS_PLLInitStruct->PLLP); return pllfreq; }
c
9
0.786913
165
58.7
10
/** * @brief Function to check that PLL can be modified * @param PLL_InputFrequency PLL input frequency (in Hz) * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains * the configuration information for the PLL. * @retval PLL output frequency (in Hz) */
function
@POST @Path(CoordConsts.SVC_RSC_LIST_CONTAINERS) @Produces(MediaType.APPLICATION_JSON) @Deprecated public JSONArray listContainers( @FormDataParam(CoordConsts.SVC_KEY_API_KEY) String apiKey, @FormDataParam(CoordConsts.SVC_KEY_VERSION) String clientVersion) { return listNetworksHelper(apiKey, clientVersion); }
java
8
0.764881
73
36.444444
9
/** * List the networks that the specified API key can access * * @param apiKey The API key of the client * @param clientVersion The version of the client * @return TODO: document JSON response * @deprecated because containers were renamed to networks. Use {@link #listNetworks(String, * String) listNetworks} instead. */
function
def nearest_neighbor_threshold( self, vectors, threshold=0.5, batch_size=100, show_progressbar=False, return_names=True, ): vectors = np.array(vectors) if np.ndim(vectors) == 1: vectors = vectors[None, :] return list( self._threshold_batch( vectors, batch_size, threshold, show_progressbar, return_names ) )
python
9
0.519187
78
26.75
16
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily not in the vocabulary. Parameters ---------- vectors : list of arrays or numpy array The vectors to find the nearest neighbors to. threshold : float, optional, default .5 The threshold within to retrieve items. batch_size : int, optional, default 100. The batch size to use. 100 is a good default option. Increasing the batch size may increase speed. show_progressbar : bool, optional, default False Whether to show a progressbar. return_names : bool, optional, default True Whether to return the item names, or just the distances. Returns ------- sim : list of tuples. For each item in the input the num most similar items are returned in the form of (NAME, DISTANCE) tuples. If return_names is set to false, only the distances are returned.
function
def interpolate_NaNs_in_feature_variables(ds=None, res='4x5', save2NetCDF=False, debug=False): months = np.arange(1, 13) filename = 'Oi_prj_feature_variables_{}.nc'.format(res) if isinstance(ds, type(None)): ds = xr.open_dataset(filename) for var in ds.data_vars: da = ds[var] coords = [i for i in da.coords] da = da.astype(np.float64) arr = np.ma.array(da.values) if var == 'Depth_GEBCO': arr[arr >= -1.] = np.NaN if 'WOA_' in var: arr[arr == 0.] = np.NaN arr[arr == -99.9] = np.NaN NaNs_presnt = arr[~np.isfinite(arr)].shape[0] print("Interpolating={} for '{}' at {}".format(NaNs_presnt, var, res)) if NaNs_presnt > 0: if 'time' in coords: months_eq = ds['time.month'].values == months assert months_eq.all(), 'Months not in order!' ars = [arr[i, ...] for i in range(len(months))] else: ars = [arr] subX = da['lon'].values subY = da['lat'].values p = Pool(12) if debug: print(ars[0][:5, :5]) ars = p.map(partial(interpolate_array_with_GRIDDATA, da=da), ars) p.close() if 'time' in coords: da.values = np.ma.array(ars) else: da.values = ars[0] ds[var] = da.copy() gc.collect() if save2NetCDF: print('Saving interpolated NetCDF at {}'.format(res)) ds.to_netcdf(filename.split('.nc')[0]+'_INTERP_NEAREST.nc') print('Interpolated variables at {}'.format(res)) return ds
python
17
0.493885
78
38.953488
43
Interpolate the NaNs in 2D arrarys of feature variables Parameters ------- ds (xr.Dataset): dataset object with variables to interpolate res (str): horizontal resolution (e.g. 4x5) of Dataset save2NetCDF (bool): save interpolated Dataset to as a NetCDF? debug (bool): print out debugging output? Returns ------- (xr.Dataset)
function
fn cmp(&self, other: &Self) -> Ordering { fn to_tuple( report_body: &ReportBody, ) -> ( FamilyId, ProductId, SecurityVersion, ExtendedProductId, MrSigner, MrEnclave, Attributes, MiscSelect, ConfigId, ConfigSecurityVersion, CpuSecurityVersion, ReportData, ) { ( report_body.family_id(), report_body.product_id(), report_body.security_version(), report_body.extended_product_id(), report_body.mr_signer(), report_body.mr_enclave(), report_body.attributes(), report_body.misc_select(), report_body.config_id(), report_body.config_security_version(), report_body.cpu_security_version(), report_body.report_data(), ) } to_tuple(self).cmp(&to_tuple(other)) }
rust
8
0.455993
54
30.441176
34
/// Create an arbitrary sort order for report body types /// /// We sort by Family ID, ProdID, Extended ProdID, SVN, MrSigner, MrEnclave, Attributes, /// Misc Select, ConfigId, ConfigSVN, CPU SVN, and ReportData, in that order
function
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): escape = '\\{}'.format return ''.join( escape(c) if c in chars or c.isspace() else '\\000' if c == '\x00' else c for c in pattern )
python
11
0.480687
61
32.428571
7
Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str
function
@Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { flushChars(); write("<"); write(qName); outputAttributes(namespaces); outputAttributes(atts); write(">"); namespaces.clear(); }
java
7
0.720307
108
25.2
10
/** * Receive notification of the start of an element. * <p/> * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param uri The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param qName The qualified name (with prefix), or the * empty string if qualified names are not available. * @param atts The attributes attached to the element. If * there are no attributes, it shall be an empty * Attributes object. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement */
function
def decompr_files(dname, fnames): try: for fname in fnames: if os.path.exists(dname + fname): sh.gunzip(dname + fname) elif os.path.exists(dname + os.path.splitext(fname)[0]): return else: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), dname + fname) except BaseException: raise
python
16
0.481876
79
38.166667
12
Runs gunzip on a list of files. Args: dname (str): The Dirname containing files to gunzip. fnames (list): list of filenames in dir. Examples: Pipe.decompr_files('user/inputs/', ['a.gz', 'b.gz'])
function
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "familyMember", propOrder = { "dateOfBirth", "fmemberIds", "fmemberName", "surname", "typeOfFmember" }) @Entity public class FamilyMember { @XmlElement(name = "date_of_birth") @NotNull(message = "Format: DD-MM-YYYY") protected String dateOfBirth; @Id @GeneratedValue(strategy=GenerationType.AUTO) @XmlElement(name = "fmember_ids") protected int fmemberIds; @XmlElement(name = "fmember_name") @Size(min = 2, max = 200) @NotNull(message = "Name cannot be null") protected String fmemberName; @Size(min = 2, max = 200) @NotNull(message = "Surname cannot be null") protected String surname; @XmlElement(name = "type_of_fmember") protected String typeOfFmember; /** * Gets the value of the dateOfBirth property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public String getDateOfBirth() { return dateOfBirth; } /** * Sets the value of the dateOfBirth property. * * @param date * allowed object is * {@link XMLGregorianCalendar } * */ public void setDateOfBirth(String date) { this.dateOfBirth = date; } /** * Gets the value of the fmemberIds property. * */ public int getFmemberIds() { return fmemberIds; } /** * Sets the value of the fmemberIds property. * */ public void setFmemberIds(int value) { this.fmemberIds = value; } /** * Gets the value of the fmemberName property. * * @return * possible object is * {@link String } * */ public String getFmemberName() { return fmemberName; } /** * Sets the value of the fmemberName property. * * @param value * allowed object is * {@link String } * */ public void setFmemberName(String value) { this.fmemberName = value; } /** * Gets the value of the surname property. * * @return * possible object is * {@link String } * */ public String getSurname() { return surname; } /** * Sets the value of the surname property. * * @param value * allowed object is * {@link String } * */ public void setSurname(String value) { this.surname = value; } /** * Gets the value of the typeOfFmember property. * * @return * possible object is * {@link String } * */ public String getTypeOfFmember() { return typeOfFmember; } /** * Sets the value of the typeOfFmember property. * * @param value * allowed object is * {@link String } * */ public void setTypeOfFmember(String value) { this.typeOfFmember = value; } }
java
9
0.543629
52
20.546099
141
/** * <p>Java class for familyMember complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="familyMember"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="date_of_birth" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/&gt; * &lt;element name="fmember_ids" type="{http://www.w3.org/2001/XMLSchema}int"/&gt; * &lt;element name="fmember_name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="surname" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="type_of_fmember" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */
class
public class ChecksCache { public static readonly Check ImageScanCheck = new Check { Id = "container_image.CVE_scan", Category = "Security", Severity = CheckSeverity.High, Description = "Container Image scan with trivy", Remediation = "Update packages with found CVEs to versions, where these CVEs are addressed", }; private static readonly ILogger Logger = Log.ForContext<ChecksCache>(); private readonly JosekiConfiguration config; private readonly JosekiDbContext db; private readonly IMemoryCache cache; public ChecksCache(ConfigurationParser config, JosekiDbContext db, IMemoryCache cache) { this.config = config.Get(); this.db = db; this.cache = cache; } public async Task<int> GetOrAddItem(string id, Func<Check> checkFactory) { if (!this.cache.TryGetValue<CheckCacheItem>(id, out var item)) { var entity = await this.db.Set<CheckEntity>().AsNoTracking().FirstOrDefaultAsync(e => e.CheckId == id); if (entity == null) { Logger.Information("Adding new Check item {CheckId} to the database", id); var addedEntity = this.db.Set<CheckEntity>().Add(checkFactory().ToEntity()); await this.db.SaveChangesAsync(); entity = addedEntity.Entity; } var cacheItem = new CheckCacheItem { CheckId = id, Id = entity.Id, UpdatedAt = entity.DateUpdated, }; item = this.cache.Set(cacheItem.Key, cacheItem); } var threshold = DateTime.UtcNow.AddDays(-this.GetItemTtl(id)); if (item.UpdatedAt < threshold) { Logger.Information("Updating expired Check item {CheckId} in the database", id); var entity = await this.db.Set<CheckEntity>().FirstOrDefaultAsync(i => i.CheckId == id); var newCheckData = checkFactory(); entity.Category = newCheckData.Category; entity.Description = newCheckData.Description; entity.Remediation = newCheckData.Remediation; entity.Severity = newCheckData.Severity.ToEntity(); this.db.Set<CheckEntity>().Update(entity); await this.db.SaveChangesAsync(); item.UpdatedAt = DateTime.UtcNow; } return item.Id; } public Task<int> GetImageScanCheck() { return this.GetOrAddItem(ImageScanCheck.Id, () => ImageScanCheck); } private int GetItemTtl(string id) { if (id.StartsWith("polaris")) { return this.config.Cache.PolarisCheckTtl; } else if (id.StartsWith("azsk")) { return this.config.Cache.AzureCheckTtl; } else { return this.config.Cache.DefaultTtl; } } }
c#
20
0.539875
119
41.25
76
/// <summary> /// Keeps track of Check items to reduce amount of interactions with real database. /// The objects stores in memory identifiers of Checks, that are already in database. /// It does requests only to update expired items or query not cached yet records. /// The cache is expected to be used in Singleton mode. /// </summary>
class
class CThreadPool_Controller_PID : public CThreadPool_Controller { public: CThreadPool_Controller_PID(unsigned int max_threads, unsigned int min_threads); void SetQueuedTasksThreshold(double threshold); @sa SetQueuedTasksThreshold() double GetQueuedTasksThreshold(void); Set maximum time (in seconds) that task can wait in queue for processing until new thread will be launched. coefficient in integral part of the algorithm and effectively if only one task will be considered then coefficient will be multiplied by number of currently running threads and currently set threshold. By default parameter is set to 0.2. @sa SetQueuedTasksThreshold() void SetTaskMaxQueuedTime(double queued_time); Get maximum time that task can wait in queue for processing until new thread will be launched. @sa SetTaskMaxQueuedTime() double GetTaskMaxQueuedTime(void); Set the time period (in seconds) for which average speed of changing of waiting tasks number is calculated. Average speed is calculated by simple division of changing in waiting tasks number during this time period per time period value (all counts of tasks are calculated per each thread). By default parameter is set to 0.3. void SetChangeCalcTime(double calc_time); Get the time period for which average speed of changing of waiting tasks number is calculated. double GetChangeCalcTime(void); Set period of prediction of number of tasks in queue coefficient in derivative part of the algorithm. Meaning of the coefficient is like this: take average speed of changing of tasks count, multiply it by this prediction time, if the resulting value is greater than threshold then new thread is needed. By default parameter is set to 0.5. @sa SetQueuedTasksThreshold() void SetChangePredictTime(double predict_time); Get period of prediction of number of tasks in queue @sa SetChangePredictTime() double GetChangePredictTime(void); Get maximum timeout for which calls to method HandleEvent() can be missing. @sa CThreadPool_Controller::GetSafeSleepTime() virtual CTimeSpan GetSafeSleepTime(void) const; protected: Main method for implementation of controlling algorithm virtual void OnEvent(EEvent event); private: Timer for measuring time periods CStopWatch m_Timer; History of changing of "error" value "error" - number of tasks per thread waiting in queue. Controller will try to tend this value to zero. deque<SThreadPool_PID_ErrInfo> m_ErrHistory; Value of "error" integrated over all working time double m_IntegrErr; Threshold value @sa SetQueuedTasksThreshold() double m_Threshold; Integral coefficient @sa SetTaskMaxQueuedTime() double m_IntegrCoeff; Derivative coefficient @sa SetChangePredictTime() double m_DerivCoeff; Period of taking average "error" change speed @sa SetChangeCalcTime() double m_DerivTime; }
c++
8
0.699538
74
45.371429
70
/// Default ThreadPool controller based on Proportional-Integral-Derivative /// algorithm. Controller looks at number of tasks waiting in the queue /// per each thread running and adjusts number of threads with respect to /// all coefficients set in it. /// Implementation of the class assumes that all coefficients are set before /// pool begin to work and controller begins to be extencively used. /// All changing of coefficients implemented in non-threadsafe manner and if /// they will be changed at the same time when OnEvent() is executed /// unpredictable consequences can happen.
class
func NewConsulResolver(ctx context.Context, conf ResolverConfig) (*ServiceResolver, error) { if conf.Client == nil { return nil, errors.New("consul client must not be nil") } if conf.ServiceSpec.ServiceName == "" { return nil, errors.New("service name must not be empty") } if conf.Query == nil { conf.Query = &api.QueryOptions{} } else { conf.Query.WaitIndex = 0 } if conf.Balancer == nil { conf.Balancer = &lb.RoundRobinLoadBalancer{} } if conf.Log == nil { conf.Log = log.Printf } resolver := &ServiceResolver{ log: conf.Log, ctx: ctx, queryOpts: conf.Query, spec: conf.ServiceSpec, client: conf.Client.Health(), balancer: conf.Balancer, init: make(chan struct{}), initDone: sync.Once{}, } go resolver.populateFromConsul() return resolver, nil }
go
15
0.663814
92
25.419355
31
// NewConsulResolver creates a new Consul Resolver // ctx - a context used for graceful termination of the consul-watcher go routine. // Note that canceling the context will render the resolver stale, and any attempt to use it will immediately return an error // conf - the resolver's config
function
draw_termini(termini_data) { let loop_length_calculation; let loop_drawing_shape; if (termini_data.terminus_type === "N") { loop_length_calculation = this.style_obj.protein.nter_loop_draw_opts.calc_len; loop_drawing_shape = this.style_obj.protein.nter_loop_draw_opts.shape; } else { loop_length_calculation = this.style_obj.protein.cter_loop_draw_opts.calc_len; loop_drawing_shape = this.style_obj.protein.cter_loop_draw_opts.shape; } if (loop_length_calculation.type === "fixed") { termini_data = this.calculateFixedPointTermini(termini_data, loop_length_calculation, loop_drawing_shape); } else if (loop_length_calculation.type === "reslen") { termini_data = this.calculateResLengthPointData([termini_data], loop_length_calculation, loop_drawing_shape); this.draw_loop_paths(termini_data, termini_data[0].terminus_type+"ter_loops"); } }
javascript
12
0.647475
121
57.294118
17
/** * Function responsbile for controlling addition of points to termini data and drawing of termini curves * @namespace * @exports NaView * @name draw_termini * @param {Object} termini_data termini loop data Object generated by processRawUniProt */
function
def findMessages(): with open('hiddenMessageInput.txt', 'w') as hiddenMessageInputOutput: hiddenMessageInputOutput.write('') hiddenMessageInputOutput.close() logging.debug('Displaying confirmation screen.') print('''To find the hidden message, copy and paste the text into the file "hiddenMessageInput.txt".''') hiddenAsk = input('\n' + Fore.GREEN + 'Confirm - ' + Style.RESET_ALL + '''Press enter once you have pasted to the file:''') if hiddenAsk == str(''): with open('storyMaster.txt', 'r') as storyMaster: with open('hiddenMessageInput.txt', 'r') as hiddenInput: storyMasterContents = storyMaster.readlines() hiddenInputContents = hiddenInput.readlines() logging.debug('Contrasting hiddenMessageInput.txt with storyMaster.txt') try: for i in range(0, len(storyMasterContents) - 1, 1): if storyMasterContents[i] != hiddenInputContents[i]: print('Hidden Message: ' + hiddenInputContents[i]) except IndexError: print(Fore.RED + 'Error: ' + Style.RESET_ALL + 'There was an error finding the hidden message, make sure you saved the file "hiddenMessageInput.txt"') time.sleep(2) os.system('cls') print(launchScreen) findMessages() elif hiddenAsk in acceptableMenu: print() print(Style.BRIGHT + Fore.GREEN + 'Notification: ' + Style.RESET_ALL + 'Returning to menu, standby.') time.sleep(2) os.system('cls') print(launchScreen) menu() logging.debug('Requesting menu return input.') findMessageAsk = input('\nWould you like to go back to the main menu?:').strip(' ') if findMessageAsk.lower() in acceptableReturnMenu: os.system('cls') print(launchScreen) menu() elif findMessageAsk.lower() in remain: print() print(Style.BRIGHT + Fore.GREEN + 'Notification: ' + Style.RESET_ALL + 'Restarting function, standby.') time.sleep(2) os.system('cls') print(launchScreen) hiddenMessages() else: print() print(Fore.RED + 'Error: ' + Style.RESET_ALL + 'Unacceptable input, returning to menu.') print() time.sleep(2) os.system('cls') print() print(launchScreen) menu() return findMessageAsk logging.debug('End of function findMessages.')
python
16
0.655158
159
41.925926
54
Find hidden messages in Romeo and Juliet. This function takes an input from the user, from a file (hiddenMessageInput.txt) and compares the input to storyMaster.txt and outputs any differences between the two files, the purpose of this function is to find/locate a hidden message in the text from another agent. Parameters ---------- none Returns ------- string The input of findMessageAsk
function
public static List<Class> findClassesFromJar(JarFile jarFile, String packageName) throws ClassNotFoundException, MalformedURLException { List<Class> classes = new ArrayList<Class>(); if (jarFile == null || packageName == null) { return classes; } URL[] urls = { new URL("jar:file:/" + jarFile.getName() + "!/")}; URLClassLoader loader = URLClassLoader.newInstance(urls, Thread.currentThread().getContextClassLoader()); for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); if (!entry.isDirectory()) { String className = entry.getName().replace('/', '.'); if (className.startsWith(packageName)) { if (className.endsWith(".class") && !className.contains("$")) { className = className.substring(0, className.lastIndexOf('.')); Class clazz = loader.loadClass(className); if (!classes.contains(clazz)) { classes.add(loader.loadClass(className)); } } } } } return classes; }
java
18
0.543015
136
51.833333
24
/** * Scans all classes in the specified jar file which belong to the given * package and its descendants. * * @param jarFile to search * @param packageName * @return list of classes found (never null) * @throws ClassNotFoundException * @throws IOException */
function
@ApiModel(value = "lookup-values-list", description = "[ { field : value} ]") @EqualsAndHashCode public class JSONLookupValuesList { public static final JSONLookupValuesList ofLookupValuesList( @Nullable final LookupValuesList lookupValues, @NonNull final String adLanguage) { if (lookupValues == null || lookupValues.isEmpty()) { return EMPTY; } Stream<JSONLookupValue> jsonValues = lookupValues.getValues() .stream() .map(lookupValue -> JSONLookupValue.ofLookupValue(lookupValue, adLanguage)); if (!lookupValues.isOrdered()) { jsonValues = jsonValues.sorted(Comparator.comparing(JSONLookupValue::getCaption)); } final ImmutableList<JSONLookupValue> jsonValuesList = jsonValues.collect(ImmutableList.toImmutableList()); final DebugProperties otherProperties = lookupValues.getDebugProperties(); return new JSONLookupValuesList(jsonValuesList, otherProperties); } @JsonCreator private static final JSONLookupValuesList ofJSONLookupValuesList(@JsonProperty("values") final List<JSONLookupValue> jsonLookupValues) { if (jsonLookupValues == null || jsonLookupValues.isEmpty()) { return EMPTY; } return new JSONLookupValuesList(ImmutableList.copyOf(jsonLookupValues), DebugProperties.EMPTY); } public static final Collector<JSONLookupValue, ?, JSONLookupValuesList> collect() { final Supplier<List<JSONLookupValue>> supplier = ArrayList::new; final BiConsumer<List<JSONLookupValue>, JSONLookupValue> accumulator = List::add; final BinaryOperator<List<JSONLookupValue>> combiner = (l, r) -> { l.addAll(r); return l; }; final Function<List<JSONLookupValue>, JSONLookupValuesList> finisher = JSONLookupValuesList::ofJSONLookupValuesList; return Collector.of(supplier, accumulator, combiner, finisher); } public static final LookupValuesList lookupValuesListFromJsonMap(final Map<String, Object> map) { @SuppressWarnings("unchecked") final List<Object> values = (List<Object>)map.get("values"); // // Corner case: the `map` it's just a single lookup value if (values == null && map.get(JSONLookupValue.PROPERTY_Key) != null) { final StringLookupValue lookupValue = JSONLookupValue.stringLookupValueFromJsonMap(map); return LookupValuesList.fromNullable(lookupValue); } if (values == null || values.isEmpty()) { return LookupValuesList.EMPTY; } return values.stream() .map(valueObj -> { @SuppressWarnings("unchecked") final Map<String, Object> valueAsMap = (Map<String, Object>)valueObj; return JSONLookupValue.stringLookupValueFromJsonMap(valueAsMap); }) .collect(LookupValuesList.collect()); } @VisibleForTesting static final JSONLookupValuesList EMPTY = new JSONLookupValuesList(); @JsonProperty("values") private final List<JSONLookupValue> values; @JsonProperty("defaultValue") @JsonInclude(JsonInclude.Include.NON_ABSENT) private String defaultValue; private LinkedHashMap<String, Object> otherProperties; @VisibleForTesting JSONLookupValuesList(final ImmutableList<JSONLookupValue> values, final DebugProperties otherProperties) { this.values = values; if (otherProperties != null && !otherProperties.isEmpty()) { this.otherProperties = new LinkedHashMap<>(otherProperties.toMap()); } } private JSONLookupValuesList() { values = ImmutableList.of(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("values", values) .add("properties", otherProperties == null || otherProperties.isEmpty() ? null : otherProperties) .toString(); } public List<JSONLookupValue> getValues() { return values; } @JsonAnyGetter public Map<String, Object> getOtherProperties() { return otherProperties == null ? ImmutableMap.of() : otherProperties; } @JsonAnySetter public void putOtherProperty(final String name, final String jsonValue) { if (otherProperties == null) { otherProperties = new LinkedHashMap<>(); } otherProperties.put(name, jsonValue); } public JSONLookupValuesList setDefaultValue(final JSONLookupValue defaultValue) { this.defaultValue = defaultValue == null ? null : defaultValue.getKey(); return this; } public JSONLookupValuesList setDefaultValue(final LookupValue defaultValue) { this.defaultValue = defaultValue == null ? null : defaultValue.getIdAsString(); return this; } @JsonSetter public JSONLookupValuesList setDefaultValue(final String defaultValue) { this.defaultValue = defaultValue; return this; } public String getDefaultValue() { return defaultValue; } }
java
16
0.749673
135
27.66875
160
/* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */
class
static llvm::Function *ImplementExplicitArgsEntryPoint( const NativeObject *cfg_func, const std::string &name) { auto num_args = FLAGS_explicit_args_count; if (name == "main") { num_args = 3; } auto bb = remill::BasicBlockFunction(gModule); auto state_ptr_arg = remill::NthArgument(bb, remill::kStatePointerArgNum); auto mem_ptr_arg = remill::NthArgument(bb, remill::kMemoryPointerArgNum); auto pc_arg = remill::NthArgument(bb, remill::kPCArgNum); auto pc_type = pc_arg->getType(); LOG(INFO) << "Generating explicit argument entrypoint function for " << name << ", calling into " << cfg_func->lifted_name; std::vector<llvm::Type *> arg_types(num_args, pc_type); auto func_type = llvm::FunctionType::get(pc_type, arg_types, false); auto func = llvm::Function::Create( func_type, llvm::GlobalValue::InternalLinkage, name, gModule); remill::ValueMap value_map; value_map[mem_ptr_arg] = llvm::Constant::getNullValue(mem_ptr_arg->getType()); value_map[pc_arg] = llvm::ConstantInt::get(pc_type, cfg_func->ea); value_map[state_ptr_arg] = GetStatePointer(); remill::CloneFunctionInto(bb, func, value_map); decltype(func->getAttributes()) attr_set_or_list; func->setAttributes(attr_set_or_list); func->addFnAttr(llvm::Attribute::NoInline); func->addFnAttr(llvm::Attribute::NoBuiltin); auto block = &(func->front()); auto term = block->getTerminator(); term->eraseFromParent(); CallingConvention loader(gArch->DefaultCallingConv()); auto old_sp = loader.LoadStackPointer(block); std::vector<llvm::Value *> explicit_args; for (auto &arg : func->args()) { explicit_args.push_back(&arg); } loader.StoreArguments(block, explicit_args); loader.AllocateReturnAddress(block); std::vector<llvm::Value *> args(3); args[remill::kMemoryPointerArgNum] = remill::LoadMemoryPointer(block); args[remill::kStatePointerArgNum] = value_map[state_ptr_arg]; args[remill::kPCArgNum] = value_map[pc_arg]; llvm::CallInst::Create( gModule->getFunction(cfg_func->lifted_name), args, "", block); loader.StoreStackPointer(block, old_sp); llvm::ReturnInst::Create( *gContext, loader.LoadReturnValue(block, pc_type), block); if (!FLAGS_pc_annotation.empty()) { legacy::AnnotateInsts(func, cfg_func->ea); } return func; }
c++
10
0.699437
80
43.423077
52
// Implements a stub for an externally defined function in such a way that // the external is explicitly called, and arguments from the modeled CPU // state are passed into the external.
function
func (x *BindImageMemoryInfoKHX) Deref() { if x.reffcb13766 == nil { return } x.SType = (StructureType)(x.reffcb13766.sType) x.PNext = (unsafe.Pointer)(unsafe.Pointer(x.reffcb13766.pNext)) x.Image = *(*Image)(unsafe.Pointer(&x.reffcb13766.image)) x.Memory = *(*DeviceMemory)(unsafe.Pointer(&x.reffcb13766.memory)) x.MemoryOffset = (DeviceSize)(x.reffcb13766.memoryOffset) x.DeviceIndexCount = (uint32)(x.reffcb13766.deviceIndexCount) hxffe3496 := (*sliceHeader)(unsafe.Pointer(&x.PDeviceIndices)) hxffe3496.Data = uintptr(unsafe.Pointer(x.reffcb13766.pDeviceIndices)) hxffe3496.Cap = 0x7fffffff x.SFRRectCount = (uint32)(x.reffcb13766.SFRRectCount) packSRect2D(x.PSFRRects, x.reffcb13766.pSFRRects) }
go
13
0.759441
71
43.75
16
// Deref uses the underlying reference to C object and fills the wrapping struct with values. // Do not forget to call this method whether you get a struct for C object and want to read its values.
function
public class SoapHeaderElementMethodArgumentResolver implements MethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { SoapHeader soapHeader = parameter.getParameterAnnotation(SoapHeader.class); if (soapHeader == null) { return false; } Class<?> parameterType = parameter.getParameterType(); // Simple SoapHeaderElement parameter if (SoapHeaderElement.class.equals(parameterType)) { return true; } // List<SoapHeaderElement> parameter if (List.class.equals(parameterType)) { Type genericType = parameter.getGenericParameterType(); if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; Type[] typeArguments = parameterizedType.getActualTypeArguments(); if (typeArguments.length == 1 && SoapHeaderElement.class.equals(typeArguments[0])) { return true; } } } return false; } @Override public Object resolveArgument(MessageContext messageContext, MethodParameter parameter) throws Exception { Assert.isInstanceOf(SoapMessage.class, messageContext.getRequest()); SoapMessage request = (SoapMessage) messageContext.getRequest(); org.springframework.ws.soap.SoapHeader soapHeader = request.getSoapHeader(); String paramValue = parameter.getParameterAnnotation(SoapHeader.class).value(); Assert.isTrue(QNameUtils.validateQName(paramValue), "Invalid header qualified name [" + paramValue + "]. " + "QName must be of the form '{namespace}localPart'."); QName qname = QName.valueOf(paramValue); Class<?> parameterType = parameter.getParameterType(); if (SoapHeaderElement.class.equals(parameterType)) { return extractSoapHeader(qname, soapHeader); } else if (List.class.equals(parameterType)) { return extractSoapHeaderList(qname, soapHeader); } // should not happen throw new UnsupportedOperationException(); } private SoapHeaderElement extractSoapHeader(QName qname, org.springframework.ws.soap.SoapHeader soapHeader) { Iterator<SoapHeaderElement> elements = soapHeader.examineAllHeaderElements(); while (elements.hasNext()) { SoapHeaderElement e = elements.next(); if (e.getName().equals(qname)) { return e; } } return null; } private List<SoapHeaderElement> extractSoapHeaderList(QName qname, org.springframework.ws.soap.SoapHeader soapHeader) { List<SoapHeaderElement> result = new ArrayList<SoapHeaderElement>(); Iterator<SoapHeaderElement> elements = soapHeader.examineAllHeaderElements(); while (elements.hasNext()) { SoapHeaderElement e = elements.next(); if (e.getName().equals(qname)) { result.add(e); } } return result; } }
java
15
0.750277
110
33.278481
79
/** * Implementation of {@link MethodArgumentResolver} that supports resolving {@link SoapHeaderElement} parameters. Target * method parameters must be annotated with {@link SoapHeader} to indicate the SOAP header to resolve. This resolver * supports simple {@link SoapHeaderElement} parameters and {@link List} parameters for elements that appear multiple * times in the same SOAP header. </p> The following snippet shows an example of supported declarations. * <pre><code> * public void soapHeaderElement(@SoapHeader("{http://springframework.org/ws}header") SoapHeaderElement element) * * public void soapHeaderElementList(@SoapHeader("{http://springframework.org/ws}header") List&lt;SoapHeaderElement&gt; elements) * </code></pre> * * @author Tareq Abedrabbo * @author Arjen Poutsma * @see SoapHeader * @since 2.0 */
class
func New(deployment, cwd string, timeout time.Duration, logger log15.Logger, sudo bool, ram ...int) (*Scheduler, error) { cwd, err := pickCWD(cwd) if err != nil { return nil, err } jq, err := jobqueue.ConnectUsingConfig(clog.ContextWithLogHandler(context.Background(), logger.GetHandler()), deployment, timeout) if err != nil { return nil, err } exe, err := os.Executable() rram, override := parseRAM(ram) return &Scheduler{ cwd: cwd, exe: exe, requirements: &jqs.Requirements{ RAM: rram, Time: reqTime, Cores: reqCores, Disk: reqDisk, }, override: override, jq: jq, sudo: sudo, }, err }
go
15
0.652174
88
22.888889
27
// New returns a Scheduler that is connected to wr manager using the given // deployment, timeout and logger. If sudo is true, NewJob() will prefix 'sudo' // to commands. Added jobs will have the given cwd, which matters. If cwd is // blank, the current working dir is used. If ram is supplied, we set override // 1, otherwise it defaults to 50MB with no override.
function
public static PropertyInfo GetPropertyInfo(this Object obj, String name) { if (obj is null) { throw new ArgumentNullException(nameof(obj)); } return GetPropertyInfo(obj.GetType(), name); }
c#
13
0.544776
72
32.625
8
/// <summary> /// Gets the property information by name for the type of the object. /// </summary> /// <param name="obj">Object with a type that has the specified property.</param> /// <param name="name">The name of the property.</param>
function
def transformWalkDown(node, add=False, multi=False): oChild = [] if not isinstance(node, list): node = [node] for n in node: relatives = n.listRelatives(typ='transform') if relatives: if multi: oChild = oChild + relatives else: oChild.append(relatives[0]) if oChild: pm.select(oChild, add=add) else: pm.displayWarning("No child to walk Down.")
python
14
0.553377
52
29.666667
15
Walks to the child transform dagNode on the hierarcy Arguments: node (dagNode or list of dagNode): dagNode to walk add (bool, optional): if True, will add to the selection multi (bool, optional): if True will select all the childrens
function
def divide_data_to_table_and_attribute( self,data,required_column='experiment_igf_id', table_columns=None,attribute_name_column='attribute_name', attribute_value_column='attribute_value'): try: if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data) experiment_columns = \ self.get_table_columns( table_name=Experiment, excluded_columns=[ 'experiment_id', 'project_id', 'sample_id' ]) experiment_columns.\ extend([ 'project_igf_id', 'sample_igf_id']) (experiment_df, experiment_attr_df)=\ BaseAdaptor.\ divide_data_to_table_and_attribute(\ self, data=data, required_column=required_column, table_columns=experiment_columns, attribute_name_column=attribute_name_column, attribute_value_column=attribute_value_column) return (experiment_df, experiment_attr_df) except Exception as e: raise ValueError( 'Failed to dividee exp data, error: {0}'.format(e))
python
12
0.527359
80
39.709677
31
A method for separating data for Experiment and Experiment_attribute tables :param data: A list of dictionaries or a Pandas DataFrame :param table_columns: List of table column names, default None :param required_column: column name to add to the attribute data :param attribute_name_column: label for attribute name column :param attribute_value_column: label for attribute value column :returns: Two pandas dataframes, one for Experiment and another for Experiment_attribute table
function
@Override public SAMRecordIterator assertSorted(final SAMFileHeader.SortOrder sortOrder) { if (sortOrder != SAMFileHeader.SortOrder.coordinate) { throw new IllegalStateException("Cannot assort " + sortOrder + " when expecting coordinate sorted input"); } return this; }
java
11
0.690096
118
43.857143
7
/** * Establishes that records returned by this iterator are expected to * be in the specified sort order. If this method has been called, * then implementers must throw an IllegalStateException from tmpReadEnds() * when a samRecordWithOrdinal is read that violates the sort order. This method * may be called multiple times over the course of an iteration, * changing the expected sort, if desired -- from the time it is called, * it validates whatever sort is set, or stops validating if it * is set to null or SAMFileHeader.SortOrder.unsorted. If this method * is not called, then no validation of the iterated records is done. * * @param sortOrder The order in which records are expected to be returned * @return This SAMRecordIterator */
function
def evolve_wavefn_free(psi_0, a, b, m, dt=(1e-4*SECOND), delay=(0*SECOND), N=100, show_components=True): delay = delay.to(SECOND).value step_quantity = (b - a) / (N - 1) X_quantity = [a + i*step_quantity for i in range(N)] Y_quantity = [psi_0(x).standardize() for x in X_quantity] if Y_quantity[0].dimension() != LENGTH**(-1/2): raise ValueError('psi_0 should return Quantity with dimension {}, not {}'.format(LENGTH**(-1/2), Y_quantity[0].dimension())) step = float( step_quantity.standardize().value ) multiplier = complex( (dt * 1j * hbar / (2 * m)).standardize().value ) / (step ** 2) X_display = np.array([float(x.value) for x in X_quantity]) X = np.array([float(x.standardize().value) for x in X_quantity]) Y = np.array([complex(y.value) for y in Y_quantity]) Y /= ( np.abs(Y[:-1])**2 * np.diff(X) ).sum()**(1/2) if show_components: plot = MovingPlot(X_display, np.abs(Y), np.real(Y), np.imag(Y)) plot.lines[1].set_color('blue') plot.lines[1].set_linewidth(1) plot.lines[2].set_color('red') plot.lines[2].set_linewidth(1) else: plot = MovingPlot(X_display, np.abs(Y)) plot.lines[0].set_color('black') plot.lines[0].set_linewidth(2) plot.lines[0].set_zorder(10) plot.ax.set_xlabel('Position ({})'.format(step_quantity.unit)) plot.ax.set_ylabel('Wavefunction Magnitude ({})'.format(Y_quantity[0].unit)) t = 0*dt plot.ax.set_title('Evolving Wavefunction... (t = {})'.format(t)) change = np.zeros(Y.shape, complex) while True: time.sleep(delay) change[1:-1] = (Y[:-2] + Y[2:] - 2*Y[1:-1]) change[0] = change[1] / 2 change[-1] = change[-2] / 2 Y += multiplier * change Y /= (( np.abs(Y[:-1])**2 ).sum() * step)**(1/2) t += dt plot.ax.set_title('Evolving Wavefunction... (t = {})'.format(t)) if show_components: plot.batch_update(np.abs(Y), np.real(Y), np.imag(Y)) else: plot.update(np.abs(Y))
python
19
0.571359
132
47.738095
42
Generates a moving plot of the free wavefunction over time, in the interval [a, b], for a particle of mass m. psi_0 should be a function returning a Quantity, in appropriate units. a and b should be Quantities with units of length. dt should be a Quantity with units of time. N is an integer, the number of sample points to evolve with. delay is a Quantity, the amount of time to sleep between updates.
function
public class SemaphoreHandlerLock : IHandlerLock { private readonly int _operationCost; private readonly System.Threading.Semaphore _semaphore; private int _acquired = 0; public SemaphoreHandlerLock(string semaphoreName, int maxConcurrency = 1, int operationCost = 1) { _operationCost = operationCost; _semaphore = new System.Threading.Semaphore(maxConcurrency, maxConcurrency, semaphoreName); } public void Dispose() { if (_acquired > 0) { _semaphore.Release(_acquired); } _semaphore.Dispose(); } public Task<bool> TryAcquire() { if (_acquired < _operationCost) { for (int request = _acquired; request < _operationCost; request++) { if (_semaphore.WaitOne(TimeSpan.FromMilliseconds(50)) == false) { break; } _acquired++; } } return Task.FromResult(_acquired == _operationCost); } }
c#
17
0.687646
100
32.038462
26
/// <summary> /// An implementation of <seealso cref="IHandlerLock"/> which uses a machine wide <seealso cref="System.Threading.Semaphore"/> to provide single access saga controls to a single machine. If you have multiple worker machines you will need to use a distributed locking mechanism /// </summary>
class
@JsType(isNative = true, namespace = "PIXI") public class ObservablePoint { /** * The position of the displayObject on the x axis * relative to the local coordinates of the parent. */ @JsProperty public double x; /** * The position of the displayObject on the x axis * relative to the local coordinates of the parent. */ @JsProperty public double y; /** * * @param callback - callback when changed * @param scope - owner of callback * @param x - position of the point on the x axis * @param y - position of the point on the y axis */ @JsConstructor public ObservablePoint(Object callback, Object scope, double x, double y){} /** * Copies the data from another point * @param point - point to copy from * @return */ @JsMethod public native Point copy(Point point); /** * Copies the data from another point * @param point - point to copy from * @return */ @JsMethod public native Point copy(ObservablePoint point); /** * Sets the point to a new x and y position. * If y is omitted, both x and y will be set to x. * @param x - position of the point on the x axis * @param y - position of the point on the y axis */ @JsMethod public native void set(double x, double y); }
java
7
0.612691
79
24.886792
53
/** * Created by klaun on 12/09/16. * The Point object represents a location in a two-dimensional * coordinate system, where x represents the horizontal axis * and y represents the vertical axis. * An observable point is a point that triggers a callback when * the point's position is changed. * @see <a href="https://pixijs.github.io/docs/PIXI.ObservablePoint.html">ObservablePoint</a> * TODO: create test for callback and scope */
class
@Test public void choosing_new_card_twice_state_bug() throws InterruptedException, BSPaymentRequestException, JSONException { setupBeforeSubscription(true, false); onView(ViewMatchers.withId(R.id.newCardButton)).perform(click()); Espresso.pressBack(); onView(ViewMatchers.withId(R.id.newCardButton)).perform(click()); String state = ContactInfoTesterCommon.getDefaultStateByCountry(ContactInfoTesterCommon.billingContactInfo.getCountryKey()); if (state != null) { ContactInfoTesterCommon.changeState(R.id.billingViewComponent, state); } }
java
11
0.723127
132
54.909091
11
/** * Test a bug in new card subscription flow when trying to choose new card twice and then change the state. * For full billing with shipping with email new shopper * with price details presented */
function
func (cr *ChunkedReader) openRange() (err error) { now := time.Now() defer func() { promOpenTimes.Observe(time.Since(now).Seconds()) if err != nil { promOpenErrors.Add(1) } }() offset, length := cr.chunkOffset, cr.chunkSize fs.Debugf(cr.o, "ChunkedReader.openRange at %d length %d", offset, length) if cr.closed { return ErrorFileClosed } if rs, ok := cr.rc.(fs.RangeSeeker); ok { n, err := rs.RangeSeek(offset, io.SeekStart, length) if err == nil && n == offset { cr.offset = offset promOpenSeeks.Add(1) return nil } if err != nil { fs.Debugf(cr.o, "ChunkedReader.openRange seek failed (%s). Trying Open", err) } else { fs.Debugf(cr.o, "ChunkedReader.openRange seeked to wrong offset. Wanted %d, got %d. Trying Open", offset, n) } } var rc io.ReadCloser if length <= 0 { if offset == 0 { rc, err = cr.o.Open() } else { rc, err = cr.o.Open(&fs.RangeOption{Start: offset, End: -1}) } } else { rc, err = cr.o.Open(&fs.RangeOption{Start: offset, End: offset + length - 1}) } if err != nil { return err } return cr.resetReader(rc, offset) }
go
17
0.632911
111
26
41
// openRange will open the source Object with the current chunk range // // If the current open reader implements RangeSeeker, it is tried first. // When RangeSeek fails, o.Open with a RangeOption is used. // // A length <= 0 will request till the end of the file
function
func (c *Client) readPump() { defer func() { c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { logObj.Println("error: %v", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) if c.Player != nil { logObj.Printf("%s -> %s", c.Player.Playername, string(message)) } else { logObj.Printf("%s -> %s", "(no_player)", string(message)) } var msg json.RawMessage env := Envelope{ Msg: &msg, } if err := json.Unmarshal(message, &env); err != nil { logObj.Println("Error: ", err) return } switch strings.ToUpper(env.Type) { case "REGISTER": var r Registration if err := json.Unmarshal(msg, &r); err != nil { logObj.Println("REGISTER Error: ", err) return } var uname = r.Playername logObj.Println("uname", uname) err, pl := CreatePlayer(c, uname) c.Player = pl if err != nil { resp := Envelope{ Type: "Error", Msg: ErrorMsg { Message: err.Error(), }, } buf, _ := json.Marshal(resp) c.send <- buf break } globalLobby.register <- c resp := Envelope{ Type: "RegistrationOK", Msg: RegistrationOK{ Playername: c.Player.Playername, Playerhash: c.Player.Playerhash, }, } buf, _ := json.Marshal(resp) c.send <- buf break case "CHAT": var r Chat if c.Player == nil { break } if err := json.Unmarshal(msg, &r); err != nil { logObj.Print("CHAT Error: ", err) break } if (r.Lobby == "") || (r.Message == "") { break } hub := findHubNamed(r.Lobby) if hub == nil { break } retMsg := fmt.Sprintf("%s: %s", c.Player.Playername, r.Message) buf, _ := json.Marshal(Envelope{ Type: "Chat", Msg: Chat{ Lobby: r.Lobby, Message: retMsg, }, }) hub.broadcast <- buf } } }
go
21
0.586854
107
22.677778
90
// readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine.
function
public static IApplicationBuilder MapVersion( this IApplicationBuilder app, string path, object source = null) { if (app == null) throw new ArgumentNullException(nameof(app)); switch (source ?? Assembly.GetEntryAssembly()) { case Assembly a: return app.MapVersion(path, a); default: return app.Map(path, appBuilder => appBuilder.UseMiddleware<VersionMiddleware>(source)); } }
c#
16
0.51049
77
37.2
15
/// <summary> /// Adds a custom endpoint to the pipeline, /// responding only to GET requests with the output /// from the specified version source. /// </summary> /// <param name="app">The `IApplicationBuilder` instance from `Startup.Configure()`.</param> /// <param name="path">The endpoint path to use.</param> /// <param name="source"> /// An optional source supported by the configured VersionInformationService. /// /// Defaults to Entry Assembly Informational Version. /// </param> /// <returns>The `IApplicationBuilder` instance</returns>
function
public class SolutionTester implements Function<SolutionTest, CompletableFuture<TestResults>> { /** * The {@link SolutionPrinter} to use. Can be null if not needed. * * @since 1.0.0 */ protected @Nullable SolutionPrinter printer; /** * Construct a new <code>SolutionTester</code> with the default <code>PrintStream</code> of {@link System#out} * * @since 1.0.0 */ public SolutionTester() { this.printer = new SolutionPrinter(System.out::println); } /** * Construct a new <code>SolutionTester</code> with a {@link SolutionPrinter} instance * * @param printer The {@link SolutionPrinter} to use. Nullable. * @since 1.0.0 */ public SolutionTester(@Nullable SolutionPrinter printer) { this.printer = printer; } /** * Solve a {@link SolutionTest} * * @param solutionTest The <code>SolutionTest</code> to solve * @return The {@link CompletableFuture} of the {@link TestResults} */ private CompletableFuture<TestResults> solve(@NotNull final SolutionTest solutionTest) { final CompletableFuture<TestResults> testFuture = CompletableFuture.supplyAsync(solutionTest._toSolver()); if(printer != null) testFuture.thenAccept(printer); return testFuture; } /** * Solve a {@link SolutionTest} * * @param solutionTest The <code>SolutionTest</code> to solve * @return The {@link CompletableFuture} of the {@link TestResults} * @since 1.0.0 */ @Override public CompletableFuture<TestResults> apply(@NotNull final SolutionTest solutionTest) { try { return solve(solutionTest); } catch(Exception e) { e.printStackTrace(); return null; } } /** * Get the {@link SolutionPrinter} for this tester. Can be null. * * @return The <code>SolutionPrinter</code> * @since 1.0.0 */ public @Nullable SolutionPrinter getPrinter() { return printer; } /** * Set the {@link SolutionPrinter} for this tester. Can be null. * * @param printer The new <code>SolutionPrinter</code> * @since 1.0.0 */ public void setPrinter(@Nullable SolutionPrinter printer) { this.printer = printer; } /** * Gets result String if all processes have been completed * * @return Result String given that a printer exists and operations have finished * @since 1.0.0 */ @Override public String toString() { return printer != null ? printer.toString() : super.toString(); } }
java
11
0.621069
114
29
88
/** * Tester for {@link SolutionTest} tests. Utilizes {@link SolutionTestSolver} and {@link SolutionPrinter} to test and * print results. * <p> * Use {@link SolutionTester#apply(SolutionTest)} for * inputting a <code>SolutionTest</code>. * * @author Mikedeejay2 * @since 1.0.0 */
class
func (c *Client) ApplyMacros(in string, r *Recipient) (string, error) { if c.macros == nil { return in, nil } tokens, err := Tokenize(in) if err != nil { return "", err } chunks := make([]string, len(tokens)) for idx, token := range tokens { switch token.Type { case StaticToken: chunks[idx] = token.Text case MacroToken: body := strings.TrimSpace(strings.Trim(token.Text, "{}")) atoms := strings.SplitN(body, " ", 2) if m, ok := c.macros[atoms[0]]; ok { var params string if len(atoms) == 2 { params = atoms[1] } else { params = "" } if r != nil { params, err = r.Apply(params) if err != nil { return "", err } } chunks[idx] = m.Func(params) } else { chunks[idx] = token.Text } } } if len(chunks) == 1 { return chunks[0], nil } return strings.Join(chunks, ""), nil }
go
16
0.561283
71
20.85
40
// ApplyMacros runs all Macros registered with the Client against the provided string, returning the result. // If a Recipient is provided, substitution is performed on the macro parameter before the macro runs. // Any placeholders not handled by a macro are left intact.
function
ruuvi_driver_status_t ruuvi_interface_communication_ble4_gatt_dis_init(const ruuvi_interface_communication_ble4_gatt_dis_init_t* const dis) { if(NULL == dis) { return RUUVI_DRIVER_ERROR_NULL; } ret_code_t err_code = NRF_SUCCESS; ble_dis_init_t dis_init; memset(&dis_init, 0, sizeof(dis_init)); ruuvi_interface_communication_ble4_gatt_dis_init_t dis_local; memcpy(&dis_local, dis, sizeof(dis_local)); ble_srv_ascii_to_utf8(&dis_init.manufact_name_str, dis_local.manufacturer); ble_srv_ascii_to_utf8(&dis_init.model_num_str, dis_local.model); ble_srv_ascii_to_utf8(&dis_init.serial_num_str, dis_local.deviceid); ble_srv_ascii_to_utf8(&dis_init.hw_rev_str, dis_local.hw_version); ble_srv_ascii_to_utf8(&dis_init.fw_rev_str, dis_local.fw_version); dis_init.dis_char_rd_sec = SEC_OPEN; err_code = ble_dis_init(&dis_init); return ruuvi_platform_to_ruuvi_error(&err_code); }
c
8
0.724022
139
51.705882
17
/** * Initialize BLE4 Device Information service * * parameter dis: pointer to data which should be presented over DIS. Memory will be deep-copied */
function
private boolean isUSLanguageRefex(DescriptionVersionBI<?> desc) throws Exception { for (RefexVersionBI<?> annotation : desc.getAnnotationsActive(OTFUtility .getViewCoordinate())) { if (annotation.getAssemblageNid() == Snomed.US_LANGUAGE_REFEX.getNid()) { return true; } } return false; }
java
10
0.672673
79
32.4
10
/** * Indicates whether or not US language refex is the case. * * @param desc the desc * @return <code>true</code> if so, <code>false</code> otherwise * @throws Exception the exception */
function
public static IList<IODataRoutingConvention> CreateDefaultWithAttributeRouting( string routeName, IRouteBuilder builder) { if (builder == null) { throw Error.ArgumentNull(nameof(builder)); } return CreateDefaultWithAttributeRouting(routeName, builder.ServiceProvider); }
c#
13
0.604278
89
36.5
10
/// <summary> /// Creates a mutable list of the default OData routing conventions with attribute routing enabled. /// </summary> /// <param name="routeName">The name of the route.</param> /// <param name="builder">The <see cref="IRouteBuilder"/> to add the route to.</param> /// <returns>A mutable list of the default OData routing conventions.</returns>
function
function resizeHeight() { if ($('#console-page').hasClass('collapsed')) { return; } var rowHeight = 200; $('.console-leaf-category').each(function() { const thisContainer = $('.console-build-column-stacked .console-cell-container-inner').first(); const thisHeight = thisContainer.height(); if (thisHeight > rowHeight) rowHeight = thisHeight; }); $('.console-cell-container').height(rowHeight); $('.console-commit-item').each(function() { $(this).height(rowHeight - 1); const desc = $(this).find('.console-commit-description').first(); const text = desc.find('p').first(); const isClipped = desc.height() < text.height(); $(this).toggleClass('bottom-hidden', isClipped); }); var width = 0; $('#console>.console-column').each(function() {width += $(this).width();}); $('.console-commit-item-overlay').width(width); }
javascript
16
0.609783
101
40.863636
22
/** * Resizes commit cells when the window resizes. * * In the expanded view, the width is set by the browser window size. * When the window sizes changes, it changes the height of all the cells * because the cells contains elements that flow left to right. * Because the commit description on the left size are disjoint from * the cells, the height of the commit descriptions need to be updated. */
function
public boolean process( List<AssociatedPair> points, DMatrixRMaj solution ) { if (points.size() < 8) throw new IllegalArgumentException("Must be at least 8 points. Was only " + points.size()); LowLevelMultiViewOps.computeNormalization(points, N1, N2); createA(points, A); if (process(A, solution)) return false; PerspectiveOps.multTranA(N2.matrix(null), solution, N1.matrix(null), solution); if (computeFundamental) return projectOntoFundamentalSpace(solution); else return projectOntoEssential(solution); }
java
10
0.749064
94
40.153846
13
/** * <p> * Computes a fundamental or essential matrix from a set of associated point correspondences. * </p> * * @param points List of corresponding image coordinates. In pixel for fundamental matrix or * normalized coordinates for essential matrix. * @return true If successful or false if it failed */
function
makeRequestHeader(uri, options = {}) { return { rejectUnauthorized: this.strictSSL, method: options.method || 'GET', uri, json: true, ...options, }; }
javascript
7
0.547368
41
20.222222
9
/** * @name makeRequestHeader * @function * Creates a requestOptions object based on the default template for one * @param {string} uri * @param {object} [options] - an object containing fields and formatting how the */
function
update(endPosX, endPosY, offsetX, offsetY) { let endPos = createVector(endPosX + offsetX, endPosY + offsetY); if (this.flying) { if (this.origin.y < 200) { this.forward(); } else { if (this.angX > -480) { this.loopDeLoop(); } else if (this.origin.y > 110) { this.forward(); } else { if (this.origin.dist(endPos) < 0.5) { this.flying = false; this.floating = true; } else { this.fallIn(endPos); } } } } if (this.floating) { this.float(endPos); } }
javascript
18
0.472492
68
24.791667
24
// the flight behaviour needs to be based on three parts in sequence: flight to rotation, then rotation, then flight to formation
function
static void checkDirectMemCapacity(final int k, final long n, final long memCapBytes) { final int reqBufBytes = getUpdatableStorageBytes(k, n); if (memCapBytes < reqBufBytes) { throw new SketchesArgumentException("Possible corruption: Memory capacity too small: " + memCapBytes + " < " + reqBufBytes); } }
java
12
0.701493
92
47
7
/** * Checks the validity of the direct memory capacity assuming n, k. * @param k the given value of k * @param n the given value of n * @param memCapBytes the current memory capacity in bytes */
function
public class EvaluationRunner extends Thread { private final Field cells; private int delayMs = 300; private int limitPopulation = 200000; //stop evaluation, when reached this limit volatile boolean stopRequested = false; private NotificationReceiver receiver=null; private TotalisticRule rule; public EvaluationRunner( Field cells, TotalisticRule rul, NotificationReceiver r ) { super("Evaluator"); this.cells = cells; rule = rul; receiver = r; } @Override public void run() { int count = 0; while( ! stopRequested ){ if (cells.population() >= limitPopulation ){ System.out.println("Population reached "+cells.population()+" which exceeeds limit:"+limitPopulation+" stopping simulation"); stopRequested = true; break; } try{ cells.evaluate(rule); receiver.notifyUpdate( cells ); count += 1; Thread.sleep( delayMs ); }catch(OutOfMemoryError err){ System.out.println( "Memory exceeded on population " + cells.population() + ", evaluation stopped." ); stopRequested = true; } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Evaluation stopped after "+count+" steps on population "+cells.population()); } public void requestStop() { stopRequested = true; } /*Setter-getter boilerplate*/ public void setLimitPopulation(int limitPopulation) { if ( limitPopulation < 0 ) throw new RuntimeException("Limit mus be > 1"); this.limitPopulation = limitPopulation; } public int getLimitPopulation() { return limitPopulation; } public void setDelayMs(int delayMs) { if (delayMs < 0) throw new RuntimeException("Delay must be >= 0"); this.delayMs = delayMs; } public int getDelayMs() { return delayMs; } }
java
18
0.704532
129
27.590164
61
/**Thread, that runs in background and continuously evaluates the field, when requested*/
class
def IsConfigUserInputValid(user_input, valid_el): if not user_input: return False try: valid_el.index(str(user_input)) except ValueError: return False return True
python
10
0.730337
49
24.571429
7
Sanity check for user input. Args: user_input: str User input. valid_el: list List of valid elements. Returns: bool True if user input is valid, False otherwise.
function
@Async public Future<String> run(RasterCropRequest payload, String id) throws AmazonClientException, InvalidInputException, IOException, InterruptedException { ServiceResource serviceResource = new ServiceResource(); serviceResource.setServiceResourceId(id); int percent = (new SecureRandom()).nextInt(101); JobProgress jobProgress = new JobProgress(percent); StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_RUNNING); statusUpdate.setProgress(jobProgress); serviceResource.setStatus(statusUpdate); dataAccessor.addServiceResource(serviceResource); LOGGER.info("Updating DB with running status PRIOR to run."); DataResource dataResource = cropRasterCoverage(payload, id); LOGGER.info("Updating DB with complete status AFTER crop."); percent = 100; jobProgress = new JobProgress(percent); statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS); statusUpdate.setProgress(jobProgress); serviceResource.setStatus(statusUpdate); serviceResource.setResult(dataResource); dataAccessor.update(serviceResource); return new AsyncResult<String>("crop raster thread"); }
java
9
0.800534
91
47.869565
23
/** * Asynchronous handler for cropping the image demonstrating service monitor capabilities of piazza. * * @return Future */
function
def PenalizedLoss(mask, loss_func, mask_prop=1.0, mask_scaling=1.0, preprocessing_func=None): def scale_mask(mask, scaling): if scaling != 1.0: size = round(1 / scaling) mask = K.pool2d(mask, pool_size=(size, size), strides=(size, size), padding="valid", data_format=K.image_data_format(), pool_mode="avg") logger.debug("resized tensor: %s", mask) return mask mask = scale_mask(mask, mask_scaling) if preprocessing_func is not None: mask = preprocessing_func(mask) mask_as_k_inv_prop = 1 - mask_prop mask = (mask * mask_prop) + mask_as_k_inv_prop def inner_loss(y_true, y_pred): if K.backend() == "plaidml.keras.backend": n_true = y_true * mask n_pred = y_pred * mask else: n_true = K.concatenate([y_true[:, :, :, i:i+1] * mask for i in range(3)], axis=-1) n_pred = K.concatenate([y_pred[:, :, :, i:i+1] * mask for i in range(3)], axis=-1) return loss_func(n_true, n_pred) return inner_loss
python
17
0.501658
94
43.703704
27
Plaidml + tf Penalized loss function mask_scaling: For multi-decoder output the target mask will likely be at full size scaling, so this is the scaling factor to reduce the mask by. preprocessing_func: The preprocessing function to use. Should take a Keras Input as it's only input
function
function generateText(table, textSize) { var key = randomKey(table); var text = key.split(" "); var prefixSize = text.length; for (var i=0; i < textSize-prefixSize; i++) { word = randomArrayElement(table[key]) text.push(word); key = text.slice(text.length-prefixSize, text.length).join(" "); } return text.join(" "); }
javascript
13
0.597297
72
27.538462
13
/* Generate text from a Markov Random Chain @param {Object} table - associative array mapping prefixes => list of words. @param {int} textSize - number of words to include in the generated text. */
function
public class BidirectionalMultiMap<K, V> { /** * The multimap holding mappings from K -> V. */ private final SetMultimap<K, V> _primaryMap; /** * The multimap holding mappings from V -> K. */ private final SetMultimap<V, K> _secondaryMap; /** * The inverted BidirectionalMultiMap which is a view over the same * underlying data. */ private final BidirectionalMultiMap<V, K> _inverse; /** * Create the multimap. */ public BidirectionalMultiMap() { this(HashMultimap.<K, V>create(), HashMultimap.<V, K>create()); } /** * Private constructor taking the underlying multimaps. No arg checking as * only called from this class. The inverse will be generated from the * passed multimaps. * * @param primaryMap the multimap holding mappings from K -> V * @param secondaryMap the multimap holding mappings from V -> K */ private BidirectionalMultiMap(SetMultimap<K, V> primaryMap, SetMultimap<V, K> secondaryMap) { _primaryMap = primaryMap; _secondaryMap = secondaryMap; // Ensure that this instance is used as the inverse of the inverse _inverse = new BidirectionalMultiMap<>(_secondaryMap, _primaryMap, this); } /** * Private constructor taking the underlying multimaps and the inverse. * No arg checking as only called from this class. * * @param primaryMap the multimap holding mappings from K -> V * @param secondaryMap the multimap holding mappings from V -> K * @param inverse the inverse of this BidirectionalMultiMap */ private BidirectionalMultiMap(SetMultimap<K, V> primaryMap, SetMultimap<V, K> secondaryMap, BidirectionalMultiMap<V, K> inverse) { _primaryMap = primaryMap; _secondaryMap = secondaryMap; _inverse = inverse; } /** * Return the inverse of this BidirectionalMultiMap. * * @return the inverse, not null */ public BidirectionalMultiMap<V, K> inverse() { return _inverse; } /** * Add a mapping from key to value into this multimap. If the mapping already * exists then this method will have no effect. * * @param key they key the value is added against, not null * @param value the value to add for the key, not null */ public void put(K key, V value) { _primaryMap.put(ArgumentChecker.notNull(key, "key"), ArgumentChecker.notNull(value, "value")); _secondaryMap.put(value, key); } /** * Returns the collection of values associated with the specified * key in this multimap, if any. An empty collection will be * returned if there are no mappings. The returned collection does * not permit modifications. * * @param key the key find mappings for * @return the collection of values associated with the key, not null */ public Set<V> get(K key) { return Collections.unmodifiableSet(_primaryMap.get(key)); } /** * Returns true if this multimap contains at least one key-value * pair with the specified key. * * @param key the key to check for * @return true if this multimap contains at least one key-value * pair with the specified key */ public boolean containsKey(K key) { return _primaryMap.containsKey(key); } /** * Returns all distinct keys contained in this multimap. The * returned set does not permit modifications. * * @return the set of distinct keys, not null */ public Set<K> keySet() { return Collections.unmodifiableSet(_primaryMap.keySet()); } /** * Remove an entry from this multimap. * * @param key they key the value is removed from, not null * @param value the value to remove for the key, not null */ public void remove(K key, V value) { _primaryMap.remove(ArgumentChecker.notNull(key, "key"), ArgumentChecker.notNull(value, "value")); _secondaryMap.remove(value, key); } /** * Return the number of mappings in this multimap. * * @return the number of mappings */ public int size() { return _primaryMap.size(); } /** * Remove all the mappings for a key, returning the set * of values removed. At the same time, all values * referencing the key will have the key removed. The * returned set does not permit modifications. * * @param key the key to remove * @return the set of values removed */ public Set<V> removeAll(K key) { Set<V> removed = _primaryMap.removeAll(key); for (V value : removed) { _inverse.remove(value, key); } return Collections.unmodifiableSet(removed); } }
java
11
0.672095
101
29.709459
148
/** * A cut down multimap that also provides an inverted version of itself. If * there are many to many mappings from types K -> V and V -> K, this provides * methods to lookup all Vs associated with a K. By using the {@link #inverse()} * method, it is then possible to lookup all Ks associated with a V. * <p> * Modifications made to this instance will be automatically reflected in its * inverse. Similarly, modifications made to the inverse will be reflected in * this instance. * <p> * This code is not thread-safe, so any synchronization required must be done * externally. * * @param <K> the type of the keys for the map * @param <V> the type of the values for the map, recommended to be * a different type from K to avoid confusion when calling methods */
class
public class WeakReferenceObservable extends DefaultObservable { public WeakReferenceObservable(final Observable observable) { super(observable); } @Override public void addObserver(final Observer referent) { super.addObserver(new WeakReferenceObserver(referent)); } /** * This method deletes the Observer passed as argument but also discards those Observers which where reclaimed by gc */ @Override public void deleteObserver(final Observer observer) { for (final Observer weakObserver : getObservers()) { final WeakReferenceObserver weakReference = (WeakReferenceObserver) weakObserver; final Observer referent = weakReference.get(); if (referent == null || referent.equals(observer)) deleteWeakReference(weakReference); } } private void deleteWeakReference(final WeakReferenceObserver observer){ super.deleteObserver(observer); } // // inner classes // private class WeakReferenceObserver extends WeakReference<Observer> implements Observer { public WeakReferenceObserver(final Observer referent) { super(referent); } @Override //XXX::OBS public void update(final Observable o, final Object arg) { public void update() { final Observer referent = get(); if (referent != null) //XXX::OBS referent.update(o, arg); referent.update(); else deleteWeakReference(this); } } }
java
12
0.636706
120
29.615385
52
/** * Implementation of Observable that holds references to Observers as * WeakReferences. * * @note This implementation notifies the observers in a synchronous * fashion. Note that this can cause trouble if you notify observers while * in a transactional context because the notification is then done also in the * transaction. * * <p> * This class is based on the work done by Martin Fischer. See references below. * * @see <a * href="http://www.jroller.com/martin_fischer/entry/a_generic_java_observer_pattern"> * Martin Fischer: Observer and Observable interfaces</a> * @see <a href="http://jdj.sys-con.com/read/35878.htm">Improved Observer/Observable</a> * * @see Observable * @see Observer * @see DefaultObservable * * @author Martin Fischer (original author) * @author Richard Gomes * @author Srinivas Hasti */
class
pub fn validate(&self) -> Result<(), &'static str> { if let Err(err) = self.validate_head() { return Err(err); } if let Some(ref tail) = self.tail { Chain::validate(tail) } else if self.head .hash() .eq(Block::genesis_block(self.head.difficulty.clone()).hash()) { Ok(()) } else { Err(CHAIN_ERROR_INVALID_GENESIS) } }
rust
17
0.466518
74
28.933333
15
/// Checks that the chain is valid from head to tail and that it starts from the genesis block. /// The current implementation is not the most efficient but is efficient enough /// for this simulation.
function
public class Bitboards { // Section 1 - Basic areas of the board. /** * Array of 64 bitboards representing single squares on a chessboard. They are * ordered from h1 to a8, the reason for this seemingly strange ordering is due * to the fact this is the natural representation taking into account these * bitboards are just numbers growing in size. The bitboard representing h1 is * the smallest, a8 the largest. */ public static final long[] SOB; /** * Array of 8 bitboards representing the ranks on a chessboard. Ordered rank 1 * up to rank 8. */ public static final long[] RNK; /** * Array of 8 bitboards representing the files on a chessboard. Ordered from a * to h. */ public static final long[] FILE; /** * Array of 15 bitboards representing the diagonals of gradient 1 on a * chessboard. Ordered from right to left. */ public static final long[] DGNL; /** * Array of 15 bitboards representing the diagonals of gradient -1 on a * chessboard. Ordered from left to right. */ public static final long[] ADGNL; static { SOB = generateSingleOccupancyBitboards(); RNK = generateRankBitboards(); FILE = generateFileBitboards(); DGNL = generateDiagonalBitboards(); ADGNL = generateAntidiagonalBitboards(); } /** Universal set bitboard (all bits set) */ public static final long USET = multipleOr(RNK); /** Border set */ public static final long BSET = multipleOr(new long[] { RNK[0], FILE[0], RNK[7], FILE[7] }); /** * Empty board movesets, ordered wp, bp, Bishop, Knight, Rook, Queen, King */ public static final long[][] EBM; /** * Empty board attacksets, ordered wp, bp, Bishop, Knight, Rook, Queen, King */ public static final long[][] EBA; static { EBM = generateAllEmptyBoardPieceMovementBitboards(); EBA = generateAllEmptyBoardPieceAttackBitboards(); } // ----------------------------------- // Section 2 - Constants required for Magic bitboard implementation for // Rooks, Bishops amd Pawn first moves /** * Bishop occupancy masks for each square. An bishop occupancy mask for square i * is the corresponding empty board bishop moveset & ~(border set). */ public static final long[] BOM; /** * Rook occupancy masks for each square. Slightly more complicated to construct * than bishop ones if the rook lies in the border set. Basically you just * remove the end squares of the rook move path on an empty board and keep the * rest (except the square containing the rook). */ public static final long[] ROM; /** * Container of all the possible bishop occupancy variations for each different * square. A bov for square i is BOM[i] & (location of all pieces on the board). * There are 2^(Cardinality(BOM[i])) variations. */ public static final long[][] BOV; /** * Container of all the possible rook occupancy variations for each different * square. A rov for square i is ROM[i] & (location of all pieces on the board). * There are 2^(Cardinality(ROM[i])) variations. */ public static final long[][] ROV; /** * Bishop magic bitshift values for each square. BMB[i] = Cardinality(BOM[i]). * The magic bitshifts form part of the surjective mapping definition behind * magic bitboards */ public static final byte[] BMB; /** * Rook magic bitshift values for each square. RMB[i] = Cardinality(ROM[i]). The * magic bitshifts form part of the surjective mapping definition behind magic * bitboards */ public static final byte[] RMB; /** * For pawns all occ masks have the same cardinality so there is only one magic * bitshift value */ public static final byte PFMB = 62; /** * Bishop magic number values for each square. Used for defining the surjective * map definition used in magic bitboards. */ public static final long[] BMN = { 0x8480100440302L, 0x200200a1010000L, 0x4010040441508100L, 0x491040080030021L, 0x21104080208000L, 0x1032011000000L, 0x41c0128080000L, 0x2002020201040200L, 0x120430040040L, 0x201040812084209L, 0x4220801002204L, 0x8044502000000L, 0x10031040000102L, 0x51008040004L, 0x10080a0090041000L, 0x4060002208040400L, 0x480a000420042410L, 0x20880801041882L, 0x8005408011012L, 0x800048e004000L, 0x1001820080000L, 0x203410080821L, 0x4800800410881800L, 0x411400022021000L, 0x4200040080100L, 0x3200008024401L, 0x2000480001020402L, 0x1408080000820500L, 0x1060004008400L, 0x2200200200b000L, 0xc018004002020200L, 0x1020001084500L, 0x208334000086808L, 0x4040404200120L, 0x404004840040400L, 0x600800010104L, 0x40004100401100L, 0x80820080041000L, 0xc004010040020820L, 0x12006202010182L, 0x400880840040800L, 0xc008404401108L, 0x8011080100c800L, 0x1024010400200L, 0x5010124000201L, 0x10a0221000400209L, 0x118080080800400L, 0x4008202000040L, 0x905108220200001L, 0x40482008a200008L, 0xa0084040880L, 0x2220084020a80000L, 0x241002020004L, 0x2500048408820000L, 0x42020224050000L, 0x20010200810000L, 0x2002082086000L, 0x40020104460200L, 0x20084018820L, 0x110000a2420200L, 0x2200000010020200L, 0x220021a0200L, 0x402041006020400L, 0x20110102040840L }; /** * Rook magic number values for each square. Used for defining the surjective * map definition used in magic bitboards. */ public static final long[] RMN = { 0x10800480a0104000L, 0x40002000403000L, 0x80281000200080L, 0x800c0800500280L, 0x8200200410081200L, 0x4a00080200040510L, 0x2180408002000100L, 0x180004100002080L, 0x4000800080204000L, 0x802010814000L, 0x444801000822001L, 0x801000680080L, 0x1120808004000800L, 0x42000408060010L, 0x80800200110080L, 0x800140800500L, 0x208000804008L, 0x140240400a201000L, 0x200808010002000L, 0x1010008201000L, 0x8808018018400L, 0x808004000200L, 0x110808002000500L, 0x20021004084L, 0x1802080004000L, 0x200040100040L, 0x200080803000L, 0x100080080284L, 0x28080080800400L, 0x800040080020080L, 0x80400100a01L, 0x202100090000804aL, 0x401282800020L, 0x200040401000L, 0x4200080801000L, 0x40800800801000L, 0x800800801400L, 0x800c00800200L, 0x8000500224000801L, 0x800840800100L, 0x90824002208000L, 0x420600050004000L, 0x406001010010L, 0x20100008008080L, 0x200040801010010L, 0x20004008080L, 0x9008600010004L, 0x100010080420004L, 0x800040002004c0L, 0x400080210100L, 0x200200081100080L, 0x8000880080100080L, 0x1080082040080L, 0x4068810400020080L, 0x20801100400L, 0x1000202418100L, 0x408001102501L, 0x11008042002852L, 0x8800406001043009L, 0x1012000821100442L, 0x1000442080011L, 0x1001000c00020801L, 0x400082104821004L, 0x2080010140208402L }; static { BOV = generateAllBishopOccupancyVariations(); ROV = generateAllRookOccupancyVariations(); ROM = generateRookOccupancyMasks(); BOM = generateBishopOccupancyMasks(); RMB = generateRookMagicBitshifts(); BMB = generateBishopMagicBitshifts(); } // -------------------------------------------- // Section 3 - the move databases /** * Bishop move database implementing the magic bitboard mapping technique. The * domain of the map is the set of all bishop occupancy variations and the * target of the map is this database. */ public static final long[][] BMM; /** * Rook move database implementing the magic bitboard mapping technique. The * domain of the map is the set of all rook occupancy variations and the target * of the map is this database. */ public static final long[][] RMM; static { RMM = generateRookMagicMoveDatabase(); BMM = generateBishopMagicMoveDatabase(); } }
java
10
0.726717
113
39.468421
190
/** * A class initialising all the variables we need to implement board * representation via the well known magic bitboard approach. * * @author TB * @date 21 Jan 2017 */
class
public async Task<Tuple<string, string>> Read(string collectionName, string key) { var docID = GetDocumentID(collectionName, key); var result = await bucket.GetAsync<string>(docID); if (result.Success) return Tuple.Create<string, string>(result.Value, result.Cas.ToString()); if (!result.Success && result.Status == Couchbase.IO.ResponseStatus.KeyNotFound) return Tuple.Create<string, string>(null, ""); throw result.Exception; }
c#
13
0.613383
93
52.9
10
/// <summary> /// Reads a document representing a grain state object. /// </summary> /// <param name="collectionName">The type of the grain state object.</param> /// <param name="key">The grain id string.</param> /// <returns>Completion promise for this operation.</returns>
function
public Object authenticate(HpcIntegratedSystemAccount dataTransferAccount, String s3URLorRegion, String encryptionAlgorithm, String encryptionKey) throws HpcException { if (dataTransferAccount.getIntegratedSystem().equals(HpcIntegratedSystem.AWS)) { return authenticateAWS(dataTransferAccount.getUsername(), dataTransferAccount.getPassword(), s3URLorRegion, encryptionAlgorithm, encryptionKey); } else { boolean pathStyleAccessEnabled = pathStyleAccessEnabledProviders .contains(dataTransferAccount.getIntegratedSystem()); return authenticateS3Provider(dataTransferAccount.getUsername(), dataTransferAccount.getPassword(), s3URLorRegion, pathStyleAccessEnabled, dataTransferAccount.getIntegratedSystem(), encryptionAlgorithm, encryptionKey); } }
java
11
0.825255
110
59.384615
13
/** * Authenticate a (system) data transfer account to S3 (AWS or 3rd Party * Provider) * * @param dataTransferAccount A data transfer account to authenticate. * @param s3URLorRegion The S3 URL if authenticating with a 3rd party S3 * Provider (Cleversafe, Cloudian, etc), or Region if * authenticating w/ AWS. * @param encryptionAlgorithm (Optional) The encryption algorithm. * @param encryptionKey (Optional) The encryption key. * @return An authenticated TransferManager object, or null if authentication * failed. * @throws HpcException if authentication failed */
function
public class LineBasedProtocol : IInternetPacket { public static byte[] CRLF = { 0x0D, 0x0A }; public byte[] EndOfLine { get; set; } = CRLF; public bool UsePrompt { get; set; } = false; internal byte[] PromptSequence { get; set; } public string Prompt { get => MessageToString(Trim(PromptSequence)); set => PromptSequence = EndOfLine.Concat(StringToMessage(value)).ToArray(); } public IEnumerable<int> FindPackets(byte[] bytes, uint newBytesLength = 0) { byte[] Delim = (UsePrompt && PromptSequence != null) ? PromptSequence : EndOfLine; for (int i = 0; i < bytes.Length; i++) { if (bytes.Skip(i).Take(Delim.Length).SequenceEqual(Delim)) yield return i + Delim.Length; } } public byte[] Trim(byte[] Message) { byte[] Delim = (UsePrompt && PromptSequence != null) ? PromptSequence : EndOfLine; int Index = Message.Length - 1; int EOLIndex = Delim.Length - 1; while ((Index >= 0) && (EOLIndex >= 0) && (Message[Index] == Delim[EOLIndex])) { Index--; EOLIndex--; } int MessageStart = -1; if (UsePrompt && PromptSequence != null) { byte[] PromptBytes = PromptSequence.Skip(EndOfLine.Length).ToArray(); for (int i = 0; (MessageStart == -1) && (i < Index); i += PromptBytes.Length) { if (!Message.Skip(i).Take(PromptBytes.Length).SequenceEqual(PromptBytes)) MessageStart = i; } } if (MessageStart == -1) MessageStart = 0; if ((EOLIndex < 0) && (Index >= 0)) { byte[] NewMessage = new byte[Index + 1 - MessageStart]; Buffer.BlockCopy(Message, MessageStart, NewMessage, 0, Index + 1 - MessageStart); return NewMessage; } else if ((Index < 0) && (EOLIndex < 0)) return new byte[0]; else return Message; } public string MessageToString(byte[] Message) { return UTF8Encoding.UTF8.GetString(Trim(Message)); } public byte[] StringToMessage(string Line) { return UTF8Encoding.UTF8.GetBytes(Line); } }
c#
18
0.498604
97
39.451613
62
/// <summary> /// Defines the "packet type" of line-based internet protocols /// Optionally will block lines received until a prompt sequence is received /// </summary>
class
@ServerEndpoint("/wstraffic") public class TrafficEndpoint { /* Queue for all open WebSocket sessions */ static Queue<Session> queue = new ConcurrentLinkedQueue<>(); private static final Logger log = Logger.getLogger("TrafficEndpoint"); /* Called by WebMDB when it receives messages from the JMS topic */ public static synchronized void sendAll(String msg) { log.info("[TrafficEndpoint] sendAll()"); try { /* Send messages from the JMS queue to all sessions */ for (Session session : queue) { if (session.isOpen()) { session.getBasicRemote().sendText(msg); log.log(Level.INFO, "[TrafficEndpoint] Sent: {0}", msg); } } } catch (IOException e) { log.log(Level.INFO, "[TrafficEndpoint] Exception: {0}", e.getMessage()); } } /* Add and remove sesions from the queue */ @OnOpen public void openConnection(Session session) { log.info("[TrafficEndpoint] openConnection()"); queue.add(session); } @OnClose public void closedConnection(Session session) { log.info("[TrafficEndpoint] closedConnection()"); queue.remove(session); } @OnError public void error(Session session, Throwable t) { queue.remove(session); log.info("[TrafficEndpoint] error()"); } }
java
15
0.588603
84
32.488372
43
/* This endpoint forwards to web clients the JSON messages * received by the WebMDB bean from the JMS topic */
class
public async Task<string> TranslateAsync(string text, string fromLanguage = null, string toLanguage = null) { try { text = text.Replace(" ", "%20"); var requestMethod = string.Format(_translateTextRequest, text, fromLanguage ?? _defaultFromLanguage, toLanguage ?? _defaultToLanguage); var request = new RestRequest(requestMethod, DataFormat.Json); var response = _client.Get(request); if (response.StatusCode == HttpStatusCode.OK) { var content = response.Content; var json = (JsonObject)SimpleJson.DeserializeObject(content); var responseCode = (long)json["responseStatus"]; var responseData = (JsonObject)json["responseData"]; switch (responseCode) { case 200: return responseData["translatedText"].ToString(); case 400: throw new Exception($"Bad parameters; a compulsory argument is missing, or there is an argument with wrong format. Details: {json["responseDetails"]}"); case 451: throw new Exception("Unsupported pair; the translation engine can't translate with the requested language pair."); case 452: throw new Exception("Unsupported format; the translation engine doesn't recognize the requested format."); case 500: throw new Exception($"Unexpected error; an unexpected error happened. Details: {json["responseDetails"]}"); case 552: throw new Exception("The traffic limit for your IP or your user has been reached."); default: throw new Exception("Error parsing response."); } } else { throw new Exception($"HTTP Error {response.StatusCode}! {response.ErrorMessage}", response.ErrorException); } } catch (Exception ex) { throw; } }
c#
21
0.508576
180
54.547619
42
/// <summary> /// Translates a specific text from a particular language to another language. /// </summary> /// /// <exception cref="Exception"> Thrown when an exception error condition occurs. </exception> /// /// <param name="text"> The text to translate. </param> /// <param name="fromLanguage"> (Optional) The language to translate the text from. Defaults to the configured DefaultFromLanguage. </param> /// <param name="toLanguage"> (Optional) The language to translate the text to. Defaults to the configured DefaultToLanguage. </param> /// /// <returns> /// The translated text. /// </returns>
function
def interamp(SegyData1, SegyData2, shot=1, shot2=None, n_blocks=2, cap=0., levels=50, vmin=None, vmax=None, cmap=plt.cm.seismic, wstart=0, wend=None, xstart=0, xend=None, save=False, save_path="./"): if not (isinstance(SegyData1, tools.SegyData) and isinstance(SegyData2, tools.SegyData)): raise TypeError("SegyData must be a fullwaveqc.tools.SegyData instance.") data1 = SegyData1.data[shot-1] if shot2 is not None: data2 = SegyData2.data[shot2-1] else: data2 = SegyData2.data[shot-1] assert (data1.shape == data2.shape) nx = data1.shape[0] block_len = int(nx / n_blocks) data_inter = np.zeros_like(data1) init = 0 for i in range(0, n_blocks, 2): data_inter[init:block_len * (i + 1), ] = data1[init:block_len * (i + 1), ] data_inter[init + block_len:block_len * (i + 2), :] = data2[init + block_len:block_len * (i + 2), :] init = init + 2 * block_len InterData = copy.deepcopy(SegyData1) InterData.data[shot-1] = data_inter InterData.name = SegyData2.name + "-" + SegyData1.name + "-INTERAMP" amplitude(InterData, shot=shot, cap=cap, levels=levels, vmin=vmin, vmax=vmax, cmap=cmap, save=save, wstart=wstart, wend=wend, xstart=xstart, xend=xend, save_path=save_path) del InterData return None
python
12
0.637115
108
52.28
25
Plots the interleaving amplitude map of a SegyData1 and SegyData2 objects in timesamples vs receiver index. Uses properties of matplotlib.contourf. Parameters ---------- SegyData1: fullwaveqc.tools.SegyData object outputted from fullwaveqc.tools.load function for the segy data SegyData2: fullwaveqc.tools.SegyData object outputted from fullwaveqc.tools.load function for the segy data Requires same number of samples, sampling interval, shots and receiver positions as SegyData1 shot: int, optional shot number to visualise SegyData1. Count starts from 1. Default 1 shot2: int, optional shot number to visualise SegyData2. Count starts from 1. If None, will . be read the same as 'shot'. Default None n_blocks: int, optional Number of total blocks in the interleaving space levels: int, optional amount of levels in the contour plot. See matplotlib.pyplot.contourf parameters. Default 50 cap: float, optional absolute value of amplitudes to cap, shown as 0. Default 0. vmin: float, optional min val of color plot scale. See matplotlib.pyplot.contourf parameters. Default None. vmax: float, optional max val of color plot scale. See matplotlib.pyplot.contourf parameters. Default None. cmap: matplotlib.pyplot.cm colormap. Default plt.cm.seismic xstart: int, optional first receiver index to plot. Default 0. xend: int, optional last receiver index to plot. Default None wstart: int, optional first timesample in time units to plot. Default 0 wend: int, optional last timesample in time units to plot. Default None save: bool, optional set to true in order to save the plot in png 300dpi. Default False save_path: str, optional path to save the plot. Default "./" Returns ------- None
function
public class DbContextOperations { private readonly IOperationReporter _reporter; private readonly Assembly _assembly; private readonly Assembly _startupAssembly; private readonly string[] _args; private readonly AppServiceProviderFactory _appServicesFactory; public DbContextOperations( [NotNull] IOperationReporter reporter, [NotNull] Assembly assembly, [NotNull] Assembly startupAssembly, [NotNull] string[] args) : this(reporter, assembly, startupAssembly, args, new AppServiceProviderFactory(startupAssembly, reporter)) { } protected DbContextOperations( [NotNull] IOperationReporter reporter, [NotNull] Assembly assembly, [NotNull] Assembly startupAssembly, [NotNull] string[] args, [NotNull] AppServiceProviderFactory appServicesFactory) { Check.NotNull(reporter, nameof(reporter)); Check.NotNull(assembly, nameof(assembly)); Check.NotNull(startupAssembly, nameof(startupAssembly)); Check.NotNull(args, nameof(args)); _reporter = reporter; _assembly = assembly; _startupAssembly = startupAssembly; _args = args; _appServicesFactory = appServicesFactory; } public virtual void DropDatabase([CanBeNull] string contextType) { using var context = CreateContext(contextType); var connection = context.Database.GetDbConnection(); _reporter.WriteInformation(DesignStrings.DroppingDatabase(connection.Database)); if (context.Database.EnsureDeleted()) { _reporter.WriteInformation(DesignStrings.DatabaseDropped(connection.Database)); } else { _reporter.WriteInformation(DesignStrings.NotExistDatabase(connection.Database)); } } public virtual string ScriptDbContext([CanBeNull] string contextType) { using var context = CreateContext(contextType); return context.Database.GenerateCreateScript(); } public virtual DbContext CreateContext([CanBeNull] string contextType) => CreateContext(FindContextType(contextType).Value); private DbContext CreateContext(Func<DbContext> factory) { var context = factory(); _reporter.WriteVerbose(DesignStrings.UseContext(context.GetType().ShortDisplayName())); var loggerFactory = context.GetService<ILoggerFactory>(); loggerFactory.AddProvider(new OperationLoggerProvider(_reporter)); return context; } public virtual IEnumerable<Type> GetContextTypes() => FindContextTypes().Keys; public virtual Type GetContextType([CanBeNull] string name) => FindContextType(name).Key; private IDictionary<Type, Func<DbContext>> FindContextTypes() { _reporter.WriteVerbose(DesignStrings.FindingContexts); var contexts = new Dictionary<Type, Func<DbContext>>(); _reporter.WriteVerbose(DesignStrings.FindingContextFactories); var contextFactories = _startupAssembly.GetConstructibleTypes() .Where(t => typeof(IDesignTimeDbContextFactory<DbContext>).GetTypeInfo().IsAssignableFrom(t)); foreach (var factory in contextFactories) { _reporter.WriteVerbose(DesignStrings.FoundContextFactory(factory.ShortDisplayName())); var manufacturedContexts = from i in factory.ImplementedInterfaces where i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == typeof(IDesignTimeDbContextFactory<>) select i.GenericTypeArguments[0]; foreach (var context in manufacturedContexts) { _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName())); contexts.Add( context, () => CreateContextFromFactory(factory.AsType())); } } var appServices = _appServicesFactory.Create(_args); var registeredContexts = appServices.GetServices<DbContextOptions>() .Select(o => o.ContextType); foreach (var context in registeredContexts.Where(c => !contexts.ContainsKey(c))) { _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName())); contexts.Add( context, FindContextFactory(context) ?? (() => (DbContext)ActivatorUtilities.GetServiceOrCreateInstance(appServices, context))); } _reporter.WriteVerbose(DesignStrings.FindingReferencedContexts); var types = _startupAssembly.GetConstructibleTypes() .Concat(_assembly.GetConstructibleTypes()) .ToList(); var contextTypes = types.Where(t => typeof(DbContext).GetTypeInfo().IsAssignableFrom(t)).Select( t => t.AsType()) .Concat( types.Where(t => typeof(Migration).GetTypeInfo().IsAssignableFrom(t)) .Select(t => t.GetCustomAttribute<DbContextAttribute>()?.ContextType) .Where(t => t != null)) .Distinct(); foreach (var context in contextTypes.Where(c => !contexts.ContainsKey(c))) { _reporter.WriteVerbose(DesignStrings.FoundDbContext(context.ShortDisplayName())); contexts.Add( context, FindContextFactory(context) ?? (() => { try { return (DbContext)Activator.CreateInstance(context); } catch (MissingMethodException ex) { throw new OperationException(DesignStrings.NoParameterlessConstructor(context.Name), ex); } })); } return contexts; } public virtual ContextInfo GetContextInfo([CanBeNull] string contextType) { using var context = CreateContext(contextType); var info = new ContextInfo(); var provider = context.GetService<IDatabaseProvider>(); info.ProviderName = provider.Name; var connection = context.Database.GetDbConnection(); info.DataSource = connection.DataSource; info.DatabaseName = connection.Database; var options = context.GetService<IDbContextOptions>(); info.Options = options.BuildOptionsFragment().Trim(); return info; } private Func<DbContext> FindContextFactory(Type contextType) { var factoryInterface = typeof(IDesignTimeDbContextFactory<>).MakeGenericType(contextType).GetTypeInfo(); var factory = contextType.GetTypeInfo().Assembly.GetConstructibleTypes() .FirstOrDefault(t => factoryInterface.IsAssignableFrom(t)); return factory == null ? (Func<DbContext>)null : (() => CreateContextFromFactory(factory.AsType())); } private DbContext CreateContextFromFactory(Type factory) { _reporter.WriteVerbose(DesignStrings.UsingDbContextFactory(factory.ShortDisplayName())); return ((IDesignTimeDbContextFactory<DbContext>)Activator.CreateInstance(factory)) .CreateDbContext(_args); } private KeyValuePair<Type, Func<DbContext>> FindContextType(string name) { var types = FindContextTypes(); if (string.IsNullOrEmpty(name)) { if (types.Count == 0) { throw new OperationException(DesignStrings.NoContext(_assembly.GetName().Name)); } if (types.Count == 1) { return types.First(); } throw new OperationException(DesignStrings.MultipleContexts); } var candidates = FilterTypes(types, name, ignoreCase: true); if (candidates.Count == 0) { throw new OperationException(DesignStrings.NoContextWithName(name)); } if (candidates.Count == 1) { return candidates.First(); } candidates = FilterTypes(candidates, name); if (candidates.Count == 0) { throw new OperationException(DesignStrings.MultipleContextsWithName(name)); } if (candidates.Count == 1) { return candidates.First(); } candidates = candidates.Where(t => t.Key.Namespace == null).ToDictionary(t => t.Key, t => t.Value); if (candidates.Count == 0) { throw new OperationException(DesignStrings.MultipleContextsWithQualifiedName(name)); } Debug.Assert(candidates.Count == 1, "candidates.Count is not 1."); return candidates.First(); } private static IDictionary<Type, Func<DbContext>> FilterTypes( IDictionary<Type, Func<DbContext>> types, string name, bool ignoreCase = false) { var comparisonType = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return types .Where( t => string.Equals(t.Key.Name, name, comparisonType) || string.Equals(t.Key.FullName, name, comparisonType) || string.Equals(t.Key.AssemblyQualifiedName, name, comparisonType)) .ToDictionary(t => t.Key, t => t.Value); } }
c#
27
0.578403
119
47.380952
210
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary>
class
static int32_t I2C_GetDataCount (I2C_RESOURCES *i2c) { int32_t val; if ((i2c->info->status.mode == I2C_MODE_SLAVE) && ((i2c->info->ctrl & XFER_CTRL_ADDR_DONE) == 0U)) { val = -1; } else { if (i2c->info->status.direction == I2C_DIR_TX) { val = (int32_t)i2c->info->tx.cnt; } else { val = (int32_t)i2c->info->rx.cnt; } } return (val); }
c
15
0.552279
102
25.714286
14
/** \fn int32_t I2C_GetDataCount (void) \brief Get transferred data count. \return number of data bytes transferred; -1 when Slave is not addressed by Master */
function
def element_wise(counter_method): def _make_iterator(*args): monitor_level = args[1] arg_pid = args[2] if hasattr(arg_pid, '__iter__'): pid_itr = (i for i in xrange(arg_pid[0], arg_pid[1])) else: pid_itr = (arg_pid,) if monitor_level == 'Thread': arg_tid = args[3] if hasattr(arg_tid, '__iter__'): tid_itr = (i for i in xrange(arg_tid[0], arg_tid[1])) else: tid_itr = (arg_tid,) if monitor_level == 'Process': return_itr = pid_itr elif monitor_level == 'Thread': return_itr = (pid_itr, tid_itr) return return_itr @wraps(counter_method) def _element_wise(*args): if args[1] == 'Thread': pid_itr, tid_itr = _make_iterator(*args) retval = [counter_method(args[0], args[1], pid, tid) for pid, tid in product(pid_itr, tid_itr)] return np.array(retval) elif args[1] == 'Process': pid_itr = _make_iterator(*args) retval = [counter_method(args[0], args[1], pid) for pid in pid_itr] return np.array(retval) elif args[1] == 'Application': return np.array(counter_method(*args)) else: print 'Unknown monitor level' return _element_wise
python
16
0.506569
79
38.171429
35
This is a decorator function allowing multi-process/thread input. Note that this decorator should always follow the decorator 'tag_maker'.
function
@XmlRootElement(name = "VehicleProfiles") @XmlAccessorType(XmlAccessType.NONE) private final class VehicleProfilesXML { /** * List of vehicle profiles. */ @XmlElement(name = "profile", required = false) private List<VehicleProfile> profiles = new LinkedList<>(); /** * Name of the selected profile. */ @XmlAttribute(name = "selectedProfile", required = false) private String selectedProfile; /** * Create instance. */ public VehicleProfilesXML() { // Do nothing. } /** * Set the profiles. * * @param profiles List of profiles */ public void setProfiles(List<VehicleProfile> profiles) { this.profiles = profiles; } /** * Get the profiles. * * @return List of profiles. */ public List<VehicleProfile> getProfiles() { return profiles; } /** * Set the selected profile. * * @param name Name of the selected profile. Might be <code>null</code>. */ public void setSelectedProfile(String name) { selectedProfile = name; } /** * Get the name of the selected profile. * * @return profile name */ public String getSelectedProfile() { return selectedProfile; } }
java
9
0.592852
76
21.206897
58
/** * JAXB compatible class that wraps a list of profiles and optionally the name * of the selected profile. */
class
private void dumpIgnores(PhysicsCollisionObject pco, String indent) { stream.print(':'); long[] idList = pco.listIgnoredIds(); String moreIndent = indent + indentIncrement(); for (long otherId : idList) { addLine(moreIndent); PhysicsDescriber describer = getDescriber(); PhysicsCollisionObject otherPco = PhysicsCollisionObject.findInstance(otherId); String desc = describer.describePco(otherPco, dumpNativeIDs); stream.print(desc); } addLine(indent); }
java
9
0.611966
73
40.857143
14
/** * Dump all ignored objects in the specified collision object. * * @param pco the body to dump (not null, unaffected) * @param indent (not null) */
function
def plot_topomap(self, times=None, ch_type='mag', layout=None, vmax=None, cmap='RdBu_r', sensors='k,', colorbar=True, scale=None, unit=None, res=256, size=1, format="%3.1f", proj=False, show=True): plot_evoked_topomap(self, times=times, ch_type=ch_type, layout=layout, vmax=vmax, cmap=cmap, sensors=sensors, colorbar=colorbar, scale=scale, unit=unit, res=res, proj=proj, size=size, format=format)
python
7
0.526316
79
68
8
Plot topographic maps of specific time points Parameters ---------- times : float | array of floats | None. The time point(s) to plot. If None, 10 topographies will be shown will a regular time spacing between the first and last time instant. ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg' The channel type to plot. For 'grad', the gradiometers are collec- ted in pairs and the RMS for each pair is plotted. layout : None | Layout Layout instance specifying sensor positions (does not need to be specified for Neuromag data). If possible, the correct layout file is inferred from the data; if no appropriate layout file was found, the layout is automatically generated from the sensor locations. vmax : scalar The value specfying the range of the color scale (-vmax to +vmax). If None, the largest absolute value in the data is used. cmap : matplotlib colormap Colormap. sensors : bool | str Add markers for sensor locations to the plot. Accepts matplotlib plot format string (e.g., 'r+' for red plusses). colorbar : bool Plot a colorbar. scale : float | None Scale the data for plotting. If None, defaults to 1e6 for eeg, 1e13 for grad and 1e15 for mag. units : str | None The units of the channel types used for colorbar lables. If scale == None the unit is automatically determined. res : int The resolution of the topomap image (n pixels along each side). size : scalar Side length of the topomaps in inches (only applies when plotting multiple topomaps at a time). format : str String format for colorbar values. proj : bool | 'interactive' If true SSP projections are applied before display. If 'interactive', a check box for reversible selection of SSP projection vectors will be shown. show : bool Call pyplot.show() at the end.
function
func (kv KVStoreClientImpl) Get(key string, retry bool) ([]byte, error) { var err error = fmt.Errorf("DUMMY") var val []byte for err != nil { val, err = kv.getWithoutRetry(key) if !retry || !isRetryable(err) { return val, err } time.Sleep(RETRY_WAIT) } return val, nil }
go
10
0.65035
73
22.916667
12
// Inform the lock manager we're interested in reading the value for key. // Expected return value: // Current version number associated with key // Expected error conditions: // Network failure => Retryable failure // Key does not exist => Fail immediately // // Once current version number has been successfully read, contact nodes // KV Store to read value at expected version. // Expected error conditions: // Key/version does not exist => Retry with another node // All nodes returned error => Fail // // Optimization: // Prioritize reading from local vnode if one of them may contain this data.
function
void on_each_cpu_cond_mask(smp_cond_func_t cond_func, smp_call_func_t func, void *info, bool wait, const struct cpumask *mask) { int cpu = get_cpu(); smp_call_function_many_cond(mask, func, info, wait, cond_func); if (cpumask_test_cpu(cpu, mask) && cond_func(cpu, info)) { unsigned long flags; local_irq_save(flags); func(info); local_irq_restore(flags); } put_cpu(); }
c
8
0.670103
75
28.923077
13
/* * on_each_cpu_cond(): Call a function on each processor for which * the supplied function cond_func returns true, optionally waiting * for all the required CPUs to finish. This may include the local * processor. * @cond_func: A callback function that is passed a cpu id and * the info parameter. The function is called * with preemption disabled. The function should * return a blooean value indicating whether to IPI * the specified CPU. * @func: The function to run on all applicable CPUs. * This must be fast and non-blocking. * @info: An arbitrary pointer to pass to both functions. * @wait: If true, wait (atomically) until function has * completed on other CPUs. * * Preemption is disabled to protect against CPUs going offline but not online. * CPUs going online during the call will not be seen or sent an IPI. * * You must not call this function with disabled interrupts or * from a hardware interrupt handler or from a bottom half handler. */
function
func (e *Engine) LedgerForPeer(p peer.ID) *Receipt { ledger := e.findOrCreate(p) ledger.lk.Lock() defer ledger.lk.Unlock() return &Receipt{ Peer: ledger.Partner.String(), Value: ledger.Accounting.Value(), Sent: ledger.Accounting.BytesSent, Recv: ledger.Accounting.BytesRecv, Exchanged: ledger.ExchangeCount(), } }
go
13
0.682997
52
28
12
// LedgerForPeer returns aggregated data about blocks swapped and communication // with a given peer.
function
@Override public void destroy() throws IOException { close(); serializer = null; monitorCache = null; client = null; }
java
6
0.630435
44
18.857143
7
/** * Notes: All the nodes and their datum will be deleted once the connection is broken(by call * {@code destroy()} or session timeout) between the zookeeper's client and server. * */
function
internal void SetTypes(ITypeSymbol targeType, ITypeSymbol sourceType) { if (TargetType is not null || SourceType is not null) { throw MappaGeneratorDiagnostics.InternalError("Unexpectedly setting source/target types twice", Method?.GetLocation()).AsException(); } TargetType = targeType; SourceType = sourceType; }
c#
15
0.673797
145
40.666667
9
/// <summary> /// Set the source and targe types. /// </summary> /// <param name="targeType">The target mapping type.</param> /// <param name="sourceType">The source mapping type.</param> /// <exception cref="Exceptions.MappaGeneratorException">If either the target type or the soruce type have been set already.</exception>
function
function useIsFontSizeDisabled( { name: blockName } = {} ) { const fontSizes = useFontSizes(); const hasFontSizes = fontSizes.length; return ( ! hasBlockSupport( blockName, FONT_SIZE_SUPPORT_KEY ) || ! hasFontSizes ); }
javascript
9
0.711111
73
31.285714
7
/** * Custom hook that checks if font-size settings have been disabled. * * @param {string} name The name of the block. * @return {boolean} Whether setting is disabled. */
function
public static bool IsDeepEqual<T>(this T x, T y, bool checkStrictTypeEquality = true) where T : class { if (x == y) return true; if (x == null || y == null) return false; var leftType = x.GetType(); var equatableType = leftType.GetInterface(typeof(IEquatable<>).Name)?.GenericTypeArguments .SingleOrDefault(); var rightType = y.GetType(); if (checkStrictTypeEquality) { if (leftType != rightType) { return false; } } if (equatableType == rightType) { return x.Equals(y); } var properties = GetCachedTypeInfo(typeof(T)) .Properties .Where(p => p.CanRead); foreach (var property in properties) { var leftValue = property.GetValue(x, null); var rightValue = property.GetValue(y, null); if (property.PropertyType.IsClass && property.PropertyType.IsNested) { if (!IsDeepEqual(leftValue, rightValue)) return false; } else { if (leftValue != rightValue) return false; } } return true; }
c#
18
0.437628
102
34.804878
41
/// <summary> /// The IsDeepEqual function detects if two objects have strictly the same properties (not necessarily the same object). /// </summary> /// <typeparam name="T">The type of objects that are compared.</typeparam> /// <param name="x">First object to compare.</param> /// <param name="y">Second object to compare.</param> /// <param name="checkStrictTypeEquality"> /// If enabled, ensures that the two objects have strictly the same type. /// </param> /// <returns>Returns true if all properties of the object are the same.</returns>
function
bool idMatX::IsPositiveDefinite( const float epsilon ) const { int i, j, k; float d, s; idMatX m; if( !IsSquare() ) { return false; } m.SetData( numRows, numColumns, MATX_ALLOCA( numRows * numColumns ) ); m = *this; for( i = 0; i < numRows; i++ ) { for( j = 0; j < numColumns; j++ ) { m[i][j] += ( *this )[j][i]; } } for( i = 0; i < numRows; i++ ) { for( j = i; j < numColumns; j++ ) { if( m[j][j] <= epsilon ) { return false; } } d = 1.0f / m[i][i]; for( j = i + 1; j < numColumns; j++ ) { s = d * m[j][i]; m[j][i] = 0.0f; for( k = i + 1; k < numRows; k++ ) { m[j][k] -= s * m[i][k]; } } } return true; }
c++
15
0.457903
71
15.95
40
/* ============ idMatX::IsPositiveDefinite returns true if the matrix is Positive Definite (PD) A square matrix M of order n is said to be PD if y'My > 0 for all vectors y of dimension n, y != 0. ============ */
function
def _chooseBuild(self, buildrequests): if self.nextBuild: d = defer.gatherResults([ self._brdictToBuildRequest(brdict) for brdict in buildrequests ]) d.addCallback(lambda requestobjects : self.nextBuild(self, requestobjects)) def to_brdict(brobj): return brobj.brdict d.addCallback(to_brdict) return d else: return defer.succeed(buildrequests[0])
python
12
0.547244
72
41.416667
12
Choose the next build from the given set of build requests (represented as dictionaries). Defaults to returning the first request (earliest submitted). @param buildrequests: sorted list of build request dictionaries @returns: a build request dictionary or None via Deferred
function
public sealed class ClientModel { readonly IMessageQueue _queue; ImmutableDictionary<StuffId, ImmutableStuff> _stuffInInbox = ImmutableDictionary.Create<StuffId, ImmutableStuff>(); readonly List<MutableProject> _projectList = new List<MutableProject>(); readonly Dictionary<ProjectId, MutableProject> _projects = new Dictionary<ProjectId, MutableProject>(); readonly Dictionary<ActionId, MutableAction> _actions = new Dictionary<ActionId, MutableAction>(); public IList<ImmutableProject> ListProjects() { return _projectList.Select(m => m.Freeze()).ToList().AsReadOnly(); } public ImmutableProject GetProjectOrNull(ProjectId projectId) { MutableProject value; if (_projects.TryGetValue(projectId, out value)) return value.Freeze(); return null; } public ImmutableInbox GetInbox() { return new ImmutableInbox(_stuffInInbox); } public int GetTheNumberOfItemsOfStuffInInbox() { return _stuffInInbox.Count; } public readonly TrustedSystemId Id; public ClientModel(IMessageQueue queue, TrustedSystemId id) { _queue = queue; Id = id; } bool _loadingCompleted; public void LoadingCompleted() { _loadingCompleted = true; var model = new ImmutableClientModel( GetInbox(), ImmutableList.Create(_projectList.Select(m => m.Freeze()).ToArray())); #region This event sends copy the ENTIRE immutable state to the UI! Cool... #endregion Publish(new Dumb.ClientModelLoaded(model)); } void Publish(Dumb.CliendModelEvent e) { if (!_loadingCompleted) return; _queue.Enqueue(e); } uint _stuffOrderCounter; public void StuffPutInInbox(StuffId stuffId, string descriptionOfStuff, DateTime date) { var key = "stuff-" + Id.Id; var item = new ImmutableStuff(stuffId, descriptionOfStuff, key, _stuffOrderCounter++); _stuffInInbox = _stuffInInbox.Add(stuffId, item); Publish(new Dumb.StuffAddedToInbox(item, _stuffInInbox.Count)); } public void StuffTrashed(StuffId stuffId) { ImmutableStuff value; if (!_stuffInInbox.TryGetValue(stuffId, out value)) return; _stuffInInbox = _stuffInInbox.Remove(stuffId); Publish(new Dumb.StuffRemovedFromInbox(value, _stuffInInbox.Count)); } public void StuffArchived(StuffId stuffId) { ImmutableStuff value; if (!_stuffInInbox.TryGetValue(stuffId, out value)) return; _stuffInInbox = _stuffInInbox.Remove(stuffId); Publish(new Dumb.StuffRemovedFromInbox(value, _stuffInInbox.Count)); } public void ProjectDefined(ProjectId projectId, string projectOutcome, ProjectType type) { var project = new MutableProject(projectId, projectOutcome, type); _projectList.Add(project); _projects.Add(projectId, project); Publish(new Dumb.ProjectAdded(project.UIKey, projectOutcome, projectId)); } public void ActionDefined(ProjectId projectId, ActionId actionId, string outcome) { var action = new MutableAction(actionId, outcome, projectId); var project = _projects[projectId]; project.Actions.Add(action); _actions.Add(actionId, action); Publish(new Dumb.ActionAdded(action.Freeze())); } public void ActionMoved(ActionId actionId, ProjectId oldProjectId, ProjectId newProjectId) { var action = _actions[actionId]; Publish(new Dumb.ActionRemoved(action.Freeze())); action.MoveToProject(newProjectId); Publish(new Dumb.ActionAdded(action.Freeze())); _projects[oldProjectId].Actions.Remove(action); _projects[newProjectId].Actions.Add(action); } public void ActionCompleted(ActionId actionId) { var action = _actions[actionId]; var project = _projects[action.ProjectId]; action.MarkAsCompleted(); Publish(new Dumb.ActionUpdated(action.Freeze(), project.UIKey)); } public void DescriptionOfStuffChanged(StuffId stuffId, string newDescriptionOfStuff) { var oldStuff = _stuffInInbox[stuffId]; var newValue = oldStuff.WithDescription(newDescriptionOfStuff); _stuffInInbox = _stuffInInbox.SetItem(stuffId, newValue); Publish(new Dumb.StuffUpdated(newValue)); } public void ProjectOutcomeChanged(ProjectId projectId, string outcome) { _projects[projectId].OutcomeChanged(outcome); } public void ActionOutcomeChanged(ActionId actionId, string outcome) { var action = _actions[actionId]; var project = _projects[action.ProjectId]; action.OutcomeChanged(outcome); var immutable = action.Freeze(); Publish(new Dumb.ActionUpdated(immutable, project.UIKey)); } public void ActionArchived(ActionId id) { var action = _actions[id]; action.MarkAsArchived(); Publish(new Dumb.ActionAdded(action.Freeze())); } public void ProjectTypeChanged(ProjectId projectId, ProjectType type) { _projects[projectId].TypeChanged(type); } public void DeferredUtil(ActionId actionId, DateTime deferUntil) { var action = _actions[actionId]; action.DeferUntilDate(deferUntil); } public void DueDateAssigned(ActionId actionId, DateTime newDueDate) { _actions[actionId].DueDateAssigned(newDueDate); } public void Verify(TrustedSystemId id) {} public void Create(TrustedSystemId id) {} sealed class MutableProject { ProjectId ProjectId { get; set; } string Outcome { get; set; } ProjectType Type { get; set; } public readonly string UIKey; public MutableProject(ProjectId projectId, string outcome, ProjectType type) { ProjectId = projectId; Outcome = outcome; Type = type; UIKey = "project-" + projectId.Id; } public ImmutableProject Freeze() { var ma = Actions.Select(mutable => mutable.Freeze()).ToList().AsReadOnly(); var info = new ImmutableProjectInfo(ProjectId, Outcome, Type, UIKey); return new ImmutableProject(info, ma); } public readonly List<MutableAction> Actions = new List<MutableAction>(); public void OutcomeChanged(string outcome) { Outcome = outcome; } public void TypeChanged(ProjectType type) { Type = type; } } sealed class MutableAction { ActionId Id { get; set; } string Outcome { get; set; } bool Completed { get; set; } bool Archived { get; set; } public ProjectId ProjectId { get; private set; } DateTime DeferUntil { get; set; } DateTime DueDate { get; set; } string UIKey { get { return "action-" + Id.Id; } } public MutableAction(ActionId action, string outcome, ProjectId project) { Id = action; Outcome = outcome; Completed = false; Archived = false; ProjectId = project; } public void MarkAsCompleted() { Completed = true; } public void MoveToProject(ProjectId newProject) { ProjectId = newProject; } public void OutcomeChanged(string outcome) { Outcome = outcome; } public void MarkAsArchived() { Archived = true; } public ImmutableAction Freeze() { return new ImmutableAction(UIKey, Id, Outcome, Completed, Archived, ProjectId, DeferUntil, DueDate); } public void DeferUntilDate(DateTime newStartDate) { DeferUntil = newStartDate; } public void DueDateAssigned(DateTime newDueDate) { DueDate = newDueDate; } } }
c#
23
0.559069
111
38.262931
232
/// <summary> This is part of the "Client Model" or "UI" Context /// This context is similar to a read model but it also has certain behaviors. /// You can perceive this "client model context" as an Aggregate that reacts to /// Events that are published by the to Domain Model. /// This "aggregate" maintains its own internal state that represents the state /// of a UI like a desktop application. When this state changes, this ClientModel /// publishes high-level UI-specific events like: StuffAddedToInbox, ProjectAdded, etc. /// These UI events are not "event sourced" (persisted events which are then replayed to get state), /// they are in-memory "dumb" UI events that do not need the level of detail that /// our persisted Event-Sourced Domain Model Events need. /// Our Domain Events are still the same granular ones that matter for when we are /// persisting the Domain Model state changes and using them to resolve the /// sync issues that come along with multi-user/device collaboration scenarios, but these /// in-memory "dumb" UI events do not need that level of detail to keep the UI up to date. /// Basically, we are modeling the things that will eventually be represented /// on a client's screen. Client Model is an underlying read model and notification sub-system /// for implementing a client application. Technically this Client Model context is reusable /// across various client/device types (desktop, tablet, web, phone, etc.), /// but the practicality of reusing it remains to be seen. /// </summary>
class
static int analogix_dp_prepare_panel(struct analogix_dp_device *dp, bool prepare, bool is_modeset_prepare) { int ret = 0; if (!dp->plat_data->panel) return 0; mutex_lock(&dp->panel_lock); if (dp->panel_is_modeset && !is_modeset_prepare) goto out; if (prepare) ret = drm_panel_prepare(dp->plat_data->panel); else ret = drm_panel_unprepare(dp->plat_data->panel); if (ret) goto out; if (is_modeset_prepare) dp->panel_is_modeset = prepare; out: mutex_unlock(&dp->panel_lock); return ret; }
c
11
0.670543
67
23.619048
21
/* * This function is a bit of a catch-all for panel preparation, hopefully * simplifying the logic of functions that need to prepare/unprepare the panel * below. * * If @prepare is true, this function will prepare the panel. Conversely, if it * is false, the panel will be unprepared. * * If @is_modeset_prepare is true, the function will disregard the current state * of the panel and either prepare/unprepare the panel based on @prepare. Once * it finishes, it will update dp->panel_is_modeset to reflect the current state * of the panel. */
function
@Override public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { final Map<String, Object> processed = super.postProcessAllModels(objs); postProcessEnumRefs(processed); updateValueTypeProperty(processed); updateNullableTypeProperty(processed); return processed; }
java
7
0.710843
79
40.625
8
/** * Invoked by {@link DefaultGenerator} after all models have been post-processed, allowing for a last pass of codegen-specific model cleanup. * * @param objs Current state of codegen object model. * @return An in-place modified state of the codegen object model. */
function
public sealed class AssetArchive : Archive { public AssetArchive(IDictionary<string, AssetOrArchive> assets) : base(Constants.ArchiveAssetsName, assets.ToImmutableDictionary()) { } }
c#
9
0.654867
79
31.428571
7
/// <summary> /// An AssetArchive is an archive created from an in-memory collection of named assets or other /// archives. /// </summary>
class
def choose_move(self, move_temperature, random_move_probability=0.0): x = np.random.rand() if x < random_move_probability: valid_moves = (self.root.edge_stats['N'] > 0) probs = valid_moves.astype(np.float32) / np.sum(valid_moves) else: exponent = 1.0 / move_temperature exp_N = np.power(self.root.edge_stats['N'] / np.max(self.root.edge_stats['N']), exponent) probs = exp_N / np.sum(exp_N) frand = np.random.rand() cum_probs = np.cumsum(probs) imove = np.searchsorted(cum_probs, frand) return imove, probs
python
16
0.552308
73
45.5
14
Chooses a move (policy) according to the MCTS stats. Args: move_temperature: float: exponential factor to rebalance the policy and control its level of exploration. This value corresponds to 1 / \tau in [1]. random_move_probability: float: probability of making a totally random move. Returns: int: chosen move index. np.array: a vector with the probability of playing at each position.
function
@Test(groups = "functional", testName = "iteration.ReplicatedEntryRetrieverWithLoaderTest") public class ReplicatedEntryRetrieverWithLoaderTest extends BaseEntryRetrieverWithLoaderTest { public ReplicatedEntryRetrieverWithLoaderTest() { super(false, CacheMode.REPL_SYNC, "ReplicatedEntryRetrieverWithLoaderTest"); } }
java
8
0.824242
94
46.285714
7
/** * Test to verify replicated entry behavior when a loader is present * * @author afield * @since 7.0 */
class
void AliQnCorrectionsQnVectorBuild::NormalizeQoverM() { if(fSumW < fMinimumSignificantValue) { SetGood(kFALSE); } else { for(Int_t h = 1; h < fHighestHarmonic + 1; h++){ if ((fHarmonicMask & harmonicNumberMask[h]) == harmonicNumberMask[h]) { fQnX[h] = (fQnX[h] / fSumW); fQnY[h] = (fQnY[h] / fSumW); } } } }
c++
16
0.583099
77
26.384615
13
/// Normalizes the build Q vector for the whole harmonics set /// /// Normalizes the build Q vector as \f$ Qn = \frac{Qn}{M} \f$. /// A check for significant value is made. Not passing it /// does set the Q vector quality as bad
function
func (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error { cfg, err := loadConfig(ch.Config) if err != nil { return err } ib, err := c.getIbClient(&cfg, ch.ResourceNamespace) if err != nil { return err } recordName := c.DeDot(ch.ResolvedFQDN) recordRef, err := c.GetTXTRecord(ib, recordName, ch.Key, cfg.View) if err != nil { return nil } if recordRef != "" { logf.V(logf.InfoLevel).InfoS("TXT record already present", "name", recordName, "ref", recordRef) } else { recordRef, err := c.CreateTXTRecord(ib, recordName, ch.Key, cfg.View) if err != nil { return err } logf.V(logf.InfoLevel).InfoS("Created new TXT record", "name", recordName, "ref", recordRef) } return nil }
go
11
0.676754
98
28.12
25
// Present is responsible for actually presenting the DNS record with the // DNS provider. // This method should tolerate being called multiple times with the same value. // cert-manager itself will later perform a self check to ensure that the // solver has correctly configured the DNS provider.
function
def _define_criteria( self, min_improvement_per_round: float = MIN_IMPROVEMENT_PER_ROUND, max_num_rounds: int = MAX_NUM_ROUNDS, distance_to_the_wall: float = DISTANCE_TO_THE_WALL, num_near_the_wall: int = NUM_NEAR_THE_WALL, min_num_init: int = MIN_NUM_INIT, max_num_init: int = MAX_NUM_INIT, ) -> None: self._min_improvement = min_improvement_per_round self._max_num_rounds = max_num_rounds self._distance_to_the_wall = distance_to_the_wall self._num_near_the_wall = num_near_the_wall self._min_num_init = min_num_init self._max_num_init = max_num_init
python
6
0.610606
69
43.066667
15
Define criteria that control the number of iterations in the algorithm. There are two types of iterations in the algorithm: (i) Multiple rounds of coordinate descent until a local optimum is reached. (ii) Multiple choices of initial values until we have confidence that the best-so-far local optimum is close to the global optimum. In our algorithm, type-(i) iterations are terminated if one round of iteration fails to improve the fit, i.e., reduce the loss function. Type-(ii) iterations are terminated if we "hit a wall at bottom". Explicitly, we track the local-opt-losses, i.e., the loss function of all local optima. We keep an eye on the bottom, say, the minimum 10 among all the local-opt-losses. If these bottom local-opt-losses are far away from each other, then there're still space to search for better local optimum. If, however, the bottom losses become close to each other, we make a reasonable guess that these bottom local-opt-losses converge to a bound, and that the wall is exactly the global optimum. We then approximate the global optimum as the minimum local-opt-loss found so far. In addition to the termination criteria, we also specify some maximum or minimum number of iterations in this method. Args: min_improvement_per_round: A threshold for terminating type-(i) iterations. We terminate the iterations if we fail to reduce the loss function by this much at a round. max_num_rounds: Force type-(i) to terminate if the number of rounds exceeds this number. distance_to_the_wall: Relative distance to the minimum loss so far. Starting from each initial value, we find a local optimum. For each local optimum, we obtain its value of loss function. Put these values into a list called local_opt_losses. Any element local_opt_losses[i] is considered close enough to the bottom wall if local_opt_losses[i] < min(local_opt_losses) * (1 + distance_to_the_wall). num_near_the_wall: Number of points close enough to the bottom wall when we terminate the search for more local optima. At each iteration, count how many points are close enough to the bottom wall, i.e., count of i that local_opt_losses[i] < min(local_opt_losses) * (1 + distance_to_the_wall). Terminate if the count becomes greater than num_near_the_wall. min_num_init: Force searching for at least these many initial points. max_num_init.: Force type-(ii) iterations to terminate if the number of initial points exceeds max_num_init.
function
pub fn new( irq: u32, ioapic: Arc<Mutex<Ioapic<WhpInterruptController>>>) -> Result<InterruptEvent> { Ok(InterruptEvent{ ioapic: ioapic, irq: irq, }) }
rust
10
0.484581
62
21.8
10
/// Create a new InterruptEvent object. // TODO(lpetrut): we may consider assigning those separately so that // we keep a similar interface with EventFd.
function
public Boolean IsAuthenticated(String domain, String username, String password) { bool stat = false; string path = String.Format("LDAP://{0}", domain.ToUpper()); DirectoryEntry entry = new DirectoryEntry(path, username, password); try { Object obj = entry.NativeObject; this.Groups.Clear(); GetGroups(entry, username); stat = true; } catch (DirectoryServicesCOMException) { } return stat; }
c#
13
0.540293
81
41.076923
13
/// <summary> /// Checks to see if username and password are authenticatable. /// </summary> /// <param name="username">The username to use.</param> /// <param name="password">The password to use.</param> /// <returns>Return true if authenticated.</returns> ///
function
def _save_cluster_representatives(self, clusters, dataframe, path, representatives_criterion): import os from collections import defaultdict import numpy as np from pele_platform.Utilities.Helpers import get_suffix from pele_platform.Utilities.Helpers.bestStructs import ( extract_snapshot_from_pdb, extract_snapshot_from_xtc) from pele_platform.analysis.clustering import get_cluster_label from pele_platform.constants.constants import \ cluster_representatives_criterion representatives_criterion = representatives_criterion.lower() if representatives_criterion not in cluster_representatives_criterion: raise ValueError('Invalid cluster_representatives_criterion' '\'{}\''.format(representatives_criterion) + '. It must be one of ' + '{}'.format( cluster_representatives_criterion.keys())) if representatives_criterion.startswith('total'): metric = 'currentEnergy' else: metric = dataframe.columns[self.be_column - 1] metrics = list(dataframe[metric]) metrics_per_cluster = defaultdict(list) for cluster, value in zip(clusters, metrics): if cluster < 0: continue metrics_per_cluster[cluster].append(value) golden_values_per_cluster = {} if '_25_percentile' in representatives_criterion: for cluster, metrics_array in metrics_per_cluster.items(): golden_values_per_cluster[cluster] = \ np.percentile(metrics_array, 25) elif '_5_percentile' in representatives_criterion: for cluster, metrics_array in metrics_per_cluster.items(): golden_values_per_cluster[cluster] = \ np.percentile(metrics_array, 5) elif '_min' in representatives_criterion: for cluster, metrics_array in metrics_per_cluster.items(): golden_values_per_cluster[cluster] = np.min(metrics_array) else: for cluster, metrics_array in metrics_per_cluster.items(): golden_values_per_cluster[cluster] = np.mean(metrics_array) representative_structures = {} lowest_energetic_diff = {} trajectories = list(dataframe["trajectory"]) steps = list(dataframe["numberOfAcceptedPeleSteps"]) for cluster, metric, trajectory, step in zip(clusters, metrics, trajectories, steps): if cluster < 0: continue energetic_diff = \ np.abs(golden_values_per_cluster[cluster] - metric) if cluster not in representative_structures: representative_structures[cluster] = [trajectory, step] lowest_energetic_diff[cluster] = energetic_diff elif lowest_energetic_diff[cluster] > energetic_diff: representative_structures[cluster] = [trajectory, step] lowest_energetic_diff[cluster] = energetic_diff for cluster, [trajectory, step] in representative_structures.items(): if not self.topology: try: label = get_cluster_label(cluster) extract_snapshot_from_pdb( path=trajectory, f_id=get_suffix(os.path.splitext(trajectory)[0]), output=path, topology=self.topology, step=step, out_freq=1, f_out="cluster_{}.pdb".format(label)) except UnicodeDecodeError: raise Exception("XTC output being treated as PDB. " + "Please specify XTC with the next " + "flag. traj: 'trajectory_name.xtc' " + "in the input.yaml") else: label = get_cluster_label(cluster) extract_snapshot_from_xtc( path=trajectory, f_id=get_suffix(os.path.splitext(trajectory)[0]), output=path, topology=self.topology, step=step, out_freq=1, f_out="cluster_{}.pdb".format(label)) self._save_top_selections(representative_structures, path, dataframe)
python
19
0.548617
78
51.602273
88
It saves the resulting clusters to disk. The selection of the representative structures is based on the total energy. The structure chosen as the representative will be the closer to the 5th percentile of total energy. Parameters ---------- clusters : a numpy.array object The array of cluster labels that were obtained dataframe : a pandas.dataframe object The dataframe containing the PELE reports information that follows the same ordering as the array of clusters path : str The path where the clusters will be saved at representatives_criterion : str Criterion to select cluster representative structures. One of ["total_25_percentile", "total_5_percentile", "total_mean", "total_min", "interaction_25_percentile", "interaction_5_percentile", "interaction_mean", "interaction_min"]
function
class HrefButtonArea extends ImageMapArea { /** The URL to be fetched when the user clicks on this area. */ URL anchor; /** The highlight image for the bright parts of the 3-D effect. */ Image brightImage; /** The highlight image for the dark parts of the 3-D effect. */ Image darkImage; /** The highlight image for the depressed part of the 3-D "button". */ Image pressImage; /** This flag indicates if the "button" is currently pressed. */ boolean pressed = false; /** The border size for the 3-D effect. */ int border = 5; /** * The argument string is the URL to be fetched. * This method also constructs the various highlight images needed * to achieve the 3-D effect. */ public void handleArg(String arg) { anchor = new URL(parent.documentURL, arg); brightImage = parent.getHighlight(parent.BRIGHTER, parent.hlpercent); darkImage = parent.getHighlight(parent.DARKER, parent.hlpercent); pressImage = parent.getHighlight(parent.DARKER, parent.hlpercent/2); if (border * 2 > W || border * 2 > H) { border = Math.min(W, H) / 2; } } /** * A utility function to draw a 3-D button wrapped with an image. */ public void drawButton(Graphics g) { drawImage(g, pressed ? darkImage : brightImage, X, Y, W, border); drawImage(g, pressed ? darkImage : brightImage, X, Y, border, H); int R = X + W - 1; int B = Y + H - 1; if (pressed) { drawImage(g, pressImage, X+border, Y+border, W-border*2, H-border*2); } for (int i = 0; i < border; i++) { drawImage(g, pressed ? brightImage : darkImage, X+i, B-i, W-i, 1); drawImage(g, pressed ? brightImage : darkImage, R-i, Y+i, 1, H-i); } } /** * The status message area is updated to show the destination URL. * The graphical highlight is achieved using the drawButton method. */ public void highlight(Graphics g, boolean on) { if (on) { drawButton(g); } else { super.highlight(g, false); } parent.showStatus(on ? "Go To " + anchor.toExternalForm() : null); } /** * Since the highlight changes when the button is pressed, we need * to record the "pressed" state and induce a repaint. */ public void press() { parent.repaint(); pressed = true; } /** * The new URL is fetched when the user releases the mouse button * only if they are still in the area. */ public void lift(int x, int y) { pressed = false; if (inside(x, y)) { parent.showDocument(anchor); } // Note that we should not be active, so no repaint is necessary. } }
java
12
0.614413
74
31.259259
81
/** * An improved "Fetch a URL" ImageArea class. * This class extends the basic ImageArea Class to fetch a URL when * the user clicks in the area. In addition, special custom highlights * are used to make the area look and feel like a 3-D button. * * @author Jim Graham * @version %I%, %G% */
class
def scrape_meetings(self, meetings, group): for meeting in meetings: when = self.get_date(meeting) description = self.get_description(meeting) location = self.get_location(meeting) if when and description and location: kwargs = {} if group in self.metadata['chambers'].keys(): kwargs['chamber'] = group agenda = self.get_agenda(meeting) if agenda: kwargs['agenda'] = agenda event = Event(self.session, when, 'committee:meeting', description, location, **kwargs) event.add_source(url) self.save_event(event)
python
13
0.51897
70
45.1875
16
Scrape and save event data from a list of meetings. Arguments: meetings -- A list of lxml elements containing event information group -- The type of meeting. The legislature site applies different formatting to events based on which group they correspond to. `group` should be one of the following strings: 'house', 'senate', or 'commission'.
function
function registerSubscription(forceCreate) { return new Promise(function (resolve, reject) { var FILE_SUBSCRIPTION = 'subscription.id'; var subscriptionId; try { subscriptionId = fs.readFileSync(__dirname + '/' + FILE_SUBSCRIPTION, 'UTF-8'); } catch(e) { console.log('Subscription id not present'); } var subscription = { type: 'urn:smartsantander:entityType:parkingSensor', pattern: 'urn:x-iot:smartsantander:u7jcfa:fixed:np.*', }; var options = { callback: 'http://' + SERVER_ADDRESS + ':' + PORT + '/on_context_change', throttling: 'PT30S', attributes: [ 'presenceStatus:parking' ] }; if (subscriptionId && !forceCreate) { console.log('Using existing subscription id: ', subscriptionId); options.subscriptionId = subscriptionId; } SantanderClient.subscribeContext(subscription, options, { path: '/parking/#' }).then(function(data) { if (!data) { reject({ code: 404 }); return; } fs.writeFileSync(__dirname + '/' + FILE_SUBSCRIPTION, data.subscriptionId); resolve(data.subscriptionId); }).catch(function(err) { reject(err); }); }); }
javascript
22
0.570444
79
29.395349
43
// Subscribes to context changes creating or renewing a subscription
function
public virtual CreateRegexMatchSetResponse CreateRegexMatchSet(CreateRegexMatchSetRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateRegexMatchSetRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateRegexMatchSetResponseUnmarshaller.Instance; return Invoke<CreateRegexMatchSetResponse>(request, options); }
c#
10
0.747017
98
59
7
/// <summary> /// <note> /// <para> /// This is <b>AWS WAF Classic</b> documentation. For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html">AWS /// WAF Classic</a> in the developer guide. /// </para> /// /// <para> /// <b>For the latest version of AWS WAF</b>, use the AWS WAFV2 API and see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html">AWS /// WAF Developer Guide</a>. With the latest version, AWS WAF has a single set of endpoints /// for regional and global use. /// </para> /// </note> /// <para> /// Creates a <a>RegexMatchSet</a>. You then use <a>UpdateRegexMatchSet</a> to identify /// the part of a web request that you want AWS WAF to inspect, such as the values of /// the <code>User-Agent</code> header or the query string. For example, you can create /// a <code>RegexMatchSet</code> that contains a <code>RegexMatchTuple</code> that looks /// for any requests with <code>User-Agent</code> headers that match a <code>RegexPatternSet</code> /// with pattern <code>B[a@]dB[o0]t</code>. You can then configure AWS WAF to reject those /// requests. /// </para> /// /// <para> /// To create and configure a <code>RegexMatchSet</code>, perform the following steps: /// </para> /// <ol> <li> /// <para> /// Use <a>GetChangeToken</a> to get the change token that you provide in the <code>ChangeToken</code> /// parameter of a <code>CreateRegexMatchSet</code> request. /// </para> /// </li> <li> /// <para> /// Submit a <code>CreateRegexMatchSet</code> request. /// </para> /// </li> <li> /// <para> /// Use <code>GetChangeToken</code> to get the change token that you provide in the <code>ChangeToken</code> /// parameter of an <code>UpdateRegexMatchSet</code> request. /// </para> /// </li> <li> /// <para> /// Submit an <a>UpdateRegexMatchSet</a> request to specify the part of the request that /// you want AWS WAF to inspect (for example, the header or the URI) and the value, using /// a <code>RegexPatternSet</code>, that you want AWS WAF to watch for. /// </para> /// </li> </ol> /// <para> /// For more information about how to use the AWS WAF API to allow or block HTTP requests, /// see the <a href="https://docs.aws.amazon.com/waf/latest/developerguide/">AWS WAF Developer /// Guide</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateRegexMatchSet service method.</param> /// /// <returns>The response from the CreateRegexMatchSet service method, as returned by WAF.</returns> /// <exception cref="Amazon.WAF.Model.WAFDisallowedNameException"> /// The name specified is invalid. /// </exception> /// <exception cref="Amazon.WAF.Model.WAFInternalErrorException"> /// The operation failed because of a system problem, even though the request was valid. /// Retry your request. /// </exception> /// <exception cref="Amazon.WAF.Model.WAFLimitsExceededException"> /// The operation exceeds a resource limit, for example, the maximum number of <code>WebACL</code> /// objects that you can create for an AWS account. For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/limits.html">Limits</a> /// in the <i>AWS WAF Developer Guide</i>. /// </exception> /// <exception cref="Amazon.WAF.Model.WAFStaleDataException"> /// The operation failed because you tried to create, update, or delete an object by using /// a change token that has already been used. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/waf-2015-08-24/CreateRegexMatchSet">REST API Reference for CreateRegexMatchSet Operation</seealso>
function
@Variability(id = { AnnotationConstants.VAR_GATHER_DATA, AnnotationConstants.VAR_WIFI_DATA }, op = Operation.AND) public class Data implements DataMBean { /** * Instance of {@link IDataGatherer} for gathering required informations. * * @since 1.00 */ @Variability(id = { AnnotationConstants.VAR_GATHER_DATA, AnnotationConstants.VAR_WIFI_DATA }, op = Operation.AND) private IDataGatherer dataGatherer; /** * Constructor. * * @since 1.00 */ @Variability(id = { AnnotationConstants.VAR_GATHER_DATA, AnnotationConstants.VAR_WIFI_DATA }, op = Operation.AND) public Data() { dataGatherer = GathererFactory.getDataGatherer(); } @Override @Variability(id = AnnotationConstants.VAR_WIFI_DATA) public AccessPointData[] gatherWifiSignals(int timeout) { return dataGatherer.gatherWifiSignals(timeout); } @Override public boolean supportsJVMTI() { return dataGatherer.supportsJVMTI(); } @Override public boolean needsThreadRegistration() { return dataGatherer.needsThreadRegistration(); } @Override public void registerThisThread(boolean arg0) { dataGatherer.registerThisThread(arg0); } @Override public int redefineClass(Class<?> arg0, byte[] arg1) { return dataGatherer.redefineClass(arg0, arg1); } @Override public int redefineClasses(Class<?>[] arg0, byte[][] arg1) { return dataGatherer.redefineClasses(arg0, arg1); } @Override public int redefineMultiClasses(Class<?>[] arg0, byte[][] arg1) { return dataGatherer.redefineMultiClasses(arg0, arg1); } }
java
10
0.633277
77
27
61
/** * Defines an object for delegation of the values from the interface * {@link IDataGatherer} to the {@link StandardMBeanAgent}. * * @author Stephan Dederichs * * @since 1.00 * @version 1.00 */
class
public class RemoveItem extends ShellCommands { /** * This method removes all the child node of the node tar * @param fileSys * @param tar */ private static void clearAllChildren(FileManager fileSys, FileSystemNode tar) { ArrayList<FileSystemNode> list = fileSys.getChildren(tar); if (list == null) { //OutputCommands.print("complete!"); return; } for (FileSystemNode child : list) { //if (child.getClass() != sampleFile.getClass()) { // it is a dir//} clearAllChildren(fileSys, child); fileSys.removeNode(child); OutputCommands.println("deleted " + child.getName); } } /** * This method removes the directory from the fileSys. * @param fileSys * @param parameter */ public static void rm(FileManager fileSys, String parameter) { if (!Error.paraNumEqual(parameter, 1, RM_COMMAND)) return; if(!Error.checkDirPath(fileSys, parameter)){ return; } FileSystemNode tar = fileSys.findNode(parameter); clearAllChildren(fileSys, tar); fileSys.removeNode(tar); OutputCommands.println("deleted " + tar.getName); } }
java
12
0.65078
81
26.5
42
/** * This Class extends ShellCommands, Since users might frequently remove item * from the file system, this class is designed for this purpose */
class
public class Solution { // leetcode optimal solution public int largestPalindrome(int n) { if(n==1) return 9; int hiBound = (int)Math.pow(10,n)-1,lowBound = (int)Math.pow(10,n-1)-1; // if n = 3, first half would be 998001/1000 = 998 // the most tricky part about this problem would be: // finding the half long half = (long)hiBound*hiBound/(int)Math.pow(10,n); long palindrome = 0L; boolean found = false; while(!found){ // try each half palindrome = createPalindrome(half); for(long i=hiBound;i>lowBound;i--){ if(palindrome/i>hiBound||i*i<palindrome) break; if(palindrome%i==0){ found = true; break; } } --half; } return (int)(palindrome%1337); } private long createPalindrome(Long half){ return Long.parseLong(half+new StringBuilder( half.toString()).reverse().toString()); } public static void main(String[] args) { Solution s = new Solution(); System.out.println(s.largestPalindrome(6)); } }
java
15
0.534942
79
31.513514
37
/** * Find the largest palindrome made from the product of two n-digit numbers. * * Since the result could be very large, * you should return the largest palindrome mod 1337. * * Example: * Input: 2 * Output: 987 * Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 * * Note: * The range of n is [1,8]. */
class
public class SongRecyclerViewAdapter extends RecyclerView.Adapter<SongRecyclerViewAdapter.ViewHolder> { private static final Comparator<DatabaseSong> mComparator = (a, b) -> { if (!a.getTitle().equalsIgnoreCase(b.getTitle())) return a.getTitle().compareToIgnoreCase(b.getTitle()); return a.getArtist().compareToIgnoreCase(b.getArtist()); }; private static final int restricted_rectangle = R.drawable.restricted_song_rec; private static final int[] rectangles = new int[]{R.drawable.custom_song_rec_1, R.drawable.custom_song_rec_2, R.drawable.custom_song_rec_3, R.drawable.custom_song_rec_4}; private static final int[] transparentRectangles = new int[]{R.drawable.custom_song_rec_1_t, R.drawable.custom_song_rec_2_t, R.drawable.custom_song_rec_3_t, R.drawable.custom_song_rec_4_t}; private static final int[] layouts = new int[]{R.layout.song_display_big, R.layout.song_display_small}; private static final double[] heightFactors = new double[]{2.5, 3.5}; private final OnListFragmentInteractionListener mListener; private boolean payingCustomer; private List<DatabaseSong> mValues; private List<Recording> mRecordings; private double averageSongsPlayed; private List<String> demoSongs = new ArrayList<>(); public SongRecyclerViewAdapter(List<? extends DatabaseSong> items, OnListFragmentInteractionListener listener) { this.payingCustomer = false; setData(items); mListener = listener; } public void setAverage(double averageSongsPlayed) { this.averageSongsPlayed = averageSongsPlayed; } public void setPayingCustomer(boolean paying) { this.payingCustomer = paying; } public void addDemoSongs(List<String> demoSongs) { this.demoSongs = demoSongs; } @Override public int getItemViewType(final int position) { return Math.random() < 0.5 ? 0 : 1; } @SuppressLint("UseCompatLoadingForDrawables") @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { int randomColor = Math.random() < 0.5 ? 0 : 1; View view; view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.song_display_big, parent, false); // if (language.equals("iw")) // view.setLayoutDirection(View.LAYOUT_DIRECTION_RTL); // else // view.setLayoutDirection(View.LAYOUT_DIRECTION_LTR); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); int width = (int) (parent.getWidth() / 2.04); layoutParams.width = (width); layoutParams.height = (int) (1.3 * width); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { view.findViewById(R.id.song_placeholder).setBackground(parent.getContext().getResources().getDrawable(rectangles[viewType * 2 + randomColor], null)); view.findViewById(R.id.song_placeholder).setBackgroundTintBlendMode(BlendMode.COLOR_DODGE); } else { view.findViewById(R.id.song_placeholder).setBackground(parent.getContext().getResources().getDrawable(transparentRectangles[viewType * 2 + randomColor])); } view.setLayoutParams(layoutParams); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull final ViewHolder holder, int position) { // DatabaseSong song = mValues.get(position); // ShapeableImageView mCover = (ShapeableImageView) holder.mCover; holder.setItem(holder.mView, mValues.get(position)); holder.itemView.setOnClickListener(view -> { if (null != mListener) { if (payingCustomer || demoSongs.contains(holder.mItem.getTitle())) { mListener.onListFragmentInteractionPlay(holder.mItem); } else { mListener.onListFragmentInteractionOpenPay(holder.mItem); } } }); } @Override public int getItemCount() { return mValues.size(); } public void setData(List<? extends DatabaseSong> songs) { mValues = new ArrayList<>(songs); // make a copy Collections.sort(mValues, mComparator); } public class ViewHolder extends RecyclerView.ViewHolder { // public Song mItem; public DatabaseSong mItem; private final View mView; private TextView mLblTitle; private TextView mLblArtist; private String url; public ViewHolder(View view) { super(view); this.mView = view; // ((TextView) view.findViewById(R.id.play_button)).setText(text); } @Override public String toString() { return super.toString() + " '" + mLblArtist.getText() + "'" + mLblTitle.getText() + "'" + url; } public void setItem(View mView, DatabaseSong song) { if (mView == this.mView) { url = song.getImageResourceFile(); mLblTitle = mView.findViewById(R.id.lbl_title); mLblArtist = mView.findViewById(R.id.lbl_artist); ShapeableImageView mCover = mView.findViewById(R.id.img_cover); setPopularTag(song); setNewTag(song); setDemoAttributes(song); mItem = song; mLblTitle.setText(song.getTitle()); mLblArtist.setText(song.getArtist()); // if (!language.equals("English")) { if (!song.getImageResourceFile().equals("") && !song.getImageResourceFile().equals("no image resource")) { Picasso.get() .load(song.getImageResourceFile()) // .load("https://firebasestorage.googleapis.com/v0/b/shira-8ed6f.appspot.com/o/images%2FIMG_4196.JPG?alt=media&token=95a20ae9-19f3-45ad-b2b0-a183a41f969f") .placeholder(R.drawable.ashira) .fit() .into(mCover); } mCover.setShapeAppearanceModel(mCover.getShapeAppearanceModel() .toBuilder() .setTopRightCorner(CornerFamily.ROUNDED, Converter.convertDpToPx(17)) .setTopLeftCorner(CornerFamily.ROUNDED, Converter.convertDpToPx(17)) .build()); } } private void setNewTag(DatabaseSong song) { if (song.getDate().equals("")) { mView.findViewById(R.id.new_song_tag).setVisibility(View.GONE); return; } Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); String lastNewDate = String.valueOf(new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.getTime().getTime())); if (song.getDate().compareTo(lastNewDate) > 0) { mView.findViewById(R.id.new_song_tag).setVisibility(View.VISIBLE); } else mView.findViewById(R.id.new_song_tag).setVisibility(View.GONE); } private void setPopularTag(DatabaseSong song) { if (song.getTimesPlayed() > 2 * averageSongsPlayed && (payingCustomer)) mView.findViewById(R.id.popular_song_tag).setVisibility(View.VISIBLE); else mView.findViewById(R.id.popular_song_tag).setVisibility(View.GONE); } @SuppressLint("UseCompatLoadingForDrawables") private void setDemoAttributes(DatabaseSong song) { int randomColor = Math.random() < 0.5 ? 0 : 1; if (!(demoSongs.contains(song.getTitle()) || payingCustomer)) { mView.findViewById(R.id.song_placeholder).setBackground(mView.getContext().getResources().getDrawable(restricted_rectangle, null)); mView.findViewById(R.id.member_tag).setVisibility(View.VISIBLE); } else { mView.findViewById(R.id.member_tag).setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { mView.findViewById(R.id.song_placeholder).setBackground(mView.getContext().getResources().getDrawable(rectangles[1 + randomColor], null)); mView.findViewById(R.id.song_placeholder).setBackgroundTintBlendMode(BlendMode.COLOR_DODGE); } else { mView.findViewById(R.id.song_placeholder).setBackground(mView.getContext().getResources().getDrawable(transparentRectangles[1 + randomColor])); } } } } }
java
19
0.61549
183
44.769634
191
/** * {@link RecyclerView.Adapter} that can display a {@link Song} and makes a call to the * specified {@link OnListFragmentInteractionListener}. */
class
public async Task<List<PropertyValueSuggestion>> GetAutomaticMetadataAsync(AutomaticMetadataRequestInfo requestInfo, CancellationToken token = default(CancellationToken)) { var request = new RestRequest($"/REST/objects/automaticmetadata.aspx"); request.AddJsonBody(requestInfo); var response = await this.MFWSClient.Post<List<PropertyValueSuggestion>>(request, token) .ConfigureAwait(false); return response.Data; }
c#
17
0.792237
116
47.777778
9
/// <summary> /// Returns the IML metadata suggestions for the given temporary files and object version. /// </summary> /// <param name="requestInfo">The request for automatic metadata suggestions.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>An awaitable task for any metadata suggestions.</returns>
function
public void RegisterCondition (string id, ConditionType type) { type.Id = id; ConditionInfo info = CreateConditionInfo (id); ConditionType ot = info.CondType as ConditionType; if (ot != null) ot.Changed -= new EventHandler (OnConditionChanged); info.CondType = type; type.Changed += new EventHandler (OnConditionChanged); }
c#
11
0.716332
61
34
10
/// <summary> /// Registers a new condition in the extension context. /// </summary> /// <param name="id"> /// Identifier of the condition. /// </param> /// <param name="type"> /// Condition evaluator. /// </param> /// <remarks> /// The registered condition will be particular to this extension context. /// Any event that might be fired as a result of changes in the condition will /// only be fired in this context. /// </remarks>
function
public static Gumshoe createDefaultInstance() { return new Gumshoe(new ConfigFinder() { public boolean pathExists(final String path) { return Files.exists(Path.of(path)); } public InputStream getInputStream(final String path) throws IOException { return Files.newInputStream(Path.of(path)); } }, System.getProperties(), System.getenv()); }
java
15
0.577342
64
40.818182
11
/** * This is the normal way to create an instance of Gumshoe. * * @since 1.0.0 * @return A new Gumshoe instance that is capable of interacting with the * file system and system environment. */
function