Dataset Viewer
Auto-converted to Parquet
text
stringlengths
0
26.7k
image
imagewidth (px)
16
768
language
stringclasses
32 values
```cpp #include<cstdio> #include <algorithm> using namespace std; int v[1001],w[1001]; int N,W,i,j; int dp[101][10001]; int main(){ scanf("%d %d",&N,&W); for(j = 0; j < W; j++)dp[0][j] = 0; for(i = 1;i <= N;i++){ scanf("%d %d",&v[i - 1],&w[i - 1]); for(j = 0;j <= W;j++){ if(j - w[i - 1] < 0) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j],dp[i][j - w[i - 1]] + v[i - 1]); } } printf("%d\n",dp[N][W]); return 0; } ```
C++
```javascript import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { getShowEditPost } from '../../../App/AppReducer'; import { fetchPost, editPostRequest } from '../../PostActions'; import { toggleEditPost } from '../../../App/AppActions'; import { injectIntl, FormattedMessage } from 'react-intl'; // Import Style import styles from '../../components/PostListItem/PostListItem.css'; // Import Selectors import { getPost } from '../../PostReducer'; export class PostDetailPage extends React.Component { constructor(props) { super(props); this.state = { name: this.props.post.name, title: this.props.post.title, content: this.props.post.content, }; } renderPostForm = () => { return ( <div className={styles['form-content']}> <h2 className={styles['form-title']}><FormattedMessage id="editPost" /></h2> <input placeholder={this.props.intl.messages.authorName} className={styles['form-field']} name="name" value={this.state.name} onChange={this.handleInputChange}/> <input placeholder={this.props.intl.messages.postTitle} className={styles['form-field']} name="title" value={this.state.title} onChange={this.handleInputChange}/> <textarea placeholder={this.props.intl.messages.postContent} className={styles['form-field']} name="content" value={this.state.content} onChange={this.handleInputChange}/> <a className={styles['post-submit-button']} href="#" onClick={this.handleEditPost}><FormattedMessage id="submit" /></a> </div> ); }; renderPost = () => { return ( <div className={`${styles['single-post']} ${styles['post-detail']}`}> <h3 className={styles['post-title']}>{this.props.post.title}</h3> <p className={styles['author-name']}><FormattedMessage id="by" /> {this.props.post.name}</p> <p className={styles['post-desc']}>{this.props.post.content}</p> </div> ); }; handleInputChange = (event) => { const { value, name } = event.target; this.setState({ [name]: value, }); }; handleEditPost = () => { this.props.toggleEditPost(); this.props.editPostRequest(this.state); }; render() { return ( <div> <Helmet title={this.props.post.title} /> <a className={styles['edit-post-button']} href="#" onClick={this.props.toggleEditPost}><FormattedMessage id="editPost" /></a> { this.props.showEditPost ? this.renderPostForm() : this.renderPost() } </div> ); } } // Actions required to provide data for this component to render in server side. PostDetailPage.need = [params => { return fetchPost(params.cuid); }]; // Retrieve data from store as props function mapStateToProps(state, props) { return { post: getPost(state, props.params.cuid), }; } function mapDispatchToProps(dispatch, props) { return { toggleEditPost: () => dispatch(toggleEditPost()), editPostRequest: (post) => dispatch(editPostRequest(props.params.cuid, post)), }; } function mapStateToProps(state, props) { return { post: getPost(state, props.params.cuid), showEditPost: getShowEditPost(state), }; } PostDetailPage.propTypes = { post: PropTypes.shape({ name: PropTypes.string.isRequired, title: PropTypes.string.isRequired, content: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, cuid: PropTypes.string.isRequired, }).isRequired, intl: PropTypes.shape({ messages: PropTypes.shape({ authorName: PropTypes.string.isRequired, postTitle: PropTypes.string.isRequired, postContent: PropTypes.string.isRequired, }).isRequired, }).isRequired, showEditPost: PropTypes.bool.isRequired, toggleEditPost: PropTypes.func.isRequired, editPostRequest: PropTypes.func.isRequired, }; export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(PostDetailPage)); ```
JS
```python """ metdata constants """ from enum import Enum DWD_FOLDER_MAIN = "./dwd_data" DWD_FOLDER_STATION_DATA = "station_data" DWD_FOLDER_RADOLAN = "radolan" DWD_FILE_STATION_DATA = "dwd_station_data" DWD_FILE_RADOLAN = "radolan" STATION_ID_REGEX = r"(?<!\d)\d{5}(?!\d)" RADOLAN_HISTORICAL_DT_REGEX = r"(?<!\d)\d{6}(?!\d)" RADOLAN_RECENT_DT_REGEX = r"(?<!\d)\d{10}(?!\d)" NA_STRING = "-999" STATION_DATA_SEP = ";" class DataFormat(Enum): CSV = "csv" H5 = "h5" BIN = "bin" class ArchiveFormat(Enum): ZIP = "zip" GZ = "gz" TAR_GZ = "tar.gz" ```
Python
```ruby # Jekyll Plugin - Insane Vk-video Embed # # Author: Sergey Melnikov - https://github.com/MelnikovSergey # Description: description will be later =) module Jekyll class Vk < Liquid::Tag @vk_video_params = nil VIDEO_URL = /[0-9]+.+/ def initialize(tag_name, markup, tokens) super if markup =~ VIDEO_URL @vk_video_params = markup end end def render(context) output = "<div class=\"video\">" output += "<figure>" output += "<iframe src=\"https://vk.com/video_ext.php?oid=-#{@vk_video_params}\" width=\"640\" height=\"360\" frameborder=\"0\" allowfullscreen></iframe>" output += "</figure>" output += "</div>" end end end Liquid::Template.register_tag('vk', Jekyll::Vk) ```
Ruby
```javascript $.ajax({ url: "/api/categories/", type: "GET", contentType: "application/json; charset=utf-8" }).then(function (response) { var dataToReturn = []; for (var i = 0; i < response.length; i++) { var tagToTransform = response[i]; var newTag = { id: tagToTransform["name"], text: tagToTransform["name"] }; dataToReturn.push(newTag); } $("#categories").select2({ placeholder: "Select Categories for the Acronym", tags: true, tokenSeparators: [','], data: dataToReturn }); }); ```
JS
```rust let levels = match std::env::var("LOG").ok() { Some(level) => level, None => match level { "off" => "off".to_string(), _ => [ format!("vector={}", level), format!("codec={}", level), format!("file_source={}", level), "tower_limit=trace".to_owned(), format!("rdkafka={}", level), ] .join(","), }, }; let color = match opts.color { #[cfg(unix)] Color::Auto => atty::is(atty::Stream::Stdout), #[cfg(windows)] Color::Auto => false, // ANSI colors are not supported by cmd.exe Color::Always => true, Color::Never => false, }; let json = match &opts.log_format { LogFormat::Text => false, LogFormat::Json => true, }; trace::init(color, json, levels.as_str()); metrics::init().expect("metrics initialization failed"); info!("Log level {:?} is enabled.", level); if let Some(threads) = opts.threads { if threads < 1 { error!("The `threads` argument must be greater or equal to 1."); std::process::exit(exitcode::CONFIG); } } let mut rt = { let threads = opts.threads.unwrap_or_else(|| max(1, num_cpus::get())); runtime::Builder::new() .threaded_scheduler() .enable_all() .core_threads(threads) .build() .expect("Unable to create async runtime") }; rt.block_on(async move { if let Some(s) = sub_command { std::process::exit(match s { SubCommand::Validate(v) => validate::validate(&v, color).await, SubCommand::List(l) => list::cmd(&l), SubCommand::Test(t) => unit_test::cmd(&t), SubCommand::Generate(g) => generate::cmd(&g), }) }; ```
Rust
```csharp using System; using System.Linq; namespace B { class Program { static void Main(string[] args) { string input = Console.ReadLine(); long N = Convert.ToInt64(input); long SN = 0; foreach (char c in input) { SN += (long)char.GetNumericValue(c); } if (N % SN == 0) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); } } } } ```
C#
```javascript import { connect } from "react-redux"; import { OwnTAO } from "./OwnTAO"; const mapStateToProps = (state) => { return { pastEventsRetrieved: state.globalReducer.pastEventsRetrieved, nameId: state.nameReducer.nameId, ownTAOs: state.nameReducer.taos, taosNeedApproval: state.nameReducer.taosNeedApproval, stakeEthos: state.nameReducer.stakeEthos, stakePathos: state.nameReducer.stakePathos, taos: state.globalReducer.taos, taoPositions: state.globalReducer.taoPositions }; }; const mapDispatchToProps = (dispatch) => { return {}; }; export const OwnTAOContainer = connect( mapStateToProps, mapDispatchToProps )(OwnTAO); ```
JS
```rust extern crate xvmath; use xvmath::*; fn debranch(a : vec, b : vec, c : vec) -> vec { (c & a) | c.andnot(b) } fn main() { let a = vec::newss(3.); let b = vec::newss(2.); println!("{:?}", debranch(a, b, a.lt(b))); } ```
Rust
```html </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">YDLIDAR SDK PACKAGE V1.3.4 </div> </div> </div><!--header--> <div class="contents"> <div class="textblock"><p>SDK <a href="https://github.com/yangfuyuan/sdk/tree/non-singleton">test</a> application for YDLIDAR</p> <p>Visit EAI Website for more details about <a href="http://www.ydlidar.com/">YDLIDAR</a> .</p> <h1>How to build YDLIDAR SDK samples </h1> <p>$ git clone <a href="https://github.com/yangfuyuan/sdk">https://github.com/yangfuyuan/sdk</a> $ cd sdk $ git checkout non-singleton $ cd .. $ mkdir build $ cd build $ cmake ../sdk $ make ###linux $ vs open Project.sln ###windows</p> <h1>How to run YDLIDAR SDK samples </h1> <p>$ cd samples</p> <p>linux: </p><pre class="fragment">$ ./ydlidar_test $Please enter the lidar port:/dev/ttyUSB0 $Please enter the lidar baud rate:230400 </pre><p>windows: </p><pre class="fragment">$ ydlidar_test.exe $Please enter the lidar port:COM3 $Please enter the lidar baud rate:230400 </pre><p>=====================================================================</p> <p>You should see YDLIDAR's scan result in the console: </p><pre class="fragment">Yd Lidar running correctly ! The health status: good [YDLIDAR] Connection established in [/dev/ttyUSB0]: Firmware version: 2.0.9 Hardware version: 2 Model: G4 Serial: 2018022700000003 [YDLIDAR INFO] Current Sampling Rate : 9K [YDLIDAR INFO] Current Scan Frequency : 7.400000Hz [YDLIDAR INFO] Now YDLIDAR is scanning ...... Scan received: 43 ranges Scan received: 1361 ranges Scan received: 1412 ranges </pre><h1>Lidar point data structure </h1> <p>data structure: </p><pre class="fragment">struct node_info { uint8_t sync_quality;//!intensity uint16_t angle_q6_checkbit; //!angle uint16_t distance_q2; //! distance uint64_t stamp; //! time stamp uint8_t scan_frequence;//! current_frequence = scan_frequence/10.0, If the current value equals zero, it is an invalid value } __attribute__((packed)) ; </pre><p>example: </p><pre class="fragment">if(data[i].scan_frequence != 0) { current_frequence = data[i].scan_frequence/10.0; } current_time_stamp = data[i].stamp; current_distance = data[i].distance_q2/4.f; current_angle = ((data[i].angle_q6_checkbit&gt;&gt;LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT)/64.0f); current_intensity = (float)(data[i].sync_quality &gt;&gt; 2); ###note:current_frequence = data[0].scan_frequence/10.0. ###if the current_frequence value equals zero, it is an invalid value. </pre><p>code: </p><pre class="fragment"> void ParseScan(node_info* data, const size_t&amp; size) { double current_frequence, current_distance, current_angle, current_intensity; uint64_t current_time_stamp; for (size_t i = 0; i &lt; size; i++ ) { if( data[i].scan_frequence != 0) { current_frequence = data[i].scan_frequence;//or current_frequence = data[0].scan_frequence } current_time_stamp = data[i].stamp; current_angle = ((data[i].angle_q6_checkbit&gt;&gt;LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT)/64.0f);//LIDAR_RESP_MEASUREMENT_ANGLE_SHIFT equals 8 current_distance = data[i].distance_q2/4.f; current_intensity = (float)(data[i].sync_quality &gt;&gt; 2); } if (current_frequence != 0 ) { printf("current lidar scan frequency: %f\n", current_frequence); } else { printf("Current lidar does not support return scan frequency\n"); } } </pre><h1>Upgrade Log </h1> <p>2018-05-23 version:1.3.4</p> <p>1.add automatic reconnection if there is an exception</p> <p>2.add serial file lock.</p> <p>2018-05-14 version:1.3.3</p> <p>1.add the heart function constraint.</p> <p>2.add packet type with scan frequency support.</p> <p>2018-04-16 version:1.3.2</p> <p>1.add multithreading support.</p> <p>2018-04-16 version:1.3.1</p> <p>1.Compensate for each laser point timestamp. </p> </div></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html> ```
HTML
```java // -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.model.control.contact.common.transfer; import com.echothree.util.common.transfer.BaseTransfer; public class ContactInet4AddressTransfer extends BaseTransfer { private String inet4Address; /** Creates a new instance of ContactInet4AddressTransfer */ public ContactInet4AddressTransfer(String inet4Address) { this.inet4Address = inet4Address; } public String getInet4Address() { return inet4Address; } public void setInet4Address(String inet4Address) { this.inet4Address = inet4Address; } } ```
Java
```ruby C = readlines.map{|l| l.split.map(&:to_i)} require 'matrix' a = Array.new(9){Array.new(9, 0)} b = Array.new(9, 0) C.flatten.each_with_index do |c, i| x, y = i.divmod(3) y += 3 a[i][x] = 1 a[i][y] = 1 b[i] = c end m = Matrix[*a] em = m.hstack(Matrix.column_vector(b)) puts m.rank == em.rank ? 'Yes' : 'No' ```
Ruby
```xml <object> <name>spot</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>1186</xmin> <ymin>553</ymin> <xmax>1289</xmax> <ymax>917</ymax> </bndbox> </object> <object> <name>spot</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>1464</xmin> <ymin>575</ymin> <xmax>1550</xmax> <ymax>881</ymax> </bndbox> </object> </annotation> ```
XML
```java /* * Copyright 2015 herd contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.finra.herd.service.helper.notification; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.finra.herd.core.HerdDateUtils; import org.finra.herd.dao.helper.HerdDaoSecurityHelper; import org.finra.herd.model.api.xml.Attribute; import org.finra.herd.model.api.xml.AttributeDefinition; import org.finra.herd.model.api.xml.BusinessObjectDataKey; import org.finra.herd.model.api.xml.NotificationMessageDefinition; import org.finra.herd.model.api.xml.NotificationMessageDefinitions; import org.finra.herd.model.dto.BusinessObjectDataStatusChangeNotificationEvent; import org.finra.herd.model.dto.BusinessObjectDefinitionDescriptionSuggestionChangeNotificationEvent; import org.finra.herd.model.dto.BusinessObjectFormatVersionChangeNotificationEvent; import org.finra.herd.model.dto.ConfigurationValue; import org.finra.herd.model.dto.MessageHeader; import org.finra.herd.model.dto.NotificationMessage; import org.finra.herd.model.dto.StorageUnitStatusChangeNotificationEvent; import org.finra.herd.model.dto.UserNamespaceAuthorizationChangeNotificationEvent; import org.finra.herd.model.jpa.BusinessObjectDataEntity; import org.finra.herd.model.jpa.BusinessObjectDataStatusEntity; import org.finra.herd.model.jpa.ConfigurationEntity; import org.finra.herd.service.AbstractServiceTest; /** * Tests the functionality for BusinessObjectDataStatusChangeMessageBuilder. */ public class BusinessObjectDataStatusChangeMessageBuilderTest extends AbstractNotificationMessageBuilderTestHelper { @Autowired private BusinessObjectDataStatusChangeMessageBuilder businessObjectDataStatusChangeMessageBuilder; @Test public void testAddObjectPropertyToContextOnAbstractNotificationMessageBuilder() { // Create an empty context map Map<String, Object> context = new LinkedHashMap<>(); // Create test property values. Object propertyValue = new Object(); Object jsonEscapedPropertyValue = new Object(); Object xmlEscapedPropertyValue = new Object(); // Call the method under test. businessObjectDataStatusChangeMessageBuilder .addObjectPropertyToContext(context, ATTRIBUTE_NAME + SUFFIX_UNESCAPED, propertyValue, jsonEscapedPropertyValue, xmlEscapedPropertyValue); // Validate the results. assertEquals(3, CollectionUtils.size(context)); assertEquals(propertyValue, context.get(ATTRIBUTE_NAME + SUFFIX_UNESCAPED)); assertEquals(jsonEscapedPropertyValue, context.get(ATTRIBUTE_NAME + SUFFIX_UNESCAPED + "WithJson")); assertEquals(xmlEscapedPropertyValue, context.get(ATTRIBUTE_NAME + SUFFIX_UNESCAPED + "WithXml")); } @Test public void testAddStringPropertyToContextOnAbstractNotificationMessageBuilder() { // Create an empty context map. Map<String, Object> context = new LinkedHashMap<>(); // Call the method under test. businessObjectDataStatusChangeMessageBuilder.addStringPropertyToContext(context, ATTRIBUTE_NAME + SUFFIX_UNESCAPED, ATTRIBUTE_VALUE + SUFFIX_UNESCAPED); // Validate the results. assertEquals(3, CollectionUtils.size(context)); assertEquals(ATTRIBUTE_VALUE + SUFFIX_UNESCAPED, context.get(ATTRIBUTE_NAME + SUFFIX_UNESCAPED)); assertEquals(ATTRIBUTE_VALUE + SUFFIX_ESCAPED_JSON, context.get(ATTRIBUTE_NAME + SUFFIX_UNESCAPED + "WithJson")); ```
Java
```java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.xiaomi.infra.pegasus.thrift.protocol; /** * Type constants in the Thrift protocol. */ public final class TType { public static final byte STOP = 0; public static final byte VOID = 1; public static final byte BOOL = 2; public static final byte BYTE = 3; public static final byte DOUBLE = 4; public static final byte I16 = 6; public static final byte I32 = 8; public static final byte I64 = 10; public static final byte STRING = 11; public static final byte STRUCT = 12; public static final byte MAP = 13; public static final byte SET = 14; public static final byte LIST = 15; public static final byte ENUM = 16; } ```
Java
```javascript import Component from '@ember/component'; import layout from '../templates/components/mdc-data-table-cell'; import CellMixin from '../mixins/cell'; export default Component.extend (CellMixin, { layout, tagName: 'td', classNames: ['mdc-data-table__cell'], classNameBindings: ['checkbox:mdc-data-table__cell--checkbox'] }); ```
JS
```cpp // Copyright 2015 The Emscripten Authors. All rights reserved. // Emscripten is available under two separate licenses, the MIT license and the // University of Illinois/NCSA Open Source License. Both these licenses can be // found in the LICENSE file. #include <assert.h> #include <stdio.h> #include <pthread.h> #include <emscripten.h> #include <emscripten/threading.h> // This file tests the old GCC built-in atomic operations. // See https://gcc.gnu.org/onlinedocs/gcc-4.6.4/gcc/Atomic-Builtins.html #define NUM_THREADS 8 #define T int // TEMP: Fastcomp backend doesn't implement these as atomic, so #define these to library // implementations that are properly atomic. TODO: Implement these in fastcomp. #define __sync_lock_test_and_set(...) emscripten_atomic_fence() #define __sync_lock_release(...) emscripten_atomic_fence() #define Bool int Bool atomic_bool_cas_u32(T *ptr, T oldVal, T newVal) { T old = emscripten_atomic_cas_u32(ptr, oldVal, newVal); return old == oldVal; } // Test __sync_val_compare_and_swap. T nand_and_fetch(T *ptr, T x) { for(;;) { T old = emscripten_atomic_load_u32(ptr); T newVal = ~(old & x); T old2 = __sync_val_compare_and_swap(ptr, old, newVal); if (old2 == old) return newVal; } } // Test __sync_bool_compare_and_swap. T nand_and_fetch_bool(T *ptr, T x) { for(;;) { T old = emscripten_atomic_load_u32(ptr); T newVal = ~(old & x); Bool success = __sync_bool_compare_and_swap(ptr, old, newVal); if (success) return newVal; } } volatile int nand_and_fetch_data = 0; void *thread_nand_and_fetch(void *arg) { for(int i = 0; i < 999; ++i) // Odd number of times so that the operation doesn't cancel itself out. nand_and_fetch((int*)&nand_and_fetch_data, (int)(long)arg); pthread_exit(0); } void *thread_nand_and_fetch_bool(void *arg) { for(int i = 0; i < 999; ++i) // Odd number of times so that the operation doesn't cancel itself out. nand_and_fetch_bool((int*)&nand_and_fetch_data, (int)(long)arg); pthread_exit(0); } pthread_t thread[NUM_THREADS]; int main() { { T x = 5; ```
C++
```cpp #include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int mod = 1e9 + 7; int main() { int n, m; cin >> n >> m; vector<bool> broken(m, false); for (int i=0; i<m; ++i) { int num; cin >> num; broken[num] = true; } vector<long long> dp(n + 10, 0); dp[0] = 1; for (int i=0; i<n; ++i) { if (!broken[i+1]) { dp[i+1] += dp[i]; dp[i+1] %= mod; } if (!broken[i+2]) { dp[i+2] += dp[i]; dp[i+2] %= mod; } } cout << dp[n]%mod << endl; } ```
C++
```java import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); int[] arrH = new int[N]; for(int i = 0; i < N; i++) { arrH[i] = sc.nextInt(); } int tmpA = 0; int tmpB = 0; boolean[] arrB = new boolean[N]; for(int j = 0; j < M; j++) { tmpA = sc.nextInt() - 1; tmpB = sc.nextInt() - 1; if(arrH[tmpA] > arrH[tmpB]) { arrB[tmpA] = false; arrB[tmpB] = true; } else if(arrH[tmpA] < arrH[tmpB]) { arrB[tmpA] = true; arrB[tmpB] = false; } } int cnt = 0; for(int k = 0; k < N; k++) { if(arrB[k] == false) { cnt++; } } System.out.println(cnt); } } ```
Java
```cpp #include<iostream> using namespace std; int main() { int a, b; cin >> a >> b; if (a < b) cout << a << endl; else cout << a-1 << endl; } ```
C++
```java import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.HashSet; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N = sc.nextInt(); sc.nextLine(); String S = sc.nextLine(); String[] arare = S.split(" ", 0); List<String> listA = new ArrayList<String>(); for(int i=0; i<arare.length; i++){ listA.add(arare[i]); //System.out.println(S); } //System.out.println(listA); List<String> listB = new ArrayList<String>(new HashSet<>(listA)); //System.out.println(listB.size()); if(listB.size()==3){ System.out.println("Three"); }else if(listB.size()==4){ System.out.println("Four"); } } } ```
Java
```bash #!/bin/sh set -e mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt > "$RESOURCES_TO_COPY" XCASSET_FILES=() case "${TARGETED_DEVICE_FAMILY}" in 1,2) TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" ;; 1) TARGET_DEVICE_ARGS="--target-device iphone" ;; 2) TARGET_DEVICE_ARGS="--target-device ipad" ;; *) TARGET_DEVICE_ARGS="--target-device mac" ;; esac realpath() { DIRECTORY="$(cd "${1%/*}" && pwd)" FILENAME="${1##*/}" echo "$DIRECTORY/$FILENAME" } install_resource() { if [[ "$1" = /* ]] ; then RESOURCE_PATH="$1" else RESOURCE_PATH="${PODS_ROOT}/$1" fi if [[ ! -e "$RESOURCE_PATH" ]] ; then cat << EOM error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. EOM exit 1 fi case $RESOURCE_PATH in *.storyboard) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.xib) echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} ;; *.framework) echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" ;; *.xcdatamodel) echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" ```
Sh
```typescript import React from 'react'; import './flag.scss'; import {FlagType} from "../../model"; interface ItemFlag { flag: FlagType; } export default function Flag({ item, short = false }: { item: ItemFlag; short?: boolean }) { const ucFirst = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); if (item.flag !== 'default') { let name = item.flag.toUpperCase(); let title = ucFirst(item.flag); if (short === true) { name = title[0]; } return ( <span className={`flag flag--${item.flag}`} title={title}> {name} </span> ); } return null; } ```
TS
```c #include <stdio.h> int main(void){ int a, b, c; scanf("%d %d %d", &a, &b, &c); if(a==b && b==c && c==a %% a%2==0 %% b%2==0 && c%2==0){ printf("-1\n"); return 0; } int ans=0; while(a%2==0 && b%2==0 && c%2==0){ int _a=a, _b=b, _c=c; a=_b/2+_c/2; b=_a/2+_c/2; c=_a/2+_b/2; ans++; } printf("%d\n", ans); return 0; } ```
C
```scala import scala.concurrent.Await import scala.concurrent.duration._ object WsClient extends LazyLogging { val timeout: FiniteDuration = 60 seconds implicit val bodyWrites: BodyWritable[JsValue] = BodyWritable(a => InMemoryBody(ByteString.fromArrayUnsafe(Json.toBytes(a))), "application/json") private val asyncClient: StandaloneAhcWSClient = { implicit val system: ActorSystem = ActorSystem() implicit val materializer: ActorMaterializer = ActorMaterializer() StandaloneAhcWSClient() } def post(uri: String, headers: Map[String, String], json: JsValue): StandaloneWSResponse = { println("") logger.info(s"POST request URI: $uri") logger.debug(s"POST request headers: $headers") logger.debug(s"POST request body: $json") val client = asyncClient val request = client.url(uri) val response = Await.result( request .withHttpHeaders(headers.toSeq: _*) .withFollowRedirects(false) .post(json), timeout ) println("") logger.debug(s"POST response status: ${response.status}") logger.debug(s"POST response headers: ${response.headers}") logger.debug(s"POST response body: ${response.body}") response } def delete(uri: String, headers: Map[String, String]): StandaloneWSResponse = { println("") logger.info(s"DELETE request URI: $uri") logger.debug(s"DELETE request headers: $headers") val client = asyncClient val request = client.url(uri) val response = Await.result( request .withHttpHeaders(headers.toSeq: _*) .withFollowRedirects(false) .delete(), timeout ) println("") logger.debug(s"DELETE response status: ${response.status}") logger.debug(s"DELETE response headers: ${response.headers}") logger.debug(s"DELETE response body: ${response.body}") response } } ```
Scala
```lisp (PRIMES::Q*2^S (7 6 (:REWRITE DEFAULT-<-1)) (6 6 (:REWRITE DEFAULT-<-2)) (6 2 (:REWRITE RTL::ODDP-ODD-PRIME)) (4 4 (:TYPE-PRESCRIPTION RTL::PRIMEP)) (2 2 (:REWRITE EVENP-WHEN-NOT-ACL2-NUMBERP-CHEAP)) (2 2 (:REWRITE DEFAULT-+-2)) (2 2 (:REWRITE DEFAULT-+-1)) (2 2 (:REWRITE DEFAULT-*-2)) (2 2 (:REWRITE DEFAULT-*-1)) (1 1 (:REWRITE DEFAULT-NUMERATOR)) (1 1 (:REWRITE DEFAULT-DENOMINATOR)) ) (PRIMES::NATP-OF-Q*2^S.Q (65 50 (:REWRITE DEFAULT-<-1)) (50 50 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE DEFAULT-*-2)) (28 28 (:REWRITE DEFAULT-*-1)) (19 19 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 8 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (8 8 (:LINEAR <-OF-*-AND-*)) (6 4 (:REWRITE DEFAULT-+-2)) (6 4 (:REWRITE DEFAULT-+-1)) (4 4 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (PRIMES::NATP-OF-Q*2^S.S (64 49 (:REWRITE DEFAULT-<-1)) (49 49 (:REWRITE DEFAULT-<-2)) (28 28 (:REWRITE DEFAULT-*-2)) (28 28 (:REWRITE DEFAULT-*-1)) (15 15 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (8 8 (:LINEAR <=-OF-*-AND-*-SAME-ALT-LINEAR)) (8 8 (:LINEAR <-OF-*-AND-*)) (4 4 (:REWRITE DEFAULT-+-2)) (4 4 (:REWRITE DEFAULT-+-1)) (4 4 (:LINEAR <-OF-*-SAME-LINEAR-SPECIAL)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-4)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-3)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-2)) (4 4 (:LINEAR <-OF-*-AND-*-SAME-LINEAR-1)) ) (PRIMES::Q*2^S (31 1 (:DEFINITION PRIMES::Q*2^S)) (8 4 (:REWRITE RTL::ODDP-ODD-PRIME)) (6 6 (:REWRITE DEFAULT-*-2)) (6 6 (:REWRITE DEFAULT-*-1)) (4 4 (:TYPE-PRESCRIPTION RTL::PRIMEP)) (4 4 (:REWRITE EVENP-WHEN-NOT-ACL2-NUMBERP-CHEAP)) (4 1 (:REWRITE COMMUTATIVITY-OF-+)) (3 3 (:REWRITE RATIONALP-IMPLIES-ACL2-NUMBERP)) (3 3 (:REWRITE DEFAULT-<-2)) (3 3 (:REWRITE DEFAULT-<-1)) (3 2 (:REWRITE DEFAULT-+-2)) (3 2 (:REWRITE DEFAULT-+-1)) (3 1 (:REWRITE *-OF-*-COMBINE-CONSTANTS)) ```
Lisp
``` #include "UpsampleLayer.h" namespace nvinfer1 { __device__ int translate_idx(int ii, int d1, int d2, int d3, int scale_factor) { int x, y, z, w; w = ii % d3; ii = ii/d3; z = ii % d2; ii = ii/d2; y = ii % d1; ii = ii/d1; x = ii; w = w/scale_factor; z = z/scale_factor; d2 /= scale_factor; d3 /= scale_factor; return (((x*d1+y)*d2)+z)*d3+w; } template <typename Dtype> __global__ void upscale(const Dtype *input, Dtype *output, int no_elements, int scale_factor, int d1, int d2, int d3) { int ii = threadIdx.x + blockDim.x * blockIdx.x; if (ii >= no_elements) return; int ipidx = translate_idx(ii, d1, d2, d3, scale_factor); output[ii]=input[ipidx]; } template <typename Dtype> void UpsampleLayerPlugin::forwardGpu(const Dtype* input,Dtype * output, int N,int C,int H ,int W) { int numElem = N*C*H*W; upscale<<<(numElem + mThreadCount - 1) / mThreadCount, mThreadCount>>>(input,output, numElem, mScale, C, H, W); } size_t type2size(DataType dataType) { size_t _size = 0; switch (dataType) { case DataType::kFLOAT: _size = sizeof(float);break; case DataType::kHALF: _size = sizeof(__half);break; case DataType::kINT8: _size = sizeof(u_int8_t);break; default:std::cerr << "error data type" << std::endl; } return _size; } int UpsampleLayerPlugin::enqueue(int batchSize, const void*const * inputs, void** outputs, void* workspace, cudaStream_t stream) { assert(batchSize == 1); const int channels = mCHW.d[0]; const int64_t in_height = mCHW.d[1]; const int64_t in_width = mCHW.d[2]; const int64_t out_height = mOutputHeight; const int64_t out_width = mOutputWidth; int totalElems = batchSize * in_height * in_width * channels; // Handle no-op resizes efficiently. if (out_height == in_height && out_width == in_width) { CUDA_CHECK(cudaMemcpyAsync(outputs[0], inputs[0], totalElems * type2size(mDataType), cudaMemcpyDeviceToDevice, stream)); CUDA_CHECK(cudaStreamSynchronize(stream)); return 0; } //CUDA_CHECK(cudaStreamSynchronize(stream)); switch (mDataType) { case DataType::kFLOAT : forwardGpu<float>((const float *)inputs[0],(float *)outputs[0],batchSize,mCHW.d[0],mOutputHeight,mOutputWidth); break; case DataType::kHALF: forwardGpu<__half>((const __half *)inputs[0],(__half *)outputs[0],batchSize,mCHW.d[0],mOutputHeight,mOutputWidth); break; case DataType::kINT8: forwardGpu<u_int8_t>((const u_int8_t *)inputs[0],(u_int8_t *)outputs[0],batchSize,mCHW.d[0],mOutputHeight,mOutputWidth); break; default: std::cerr << "error data type" << std::endl; } return 0; }; } ```
PlainText
```go /** * @Author: fanpengfei * @Description: * @File: hello_test.go * @Version: 1.0.0 * @Date: 2020/5/25 13:25 */ package main import "testing" func Test_hello(t *testing.T) { type args struct { name string } tests := []struct { name string args args }{ // TODO: Add test cases. {"test1", args{"fanpf"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { }) } } ```
Go
```php <!-- {{ Session::get('login')['usuario_email']}} --> <!-- <div> <?= var_dump(Session::get('login')) ?> </div> --> <!-- Componente NAVBAR --> <x-nav /> <!-- FIN Componente NAVBAR --> <div class="container mt-5"> <div class="row"> <div class="col-md-12"> </div> <div class="col-md-8 offset-2"> <form id="form-CrearContactoUsuario" method='POST' action="{{ url('storecontacto')}}"> {{ method_field('POST') }} {{ csrf_field() }} <div class=" form-group"> <label for="exampleFormControlInput1">Telefono</label> <input type="text" class="form-control" name="telefono" data-rule="required|phone" placeholder="Telefono"> </div> <div class="form-group text-center"> <button class="btn btn-light">Cancelar</button> <button type="submit" class="btn btn-primary">Enviar</button> </div> </form> </div> </div> </div> <br><br> </div> <!-- Fotter --> <x-foot /> <!-- Footer --> @endsection ```
PHP
```python Example:: >>> # model is an instance of torch.nn.Module >>> import apex >>> sync_bn_model = apex.parallel.convert_syncbn_model(model) ''' mod = module if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): mod = SyncBatchNorm(module.num_features, module.eps, module.momentum, module.affine, module.track_running_stats, process_group, channel_last=channel_last) mod.running_mean = module.running_mean mod.running_var = module.running_var if module.affine: mod.weight.data = module.weight.data.clone().detach() mod.bias.data = module.bias.data.clone().detach() for name, child in module.named_children(): mod.add_module(name, convert_syncbn_model(child, process_group=process_group, channel_last=channel_last)) # TODO(jie) should I delete model explicitly? del module return mod ```
Python
``` #include "../../cuda.h" #include "../../symbols/NaN.cuh" __inline__ __device__ int findNextPowerOfTwo(int input) { return (int)powf(2.0, ceilf(log2f((float)input))); } __device__ int findMaximum(int thisIndex, float thisValue, int nextPowerOfTwo) { for (int offset = nextPowerOfTwo / 2; offset > 0; offset /= 2) { int otherIndex = __shfl_down(thisIndex, offset, nextPowerOfTwo); float otherValue = __shfl_down(thisValue, offset, nextPowerOfTwo); if(otherValue > thisValue) { thisIndex = otherIndex; thisValue = otherValue; } } return thisIndex; } __global__ void maxPoolingKernel ( int batchSize, int* lengths, int numberEntries, int* maxIndices, float* input, float* result) { extern __shared__ int warpMaximumIndices[]; // One instance per block in the X dimension int indexInstance = blockIdx.x; // One row per block in the Y dimension int indexRow = blockIdx.y; // One column per thread int indexColumn = threadIdx.x; int numberRows = gridDim.y; int resultStartInstance = indexInstance * numberRows; int resultIndex = resultStartInstance + indexRow; if(indexInstance < batchSize) { int length = lengths[indexInstance]; int warpId = indexColumn / warpSize; int numberRequiredWarps = (length + warpSize - 1) / warpSize; // Some instances/rows require more warps than others if(warpId < numberRequiredWarps) { int laneId = indexColumn % warpSize; int thisIndex = indexInstance * numberEntries + indexColumn * numberRows + indexRow; float thisValue = indexColumn < length ? input[thisIndex] : __int_as_float(0xff800000); int lastWarpId = numberRequiredWarps - 1; int width = warpId < lastWarpId ? warpSize : findNextPowerOfTwo(length - lastWarpId * warpSize); int warpMaximumIndex = findMaximum(thisIndex, thisValue, width); if(laneId == 0) { ```
PlainText
```java package net.minecraft.network.play.client; import java.io.IOException; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; public class C0FPacketConfirmTransaction implements Packet<INetHandlerPlayServer> { private int windowId; public short uid; private boolean accepted; public C0FPacketConfirmTransaction() { } public C0FPacketConfirmTransaction(int windowId, short uid, boolean accepted) { this.windowId = windowId; this.uid = uid; this.accepted = accepted; } /** * Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer handler) { handler.processConfirmTransaction(this); } /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer buf) throws IOException { this.windowId = buf.readByte(); this.uid = buf.readShort(); this.accepted = buf.readByte() != 0; } /** * Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer buf) throws IOException { buf.writeByte(this.windowId); buf.writeShort(this.uid); buf.writeByte(this.accepted ? 1 : 0); } public int getWindowId() { return this.windowId; } public short getUid() { return this.uid; } } ```
Java
```kotlin fun testInsertFqnForJavaClass() = doTest(2, "SortedSet", "<E> (java.util)", '\n') fun testTabInsertAtTheFileEnd() = doTest(0, "vvvvv", null, '\t') fun testTabInsertBeforeBraces() = doTest(0, "vvvvv", null, '\t') fun testTabInsertBeforeBrackets() = doTest(0, "vvvvv", null, '\t') fun testTabInsertBeforeOperator() = doTest(0, "vvvvv", null, '\t') fun testTabInsertBeforeParentheses() = doTest(0, "vvvvv", null, '\t') fun testTabInsertInsideBraces() = doTest(1, "vvvvv", null, '\t') fun testTabInsertInsideBrackets() = doTest(0, "vvvvv", null, '\t') fun testTabInsertInsideEmptyParentheses() = doTest(0, "vvvvv", null, '\t') fun testTabInsertInsideParentheses() = doTest(0, "vvvvv", null, '\t') fun testTabInsertInSimpleName() = doTest(0, "vvvvv", null, '\t') fun testTabReplaceIdentifier() = doTest(1, "sss", null, '\t') fun testTabReplaceIdentifier2() = doTest(1, "sss", null, '\t') fun testTabReplaceThis() = doTest(1, "sss", null, '\t') fun testTabReplaceNull() = doTest(1, "sss", null, '\t') fun testTabReplaceTrue() = doTest(1, "sss", null, '\t') fun testTabReplaceNumber() = doTest(1, "sss", null, '\t') fun testSingleBrackets() { fixture.configureByFile(fileName()) fixture.type('(') checkResult() } fun testInsertFunctionWithBothParentheses() { fixture.configureByFile(fileName()) fixture.type("test()") checkResult() } fun testObject() = doTest() fun testEnumMember() = doTest(1, "A", null, '\n') fun testEnumMember1() = doTest(1, "A", null, '\n') fun testClassFromClassObject() = doTest(1, "Some", null, '\n') fun testClassFromClassObjectInPackage() = doTest(1, "Some", null, '\n') fun testParameterType() = doTest(1, "StringBuilder", " (java.lang)", '\n') fun testLocalClassCompletion() = doTest(1, "LocalClass", null, '\n') fun testNestedLocalClassCompletion() = doTest(1, "Nested", null, '\n') fun testTypeArgOfSuper() = doTest(1, "X", null, '\n') fun testKeywordClassName() = doTest(1, "class", null, '\n') fun testKeywordFunctionName() = doTest(1, "fun", "fun", "() (test)", '\n') fun testInfixCall() = doTest(1, "to", null, null, '\n') fun testInfixCallOnSpace() = doTest(1, "to", null, null, ' ') fun testImportedEnumMember() { doTest(1, "AAA", null, null, '\n') } fun testInnerClass() { doTest(1, "Inner", null, null, '\n') } } ```
Kotlin
```python N=int(input()) v=list(map(float,input().strip().split())) v.sort() ans=v[0] for n in range(1,N): ans=(ans+v[n])/2 print(ans) ```
Python
```sql -- selectB.test -- -- execsql { -- SELECT c FROM t1 -- EXCEPT ```
SQL
```csharp using System; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.DependencyInjection; using Stl.Serialization; namespace Stl.Fusion.Server { public class JsonifyErrorsAttribute : ExceptionFilterAttribute { public bool RewriteErrors { get; set; } public override Task OnExceptionAsync(ExceptionContext context) { var exception = context.Exception; if (RewriteErrors) { var rewriter = context.HttpContext.RequestServices.GetRequiredService<IErrorRewriter>(); exception = rewriter.Rewrite(context, exception, true); } var serializer = new JsonNetSerializer(JsonNetSerializer.DefaultSettings); var content = serializer.Serialize(exception); var result = new ContentResult() { Content = content, ContentType = "application/json", StatusCode = (int) HttpStatusCode.InternalServerError, }; context.ExceptionHandled = true; return result.ExecuteResultAsync(context); } } } ```
C#
```php <?php if(isset($_GET['excluir'])){ $idExcluir = (int)$_GET['excluir']; Panel::deletar('tb_site.servicos', $idExcluir); Panel::redirect(INCLUDE_PATH_PANEL.'lista-servicos'); }else if(isset($_GET['order']) && isset($_GET['id'])){ Panel::orderItem('tb_site.servicos', $_GET['order'], $_GET['id']); } $paginaAtual = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1; $porPagina = 4; $servicos = Panel::selectAll('tb_site.servicos', ($paginaAtual - 1) * $porPagina, $porPagina); ?> <div class="box-content"> <h2><i class="svg depoimento"></i> Serviços Cadastrados</h2> <div class="wraper-table"> <table> <tr> <th>Serviço</th> <th>Editar</th> <th>Deletar</th> <th>Subir</th> <th>Descer</th> </tr> <?php foreach($servicos as $key => $value){?> <tr> <td><?php echo $value['servico'] ?></td> <td><a class="btn edit" href="<?php echo INCLUDE_PATH_PANEL?>editar-servico?id=<?php echo $value['id']; ?>"><i class="btn svg edit-icon"></i> Editar</a></td> <td><a actionBtn="delete" class="btn deleteA" href="<?php echo INCLUDE_PATH_PANEL; ?>lista-servicos?excluir=<?php echo $value['id']?>"><i class="btn svg delete"></i> Deletar</a></td> <td><a href="<?php echo INCLUDE_PATH_PANEL; ?>lista-servicos?order=up&id=<?php echo $value['id']; ?>" class="btn order"><i class="btn svg angle-up"></i></a></td> <td><a href="<?php echo INCLUDE_PATH_PANEL; ?>lista-servicos?order=down&id=<?php echo $value['id']; ?>" class="btn order"><i class="btn svg angle-down"></i></a></td> </tr> <?php }?> </table> </div><!-- Wraper Table --> <div class="paginacao"> <?php $totalPagina = ceil(count(Panel::selectAll('tb_site.servicos')) / $porPagina); for($i = 1; $i <= $totalPagina; $i++){ if($i == $paginaAtual){ echo '<a class="page-selected">'.$i.'</a>'; }else{ echo '<a href="'.INCLUDE_PATH_PANEL.'lista-servicos?pagina='.$i.'">'.$i.'</a>'; } } ?> </div> </div><!-- Box-Content --> ```
PHP
```ruby class CreateTravels < ActiveRecord::Migration def change create_table :travels do |t| t.string :name t.string :description t.string :recommendation t.integer :distance t.integer :user_id end end end ```
Ruby
```javascript function Main(N) { var M = 0; for(var i = 1;i<10;i++){ if(Number.isInteger(N / i)){ if((N/i)< 10){ M++; } } } if(M < 0 && N<=81){ console.log("Yes"); }else{ console.log("No"); } } Main(require("fs").readFileSync("/dev/stdin", "utf8")); ```
JS
```ruby context "after_authentication" do it "should be a wrapper to after_set_user behavior" do RAM.after_authentication{|u,a,o| a.env['warden.spec.hook.baz'] = "run baz"} RAM.after_authentication{|u,a,o| a.env['warden.spec.hook.paz'] = "run paz"} RAM.after_authentication{|u,a,o| o[:event].should == :authentication } app = lambda do |e| e['warden'].authenticate(:pass) valid_response end env = env_with_params setup_rack(app).call(env) env['warden.spec.hook.baz'].should == 'run baz' env['warden.spec.hook.paz'].should == 'run paz' end it "should not be invoked on default after_set_user scenario" do RAM.after_authentication{|u,a,o| fail} app = lambda do |e| e['warden'].set_user("foo") valid_response end env = env_with_params setup_rack(app).call(env) end it "should run filters in the given order" do RAM.after_authentication{|u,a,o| a.env['warden.spec.order'] << 2} RAM.after_authentication{|u,a,o| a.env['warden.spec.order'] << 3} RAM.prepend_after_authentication{|u,a,o| a.env['warden.spec.order'] << 1} app = lambda do |e| e['warden.spec.order'] = [] e['warden'].authenticate(:pass) valid_response end env = env_with_params setup_rack(app).call(env) env['warden.spec.order'].should == [1,2,3] end it "should allow me to log out a user in an after_set_user block" do RAM.after_set_user{|u,a,o| a.logout} app = lambda do |e| e['warden'].authenticate(:pass) valid_response end env = env_with_params setup_rack(app).call(env) env['warden'].authenticated?.should be_false end end context "after_fetch" do it "should be a wrapper to after_set_user behavior" do RAM.after_fetch{|u,a,o| a.env['warden.spec.hook.baz'] = "run baz"} RAM.after_fetch{|u,a,o| a.env['warden.spec.hook.paz'] = "run paz"} RAM.after_fetch{|u,a,o| o[:event].should == :fetch } env = env_with_params setup_rack(lambda { |e| valid_response }).call(env) env['rack.session']['warden.user.default.key'] = "Foo" env['warden'].user.should == "Foo" env['warden.spec.hook.baz'].should == 'run baz' env['warden.spec.hook.paz'].should == 'run paz' end it "should not be invoked on default after_set_user scenario" do RAM.after_fetch{|u,a,o| fail} app = lambda do |e| ```
Ruby
```scala package test.scala.collection import org.junit.Test import org.junit.Assert._ import org.junit.Ignore import scala.collection.compat.immutable.LazyList import scala.collection.compat._ import scala.collection.mutable.{Builder, ListBuffer} import scala.util.Try class LazyListTest { @Test def t6727_and_t6440_and_8627(): Unit = { assertTrue(LazyList.continually(()).filter(_ => true).take(2) == Seq((), ())) assertTrue(LazyList.continually(()).filterNot(_ => false).take(2) == Seq((), ())) assertTrue(LazyList(1, 2, 3, 4, 5).filter(_ < 4) == Seq(1, 2, 3)) assertTrue(LazyList(1, 2, 3, 4, 5).filterNot(_ > 4) == Seq(1, 2, 3, 4)) assertTrue(LazyList.from(1).filter(_ > 4).take(3) == Seq(5, 6, 7)) assertTrue(LazyList.from(1).filterNot(_ <= 4).take(3) == Seq(5, 6, 7)) } @Test // scala/bug#8990 def withFilter_can_retry_after_exception_thrown_in_filter: Unit = { // use mutable state to control an intermittent failure in filtering the LazyList var shouldThrow = true val wf = LazyList.from(1).take(10).withFilter { n => if (shouldThrow && n == 5) throw new RuntimeException("n == 5") else n > 5 } assertEquals(true, Try { wf.map(identity).length }.isFailure) // throws on n == 5 shouldThrow = false // won't throw next time assertEquals(5, wf.map(identity).length) // success instead of NPE } @Test(timeout = 10000) // scala/bug#6881 def test_reference_equality: Unit = { // Make sure we're tested with reference equality val s = LazyList.from(0) ```
Scala
```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes"> <title>Test Runner</title> <meta charset="UTF-8"> <script src="../../webcomponentsjs/webcomponents.min.js"></script> <link rel="import" href="tests.html"> </head> <body> <div id="mocha"></div> </body> </html> ```
HTML
```xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.glass.sample.compass" android:versionCode="2" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:label="@string/app_name" android:icon="@drawable/ic_compass" > <uses-library android:name="com.google.android.glass" android:required="true" /> <activity android:name="com.google.android.glass.sample.compass.CompassMenuActivity" android:theme="@style/MenuTheme" /> <service android:name="com.google.android.glass.sample.compass.CompassService" android:label="@string/app_name" android:icon="@drawable/ic_compass" android:enabled="true" > <intent-filter> <action android:name="com.google.android.glass.action.VOICE_TRIGGER" /> </intent-filter> <meta-data android:name="com.google.android.glass.VoiceTrigger" android:resource="@xml/compass_show" /> </service> </application> </manifest> ```
XML
```scala "< Back" ) ) ) .build } ```
Scala
``` .section { margin-bottom: 2rem; margin-top: 2rem; position: relative; } @media (min-width: 768px) { .section { margin-bottom: 3rem; margin-top: 3rem; } } @media (min-width: 1280px) { .section { margin-bottom: 5rem; margin-top: 5rem; } } ```
PlainText
```sql -- boundary3.test -- -- db eval { -- SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r -- WHERE t2.a=66 -- ORDER BY t1.rowid -- } SELECT t1.a FROM t1 JOIN t2 ON t1.rowid <= t2.r WHERE t2.a=66 ORDER BY t1.rowid ```
SQL
```java /***************************************************************************** * Copyright (c) PicoContainer Organization. All rights reserved. * * ------------------------------------------------------------------------- * * The software in this package is published under the terms of the BSD * * style license a copy of which has been included with this distribution in * * the LICENSE.txt file. * * * * Original code by Joerg Schaible * *****************************************************************************/ package org.nanocontainer.remoting.ejb.testmodel; import javax.ejb.EJBHome; /** EJB Home interface */ public interface FooBarHome extends EJBHome { // "create" method intentionally left } ```
Java
```c /**************************************************************************/ /* */ /* Copyright (c) 1996-2014 by Express Logic Inc. */ /* */ /* This software is copyrighted by and is the sole property of Express */ /* Logic, Inc. All rights, title, ownership, or other interests */ /* in the software remain the property of Express Logic, Inc. This */ /* software may only be used in accordance with the corresponding */ /* license agreement. Any unauthorized use, duplication, transmission, */ /* distribution, or disclosure of this software is expressly forbidden. */ /* */ /* This Copyright notice may not be removed or modified without prior */ /* written consent of Express Logic, Inc. */ /* */ /* Express Logic, Inc. reserves the right to modify this software */ /* without notice. */ /* */ ```
C
```scala /** * Copyright 2018 eShares, Inc. dba Carta, Inc. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.carta.compat.java.exscalabur import java.time.{LocalDate, ZoneId} import com.carta.exscalabur._ class DataCell(key: String, value: CellType) { def this(key: String, value: String) = { this(key, StringCellType(value)) } def this(key: String, value: Long) = { this(key, LongCellType(value)) } def this(key: String, value: Double) = { this(key, DoubleCellType(value)) } def this(key: String, date: LocalDate, zoneId: ZoneId = ZoneId.systemDefault()) = { this(key, DateCellType(date, zoneId)) } def asScala: com.carta.exscalabur.DataCell = { com.carta.exscalabur.DataCell(key, value) } } ```
Scala
```rust // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! misc. type-system utilities too small to deserve their own file use hir::def_id::DefId; use infer::InferCtxt; use hir::map as ast_map; use hir::pat_util; use traits::{self, Reveal}; use ty::{self, Ty, AdtKind, TyCtxt, TypeAndMut, TypeFlags, TypeFoldable}; use ty::{Disr, ParameterEnvironment}; use ty::fold::TypeVisitor; use ty::layout::{Layout, LayoutError}; use ty::TypeVariants::*; use util::nodemap::FnvHashMap; use rustc_const_math::{ConstInt, ConstIsize, ConstUsize}; use std::cell::RefCell; use std::cmp; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; use std::intrinsics; use syntax::ast::{self, Name}; use syntax::attr::{self, SignedInt, UnsignedInt}; use syntax_pos::Span; use hir; pub trait IntTypeExt { fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx>; fn disr_incr<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, val: Option<Disr>) -> Option<Disr>; fn assert_ty_matches(&self, val: Disr); fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr; } impl IntTypeExt for attr::IntType { fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> { match *self { SignedInt(ast::IntTy::I8) => tcx.types.i8, SignedInt(ast::IntTy::I16) => tcx.types.i16, SignedInt(ast::IntTy::I32) => tcx.types.i32, SignedInt(ast::IntTy::I64) => tcx.types.i64, SignedInt(ast::IntTy::Is) => tcx.types.isize, UnsignedInt(ast::UintTy::U8) => tcx.types.u8, UnsignedInt(ast::UintTy::U16) => tcx.types.u16, UnsignedInt(ast::UintTy::U32) => tcx.types.u32, UnsignedInt(ast::UintTy::U64) => tcx.types.u64, UnsignedInt(ast::UintTy::Us) => tcx.types.usize, } } fn initial_discriminant<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Disr { match *self { SignedInt(ast::IntTy::I8) => ConstInt::I8(0), ```
Rust
``` var i,x,s,min:longint; begin min:=233; s:=0; for i:=1 to 5 do begin read(x); if (x-1) mod 10+1<min then min:=(x-1) mod 10+1; inc(s,x+9-(x-1) mod 10); end; writeln(s-10+min); end. ```
PlainText
```python S = input() c = 0 if S == "RRS" or S == "SRR": print("2") elif S == "RRR": print("3") elif S == "RSR" or S == "RSS" or S == "SSR": print("1") else: print("0") ```
Python
```scala /* * Scala.js (https://www.scala-js.org/) * * Copyright EPFL. * * Licensed under Apache License 2.0 * (https://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package org.scalajs.testsuite.scalalib import scala.reflect._ import org.junit.Test import org.junit.Assert.assertSame class ClassTagTestScala2 { /** * This is a Scala 2.x only test because: * Dotty does not have [[ClassTag]] instances for [[Nothing]] or for [[Null]]. * @see [[https://github.com/lampepfl/dotty/issues/1730]] */ @Test def apply_should_get_the_existing_instances_for_predefined_ClassTags(): Unit = { assertSame(ClassTag.Nothing, classTag[Nothing]) assertSame(ClassTag.Null, classTag[Null]) } /** * This is a Scala 2.x only test because: * Dotty does not have [[ClassTag]] instances for [[Nothing]] or for [[Null]]. * The [[Array]] needs the [[ClassTag]] for the parameterized type. * @see [[https://github.com/lampepfl/dotty/issues/1730]] */ @Test def runtimeClass(): Unit = { assertSame(classOf[Array[_]], classTag[Array[_]].runtimeClass) assertSame(classOf[Array[_ <: AnyRef]], classTag[Array[_ <: AnyRef]].runtimeClass) assertSame(classOf[Array[_ <: Seq[_]]], classTag[Array[_ <: Seq[_]]].runtimeClass) // Weird, those two return Array[s.r.Nothing$] instead of Array[Object] // The same happens on the JVM assertSame(classOf[Array[scala.runtime.Nothing$]], classTag[Array[Nothing]].runtimeClass) assertSame(classOf[Array[scala.runtime.Null$]], classTag[Array[Null]].runtimeClass) } } ```
Scala
```python import time import os import subprocess from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common import utils chrome_options = Options() chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__))) testdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(testdir) port = str(utils.free_port()) server = subprocess.Popen(['python', 'http-server.py', port]) manifest = open('package.json', 'w') manifest.write(''' { "name":"test-node-remote", "node-remote":"<all_urls>", "main":"http://localhost:%s/index.html" } ''' % (port)) manifest.close() driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_options=chrome_options, service_log_path="log", service_args=["--verbose"]) driver.implicitly_wait(5) try: print driver.current_url result = driver.find_element_by_id('result') print result.get_attribute('innerHTML') assert("success" in result.get_attribute('innerHTML')) finally: import platform if platform.system() == 'Windows': subprocess.call(['taskkill', '/F', '/T', '/PID', str(server.pid)]) else: server.terminate() driver.quit() ```
Python
```typescript import IconTop from './arrowTop.svg'; import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; interface ButtonDetailsProps { name: string; onClick: React.MouseEventHandler<HTMLButtonElement>; isButtonUp: boolean; } const ButtonDetails = ({ onClick, name, isButtonUp }: ButtonDetailsProps) => { return ( <StyledButton onClick={onClick}> {name} <StyledImg isBtnUp={isButtonUp} src={IconTop} alt="icon-top" /> </StyledButton> ); }; const StyledButton = styled(Button)(({ theme }) => ` width: 100%; height: 100%; padding: 10px 17px; background-color: ${theme.palette.secondary.main}; box-shadow: 0px 4px 10px rgba(160, 154, 198, 0.2); cursor: pointer; font-family: Rajdhani; color: ${theme.palette.text.primary}; font-size: 16px; font-weight: 700; text-transform: unset; &:hover { background-color: ${theme.palette.secondary.main}, } `); const StyledImg = styled('img', { shouldForwardProp: (prop) => prop !== 'isBtnUp' })<{isBtnUp: boolean}>(({ isBtnUp }) => ` margin-left: 20px; transform: ${!isBtnUp && 'rotate(180deg)'}; `); export default ButtonDetails; ```
TS
```python N = int(input()) dt, dx, dy = 0, 0, 0 avilable = True for i in range(N): t, x, y = map(int, input().split()) if abs(x-dx)+abs(y-dy) > t-dt or (abs(x-dx)+abs(y-dy)) % 2 != (t-dt) % 2: avilable = False if avilable: print('Yes') else: print('No') ```
Python
```python N, K = map(int, input().split()) A = list(map(int, input().split())) cnt = [0]*N town = 1 for i in range(K): if cnt[town-1] ==1: break cnt[town-1] += 1 town = A[town-1] ans1 = sum(cnt) import copy town2 = copy.deepcopy(town) cnt2 = [0]*N for i in range(K): if cnt2[town2-1] ==1: break cnt2[town2-1] += 1 town2 = A[town2-1] ans2 = sum(cnt2) if K <= (ans1-ans2): print(town) else: town3 = 1 cnt3=[0]*N K2 = ((K-(ans1-ans2))%(ans2))+(ans1-ans2) print(K2) for i in range(K2): if cnt3[town3-1] ==1: break cnt[town3-1] += 1 town3 = A[town3-1] print(town3) ```
Python
```xml <?xml version="1.0" encoding="UTF-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd"> <mapped-superclass name="HMLB\UserBundle\User\User"> <indexes> <index columns="username"/> <index columns="email"/> </indexes> <id name="id" type="ddd_identity" column="id"> <generator strategy="NONE"/> </id> <field name="username" type="string" length="100" nullable="false" unique="true"/> ```
XML
```python def solve(H, A_B): max_a = 0 for a_b in A_B: if a_b[0] > max_a: max_a = a_b[0] A_B.sort(key=lambda o: o[1], reverse=True) total_dmg = 0 nage_count = 0 for a_b in filter(lambda o: o[1] > max_a, A_B): total_dmg += a_b[1] nage_count+= 1 if total_dmg >= H: return nage_count huri_count = int((H - total_dmg) / max_a) if H - total_dmg - (huri_count * max_a) <= 0: return nage_count + huri_count else: return nage_count + huri_count + 1 N, H = map(int, input().split()) A_B = [list(map(int, input().split())) for _ in range(N)] print(solve(H, A_B)) ```
Python
```php return [ '(3rd party defined)' => '', '(Session)' => '', '(Twitter)' => '', 'A token used for the auto login feature' => '', 'A token used to avoid CSRF vulnerability' => '', 'Cookie ID (Name)' => '', 'Cookies' => '', 'descriptions' => '', 'Expires' => '', 'I agree' => '', 'Issued and used by CloudFlare' => '', 'Issued and used by Twitter' => '', 'Keep your input data while verifying email address' => '', 'Origin' => '', 'Privacy policy' => '', 'privacy policy' => '', 'Saving "Enable machine-translation" option state' => '', 'Saving the specified or automatically detected language setting' => '', 'Saving the specified or automatically detected time zone setting' => '', 'Saving the specified or default theme (color scheme) setting' => 'Saving the specified or default theme (colour scheme) setting', 'Their privacy policy' => '', 'Track your login status' => '', 'Visit their {description} and/or {privacy} for more details' => '', 'We use cookies to ensure you get the best experience on our website.' => '', 'What to use' => '', ]; ```
PHP
```python import os import subprocess as sp MAJOR = 0 MINOR = 1 MICRO = 0 ISRELEASED = False VERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO) # Return the git revision as a string # taken from numpy/numpy def git_version(): def _minimal_ext_cmd(cmd): # construct minimal environment env = {} for k in ['SYSTEMROOT', 'PATH', 'HOME']: v = os.environ.get(k) if v is not None: env[k] = v # LANGUAGE is used on win32 env['LANGUAGE'] = 'C' env['LANG'] = 'C' env['LC_ALL'] = 'C' out = sp.Popen(cmd, stdout=sp.PIPE, env=env).communicate()[0] return out try: out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD']) GIT_REVISION = out.strip().decode('ascii') except OSError: GIT_REVISION = "Unknown" return GIT_REVISION def _get_git_version(): cwd = os.getcwd() # go to the main directory fdir = os.path.dirname(os.path.abspath(__file__)) maindir = fdir # os.path.join(fdir, "..") os.chdir(maindir) # get git version res = git_version() # restore the cwd os.chdir(cwd) return res def get_version(): if ISRELEASED: return VERSION # unreleased version GIT_REVISION = _get_git_version() return VERSION + ".dev0+" + GIT_REVISION[:7] ```
Python
```python L = [] i = 0 while True: x, y = list(map(int, input().split(' '))) if x == 0 and y == 0: break if x < y: L.append([x, y]) else: L.append([y, x]) for n in L: print(*n) ```
Python
```php @extends('layouts/backend/backend') @section('title', $title) @section('content') <!--breadcrumbs start--> <div id="breadcrumbs-wrapper"> <!-- Search for small screen --> <div class="header-search-wrapper grey hide-on-large-only"> <i class="mdi-action-search active"></i> <input type="text" name="Search" class="header-search-input z-depth-2" placeholder="Explore Materialize"> </div> <div class="container"> <div class="row"> <div class="col s12 m12 l12"> <h5 class="breadcrumbs-title">{{ $title }}</h5> {!! Breadcrumbs::render('admin.program') !!} </div> </div> </div> </div> <!--breadcrumbs end--> <!--start container--> <div class="container"> <div class="section"> <div id="table-datatables"> <h4 class="header">DAFTAR PROGRAM</h4> <a class="btn btn-primary" style="float:right;" href="{{ route('admin.program.create') }}">Tambah Program</a> <div class="row"> <div class="col s12 m12 l12" id="tableProgram_container"> ```
PHP
```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { class Program { static void Main(string[] args) { string s = Console.ReadLine(); string[] sArray = s.Split(' '); List<int> list = new List<int>(); foreach (string st in sArray) { list.Add(int.Parse(st)); } list.Sort(); int c = 0; foreach (int i in list) { if (c != 0) { Console.Write(" "); } Console.Write(i); c++; } } } } ```
C#
```ruby # # Cookbook Name:: ruby-bundle-el-captain-fixes # Recipe:: eventmachine # # Copyright 2015, Marcin Nowicki # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # bundle_config "build.eventmachine --with-cppflags=-I$(brew --prefix openssl)/include" ```
Ruby
``` /* Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import "ASDisplayNodeExtras.h" #import "ASDisplayNodeInternal.h" #import "ASDisplayNode+FrameworkPrivate.h" #import <queue> ```
PlainText
```java * Copyright 2012-2022 the original author or authors. */ package org.assertj.core.api.booleanarray; import static org.assertj.core.api.Assertions.catchThrowable; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldNotBeNull.shouldNotBeNull; import static org.assertj.core.test.BooleanArrays.arrayOf; import static org.mockito.Mockito.verify; import org.assertj.core.api.BooleanArrayAssert; import org.assertj.core.api.BooleanArrayAssertBaseTest; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link BooleanArrayAssert#containsSubsequence(Boolean[])}</code>. * * @author Stefano Cordio */ class BooleanArrayAssert_containsSubsequence_with_Boolean_array_Test extends BooleanArrayAssertBaseTest { @Test void should_fail_if_values_is_null() { // GIVEN Boolean[] subsequence = null; // WHEN Throwable thrown = catchThrowable(() -> assertions.containsSubsequence(subsequence)); // THEN then(thrown).isInstanceOf(NullPointerException.class) .hasMessage(shouldNotBeNull("subsequence").create()); } @Override protected BooleanArrayAssert invoke_api_method() { return assertions.containsSubsequence(new Boolean[] { true, false }); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsSubsequence(getInfo(assertions), getActual(assertions), arrayOf(true, false)); } } ```
Java
```sql --------------------------------------------- ---------------- PROCEDURES ----------------- --------------------------------------------- ---------- #Problem: "Hanoi Towers" --------- CREATE PROCEDURE dbo.ShowTowers AS BEGIN WITH SevenNumbers(Num) AS ( SELECT 1 UNION ALL SELECT Num + 1 FROM SevenNumbers WHERE Num < 7 ), GetTowerA(Disc) AS-- towel A ( SELECT COALESCE(a.Disc, -1) AS Disc FROM SevenNumbers f LEFT JOIN #TowerA a ON f.Num = a.Disc ), GetTowerB(Disc) AS-- towel B ( SELECT COALESCE(b.Disc, -1) AS Disc FROM SevenNumbers f LEFT JOIN #TowerB a ON f.Num = b.Disc ), GetTowerC(Disc) AS-- towel C ( SELECT COALESCE(c.Disc, -1) AS Disc FROM SevenNumbers f LEFT JOIN #TowerC a ON f.Num = c.Disc ) SELECT CASE a.Disc WHEN 7 THEN ' =======7======= ' WHEN 6 THEN ' ======6====== ' WHEN 5 THEN ' =====5===== ' WHEN 4 THEN ' ====4==== ' WHEN 3 THEN ' ===3=== ' WHEN 2 THEN ' ==2== ' WHEN 1 THEN ' =1= ' ELSE ' | ' END AS Tower_A, CASE b.Disc WHEN 7 THEN ' =======7======= ' ```
SQL
```c /* ** ** File: fm2612.c -- software implementation of Yamaha YM2612 FM sound generator ** Split from fm.c to keep 2612 fixes from infecting other OPN chips ** ** Copyright Jarek Burczynski (bujar at mame dot net) ** Copyright Tatsuyuki Satoh , MultiArcadeMachineEmulator development ** ** Version 1.5 (Genesis Plus GX ym2612.c rev. 346) ** */ /* ** History: ** ** 2006~2009 Eke-Eke (Genesis Plus GX): ** Credits to Nemesis (@spritesmind.net), most of those fixes came from his tests on a Model 1 Sega Mega Drive ** More informations at http://gendev.spritesmind.net/forum/viewtopic.php?t=386 ** ** - fixed LFO implementation (Spider-Man & Venom : Separation Anxiety intro,Warlock birds, Aladdin bug sound): ** .added support for CH3 special mode ** .fixed LFO update: it is done after output calculation, like EG/PG updates ** .fixed LFO on/off behavior: LFO is reset when switched ON and holded at its current level when switched OFF (AM & PM can still be applied) ** - improved internal timers emulation ** - fixed Attack Rate update in some specific case (Batman & Robin intro) ** - fixed EG behavior when Attack Rate is maximal ** - fixed EG behavior when SL=0 (Mega Turrican tracks 03,09...) or/and Key ON occurs at minimal attenuation ** - added EG output immediate update on register writes ** - fixed YM2612 initial values (after the reset) ** - implemented Detune overflow (Ariel, Comix Zone, Shaq Fu, Spiderman & many others) ** - implemented correct CSM mode emulation ** - implemented correct SSG-EG emulation (Asterix, Beavis&Butthead, Bubba'n Six & many others) ** - adjusted some EG rates ** ** TODO: fix SSG-EG documentation, BUSY flag support ** ** 06-23-2007 Zsolt Vasvari: ** - changed the timing not to require the use of floating point calculations ** ** 03-08-2003 Jarek Burczynski: ** - fixed YM2608 initial values (after the reset) ** - fixed flag and irqmask handling (YM2608) ** - fixed BUFRDY flag handling (YM2608) ** ** 14-06-2003 Jarek Burczynski: ** - implemented all of the YM2608 status register flags ** - implemented support for external memory read/write via YM2608 ** - implemented support for deltat memory limit register in YM2608 emulation ** ** 22-05-2003 Jarek Burczynski: ** - fixed LFO PM calculations (copy&paste bugfix) ** ** 08-05-2003 Jarek Burczynski: ** - fixed SSG support ** ** 22-04-2003 Jarek Burczynski: ** - implemented 100% correct LFO generator (verified on real YM2610 and YM2608) ** ** 15-04-2003 Jarek Burczynski: ** - added support for YM2608's register 0x110 - status mask ** ** 01-12-2002 Jarek Burczynski: ** - fixed register addressing in YM2608, YM2610, YM2610B chips. (verified on real YM2608) ** The addressing patch used for early Neo-Geo games can be removed now. ** ** 26-11-2002 Jarek Burczynski, Nicola Salmoria: ** - recreated YM2608 ADPCM ROM using data from real YM2608's output which leads to: ** - added emulation of YM2608 drums. ** - output of YM2608 is two times lower now - same as YM2610 (verified on real YM2608) ** ** 16-08-2002 Jarek Burczynski: ** - binary exact Envelope Generator (verified on real YM2203); ** identical to YM2151 ** - corrected 'off by one' error in feedback calculations (when feedback is off) ** - corrected connection (algorithm) calculation (verified on real YM2203 and YM2610) ** ** 18-12-2001 Jarek Burczynski: ** - added SSG-EG support (verified on real YM2203) ** ** 12-08-2001 Jarek Burczynski: ** - corrected sin_tab and tl_tab data (verified on real chip) ** - corrected feedback calculations (verified on real chip) ** - corrected phase generator calculations (verified on real chip) ** - corrected envelope generator calculations (verified on real chip) ** - corrected FM volume level (YM2610 and YM2610B). ```
C
```cpp #include <algorithm> #include <stdexcept> #include <iostream> class division_by_zero: public std::exception {}; class wrong_operation: public std::exception {}; template <typename T> class Calculator { private: std::string results; int number = 0; T get_next(); T get_value() { T value = get_result(); while(number < results.size()) if(results[number] == '+' || results[number] == '-') { number++; if(results[number - 1] == '+') value = value + get_result(); else value = value - get_result(); } if(number < results.size()) throw wrong_operation(); return value; } T get_result() { T value = get_next(); while(number < results.size() && (results[number] == '*' || results[number] == '/')) { number++; if(results[number - 1] == '*') value = value * get_next(); else { T next = get_next(); if(next == T(0)) throw division_by_zero(); value = value / next; } } return value; } ```
C++
```rust #[doc = "Reader of register CS33"] pub type R = crate::R<u32, super::CS33>; #[doc = "Writer for register CS33"] pub type W = crate::W<u32, super::CS33>; #[doc = "Register CS33 `reset()`'s with value 0"] impl crate::ResetValue for super::CS33 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIME_STAMP`"] pub type TIME_STAMP_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TIME_STAMP`"] pub struct TIME_STAMP_W<'a> { w: &'a mut W, } impl<'a> TIME_STAMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] ```
Rust
```sql -------------------------------------------------------------------------------- -- -- -- This procedure will move possible values to solved values when there is -- -- only one possible location for a value in this block. -- -- -- -- Returns the count of cells that were solved -- -------------------------------------------------------------------------------- CREATE OR ALTER PROCEDURE SolveBlockSoloPossibles ( @PuzzleID INT ,@PuzzleSize INT ,@x INT OUT ) AS BEGIN -- Find values where there is only one possible cell in this block and move -- those cells into SquareData as a final solution value INSERT INTO dbo.SquareData ( PuzzleID ,BlockID ,RowID ,ColumnID ,SquareValue ,InitialValue ) SELECT @PuzzleID ,tsd.BlockID ,tsd.RowID ,tsd.ColumnID ,tsd.PossibleValue ,0 FROM dbo.SquareDataPossible tsd INNER JOIN ( SELECT COUNT(*) cnt ,BlockID ,PossibleValue ,PuzzleID FROM dbo.SquareDataPossible AS solo WHERE solo.PuzzleID = @PuzzleID GROUP BY BlockID ,PossibleValue ,PuzzleID ) solo ON tsd.PuzzleID = solo.PuzzleID AND tsd.PuzzleID = @PuzzleID AND tsd.BlockID = solo.BlockID AND tsd.PossibleValue = solo.PossibleValue AND solo.cnt = 1 WHERE NOT EXISTS ( SELECT NULL FROM dbo.SquareData AS sd WHERE tsd.PuzzleID = sd.PuzzleID AND tsd.BlockID = sd.BlockID AND tsd.RowID = sd.RowID AND tsd.ColumnID = sd.ColumnID ); SET @x = @@ROWCOUNT; END GO ```
SQL
```ruby n,q=gets.split.map &:to_i s=gets.chomp.chars.each_cons(2).map{|x| x=1 if (x==["A","C"])} x=[] y=[] ans=[] q.times do |i| x[i],y[i]=gets.split.map &:to_i ans[i]=s.slice(x[i]-1..y[i]-2).sum end q.times do |j| puts ans[i] end ```
Ruby
```php <!-- Fixed size after header--> <div class="content"> <!-- Always on top. Fixed position, fixed width, relative to content width--> <div class="navigation-left"> <div class="navigation-header1"><a href="../../index.php">Home</a></div> <br> <?php echo GetNavigationMenu(1); ?> </div> <!-- Scrollable div with main content --> <div class="main"> <div class="main-header"> fmPDA::getRecordById() </div> <div class="main-header main-sub-header-1"> Retrieve 3 different records by ID, last one will fail (shows error result) </div> <!-- Display the debug log --> <?php echo fmGetLog(); ?> </div> </div> <!-- Always at the end of the page --> <footer> <a href="http://www.driftwoodinteractive.com"><img src="../../img/di.png" height="32" width="128" alt="Driftwood Interactive" style="vertical-align:text-bottom"></a><br> Copyright &copy; <?php echo date('Y'); ?> Mark DeNyse Released Under the MIT License. </footer> <script src="../../js/main.js"></script> <script> javascript:ExpandDropDown("fmPDA"); </script> </body> </html> ```
PHP
```cpp #ifndef UTILITY_HPP_ # define UTILITY_HPP_ template <typename Aspect> struct AspectIsLast { typedef char yes[1]; typedef char no[2]; template <typename C> static yes& test(typename C::Super *); template <typename> static no& test(...); static const bool result = sizeof(test<Aspect>(0)) == sizeof(yes); }; template <typename Chain, template <typename, typename...> class Aspect> struct GetAspect; template <template <typename, typename...> class FirstAspect, template <typename, typename...> class Aspect, typename First, typename ...Args> struct GetAspect<FirstAspect<First, Args...>, Aspect> { typedef typename GetAspect<First, Aspect>::Type Type; }; template <template <typename, typename...> class Aspect, typename First, typename... Args> struct GetAspect<Aspect<First, Args...>, Aspect> { typedef Aspect<First> Type; }; template <typename Chain> struct GetNextChain; template <template <typename, typename...> class Aspect, typename First, typename... Args> struct GetNextChain<Aspect<First, Args...> > { typedef First Type; }; template <typename Chain> struct GetPrevChain { private: template <typename T, bool notChain = !std::is_same<Chain, T>::value, bool Dummy = false> struct Helper; template <bool Dummy> struct Helper<Chain, false, Dummy> { typedef Chain Type; }; template <template <typename, typename...> class Prev, typename ...Args, bool Dummy> struct Helper<Prev<Chain, Args...>, true, Dummy> { typedef Prev<Chain, Args...> Type; }; template <template <typename, typename...> class Prev, typename Next, typename ...Args, bool Dummy> struct Helper<Prev<Next, Args...>, true, Dummy> { typedef typename Helper<Next>::Type Type; }; public: typedef typename Helper<typename Chain::Whole>::Type Type; }; // template <typename Chain> // struct GetPrevChain<Chain>::Helper<Chain> // { // typedef Chain Type; // }; // template <typename> // struct GetUpperAspect; // template <template <typename, typename...> class Aspect, typename Super, typename ...Args> // struct GetUpperAspect<Aspect<Super, Args...> > // { // typedef typename GetAspect<typename Super::Whole, Aspect<Super, Args...> >::Type Type; // }; #endif // !UTILITY_HPP_ ```
C++
```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.demeter.cloud.model.mapper.EnrollInfoMapper"> <resultMap id="BaseResultMap" type="com.demeter.cloud.model.entity.EnrollInfo"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="subject_id" jdbcType="INTEGER" property="subjectId" /> <result column="enroll_user_id" jdbcType="INTEGER" property="enrollUserId" /> <result column="works_id" jdbcType="INTEGER" property="worksId" /> <result column="ip_address" jdbcType="VARCHAR" property="ipAddress" /> <result column="enroll_time" jdbcType="TIMESTAMP" property="enrollTime" /> <result column="is_delete" jdbcType="BIT" property="isDelete" /> <result column="create_by" jdbcType="VARCHAR" property="createBy" /> <result column="create_time" jdbcType="TIMESTAMP" property="createTime" /> <result column="update_by" jdbcType="VARCHAR" property="updateBy" /> <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" /> <result column="status" jdbcType="BIT" property="status" /> <result column="remark" jdbcType="VARCHAR" property="remark" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} ```
XML
```php <?php namespace App\Http\Controllers; use App\Http\Requests\ImpersonationRequest; use App\Models\User; class ImpersonationController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('admin')->except('destroy'); } /** * Create impersonation of user. * * @param \App\Http\Requests\ImpersonationRequest $request * @return \Illuminate\Http\RedirectResponse */ public function store(ImpersonationRequest $request) { $user = User::findOrFail($request->get('user_id')); // Administrators can't be impersonated. if (! $user->isAdmin()) { session()->put('impersonate', $user->id); session()->put('impersonated_by', auth()->id()); } return redirect()->back(); } /** * Stop impersonation of user. * * @return \Illuminate\Http\RedirectResponse */ public function destroy() { session()->forget('impersonate'); return redirect()->back(); } } ```
PHP
```java // ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.designer.core.model.process; import java.util.ArrayList; import java.util.List; import org.talend.core.model.components.IComponent; import org.talend.core.model.components.IODataComponent; import org.talend.core.model.metadata.IMetadataTable; import org.talend.core.model.metadata.MetadataTable; import org.talend.core.model.process.AbstractNode; /** * Virtual node that will be used for the generated code. * * $Id$ * */ public class DataNode extends AbstractNode { public DataNode(IComponent component, String uniqueName) { setComponentName(component.getName()); List<IMetadataTable> metaList = new ArrayList<IMetadataTable>(); IMetadataTable metaTable = new MetadataTable(); metaTable.setTableName(uniqueName); metaList.add(metaTable); setMetadataList(metaList); setComponent(component); setElementParameters(component.createElementParameters(this)); setListConnector(component.createConnectors(this)); setUniqueName(uniqueName); setHasConditionalOutputs(component.hasConditionalOutputs()); setIsMultiplyingOutputs(component.isMultiplyingOutputs()); } public DataNode() { // nothing } /* * (non-Javadoc) * * @see org.talend.core.model.process.INode#renameMetadataColumnName(java.lang.String, java.lang.String, * java.lang.String) */ @Override public void metadataInputChanged(IODataComponent dataComponent, String connectionToApply) { // TODO Auto-generated method stub } @Override public void metadataOutputChanged(IODataComponent dataComponent, String connectionToApply) { // TODO Auto-generated method stub } } ```
Java
```cpp #include <bits/stdc++.h> using namespace std; typedef long long int LL; typedef unsigned long long int ULL; typedef pair<int, int> PII; typedef map<int, int> MII; const int SZ = 112345; const int MOD = 1e9 + 7; int h, n, a[SZ]; int main() { cin >> h >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); LL s = 0; for (int i = n - 1; i >= 0; i--) { s += a[i]; if (s >= h) { cout << "Yes" << endl; return 0; } } cout << "No" << endl; return 0; } ```
C++
```go // Copyright © 2018 Jeff Coffler <jeff@taltos.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "fmt" "time" ) // Return difference between two times in a printable format func getTimeDiffString(a, b time.Time) (timeDiff string) { year, month, day, hour, min, sec := getTimeDiffNumbers(a, b) // Format the output timeDiff = "" if year > 0 { if year > 1 { timeDiff += fmt.Sprintf("%d years, ", year) ```
Go
```python import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 input=lambda :sys.stdin.readline().rstrip() def resolve(): n,m,L=map(int,input().split()) A=[[INF]*n for _ in range(n)] for _ in range(m): a,b,c=map(int,input().split()) if(c>L): continue a-=1; b-=1 A[a][b]=c A[b][a]=c # Warshall-Floyd from itertools import product next=[[0]*n for _ in range(n)] for i,j in product(range(n),repeat=2): next[i][j]=j B=[a[:] for a in A] # deep copy for k,i,j in product(range(n),repeat=3): if(B[i][j]>B[i][k]+B[k][j]): B[i][j]=B[i][k]+B[k][j] next[i][j]=next[i][k] Q=int(input()) for _ in range(Q): s,t=map(int,input().split()) s-=1; t-=1 if(B[s][t]==INF): print(-1) continue # path restoration now=L count=0 while(next[s][t]!=t): w=next[s][t] c=A[s][w] if(now<c): now=L-c count+=1 else: now-=c s=w print(count+(now<A[s][t])) resolve() ```
Python
```go package main import ( "os" "github.com/boltdb/bolt" ) // Set sets the value for a given key in a bucket. func Set(path, name, key, value string) { if _, err := os.Stat(path); os.IsNotExist(err) { fatal(err) return } db, err := bolt.Open(path, 0600) if err != nil { fatal(err) return } defer db.Close() err = db.Update(func(tx *bolt.Tx) error { ```
Go
```python # -*- coding: utf-8 -*- # Author: TDC Team # License: MIT import warnings warnings.filterwarnings("ignore") import sys from ..utils import print_sys from . import bi_pred_dataset, multi_pred_dataset from ..metadata import dataset_names class DTI(bi_pred_dataset.DataLoader): """Data loader class to load datasets in Drug-Target Interaction Prediction task. More info: https://tdcommons.ai/multi_pred_tasks/dti/ Regression task. Given the target amino acid sequence/compound SMILES string, predict their binding affinity. Args: name (str): the dataset name. path (str, optional): The path to save the data file, defaults to './data' label_name (str, optional): For multi-label dataset, specify the label name, defaults to None print_stats (bool, optional): Whether to print basic statistics of the dataset, defaults to False """ def __init__(self, name, path='./data', label_name=None, print_stats=False): """Create Drug-Target Interaction Prediction dataloader object """ super().__init__(name, path, label_name, print_stats, dataset_names=dataset_names["DTI"]) self.entity1_name = 'Drug' self.entity2_name = 'Target' self.two_types = True if print_stats: self.print_stats() print('Done!', flush=True, file=sys.stderr) ```
Python
``` .gdfvaddheader {font-weight: bold; padding: 5px;} .gdfvaddtable {border: 1px #CCCCCC solid; padding: 7px; margin: 5px; width: 100%;} .gdfvaddleft {padding: 3px;} .gdfvaddright {padding: 3px;} .gdfavaddlink {margin-top: 20px; font-size: 10px;} .gdfavaddlink A {text-decoration: none;} .gdfavlink {margin: 5px; width:100%;} .gdfavdellink {float: right; font-size: 11px; display: none;} .gdfavlinka {float: left;} .gdfavoritesform { clear: both;} ```
PlainText
```rust use std::collections::HashMap; use std::cell::RefCell; use std::default::Default; use std::collections::BTreeMap; use serde_json as json; use std::io; use std::fs; use std::mem; use std::thread::sleep; use crate::client; // ############## // UTILITIES ### // ############ /// Identifies the an OAuth2 authorization scope. /// A scope is needed when requesting an /// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). #[derive(PartialEq, Eq, Hash)] pub enum Scope { /// See your AdMob data Readonly, /// See your AdMob data Report, } impl AsRef<str> for Scope { fn as_ref(&self) -> &str { match *self { Scope::Readonly => "https://www.googleapis.com/auth/admob.readonly", Scope::Report => "https://www.googleapis.com/auth/admob.report", } } } impl Default for Scope { fn default() -> Scope { Scope::Readonly } } // ######## // HUB ### // ###### /// Central instance to access all AdMob related resource activities /// /// # Examples /// /// Instantiate a new hub /// /// ```test_harness,no_run /// extern crate hyper; /// extern crate hyper_rustls; /// extern crate yup_oauth2 as oauth2; /// extern crate google_admob1 as admob1; /// use admob1::{Result, Error}; /// # async fn dox() { /// use std::default::Default; /// use oauth2; /// use admob1::AdMob; /// /// // Get an ApplicationSecret instance by some means. It contains the `client_id` and /// // `client_secret`, among other things. /// let secret: oauth2::ApplicationSecret = Default::default(); /// // Instantiate the authenticator. It will choose a suitable authentication flow for you, /// // unless you replace `None` with the desired Flow. /// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about /// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and /// // retrieve them from storage. /// let auth = yup_oauth2::InstalledFlowAuthenticator::builder( /// secret, /// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect, /// ).build().await.unwrap(); ```
Rust
```python N = int(input()) SP = [input().split() for i in range(N)] SP = [[sp[0], int(sp[1]), i+1]for i, sp in enumerate(SP)] SP = sorted(SP, reverse=True, key=lambda x: x[1]) SP = sorted(SP, key=lambda x: x[0]) for s, p, i in SP: print(i) ```
Python
```go // Copyright (c) 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package persistencetests import ( "testing" "time" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" commonproto "go.temporal.io/temporal-proto/common" "go.temporal.io/temporal-proto/enums" "go.temporal.io/temporal-proto/serviceerror" "github.com/temporalio/temporal/common/log/loggerimpl" "github.com/temporalio/temporal/common/metrics" mmocks "github.com/temporalio/temporal/common/metrics/mocks" "github.com/temporalio/temporal/common/mocks" p "github.com/temporalio/temporal/common/persistence" c "github.com/temporalio/temporal/common/service/config" "github.com/temporalio/temporal/common/service/dynamicconfig" ) type VisibilitySamplingSuite struct { *require.Assertions // override suite.Suite.Assertions with require.Assertions; this means that s.NotNil(nil) will stop the test, not merely log an error suite.Suite client p.VisibilityManager persistence *mocks.VisibilityManager metricClient *mmocks.Client } var ( testNamespaceUUID = "fb15e4b5-356f-466d-8c6d-a29223e5c536" testNamespace = "test-namespace" testWorkflowExecution = commonproto.WorkflowExecution{ WorkflowId: "visibility-workflow-test", RunId: "843f6fc7-102a-4c63-a2d4-7c653b01bf52", } testWorkflowTypeName = "visibility-workflow" listErrMsg = "Persistence Max QPS Reached for List Operations." ) ```
Go
```cpp cin >> arr[i]; if(arr[i]%2){ odd++; if(odd_i_1<0) odd_i_1 = i+1; else odd_i_2 = i+1; } else{ even++; even_i = i+1; } } if(even || odd>1){ if(even){ cout << 1 << endl; cout << even_i << endl; } else{ cout << 2 << endl; cout << odd_i_1 << " " << odd_i_2 << endl; } } else cout << -1 << endl; } return 0; } ```
C++
```go return true, nil } } if resp.NextPage == 0 { break } nextPage = resp.NextPage } return false, nil } // PullIsMergeable returns true if the pull request is mergeable. func (g *GithubClient) PullIsMergeable(repo models.Repo, pull models.PullRequest) (bool, error) { githubPR, err := g.GetPullRequest(repo, pull.Num) if err != nil { return false, errors.Wrap(err, "getting pull request") } state := githubPR.GetMergeableState() // We map our mergeable check to when the GitHub merge button is clickable. // This corresponds to the following states: // clean: No conflicts, all requirements satisfied. // Merging is allowed (green box). // unstable: Failing/pending commit status that is not part of the required // status checks. Merging is allowed (yellow box). // has_hooks: GitHub Enterprise only, if a repo has custom pre-receive // hooks. Merging is allowed (green box). // See: https://github.com/octokit/octokit.net/issues/1763 if state != "clean" && state != "unstable" && state != "has_hooks" { return false, nil } return true, nil } // GetPullRequest returns the pull request. func (g *GithubClient) GetPullRequest(repo models.Repo, num int) (*github.PullRequest, error) { var err error var pull *github.PullRequest // GitHub has started to return 404's here (#1019) even after they send the webhook. // They've got some eventual consistency issues going on so we're just going // to retry up to 3 times with a 1s sleep. numRetries := 3 retryDelay := 1 * time.Second for i := 0; i < numRetries; i++ { pull, _, err = g.client.PullRequests.Get(g.ctx, repo.Owner, repo.Name, num) if err == nil { return pull, nil } ghErr, ok := err.(*github.ErrorResponse) if !ok || ghErr.Response.StatusCode != 404 { return pull, err } time.Sleep(retryDelay) } return pull, err } // UpdateStatus updates the status badge on the pull request. // See https://github.com/blog/1227-commit-status-api. func (g *GithubClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { ghState := "error" switch state { case models.PendingCommitStatus: ghState = "pending" case models.SuccessCommitStatus: ghState = "success" case models.FailedCommitStatus: ghState = "failure" } status := &github.RepoStatus{ State: github.String(ghState), Description: github.String(description), Context: github.String(src), TargetURL: &url, } _, _, err := g.client.Repositories.CreateStatus(g.ctx, repo.Owner, repo.Name, pull.HeadCommit, status) return err } // MergePull merges the pull request. func (g *GithubClient) MergePull(pull models.PullRequest) error { // Users can set their repo to disallow certain types of merging. // We detect which types aren't allowed and use the type that is. g.logger.Debug("GET /repos/%v/%v", pull.BaseRepo.Owner, pull.BaseRepo.Name) repo, _, err := g.client.Repositories.Get(g.ctx, pull.BaseRepo.Owner, pull.BaseRepo.Name) if err != nil { return errors.Wrap(err, "fetching repo info") } const ( defaultMergeMethod = "merge" rebaseMergeMethod = "rebase" squashMergeMethod = "squash" ) method := defaultMergeMethod if !repo.GetAllowMergeCommit() { if repo.GetAllowRebaseMerge() { method = rebaseMergeMethod } else if repo.GetAllowSquashMerge() { method = squashMergeMethod } } ```
Go
```java // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview; import android.net.ParseException; import android.util.Log; import org.chromium.base.JNINamespace; import org.chromium.base.ThreadUtils; import java.util.concurrent.Callable; /** * CookieManager manages cookies according to RFC2109 spec. * * Methods in this class are thread safe. */ @JNINamespace("android_webview") public final class CookieManager { private static final String LOGTAG = "CookieManager"; /** * Control whether cookie is enabled or disabled * @param accept TRUE if accept cookie */ public synchronized void setAcceptCookie(boolean accept) { final boolean finalAccept = accept; ThreadUtils.runOnUiThread(new Runnable() { @Override public void run() { nativeSetAcceptCookie(finalAccept); } }); } private final Callable<Boolean> acceptCookieCallable = new Callable<Boolean>() { @Override public Boolean call() throws Exception { return nativeAcceptCookie(); } }; /** * Return whether cookie is enabled * @return TRUE if accept cookie */ public synchronized boolean acceptCookie() { return ThreadUtils.runOnUiThreadBlockingNoException(acceptCookieCallable); } /** ```
Java
```python k=int(input()) s=str(input()) if k<len(s): print(s[0:k]+"...") else: print(s) ```
Python
```sql CREATE TABLE #Codesets ( codeset_id int NOT NULL, concept_id bigint NOT NULL ) ; INSERT INTO #Codesets (codeset_id, concept_id) SELECT 0 as codeset_id, c.concept_id FROM (select distinct I.concept_id FROM ( select concept_id from @vocabulary_database_schema.CONCEPT where concept_id in (45571465,35207716,35207753,35207798,35207725,35207750,35207718,35207754,45581156,35207752,35207717,35207715,35207751) ) I ) C ; with primary_events (event_id, person_id, start_date, end_date, op_start_date, op_end_date, visit_occurrence_id) as ( -- Begin Primary Events select P.ordinal as event_id, P.person_id, P.start_date, P.end_date, op_start_date, op_end_date, cast(P.visit_occurrence_id as bigint) as visit_occurrence_id FROM ( select E.person_id, E.start_date, E.end_date, row_number() OVER (PARTITION BY E.person_id ORDER BY E.sort_date ASC) ordinal, OP.observation_period_start_date as op_start_date, OP.observation_period_end_date as op_end_date, cast(E.visit_occurrence_id as bigint) as visit_occurrence_id FROM ( -- Begin Condition Occurrence Criteria SELECT C.person_id, C.condition_occurrence_id as event_id, C.condition_start_date as start_date, COALESCE(C.condition_end_date, DATEADD(day,1,C.condition_start_date)) as end_date, C.visit_occurrence_id, C.condition_start_date as sort_date FROM ( SELECT co.* FROM @cdm_database_schema.CONDITION_OCCURRENCE co JOIN #Codesets codesets on ((co.condition_source_concept_id = codesets.concept_id and codesets.codeset_id = 0)) ) C -- End Condition Occurrence Criteria ) E JOIN @cdm_database_schema.observation_period OP on E.person_id = OP.person_id and E.start_date >= OP.observation_period_start_date and E.start_date <= op.observation_period_end_date WHERE DATEADD(day,0,OP.OBSERVATION_PERIOD_START_DATE) <= E.START_DATE AND DATEADD(day,0,E.START_DATE) <= OP.OBSERVATION_PERIOD_END_DATE ) P -- End Primary Events ) SELECT event_id, person_id, start_date, end_date, op_start_date, op_end_date, visit_occurrence_id INTO #qualified_events FROM ( select pe.event_id, pe.person_id, pe.start_date, pe.end_date, pe.op_start_date, pe.op_end_date, row_number() over (partition by pe.person_id order by pe.start_date ASC) as ordinal, cast(pe.visit_occurrence_id as bigint) as visit_occurrence_id FROM primary_events pe ) QE ; --- Inclusion Rule Inserts select 0 as inclusion_rule_id, person_id, event_id INTO #Inclusion_0 FROM ( select pe.person_id, pe.event_id FROM #qualified_events pe JOIN ( -- Begin Criteria Group select 0 as index_id, person_id, event_id FROM ( select E.person_id, E.event_id FROM #qualified_events E INNER JOIN ( -- Begin Correlated Criteria select 0 as index_id, p.person_id, p.event_id from #qualified_events p LEFT JOIN ( SELECT p.person_id, p.event_id FROM #qualified_events P JOIN ( -- Begin Condition Occurrence Criteria SELECT C.person_id, C.condition_occurrence_id as event_id, C.condition_start_date as start_date, COALESCE(C.condition_end_date, DATEADD(day,1,C.condition_start_date)) as end_date, C.visit_occurrence_id, C.condition_start_date as sort_date FROM ( SELECT co.* FROM @cdm_database_schema.CONDITION_OCCURRENCE co JOIN #Codesets codesets on ((co.condition_source_concept_id = codesets.concept_id and codesets.codeset_id = 0)) ) C -- End Condition Occurrence Criteria ) A on A.person_id = P.person_id AND A.START_DATE >= DATEADD(day,-365,P.START_DATE) AND A.START_DATE <= DATEADD(day,-1,P.START_DATE) ) cc on p.person_id = cc.person_id and p.event_id = cc.event_id GROUP BY p.person_id, p.event_id HAVING COUNT(cc.event_id) = 0 -- End Correlated Criteria ```
SQL
```sql -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; -- ----------------------------------------------------- -- Schema *SchemaName* -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema *SchemaName* -- ----------------------------------------------------- USE `*SchemaName*` ; -- ----------------------------------------------------- -- Table `*SchemaName*`.`Position` -- ----------------------------------------------------- DROP TABLE IF EXISTS `*SchemaName*`.`Position` ; CREATE TABLE IF NOT EXISTS `*SchemaName*`.`Position` ( `idPosition` TINYINT NOT NULL AUTO_INCREMENT, `position` VARCHAR(45) NOT NULL DEFAULT 'No Position Defined', PRIMARY KEY (`idPosition`), UNIQUE INDEX `idPosition_UNIQUE` (`idPosition` ASC), UNIQUE INDEX `position_UNIQUE` (`position` ASC)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `*SchemaName*`.`Role` -- ----------------------------------------------------- DROP TABLE IF EXISTS `*SchemaName*`.`Role` ; CREATE TABLE IF NOT EXISTS `*SchemaName*`.`Role` ( `idRole` TINYINT NOT NULL AUTO_INCREMENT, `role` VARCHAR(45) NOT NULL DEFAULT 'No Role Defined', `read` TINYINT NOT NULL DEFAULT 1, `write` TINYINT NOT NULL DEFAULT 0, `edit` TINYINT NOT NULL DEFAULT 0, `delete` TINYINT NOT NULL DEFAULT 0, `create` TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (`idRole`), UNIQUE INDEX `idRole_UNIQUE` (`idRole` ASC)) ENGINE = InnoDB; -- ----------------------------------------------------- ```
SQL
``` jobs (incl. supersource/sink ): 102 RESOURCES - renewable : 4 R - nonrenewable : 2 N - doubly constrained : 0 D ************************************************************************ PRECEDENCE RELATIONS: jobnr. #modes #successors successors 1 1 10 2 3 4 5 6 7 9 10 12 17 2 3 7 23 22 19 18 16 13 11 3 3 6 36 28 24 23 19 8 4 3 5 35 23 15 14 13 5 3 3 21 15 11 6 3 7 36 27 25 23 22 21 19 7 3 6 36 30 27 25 23 14 8 3 5 30 27 25 20 14 9 3 4 23 22 19 13 10 3 7 37 35 30 29 28 22 21 11 3 8 44 43 36 35 34 31 26 25 12 3 5 32 30 27 26 21 13 3 7 43 34 31 28 27 26 25 14 3 4 37 26 22 21 15 3 4 32 31 27 19 16 3 4 37 32 30 21 17 3 8 44 39 37 34 32 31 30 29 18 3 7 44 43 39 35 34 30 26 19 3 5 43 39 37 30 26 20 3 9 57 44 41 40 39 38 37 35 33 21 3 7 57 47 44 43 39 34 31 22 3 7 57 45 44 39 33 32 31 ```
PlainText
```html <div id="doc-content"> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">xsysmon.c File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:ga04de4a4efc9fab7a41b88166bbffc615"><td class="memItemLeft" align="right" valign="top">int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__sysmon__v7__1.html#ga04de4a4efc9fab7a41b88166bbffc615">XSysMon_CfgInitialize</a> (<a class="el" href="struct_x_sys_mon.html">XSysMon</a> *InstancePtr, <a class="el" href="struct_x_sys_mon___config.html">XSysMon_Config</a> *ConfigPtr, UINTPTR EffectiveAddr)</td></tr> <tr class="memdesc:ga04de4a4efc9fab7a41b88166bbffc615"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function initializes a specific <a class="el" href="struct_x_sys_mon.html" title="The driver&#39;s instance data. ">XSysMon</a> device/instance. <a href="group__sysmon__v7__1.html#ga04de4a4efc9fab7a41b88166bbffc615">More...</a><br /></td></tr> <tr class="separator:ga04de4a4efc9fab7a41b88166bbffc615"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7f77755a291cf2bac28ff12a5cdd5d8a"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="group__sysmon__v7__1.html#ga7f77755a291cf2bac28ff12a5cdd5d8a">XSysMon_Reset</a> (<a class="el" href="struct_x_sys_mon.html">XSysMon</a> *InstancePtr)</td></tr> <tr class="memdesc:ga7f77755a291cf2bac28ff12a5cdd5d8a"><td class="mdescLeft">&#160;</td><td class="mdescRight">This function forces the software reset of the complete SystemMonitor/ADC Hard Macro and the SYSMON ADC Core Logic. <a href="group__sysmon__v7__1.html#ga7f77755a291cf2bac28ff12a5cdd5d8a">More...</a><br /></td></tr> ```
HTML
```yaml name: Bounty api: [3.0.0] main: Infernus101\Main version: 2.0.1 author: Infernus101 description: Bounty plugin commands: bounty: description: "Bounty help" ```
YAML
```python n=int(input()) k=2 a=list(map(int, input().split())) if n<3: print(abs(a[0]-a[-1])) exit() c=[0]*n c[-1]=0 mini=1000000 for i in reversed(range(n-k, n-1)): # print(i) c[i]=abs(a[i]-a[n-1]) mini=min(mini, c[i]) for i in reversed(range(n-k)): c[i]=min([c[t]+abs(a[i]-a[t]) for t in range(i+1, i+k+1)]) # print("?", c) print(c[0]) ```
Python
```cpp #include <bits/stdc++.h> using namespace std; #define max(a,b) ((a)>(b)?(a):(b)) #define min(a,b) ((a)<(b)?(a):(b)) typedef long long LL; int main(){ int n,m; while(1){ cin >> n >> m; if(n==0) return 0; vector<int> a(n); for(int i=0;i<n;i++){ cin >> a[i]; } int ans=0; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i!=j){ if(a[i]+a[j]<=m){ ans=max(ans,a[i]+a[j]); } } } } if(ans==0){ cout << "NONE" << endl; }else{ cout << ans << endl; } } return 0; } ```
C++
```python # gather input pixel values from nn corner indexes idx_nn = ibatch + ix_nn + num_row_major[0] * iy_nn + num_row_major[1] * iz_nn output = tf.gather(tf.reshape(im, [-1, channels]), idx_nn) if padding_mode == "zero": output = output * valid elif padding_mode == "value": output = output * valid + padding_mode_value * (1. - valid) return output n_batch = 4 input_size = (220, 220, 220) #quaternions (4,) + translations (3,) + scales (3,) transfos = tf.stack( [tf.zeros(shape=(7), dtype=tf.float32), tf.zeros(shape=(7), dtype=tf.float32), (-20)*tf.ones(shape=(7), dtype=tf.float32)] )[:n_batch] transfos = tf.stack( [[1., 0., 0., 0., 0., 0., 0.], [0.7071, 0.7071, 0., 0., 0., 0., 0.], [0.7071, 0.7071, 0., 0., -20., -20., -20.]] )[:n_batch] transfos = tf.reshape(tf.stack( [[0.7071, 0.7071, 0., 0., 20., 20., 20., 1., 1., 1.]*int(n_batch/2), [1., 0., 0., 0., 0., 0., 0., 1.5, 1.5, 1.5]*int(n_batch/2)] ), shape=(n_batch, 10)) transfos = tf.stack( [[-0.66, 0.15, 0.45, 0.59, -0.1 , -0.34, -1.4 ], [-0.47, -0.58, 0.15, -0.64, 0.38, 0.97, -1.18], [-0.3 , -0.59, -0.33, -0.68, -1.24, -0.21, -0.23], [-0.34, -0.32, 0.12, -0.87, -2.99, 28.75, -9.91]]) data_dir="/home/ltetrel/Documents/work/DeepNeuroAN" file = os.path.join(data_dir, "ses-vid001_task-video_run-01_bold_vol-0001") sitk_im = sitk.ReadImage(file + ".nii.gz", sitk.sitkFloat32) U = tf.expand_dims(sitk.GetArrayFromImage(sitk_im), axis=-1) U = tf.stack( [U]*n_batch, axis=0) out_size = (220, 220, 220) ref_size = tf.shape(U)[1:-1] ref_size_xyz = tf.concat([ref_size[1::-1], ref_size[2:]], axis=0) # min[d] and max[d] correspond to cartesian coordinate d (d=0 is x, d=1 is y ..) name='BatchSpatialTransformer3dAffine' ref_grid = create_ref_grid() sz_ref = ref_grid.GetSize() min_ref_grid = ref_grid.GetOrigin() max_ref_grid = ref_grid.TransformIndexToPhysicalPoint(sz_ref) interp_method = tf.constant("nn", dtype=tf.string) padding_mode = tf.constant("border", dtype=tf.string) padding_mode_value = tf.constant(0., dtype=tf.float32) min_ref_grid = tf.constant(min_ref_grid, dtype=tf.float32) max_ref_grid = tf.constant(max_ref_grid, dtype=tf.float32) #warm-up input_transformed = _transform_grid(ref_size_xyz, transfos, min_ref_grid, max_ref_grid) _interpolate(U + 1., input_transformed + 1., min_ref_grid, max_ref_grid, interp_method, padding_mode) tic = time.time() input_transformed = _transform_grid(ref_size_xyz, transfos, min_ref_grid, max_ref_grid) input_transformed = _interpolate(U, input_transformed, min_ref_grid, max_ref_grid, interp_method, padding_mode) output = tf.reshape(input_transformed, tf.stack([tf.shape(U)[0], *ref_size, tf.shape(U)[-1]])) from vprof import runner tmp = _transform_grid(ref_size_xyz, transfos, min_ref_grid, max_ref_grid) runner.run(_interpolate, 'cmhp', args=(U, tmp, min_ref_grid, max_ref_grid, interp_method, padding_mode), host='localhost', port=8001) ElpsTime = time.time() - tic print("*** Total %1.3f s ***"%(ElpsTime)) def save_array_to_sitk(data, name, data_dir): ref_grid = create_ref_grid() sitk_img = utils.get_sitk_from_numpy(data, ref_grid) sitk.WriteImage(sitk_img, os.path.join(data_dir, name + ".nii.gz")) return sitk_img tic=[] ElpsTime=[] for vol in range(output.shape[0]): sitk_img = save_array_to_sitk(data=output[vol,], name="vol%02d" %(vol+1), data_dir=data_dir) tic += [time.time()] num_dims = U.shape.ndims - 2 ```
Python
``` // ### // ### // ### Practical Course: GPU Programming in Computer Vision // ### // ### // ### Technical University Munich, Computer Vision Group // ### Winter Semester 2013/2014, March 3 - April 4 // ### // ### // ### Evgeny Strekalovskiy, Maria Klodt, Jan Stuehmer, Mohamed Souiai // ### // ### // ### // ### // ### // ### TODO: For every student of your group, please provide here: // ### // ### name, email, login username (for example p123) // ### // ### #include <aux.h> #include <iostream> #include <math.h> using namespace std; // uncomment to use the camera //#define CAMERA #include "non_linear_diffusion.h" int main(int argc, char **argv) { // Before the GPU can process your kernels, a so called "CUDA context" must be initialized // This happens on the very first call to a CUDA function, and takes some time (around half a second) // We will do it right here, so that the run time measurements are accurate cudaDeviceSynchronize(); CUDA_CHECK; // Reading command line parameters: // getParam("param", var, argc, argv) looks whether "-param xyz" is specified, and if so stores the value "xyz" in "var" // If "-param" is not specified, the value of "var" remains unchanged // // return value: getParam("param", ...) returns true if "-param" is specified, and false otherwise #ifdef CAMERA #else // input image string image = ""; bool ret = getParam("i", image, argc, argv); ```
PlainText
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
188