content
stringlengths
10
4.9M
def save_dataframe_as_CSV(dataframe,csv_filepath): csv_header= ['Speaker', 'Time_Stamp', 'Transcript', 'Turn-Taking Facilitation', 'Metacognitive Modeling Questions', 'Behavior Management Questions', 'Teacher Open-Ended S/Q', 'Teacher Close-Ended S/Q', 'Student Open-Ended S/Q', 'Student Close-Ended S/Q', 'Student Close-Ended Response', 'Student Open-Ended Response', 'Student Explanation + Evidence', 'Whole class discussion', 'Lecture', 'Small group + Instructor', 'Individual Work', 'Pair Work', 'Other'] df_utt_types=["Utt_Turn_Taking","Metacognitive_Modelling","Utt_Behavior","Utt_Teacher_OpenQ","Utt_Teacher_CloseQ","Utt_Student_OpenQ","Utt_Student_CloseQ","Utt_Student_CloseR","Utt_Student_OpenR","Utt_Student_ExpEvi"] df_part_types=["Part_Discussion","Part_Lecture","Part_Small_Group","Part_Individual","Part_Pairs","Part_Other"] with open(csv_filepath,"w+",encoding = 'utf-8') as output_csvfile: writer=csv.writer(output_csvfile,delimiter=",") writer.writerow(csv_header) speaker_index=dataframe.columns.get_loc("Speaker") speakers=dataframe.iloc[:,speaker_index].values timestamp_index=dataframe.columns.get_loc("Time_Stamp") timestamps=dataframe.iloc[:,timestamp_index].values utterance_index=dataframe.columns.get_loc("Utterance_String") utterances=dataframe.iloc[:,utterance_index].values predictions=[] for utt_type in df_utt_types: u_type_index=dataframe.columns.get_loc(utt_type) values=dataframe.iloc[:,u_type_index].values values=["1" if x else " " for x in values] predictions.append(values) participation_types=[] for part_type in df_part_types: p_type_index=dataframe.columns.get_loc(part_type) values=dataframe.iloc[:,p_type_index].values values=["1" if x else " " for x in values] participation_types.append(values) for i, speaker in enumerate(speakers): if timestamps[i]=="":speaker="" row=[speaker,timestamps[i],utterances[i]] for u_type in predictions: row.append(u_type[i]) for p_type in participation_types: row.append(p_type[i]) writer.writerow(row) print("File created:"+csv_filepath)
def create_ocp_node_label_line_item(self, report_period, report, node=None, node_labels=None): table_name = OCP_REPORT_TABLE_MAP["node_label_line_item"] data = self.create_columns_for_table(table_name) data["report_period_id"] = report_period.id data["report_id"] = report.id if node: data["node"] = node with OCPReportDBAccessor(self.schema) as accessor: return accessor.create_db_object(table_name, data)
package spec // NewEmptySERVICE - return an empty SERVICE, all fields are initialized func NewEmptySERVICE() SERVICE { return SERVICE{ Name: "", Description: "", Documentation: "", Executable: "", Args: []string{}, WorkingDirectory: "", Environment: map[string]string{}, DependsOn: []ServiceType{}, DependsOnOverrideByOS: map[OsType][]ServiceType{}, DependsOnOverrideByInit: map[InitType][]ServiceType{}, Start: StartConfig{}, Logging: LoggingConfig{ StdOut: LoggingConfigOut{ Disabled: true, }, StdErr: LoggingConfigOut{ Disabled: true, }, }, Credentials: CredentialsConfig{}, } } // KnownOsTypes - var KnownOsTypes = []OsType{ OsFreeBSD, OsLinux, OsMacOS, OsWindows, OsOpenBSD, OsNetBSD, } // KnownInitTypes - var KnownInitTypes = []InitType{ InitRC_D, InitSystemd, InitSystemV, InitUpstart, InitUknown, } // KnownServiceTypes - var KnownServiceTypes = []ServiceType{ ServiceNetwork, ServiceBluetooth, } // ServiceMappings - var ServiceMappings = map[InitType]map[ServiceType]string{ // based on /etc/rc.d/* and /usr/local/etc/rc.d/* InitRC_D: { ServiceNetwork: "NETWORKING", ServiceBluetooth: "bluetooth", }, // based on /etc/systemd/system/* and /usr/lib/systemd/system/* InitSystemd: { ServiceNetwork: "network.target", ServiceBluetooth: "bluetooth.target", }, }
<reponame>Bob-King/WifiTrafficAnalyzer<gh_stars>1-10 package org.mars.kjli.analyzer; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; class ProbeRequestReader implements Closeable { public ProbeRequestReader(InputStream is) { mBufferedReader = new BufferedReader(new InputStreamReader(is)); } public ProbeRequestRecord readProbeRequestRecord() throws IOException { final String line = mBufferedReader.readLine(); if (line == null) { return null; } Matcher matcher = PROBE_REQUEST_RECORD_LINE_PATTERN.matcher(line); if (!matcher.find()) { return null; } ProbeRequestRecord record = new ProbeRequestRecord(); record.ra = Long.valueOf(Utils.macAddress2Long(matcher.group(1))); record.ta = Long.valueOf(Utils.macAddress2Long(matcher.group(2))); record.tsf = Long.valueOf(matcher.group(3)); record.seq = Integer.valueOf(matcher.group(4)); record.rssi = Byte.valueOf(matcher.group(5)); return record; } private final BufferedReader mBufferedReader; private static final Pattern PROBE_REQUEST_RECORD_LINE_PATTERN = Pattern .compile("ra=((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})" + " ta=((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})" + " tsf=([1-9][0-9]*|0)" + " seq=([1-9][0-9]*|0)" + " rssi=(-[1-9][0-9]*)"); @Override public void close() throws IOException { mBufferedReader.close(); } }
/** * Launches an activity that allows user to select a device to use */ public void selectDevice() { Intent serverIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); }
/** * Method to init the Options Dialog * * @return */ public TagInputDialog build() { tagInputDialog.hint = Utils.assign(tagInputDialog.hint, tagInputDialog.activity.getString(R.string.add_text_here_text)); tagInputDialog.message = Utils.assign(tagInputDialog.message, Constant.EMPTY_STRING); tagInputDialog.errorMessage = Utils.assign(tagInputDialog.errorMessage, tagInputDialog.activity.getString(R.string.field_cannot_be_left_blank)); tagInputDialog.positiveButton = Utils.assign(tagInputDialog.positiveButton, tagInputDialog.activity.getString(R.string.ok_text)); tagInputDialog.negativeButton = Utils.assign(tagInputDialog.negativeButton, tagInputDialog.activity.getString(R.string.cancel_text)); return tagInputDialog.init(); }
Ultra-Microelectrode Voltammetric Measurement of the Hydrodynamic Radii and Shear Plane of Micellar Particles for Sodium Dodecyl Sulfate in Aqueous NaCl Solutions Abstract Ultra-microelectrode voltammetric measurements have been performed on sodium dodecyl sulfate (SDS) in the aqueous NaCl solutions at 298.2 ± 0.1 K. The hydrodynamic radii (Rh0) of micellar particles are calculated. The results suggest that Rh0 decrease initially due to collapse of the shear plane toward the micelle hard-sphere surface, and then Rh0 increase gradually due to electrolyte-induced linear spherical expansion of the micellar particles. Based on it, the location of micellar shear plane, the relationship between the shear plane and Debye–Hückel length, and the associated ζ-potential are also estimated. It is found that the relationship between the shear plane and Debye–Hückel length is linear, and, in different NaCl concentrations, the shear plane is almost located at a constant shear potential of 77 ± 10 mV, close to the hard-sphere surface of SDS micelle particles.
/** * Constants for Simbs. */ public final class Constants { /** Application version */ public static final String APP_VERSION = "1.3.3"; /** Name of {@code ResourceBundle} file */ public static final String I18N_PATH = "i18n/simbs"; // ******************* // ** SQL connection // ******************* // ********************* // ** HyperSQL(HSQLDB) // ********************* public static final String HYPER_DRIVER = "org.hsqldb.jdbcDriver"; public static final String HYPER_PROTOCOL = "jdbc:hsqldb:hsql://"; public static final String HYPER_HOST = "localhost"; public static final int HYPER_PORT = -1; public static final String HYPER_DATABASE = "bookdb"; // ******************** // ** PostgreSQL // ******************** public static final String POSTGRE_DRIVER = "org.postgresql.Driver"; public static final String POSTGRE_PROTOCOL = "jdbc:postgresql://"; public static final String POSTGRE_HOST = "localhost"; public static final int POSTGRE_PORT = 5432; public static final String POSTGRE_DATABASE = "bookdb"; private static final java.util.List<Profile> DataProfiles = new java.util.ArrayList<>(); static { ResourceBundle rb = ResourceBundle.getBundle(Constants.I18N_PATH); DataProfiles.add(new Profile(0, rb.getString("Dialog.Login.DataSource.HyperSQL"), HYPER_DRIVER, HYPER_PROTOCOL, HYPER_HOST, HYPER_PORT, HYPER_DATABASE, null, null)); DataProfiles.add(new Profile(1, rb.getString("Dialog.Login.DataSource.PostgreSQL"), POSTGRE_DRIVER, POSTGRE_PROTOCOL, POSTGRE_HOST, POSTGRE_PORT, POSTGRE_DATABASE, null, null)); } public static java.util.List<Profile> getDatabaseProfiles() { return DataProfiles; } public static Profile getDatabaseProfile(int id) { return DataProfiles.get(id); } /** User home of SIMBS */ public static final String SIMBS_HOME = String.format("%s/.simbs", System.getProperty("user.home")); // ************************ // ** Date and time format // ************************ public static final String DATE_FORMAT = "yyyy-M-d"; public static final String TIME_FORMAT = "H:m:s"; public static final String DATE_TIME_FORMAT = DATE_FORMAT+" "+TIME_FORMAT; /** Max rows in result table */ public static final int MAX_ROW_COUNT = 8; /** Days limit for customer borrow book */ public static final int MAX_LENT_DAYS = 100; /** Number of increased days when increasing level */ public static final int DAYS_OF_LEVEL = 20; /** Number of book for customer can borrow each time */ public static final int DEFAULT_LENT_LIMIT = 10; /** Default rental price of book */ public static final BigDecimal DEFAULT_RENTAL_PRICE = new BigDecimal("0.2"); /** For overdue period of price when returning books */ public static final BigDecimal OVERDUE_PERIOD_RATE = new BigDecimal(2); /** The money for upgrade limits */ public static final BigDecimal PRICE_OF_INCREASE_LIMIT = new BigDecimal(100); /** The money for upgrade level */ public static final BigDecimal PRICE_OF_INCREASE_LEVEL = new BigDecimal(150); // *********************** // ** SIMBS commands // *********************** public static final String REGISTER_BOOK = "register-book"; public static final String REGISTER_CUSTOMER = "register-customer"; public static final String EXIT_APP = "exit-app"; public static final String STORE_PROPERTIES = "store-prop"; public static final String VIEW_BILL = "view-bill"; /* Update TablePane in main Frame if the pane is shown */ public static final String UPDATE_BOOK_TABLE = "update-book"; public static final String UPDATE_CUSTOMER_TABLE = "update-customer"; public static final String UPDATE_BILL_TABLE = "update-bill"; public static final String EDIT_VIEW = "edit-view"; public static final String EDIT_MODIFY = "edit-modify"; public static final String EDIT_DELETE = "edit-delete"; public static final String SET_PROMOTE = "set-promote"; public static final String VIEW_BOOK = "view-book"; public static final String VIEW_CUSTOMER = "view-customer"; public static final String VIEW_INVENTORY = "view-inventory"; public static final String VIEW_HOME = "view-navigate"; public static final String VIEW_PROMOTION = "view-promotion"; public static final String STORE_BOOK = "store-book"; public static final String SELL_BOOK = "sell-book"; public static final String LEND_BOOK = "lend-book"; public static final String RETURN_BOOK = "return-book"; public static final String HELP_ABOUT = "help-about"; }
def handle_starttag(self, tag, attrs): self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) ) if tag in self.sanitizelist: self.level += 1 return if self.isNotPurify or tag in self.whitelist_keys: attrs = self.__attrs_str(tag, attrs) attrs = ' ' + attrs if attrs else '' tmpl = u'<%s%s />' if tag in self.unclosedTags and self.isStrictHtml else u'<%s%s>' self.data.append( tmpl % (tag, attrs,) )
<reponame>Paruck/ElE<gh_stars>1-10 #include "ElEScene.h" #include "ElE.h" ElEScene::ElEScene() { } ElEScene::~ElEScene() { this->SceneEnd(); } void ElEScene::Start() { } void ElEScene::Update() { } void ElEScene::Draw() { switch(ElE::getGraphicsRenderer()) { #ifdef RASPBERRY_COMPILE case ElEGraphicsComponents::OpenGLes20Rasp: break; #endif // RASPBERRY_COMPILE } } void ElEScene::SceneEnd() { }
Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL)Buy Photo Stores and hundreds of apartments are proposed to be added to Brandywine Hundred's Concord Plaza office complex, one of the largest commercial parks in the state. Wilmington developer Buccini/Pollin Group wants to build about 300 luxury apartments situated over restaurants, cafes and stores as well as a new office building at the complex located near Silverside Road and U.S. 202, said Larry Tarabicos, an attorney for the developer. Plans will be filed with New Castle County in the coming weeks, according to Mike Hare, senior vice president at Buccini/Pollin, who declined further comment on the property. The privately held developer, which has numerous projects in Delaware and elsewhere, has scheduled a meeting to unveil its plans to the public at 7 p.m. on Dec. 7 at the Talleyville Fire Company, 3919 Concord Pike. The 45-acre Concord Plaza has about 500,000 square feet of office space in 20 two-story, brick buildings. The developer will propose demolishing eight of the structures to make way for six luxury apartment buildings. Three will be four-stories tall and contain only housing. The other three will be five stories, with the ground floors home to about 40,000 square feet of retail space. "There will be high-end-type restaurants mixed with shops and a cafe," Tarabicos said, noting plans are still conceptual. Construction of a four-story "signature" office building also is part of the plan, Tarabicos said. The proposal will not require a rezoning. The project is in one of the busiest corridors in the county. Some residents of the Longwood neighborhood near Shipley and Silverside roads adjacent to the the site on Thursday said traffic will be a concern with new apartments and a more bustling office park. "Getting out on Silverside, the traffic can be bad at the standard times in the morning and afternoon," said Steven Jones, who has lived in Longwood for 25 years. "I guess this will add some traffic to our small part of the world. We'll wait and see. It could be hectic. I'd probably vote no If I had a vote." Others were concerned about any noise generated from a change in the office park's scenery. "They have been a perfect neighbor," said Mary Jo Gebensleb, whose backyard borders the complex. "The offices are old. They have been there a long time. It's quiet. People will probably get mad things are changing, but I don't think the traffic is that bad." About 370,000 square feet of existing office space will not be changed by the revamp. The office complex currently houses the U.S. Postal Service, a branch of Wilmington University, a daycare center, several medical service providers and smaller office tenants. The buildings are underutilized and at least a few sit vacant, said Pete Davisson, a principal with Jackson Cross Partners, a commercial real estate brokerage firm. Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL) The park was the first of its type in Delaware when it was built for DuPont Co. workers in the late 1960s, Davisson said. It was especially attractive given its location in the most developed part of the county with close access to major roadways, Davisson said. "This property was a great property when it was built. At that time, it was the best thing going," Davisson said. "It's just (corporate office) industry has gotten much more sophisticated." AstraZeneca was the park's last marquee tenant. The pharmaceutical giant consolidated its workforce elsewhere in the county between 2000 and 2005. Buccini/Pollin acquired the property around the same time. The park's redevelopment reflects a larger trend of unused office space being repurposed into stores or housing. "It happens in mid- and high-rise office buildings in the city and it happens in these suburban parks. I don't know that you have seen a lot of that here yet. We are coming out of what was the worst five or six years in the history of commercial real estate," Davisson said "This year has been a very good year for the industry. Wilmington hasn't done quite as well as other markets, but everyone is tying hard and, frankly, Buccini is trying harder than anyone." Since the company's formation in 1993, Buccini/Pollin has developed more than 6 million square feet of office and retail space in Mid-Atlantic and Northeast region. The firm owns more than $4 billion in assets, and office space holdings in Delaware include Wilmington's 500 Delaware Ave., The Nemours Building at 1007 Orange St. and the I.M. Pei Building at 105 N. Market St. The firm also owns the 450,000-square-foot Iron Hill Corporate Center near Newark and the 300,000-square-foot Foulkstone Plaza off Foulk Road, as well as four hotels throughout New Castle County. The development firm is part of a dozen developments in Wilmington in the central business district and on the Riverfront. The company has about 150 apartments along North Market Street downtown set to come online by the end of the year. Tarabicos said it is too soon to put a timeline on construction for the Concord Plaza project and it is unclear if the company will seek any state aid for the redevelopment. Financial details were not released. New Castle County Councilman Bob Weiner said the redevelopment of the office park and the development of the neighboring 111 acres of the now-shuttered Brandywine Country Club could be "transformational" for the area. In the coming months, developer Louis Capano III, whose father owns the country club property, is expected to propose building houses on the property. A public hearing about that proposal is scheduled for Dec. 10, but a location for the meeting hasn't been finalized. Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL) "We as a community will be engaged in the public hearing process to assure that the future of these two sites are consistent with community character and respectful of our traffic capacity and architecturally enhance our community," Weiner said. Contact Xerxes Wilson at (302) 324-2787 or xwilson@delawareonline.com. Follow @Ber_Xerxes on Twitter. Read or Share this story: http://delonline.us/1MllQTi
import math def solve(): x, y, p, q = map(int, input().split()) l, r = 0, 10**10 inf = 10**10 while l < r: mid = (l + r) // 2 mp, mq = mid * p, mid * q # print(f"l = {l}, r = {r}, mid = {mid}, mp = {mp}, mq = {mq}") if mp >= x and mq >= y and mp - x <= mq - y: r = mid else: l = mid + 1 print(l * q - y if l != inf else -1) if __name__ == "__main__": t = 1 t = int(input()) for _ in range(t): solve()
/* * Board.h * * Created on: 07.02.2020 * Author: LK */ #ifndef TMC_BOARDS_BOARD_H_ #define TMC_BOARDS_BOARD_H_ #include "Definitions.h" #include "tmc/helpers/API_Header.h" #ifndef TMC_CFLAGS //////////////////////////////////////////////////////////////////////////////// // User defines #define TMC_AXES_COUNT 3 #define TMC_BOARD_COUNT TMC_AXES_COUNT #define BOARD_0 ID_TMC5160 #define BOARD_1 ID_TMC5160 #define BOARD_2 ID_TMC5160 //////////////////////////////////////////////////////////////////////////////// #endif typedef enum { DRIVER_DISABLE, DRIVER_ENABLE, DRIVER_USE_GLOBAL_ENABLE } DriverState; typedef enum { TMC_ERROR_TYPE = 0x04, TMC_ERROR_ADDRESS = 0x04, TMC_ERROR_NOT_DONE = 0x20 } TMC_Error; typedef struct tmc_board_t { void *type; uint16_t id; uint8_t axis; uint8_t alive; uint32_t errors; uint32_t VMMax; uint32_t VMMin; unsigned char numberOfMotors; ConfigurationTypeDef config; uint32_t (*left) (uint8_t motor, int32_t velocity); // move left with velocity <velocity> uint32_t (*right) (uint8_t motor, int32_t velocity); // move right with velocity <velocity> uint32_t (*rotate) (uint8_t motor, int32_t velocity); // move right with velocity <velocity> uint32_t (*stop) (uint8_t motor); // stop motor uint32_t (*moveTo) (uint8_t motor, int32_t position); // move to position <position> uint32_t (*moveBy) (uint8_t motor, int32_t *ticks); // move by <ticks>, changes ticks to absolute target uint32_t (*moveProfile) (uint8_t motor, int32_t position); // move profile <position> uint32_t (*SAP) (uint8_t type, uint8_t motor, int32_t value); // set axis parameter -> TMCL conformance uint32_t (*GAP) (uint8_t type, uint8_t motor, int32_t *value); // get axis parameter -> TMCL conformance uint32_t (*STAP) (uint8_t type, uint8_t motor, int32_t value); // store axis parameter -> TMCL conformance uint32_t (*RSAP) (uint8_t type, uint8_t motor, int32_t value); // restore axis parameter -> TMCL conformance void (*readRegister) (uint8_t motor, uint8_t address, int32_t *value); // Motor needed since some chips utilize it as a switch between low and high values void (*writeRegister) (uint8_t motor, uint8_t address, int32_t value); // Motor needed since some chips utilize it as a switch between low and high values uint32_t (*getMeasuredSpeed) (uint8_t motor, int32_t *value); uint32_t (*userFunction) (uint8_t type, uint8_t motor, int32_t *value); void (*periodicJob) (uint32_t tick); void (*deInit) (void); void (*checkErrors) (uint32_t tick); void (*enableDriver) (DriverState state); uint8_t (*cover) (uint8_t data, uint8_t lastTransfer); void (*fullCover) (uint8_t *data, size_t length); uint32_t (*getMin) (uint8_t type, uint8_t motor, int32_t *value); uint32_t (*getMax) (uint8_t type, uint8_t motor, int32_t *value); DriverState driverState; } TMC_Board; TMC_Board board[TMC_BOARD_COUNT]; void Boards_init(void); void Board_init(TMC_Board *board); void board_setDummyFunctions(TMC_Board *board); #endif /* TMC_BOARDS_BOARD_H_ */
package com.zakrywilson.astro.tle; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicReference; /** * A thread-safe epoch utility class for handling conversions between the TLE epoch (year + * fractional Julian day) and the millisecond epoch from January 1, 1970 00:00:00. It also provides * functionality for formatting a millisecond epoch to the TLE format <code>yyddd.dddddddd</code>. * * @author <NAME> */ final class EpochUtils { /** * UTC timezone. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC"); /** * Number of milliseconds in one day. */ private static final double MILLIS_IN_A_DAY = 86400000.0; /** * Decimal formatter used to format the decimal values of the Julian epoch day. */ private static final AtomicReference<DecimalFormat> DECIMAL_FORMAT_ATOMIC_REFERENCE = new AtomicReference<>(new DecimalFormat(".00000000")); static { DECIMAL_FORMAT_ATOMIC_REFERENCE.get().setRoundingMode(RoundingMode.HALF_UP); } /** * Private constructor since this is a static utility class. */ private EpochUtils() {} /** * Converts a TLE epoch year and fractional Julian day into a millisecond epoch from January 1, * 1970 00:00:00. * * @param year the year to be converted * @param julianDay the fractional Julian day to be converted * @return the millisecond epoch */ static long toMillisecondEpoch(int year, double julianDay) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); // Set year calendar.set(Calendar.YEAR, year); // Set day int wholeDay = (int) julianDay; calendar.set(Calendar.DAY_OF_YEAR, wholeDay); // Set millisecond double dayFraction = julianDay - (double) wholeDay; BigDecimal ms = new BigDecimal(dayFraction * MILLIS_IN_A_DAY); int millisecond = ms.setScale(0, RoundingMode.HALF_UP).intValueExact(); calendar.set(Calendar.MILLISECOND, millisecond); return calendar.getTimeInMillis(); } /** * Formats a TLE with the millisecond from January 1, 1970 00:00:00. * * @param epochMillisecond the epoch millisecond to be formatted * @return the formatted epoch */ static String formatForTLE(long epochMillisecond) { // Get the year and day Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); int year = calendar.get(Calendar.YEAR); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); int twoDigitYear = year % 100; // Reset the calendar to contain only milliseconds accounted for by year and day of year calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, dayOfYear); // Get the fractional part of the day by subtracting out the year and day of year long remainingMilliseconds = epochMillisecond - calendar.getTimeInMillis(); double fractionalDay = remainingMilliseconds / MILLIS_IN_A_DAY; // Format year and day for TLE epoch field String decimal = DECIMAL_FORMAT_ATOMIC_REFERENCE.get().format(fractionalDay); return String.format("%02d%3d%-8s", twoDigitYear, dayOfYear, decimal); } /** * Extracts the epoch year from the epoch millisecond. * * @param epochMillisecond the number of milliseconds since January 1, 1970 00:00:00 * @return the year */ static int getEpochYear(long epochMillisecond) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); return calendar.get(Calendar.YEAR); } /** * Extracts the fractional Julian day from the epoch millisecond. * * @param epochMillisecond the number of milliseconds since January 1, 1970 00:00:00 * @return the fractional Julian day */ static double getEpochJulianDay(long epochMillisecond) { // Get the year and day Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); int year = calendar.get(Calendar.YEAR); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // Get a calendar that contains milliseconds accounted for by the year and day of year calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, dayOfYear); // Get the fractional part of the day by subtracting out the year and day of year long remainingMilliseconds = epochMillisecond - calendar.getTimeInMillis(); double fractionalDay = remainingMilliseconds / MILLIS_IN_A_DAY; // Format year and day for TLE epoch field return (double) dayOfYear + fractionalDay; } }
// Adds handlers to a map field. static void add_handlers_for_mapfield(upb_handlers* h, const upb_fielddef* fielddef, size_t offset) { const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef); map_handlerdata_t* hd = new_map_handlerdata(fielddef, map_msgdef); upb_handlerattr attr = UPB_HANDLERATTR_INIT; upb_handlers_addcleanup(h, hd, free); attr.handler_data = hd; upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr); }
from django.shortcuts import render from django.db import connection from django.shortcuts import render,redirect from django.http import HttpResponse from helpers.format import format_query from helpers.format import executeSQL from helpers.navbar import which_nav from helpers.email import send_email # Create your views here. def department_list(request): logged_in = request.session.get('logged_in') utype = request.session.get('usertype') if logged_in: navname = "logged_navbar.html" else: navname = "navbar.html" sql = f"SELECT * FROM Department" departments = executeSQL(sql, ['DeptID', 'DeptName', 'NumberOfEmployees', 'Budget', 'Location']) return render(request, 'department/department_list.html', {"departments":departments, "titles": list(departments[0].keys()), "nav": navname})
<reponame>cdslabamotong/StenierSolver<gh_stars>0 import math import numpy def mst_instance(current_node): cost = numpy.zeros([len(current_node), len(current_node)]) for i in range(len(current_node)): for j in range(i,len(current_node)): temp = (current_node[j][0] -current_node[i][0])*(current_node[j][0] -current_node[i][0]) + (current_node[j][1] -current_node[i][1]) * (current_node[j][1] -current_node[i][1]) cost[i][j] = math.sqrt(temp) cost[j][i] = cost[i][j] sum = 0 result = Prim(cost, 0, sum) return result def Prim (V, vertex, sum): length = len(V); lowcost = numpy.zeros([length]) U = numpy.zeros([length]) for i in range(length): lowcost[i] = V[vertex, i] U[i] = vertex lowcost[vertex] = -1; for i in range(1,length): k = 0 min = 65535 for j in range(length): if((lowcost[j] > 0) & (lowcost[j] < min)): min = lowcost[j] k = j lowcost[k] = -1 sum = sum + min for j in range(length): if((V[k, j] != 0) & ((lowcost[j] == 0 )| (V[k, j] < lowcost[j]))): lowcost[j] = V[k, j] U[j] = k return sum
red_str_list=[] blue_str_list=[] blue_cnt=int(input()) for _ in range(blue_cnt): red_str_list.append(input()) red_cnt=int(input()) for _ in range(red_cnt): blue_str_list.append(input()) ans=0 dic = dict() for i in red_str_list: if (i in dic.keys()): dic[i]+=1 else: dic[i]=1 for i in blue_str_list: if (i in dic.keys()): if dic[i]>0: dic[i]-=1 print(max(dic.values()))
The intelligence report of the Philippine National Police (PNP) indicating 17-year-old Kian Lloyd delos Santos was a drug runner could be wrong, President Rodrigo Duterte said Monday night. “Those are just information gathered by the police and the military. It is an internal thing. Hindi mo masabi na, ‘itong intel na ito.’ Maya-maya mali iyan (You just can’t say, ‘this intel,’ later on it could be wrong),” Duterte told reporters in Malacañang. ADVERTISEMENT Delos Santos was shot dead on the night of August 16, by the police in a drug operation in Caloocan City. Northern Police District Chief Superintendent Roberto Fajardo has said that Delos Santos was a newly identified drug suspect based on latest intelligence reports. But Duterte said police’s intelligence report has “no probative value” in court. “So, if there is no probative value, how can you use it in court and to the people,” he said. The chief executive in the same meeting with reporters assured the public that the police officers behind the killing Delos Santos would go to jail if proven guilty. READ: Duterte vows to punish cops in Kian killing if proven guilty “Should the investigation point to liabilities, my warning to all is there will be a prosecution and they have to go to jail. That I can assure you,” he said. “If it is really rubout, they (police) have to answer for it. They have to go to jail,” he added. The President said he would not visit the wake of Delos Santos, saying: “It is pregnant with so many presupositions.” ADVERTISEMENT He added that people might interpret his visit to the wake as a chance for him to apologize to the Delos Santos family and as confirmation of the truth of the accusations against the police. JPV RELATED VIDEO Read Next LATEST STORIES MOST READ
n = int(input()) A, B = list(), list() check = set() for i in range(n): a, b = map(int,input().split()) A.append(a);B.append(b) check.add(a) check = sorted(check) val = dict() for x in check: val[x] = list() for i in range(n): val[A[i]].append(B[i]) main_lst = list() for x in check: val[x].sort() itr, ans = 0, 0 for x in check: if itr == 0: prev = max(val[x]) itr += 1 else: if prev > min(val[x]): prev = x else: prev = max(val[x]) print(prev)
How Window Tinting Works- A Beginners Guide in Details You don't need to be a Mafia don or Hollywood star just in order to do a window-tinting job on your … [Continuous Reading--->] 12 Best Air Compressor for Painting Cars to Look This Year (2019)! A serious job requires serious tools. If you intend to paint some cars and you want the paint job … [Continuous Reading--->] How to Install Subwoofer in a Truck – Step by Step Process A truck sound subwoofer is a piece of a truck's sound framework that gives the low bass frequencies … [Continuous Reading--->] Top 10 Best Brake Bleeder Kits in 2019 (Vacuum, Pressure and Electric) Bubbles and air pockets can lead to under performance of your brake or sometimes your brakes even … [Continuous Reading--->] Best Shocks and Struts for Smooth Ride to Look at This Year (2019)! Maintaining your vehicle surely requires you to invest lots of time and effort in it. And, as one of … [Continuous Reading--->] The Difference between Brad and Finish Nailer – Which is The Best? A nailer is a popular power tool which is used to drive nails into wood or different kinds of … [Continuous Reading--->] What Is The Best Air Purifier 2019 – Complete Guide Oxygen is an important part of our daily life and fresh air is a free gift from the Almighty because … [Continuous Reading--->] 11 Best Truck Bed Bike Rack Review to Look at This Year (2019)! As we all know, biking is one of the best sports to do in order to stay in good shape, both … [Continuous Reading--->] Top 10 Best sander for cars to look at This Year (2019)! If auto body work is your professional job then an electric sander is out of the question. However, … [Continuous Reading--->] How to Remove Scratches From Cars and SUVs : Step by Step Guide Among all the damages that are being faced with a car, scratches are one of the most common ones. … [Continuous Reading--->] Are leather car seats better than fabric? The difference between them We can all agree on one thing, the seat comfort in your car is absolutely important! Just think of … [Continuous Reading--->] Best Dash Covers : Top Interior Dashboard Cover Review & Buyer Guide We all have at least one person in our life who has always claimed that dash covers are old … [Continuous Reading--->] Best RV Stabilizer 2019 – Top 10 Travel trailer & 5th wheel stabilizer review If you ever went on a camping trip in your RV, then you must know that uneven ground in a RV park or … [Continuous Reading--->] Best Head Gasket Sealers in 2019 – Top-Rated Gasket Sealer for Cars Do you have a car that may be old or new? If yes, then you’re in for different challenges. Your car … [Continuous Reading--->] How to Protect Your Car from Scratching and Damage In Details Everyone loves and wants the car to look shiny like a new penny. But as a matter of fact, when your … [Continuous Reading--->] Home Remedies for Detoxification | Body Cleanse Home Remedies Home Remedies for Detoxification your body. Typical cleanses that harness the natural processes of … [Continuous Reading--->] 15 DIY Home Remedies for Unwanted Hair Removal Naturally DIY Home Remedies for Unwanted Hair Removal Naturally. Hirsute denotes the growth of rough, dark … [Continuous Reading--->] How to Use Air Compressor to Fill Tire – Step by Step Guide A lovely sunny day and you want to take a long drive along the countryside in this beautiful … [Continuous Reading--->] How to use an Air Compressor and The Steps for Maintaining It Most power tools these days use air compressor to power themselves. An air compressor can be of … [Continuous Reading--->] Air Compressor Safety Guide and How to Maintain an Air Compressor Air compressors are units that are required to power air tools. These tools, also called pneumatic … [Continuous Reading--->] How to Use Nail Gun for Fencing – Step by Step Guide You might have a misconception that fencing is a very tough task to perform. Well, what you are … [Continuous Reading--->] How to Use Head Gasket Sealer – Step by Step Guide Head gasket sealers are like a revolution to us. Whether it’s about preventing leakage of the engine … [Continuous Reading--->] How to Use Nail Gun for Trim – Step by Step Guide Many are familiar with the term nail gun and also with its usage and befits. But, the proper usage … [Continuous Reading--->] How to Change Your Headlight Bulbs – Step by Step Guide If you have a car then you know very well the importance of car headlight. If one or both headlights … [Continuous Reading--->] 15 Home Remedies for Blackheads | Fast Home Remedies Home Remedies for Blackheads. Aesthetics are an extremely important section of the modern day … [Continuous Reading--->] Home Remedies for Weight Loss | How to Lose Weight Healthily Home Remedies for Weight Loss | How to Lose Weight Healthily. Obesity raises the risk of several … [Continuous Reading--->]
<filename>src/com/model/Users.java package com.model; public class Users { private String username; private String password; private String usersname; private String branch; private String privilege; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsersname() { return usersname; } public void setUsersname(String usersname) { this.usersname = usersname; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getPrivilege() { return privilege; } public void setPrivilege(String privilege) { this.privilege = privilege; } public Users(String username, String password, String usersname, String branch, String privilege) { this.username = username; this.password = password; this.usersname = usersname; this.branch = branch; this.privilege = privilege; } public Users() { } @Override public String toString() { return "Users{" + "username=" + username + ", password=" + password + ", usersname=" + usersname + ", branch=" + branch + ", privilege=" + privilege + '}'; } }
// InitGenesis will run module initialization using the genesis state //nolint:gocritic,gocyclo func InitGenesis(ctx sdk.Context, k keeper.Keeper, state GenesisState) { accountKeeper := k.AccountKeeper() coinKeeper := k.CoinKeeper() amount := sdk.NewInt(5000) coins := sdk.Coins{sdk.Coin{ Denom: ModuleName, Amount: amount, }} setServiceAccount(ctx, accountKeeper, coinKeeper, state.KeyService.Address, state.KeyService.PubKey, coins) setServiceAccount(ctx, accountKeeper, coinKeeper, state.BonusService.Address, state.BonusService.PubKey, coins) setServiceAccount(ctx, accountKeeper, coinKeeper, state.ClaimService.Address, state.ClaimService.PubKey, coins) if err := k.SetServiceAddress(ctx, state.KeyService.Address); err != nil { panic(err) } if err := k.SetBonusServiceAddress(ctx, state.BonusService.Address); err != nil { panic(err) } if err := k.SetClaimServiceAddress(ctx, state.ClaimService.Address); err != nil { panic(err) } for i := range state.Attendees { a := &state.Attendees[i] account := accountKeeper.GetAccount(ctx, a.GetAddress()) if account == nil { account = accountKeeper.NewAccountWithAddress(ctx, a.GetAddress()) _, e := coinKeeper.AddCoins(ctx, account.GetAddress(), coins) if e != nil { panic(e) } } _ = account.SetPubKey(a.PubKey) accountKeeper.SetAccount(ctx, account) k.SetAttendee(ctx, a) } for i := range state.Scans { k.SetScan(ctx, &state.Scans[i]) } for i := range state.Prizes { k.SetPrize(ctx, &state.Prizes[i]) } }
def circular_mean(data, weights=None, degrees=True, axis=0, exponential_weights=True): if degrees: data = np.radians(data, dtype=np.float32) sin = np.sin(data) cos = np.cos(data) if weights is None: sin = np.nanmean(sin, axis=axis) cos = np.nanmean(cos, axis=axis) else: if exponential_weights: weights = np.exp(weights) if weights.shape != data.shape: msg = ('The shape of weights {} does not match the shape of the ' 'data {} to which it is to be applied!' .format(weights.shape, data.shape)) logger.error(msg) raise RuntimeError(msg) n_weights = np.expand_dims(np.nansum(weights, axis=axis), axis) sin = np.nansum(sin * weights, axis=axis) / n_weights cos = np.nansum(cos * weights, axis=axis) / n_weights mean = np.arctan2(sin, cos) if degrees: mean = np.degrees(mean) mask = mean < 0 if isinstance(mask, np.ndarray): mean[mask] += 360 elif mask: mean += 360 return mean
// Function object for sorting vector of features and associated region ID's based on distance from a given point class DistanceAtIndexIsGreater { public: typedef std::pair< LocationRegistration::feature_sptr_type, LocationRegistration::SegmentedImageType::PixelType > FeatureIDPair; DistanceAtIndexIsGreater( itk::Point< double, 3 > const & ReferencePoint ) : m_ReferencePoint( ReferencePoint ) {} bool operator()( FeatureIDPair const & i, FeatureIDPair const & j ) { vnl_vector< double > distancei = i.first->location_ - m_ReferencePoint.GetVnlVector(); vnl_vector< double > distancej = j.first->location_ - m_ReferencePoint.GetVnlVector(); return distancei.magnitude() < distancej.magnitude(); } private: itk::Point< double, 3 > const & m_ReferencePoint; }
package faqs import ( "time" ) type FaqDocument struct { Id int64 `json:"id"` UniqHash string `json:"uniq_hash"` Question string `json:"question"` Answer string `json:"answer"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } type FaqDocuments []FaqDocument func NewDocFromFaq(faq *Faq) *FaqDocument { return &FaqDocument{ Id: faq.Id, UniqHash: faq.UniqHash, Question: faq.Question, Answer: faq.Answer, CreatedAt: faq.CreatedAt, UpdatedAt: faq.UpdatedAt, } }
// Encontrar todos los switches de acceso public List<DatapathId> accessSwitches(SwitchPort[] ap) { List<DatapathId> switches = new ArrayList<DatapathId>(); for (DatapathId switchId : switchService.getAllSwitchDpids()) { IOFSwitch sw = switchService.getSwitch(switchId); for (OFPortDesc port : sw.getPorts()) { OFPort portId = port.getPortNo(); if (switchId.equals(ap[0].getSwitchDPID()) && (portId.getShortPortNumber() == ap[0].getPort() .getShortPortNumber())) { continue; } if (topologyManager.isAttachmentPointPort(switchId, port.getPortNo())) { switches.add(sw.getId()); break; } } } return switches; }
//------------------------------------------------------------- // Procedure: getEntryCount // Note: Return the number of entries contained in given partition unsigned int PartitionRecord::getEntryCount(unsigned int ix) const { if(ix < m_partition_entry_cnt.size()) return(m_partition_entry_cnt[ix]); return(0); }
PORTLAND, Maine — Houlton’s municipal electric utility on Tuesday received final approval to disconnect from the northern Maine power grid and connect directly with Canadian lines. Houlton Water Co. is in the final stages of securing a $5.4 million loan to fund about 11 miles of new power lines connecting it directly to the electric grid maintained by New Brunswick Power, which it expects to complete by the end of 2019. The Maine Public Utilities Commission on Tuesday gave final approval to the terms of the loan and a 10-year service agreement with the Canadian utility, which Houlton Water said would save the average residential customer about $54 in the first year after becoming a direct transmission customer of the New Brunswick system. The company argued during the case that the rest of the grid stands to benefit, too, but Emera Maine said losing Houlton Water as a transmission customer will raise its costs and increase the average customer’s annual bill by about $13.21 in the first year. Regulators found the eventual impacts on rates for both utilities are “not trivial” but that rate impacts alone were not enough to approve or deny the proposal. Houlton Water serves approximately 5,000 customers in Houlton and the surrounding communities of New Limerick, Linneus, Hodgdon and Ludlow. Houlton Water argued its departure would let its customers avoid paying for expected costly upgrades on Emera’s northern Maine system and also remove the need for Emera to make upgrades to serve load to Houlton.” “With HWC leaving the Emera Maine transmission system, there will be additional benefits to the customers remaining on the northern Maine transmission system,” the company said in a prepared statement. “Those include additional transfer capability between Emera Maine and [New Brunswick Power] and avoided costs from transmission upgrades that would otherwise be necessary if HWC remained a customer of Emera.” Regulators ultimately decided those avoided costs made the difference in finding the deal in the public interest, in a ruling issued in December. They estimated that losing Houlton Water as a customer would remove Emera’s need to spend up to $20 million to upgrade transmission infrastructure serving Houlton, which it wrote is “nearing the end of its useful life.” Instead, the utility estimates it will contribute at least $5.4 million to construction of a power line 1.5-mile line from its current system to the Canadian border at Woodstock, where it would connect with a new 9.3-mile New Brunswick Power line. The avoided upgrade costs to Emera’s system, they wrote, ” tips the balance” in favor of the proposal. The state’s consumer advocate opposed the deal, arguing that the company didn’t prove the arrangement would have a public benefit, including for the rest of Emera’s customers. The Office of the Public Advocate and Emera argued Houlton water overstated projected savings. The company countered that Emera’s estimates of the costs to its customers were based on ” flawed analysis.” With their approval, regulators in December wrote they remained concerned that terms with New Brunswick Power were not clearly for more than one year. The company on Jan. 27 filed updated agreement terms, effective Feb. 1, that specify the deal will end Jan. 31, 2027. PUC members said Tuesday the updated terms satisfied those concerns. They also gave clearance for the company to hold proceeds from its loan in a Key Bank account, because lender Machias Savings does not allow depositors to hold Canadian currency.
A Geometric Hamilton-Jacobi Theory for Classical Field Theories In this paper we extend the geometric formalism of the Hamilton-Jacobi theory for hamiltonian mechanics to the case of classical field theories in the framework of multisymplectic geometry and Ehresmann connections. Introduction The standard formulation of the Hamilton-Jacobi problem is to find a function S(t, q A ) (called the principal function) such that If we put S(t, q A ) = W (q A ) − tE, where E is a constant, then W satisfies H(q A , ∂W ∂q A ) = E; (1.2) W is called the characteristic function. There are some recent attempts to extend this theory for classical field theories in the framework of the so-called multisymplectic formalism . For a classical field theory the hamiltonian is a function H = H(x µ , y i , p µ i ), where (x µ ) are coordinates in the space-time, (y i ) represent the field coordinates, and (p µ i ) are the conjugate momenta. In this context, the Hamilton-Jacobi equation is ∂S µ ∂x µ + H(x ν , y i , where S µ = S µ (x ν , y j ). In this paper we introduce a geometric version for the Hamilton-Jacobi theory based in two facts: (1) the recent geometric description for Hamiltonian mechanics developed in (see for the case of nonholonomic mechanics); (2) the multisymplectic formalism for classical field theories in terms of Ehresmann connections . We shall also adopt the convention that a repeated index implies summation over the range of the index. A geometric Hamilton-Jacobi theory for Hamiltonian mechanics First of all, we give a geometric version of the standard Hamilton-Jacobi theory which will be useful in the sequel. Let Q be the configuration manifold, and T * Q its cotangent bundle equipped with the canonical symplectic form Let H : T * Q −→ R a hamiltonian function and X H the corresponding hamiltonian vector field: The integral curves of X H , (q A (t), p A (t)), satisfy the Hamilton equations: To go further in this analysis, define a vector field on Q: X λ H = T π Q • X H • λ as we can see in the following diagram: (i)' If σ : I → Q is an integral curve of X λ H , then λ•σ is an integral curve of X H ; (i)" X H and X λ H are λ-related, i.e. T λ(X λ H ) = X H • λ so that the above theorem can be stated as follows: Theorem 2.2 (Hamilton-Jacobi Theorem). Let λ be a closed 1-form on Q. Then, the following conditions are equivalent: 3. The multisymplectic formalism 3.1. Multisymplectic bundles. The configuration manifold in Mechanics is substituted by a fibred manifold We can choose fibred coordinates (x µ , y i ) such that We will use the following useful notations: Denote by V π = ker T π the vertical bundle of π, that is, their elements are the tangent vectors to E which are π-vertical. Denote by Π : Λ n E −→ E the vector bundle of n-forms on E. The total space Λ n E is equipped with a canonical n-form Θ: is called the canonical multisymplectic form on Λ n E. Denote by Λ n r E the bundle of r-semibasic n-forms on E, say Λ n r E = {α ∈ Λ n E | i v 1 ∧···∧vr α = 0, whenever v 1 , . . . , v r are π-vertical} Since Λ n r E is a submanifold of Λ n E it is equipped with a multisymplectic form Ω r , which is just the restriction of Ω. Two bundles of semibasic forms play an special role: Λ n 1 E and Λ n 2 E. The elements of these spaces have the following local expressions: we can obtain the quotient vector space denoted by J 1 π * which completes the following exact sequence of vector bundles: We denote by π 1,0 : J 1 π * −→ E and π 1 : J 1 π * −→ M the induced fibrations. Ehresmann Connections in the fibration A connection (in the sense of Ehresmann) in π 1 is a horizontal subbundle H which is complementary to V π 1 ; namely, where V π 1 = ker T π 1 is the vertical bundle of π 1 . Thus, we have: (i) there exists a (unique) horizontal lift of every tangent vector to M; (ii) in fibred coordinates (x µ , y i , p µ i ) on J 1 π * , then where H µ is the horizontal lift of ∂ ∂x µ . (iii) there is a horizontal projector h : T J * π −→ H. Hamiltonian sections. Consider a hamiltonian section where Ω 2 is the multisymplectic form on Λ n 2 E. The field equations can be written as follows: where h denotes the horizontal projection of an Ehresmann connection in the fibred manifold π 1 : J 1 π * −→ M. The local expressions of Ω 2 and Ω h are: 3.4. The field equations. Next, we go back to the Equation (3.1). The horizontal subspaces are locally spanned by the local vector fields where Γ i µ and (Γ µ ) ν j are the Christoffel components of the connection. Assume that τ is an integral section of h; this means that τ : M −→ J 1 π * is a local section of the canonical projection π 1 : If τ (x µ ) = (x µ , τ i (x), τ µ i (x)) then the above conditions becomes ∂τ i ∂x µ = The Hamilton-Jacobi theory Let λ be a 2-semibasic n-form on E; in local coordinates we have Alternatively, we can see it as a section λ : E −→ Λ n 2 E, and then we have λ(x µ , y i ) = (x µ , y i , λ 0 (x, y), λ µ i (x, y)) . A direct computation shows that Therefore, dλ = 0 if and only if Using λ and h we construct an induced connection in the fibred manifold π : E −→ M by defining its horizontal projector as follows: where ǫ(X) ∈ T (µ•λ)(e) (J 1 π * ) is an arbitrary tangent vector which projects onto X. From the above definition we immediately proves that (i)h is a well-defined connection in the fibration π : E −→ M. (ii) The corresponding horizontal subspaces are locally spanned bỹ The following theorem is the main result of this paper. Before to begin with the proof, let us consider some preliminary results. We have Notice that h • µ • λ is again a 2-semibasic n-form on E. A direct computation shows that Therefore, we have the following result. Proof of the Theorem (i) ⇒ (ii) It should be remarked the meaning of (i). Assume that is an integral section ofh; then (i) states that in the above conditions, is a solution of the Hamilton equations, that is, Sinceh is a flat connection, we may consider an integral section σ of h. Suppose that σ(x µ ) = (x µ , σ i (x)). Then, we have that Assume that λ = dS, where S is a 1-semibasic (n − 1)-form, say An alternative geometric approach of the Hamilton-Jacobi theory for Classical Field Theories in a multisymplectic setting was discussed in . Time-dependent mechanics A hamiltonian time-dependent mechanical system corresponds to a classical field theory when the base is M = R. We have the following identification Λ 1 2 E = T * E and we have local coordinates (t, y i , p 0 , p i ) and (t, y i , p i ) on T * E and J 1 π * , respectively. The hamiltonian section is given by and therefore we obtain If we denote by η = dt the different pull-backs of dt to the fibred manifolds over M, we have the following result. The pair (Ω h , dt) is a cosymplectic structure on E, that is, Ω h and dt are closed forms and dt ∧ Ω n h = dt ∧ Ω h ∧ · · · ∧ Ω h is a volume form, where dimE = 2n + 1. The Reeb vector field R h of the structure (Ω h , dt) satisfies i R h Ω h = 0 , i R h dt = 1. The integral curves of R h are just the solutions of the Hamilton equations for H. The relation with the multisymplectic approach is the following: or, equivalently, A closed 1-form λ on E is locally represented by λ = λ 0 dt + λ i dy i . Using λ we obtain a vector field on E: such that the induced connection is h = (R h ) λ ⊗ dt Therefore, we have the following result.
/** * @author Adam Gibson */ public class ReshapeTests extends BaseNd4jTest { public ReshapeTests() { } public ReshapeTests(String name) { super(name); } public ReshapeTests(String name, Nd4jBackend backend) { super(name, backend); } public ReshapeTests(Nd4jBackend backend) { super(backend); } @Test public void testThreeTwoTwoTwo() { INDArray threeTwoTwo = Nd4j.linspace(1,12,12).reshape(3,2,2); INDArray sliceZero = Nd4j.create(new double[][]{{1, 7}, {4, 10}}); INDArray sliceOne = Nd4j.create(new double[][]{{2,8},{5,11}}); INDArray sliceTwo = Nd4j.create(new double[][]{{3,9},{6,12}}); INDArray[] assertions = new INDArray[] { sliceZero,sliceOne,sliceTwo }; for(int i = 0; i < threeTwoTwo.slices(); i++) { INDArray sliceI = threeTwoTwo.slice(i); assertEquals(assertions[i],sliceI); } INDArray linspaced = Nd4j.linspace(1,4,4).reshape(2,2); INDArray[] assertionsTwo = new INDArray[] { Nd4j.create(new double[]{1,3}),Nd4j.create(new double[]{2,4}) }; for(int i = 0; i < assertionsTwo.length; i++) assertEquals(linspaced.slice(i),assertionsTwo[i]); } @Test public void testColumnVectorReshape() { double delta = 1e-1; INDArray arr = Nd4j.create(1,3); INDArray reshaped = arr.reshape('f',3,1); assertArrayEquals(new int[]{3,1},reshaped.shape()); assertEquals(0.0, reshaped.getDouble(1),delta); assertEquals(0.0,reshaped.getDouble(2),delta); assumeNotNull(reshaped.toString()); } @Override public char ordering() { return 'f'; } }
<reponame>hjc851/SourceCodePlagiarismDetectionDataset public class Layouts { public synchronized void increaseForestall() { this.barred++; } public int barred = 0; public synchronized int driveSecurity() { return identification; } public synchronized int takeAbortAppendage() { return allocateTreat; } public synchronized int driveStem() { return barred; } public int identification = 0; public int allocateTreat = 0; public synchronized void reloadCounteract() { this.barred = 0; } public Layouts(int picture, int receiveNegotiations, int anti) { this.identification = picture; this.allocateTreat = receiveNegotiations; this.barred = anti; } }
def secs_for_next(cron_format: str, tz: tzinfo = None) -> float: now_ts = time.time() now = datetime.now(tz) if tz else now_ts cron_it = croniter(cron_format, start_time=now) return cron_it.get_next(float) - now_ts
The influence of the number of graphene layers on the atomic resolution images obtained from aberration-corrected high resolution transmission electron microscopy Image patterns formed by low voltage aberration-corrected high resolution transmission electron microscopy (HRTEM) of few layer graphene provide insight into the number of layers present. For odd numbers of graphene layers (three layers or more) and even numbers of graphene layers, distinctly different image patterns are produced. A sheet with step edges of between zero, one, two and three layers of graphene is fabricated using in situ electron beam sputtering at 80 kV and atomic resolution images are obtained. A correlation between the theoretically generated image simulations and the real HRTEM images is found and this enables us to distinguish between monolayer, bilayer, and trilayer graphene using image pattern recognition.
// Query the capabilities of a device int playerc_device_hascapability(playerc_device_t *device, uint32_t type, uint32_t subtype) { player_capabilities_req_t capreq; capreq.type = type; capreq.subtype = subtype; return playerc_client_request(device->client, device, PLAYER_CAPABILTIES_REQ, &capreq, NULL) >= 0 ? 1 : 0; }
def _CRsweep(A, B, Findex, Cindex, nu, thetacr, method): n = A.shape[0] z = np.zeros((n,)) e = deepcopy(B[:, 0]) e[Cindex] = 0.0 enorm = norm(e) rhok = 1 it = 0 while True: if method not in ('habituated', 'concurrent'): raise NotImplementedError('method not recognized: need habituated ' 'or concurrent') if method == 'habituated': gauss_seidel(A, e, z, iterations=1) e[Cindex] = 0.0 elif method == 'concurrent': gauss_seidel_indexed(A, e, z, indices=Findex, iterations=1) enorm_old = enorm enorm = norm(e) rhok_old = rhok rhok = enorm / enorm_old it += 1 if rhok < 0.1 * thetacr: break if ((abs(rhok - rhok_old) / rhok) < 0.1) and (it >= nu): break return rhok, e
a = input().split() b = int(a[0]) c = int(a[1]) def f(x,y): if x*y == 0 or x*y == 1: return 0 elif x < 3 and y < 3: return 1 elif x > 2: return 1 + f(x-2,y+1) else: return 1 + f(x+1,y-2) print(f(b,c))
//-------------------------------------------------------- // Constructor // Grab references to ATC and thermostat data //-------------------------------------------------------- ThermostatIntegratorFlux::ThermostatIntegratorFlux(AtomicRegulator * thermostat, int lambdaMaxIterations, const string & regulatorPrefix) : ThermostatGlcFs(thermostat,lambdaMaxIterations,regulatorPrefix), heatSource_(atc_->atomic_source(TEMPERATURE)) { lambdaSolver_ = new ThermostatSolverFlux(thermostat, lambdaMaxIterations, regulatorPrefix); }
A domain free of the zeros of the partial theta function We prove that for $q\in (0,1)$, the partial theta function $\theta (q,x):=\sum _{j=0}^{\infty}q^{j(j+1)/2}x^j$ has no zeros in the closed domain $\{ \{ |x|\leq 3\} \cap \{${\rm Re}$x\leq 0\} \cap \{ |${\rm Im}$x|\leq 3/\sqrt{2}\} \} \subset \mathbb{C}$ and no real zeros $\geq -5$. Introduction The present paper deals with analytic properties of the partial theta function It owes its name to the resemblance between the function θ(q 2 , x/q) = ∞ j=0 q j 2 x j and the Jacobi theta function Θ(q, x) := ∞ j=−∞ q j 2 x j ; "partial" refers to the fact that summation in the case of θ takes place only from 0 to ∞. We consider the situation when the variable x and the parameter q are real, more precisely, when (q, x) ∈ (0, 1) × R. This function has been studied also for (q, x) ∈ (−1, 0) × R and (q, x) ∈ D 1 × C; here D 1 stands for the open unit disk. For any fixed non-zero value of the parameter q (|q| < 1), the function θ(q, .) is an entire function in x of order 0. The partial theta function finds various applications -from Ramanujan type q-series ( ) to the theory of (mock) modular forms ( ), from asymptotic analysis ( ) to statistical physics and combinatorics ( ). How θ can be applied to problems dealing with asymptotics and modularity of partial and false theta functions and their relationship to representation theory and conformal field theory is made clear in and . The place which this function finds in Ramanujan's lost notebook is explained in and . Its Padé approximants are studied in . A recent interest in the partial theta function is connected with the study of sectionhyperbolic polynomials, i. e. real polynomials with positive coefficients, with all roots real negative and all whose finite sections (i.e. truncations) have also this property, see , and ; the cited papers use results of Hardy, Petrovitch and Hutchinson (see , and ). Various analytic properties of the partial theta function are proved in - and other papers of the author. The analytic properties of θ known up to now, in particular, the behaviour of its zeros, are discussed in the next section. One of them is the fact that for any q ∈ (0, 1), all complex conjugate pairs of zeros of θ(q, .) remain within the domain {Rex ∈ (−5792.7, 0), |Imx| < 132} ∪ {|x| < 18} . For q ∈ (−1, 0), this is true for the domain {|Rex| < 364.2, |Imx| < 132}, see and . In this sense the complex conjugate zeros of θ never go too far from the origin. It is also true that they never enter into the unit disk, see (but this property is false if q and x are complex, see the next section). In the present paper we exhibit a convex domain which contains the left unit half-disk, which is more than 7 times larger than the latter and which is free of zeros of θ for any q ∈ (0, 1): Theorem 1. For any fixed q ∈ (0, 1), the partial theta function has no zeros in the domain When only the real zeros of θ are dealt with, one can improve the above theorem: Proposition 2. For any q ∈ (0, 1) fixed, the function θ(q, .) has no real zeros ≥ −5. Before giving comments on these results in the next section we explain the structure of the paper. Section 3 reminds certain analytic properties of θ. Proposition 2 is proved in Section 4. In Section 5 we prove some lemmas which are used to prove Theorem 1; their proofs can be skipped at first reading. Section 6 contains a plan of the proof of Theorem 1. The proofs of the proposition and lemmas formulated in Section 6 can be found in Section 7. One can make the following observations with regard to Theorem 1 and Proposition 1: (1) It is not clear whether Theorem 1 should hold true for the whole of the left half-disk of radius 3, because |θ(0.71, e 0.5188451144πi )| = 0.0141 . . ., i. e. one obtains a very small value of |θ| for a point of the arc C 1 . This might mean that a zero of θ crosses the arc C 1 for q close to 0.71. (2) The difficulty to prove results as the ones of Theorem 1 and Proposition 2 resides in the fact that the rate of convergence of the series of θ decreases as q tends to 1 − , and for q = 1, one obtains as limit of θ the rational (not entire) function 1/(1 − x). It is true that the series of θ converges to the function 1/(1 − x) (which has no zeros at all) on a domain larger than the unit disk and containing the domain D, see . Yet one disposes of no concrete estimations about this convergence, so one cannot deduce from it the absence of zeros of θ in the domain D for all q ∈ (0, 1). We explain by examples why analogs of the property of the zeros of θ to avoid the domain D cannot be found in cases other than q ∈ (0, 1), x ≤ 0: (i) If q is complex, then some of the zeros of θ can be of modulus < 1. Indeed, for q = ρe 3πi/4 , where ρ ∈ (0, 1) is close to 1, the function θ has a zero close to 0.33 . . . + 0.44 . . . i whose modulus is 0.56 . . . < 1. Similar examples can be given for any q of the form ρe kπi/ℓ , k, ℓ ∈ Z * , see . It is true however that θ has no zeros for |x| ≤ 1/2|q|, see Proposition 7 in . (ii) If q ∈ (0, 1), the function θ has no positive zeros, but θ(0.98, .) is likely to have a zero close to 1.209 . . . + 0.511 . . . i (i. e. of modulus 1.312 . . .), see . Conjecture: As q → 1 − , one can find complex zeros of θ(q, .) as close to 1 as possible. One can check numerically that for q close to 0.726475, θ has a complex conjugate couple of zeros close to ±2.9083 . . . i (which by the way corroborates the idea that the statement of Theorem 1 cannot be extended to the whole of the left half-disk of radius 3). Thus a convex domain free of zeros of θ should belong to the rectangle {Rex ∈ (0, 1), |Imx| < 2.9083 . . .}. (iii) For q ∈ (−1, 0), it is true that the leftmost of the positive zeros of θ tends to 1 + as q tends to −1 + , see part (2) of Theorem 3 in . The function θ(−0.96, .) is supposed to have a couple of conjugate zeros close to the zeros z ± := 0.824 . . . ± 1.226 . . . i (of modulus 1.478 . . .) of its truncation θ • 100 (−0.96, .); when truncating, the first two skipped terms are of modulus 6.57 . . . × 10 −75 and 1.51 . . . × 10 −76 . As q → −1 + , the limit of θ equals (1 − x)/(1 + x 2 ). One can suppose that the zeros, which equal z ± for q = −0.96, tend to ±i as q → −1 + . One knows that for q ∈ (−1, 0), complex zeros do not cross the imaginary axis, see Theorem 8 in . Hence these zeros of θ should remain in the right half-plane and close to ±i. This means that it is hard to imagine a convex domain in the right half-plane much larger than the right unit half-disk and free of zeros of θ. As for the left half-plane, the truncation θ • 100 (−0.96, .) of θ(−0.96, .) has conjugate zeros 0.769 . . . ± 1.255 . . . i (of modulus 1.473 . . .) about which, as about z ± above, one can suggest that they tend to ±i as q → −1 + . This could make one think that if one wants to find a domain in the left half-plane containing the left unit half-disk and free of zeros of θ, then in this domain the modulus of the imaginary part should not be larger than 1. On the other hand θ(−0.7, .) has a zero close to w 0 := −2.69998 . . . so the width of the desired domain should be < |w 0 |. Known properties of the partial theta function In this section we remind first that the Jacobi theta function satisfies the Jacobi triple product from which we deduce the equalities It is clear that Notation 4. (1) When treating the function G we often change the variable x to X := 1/x. To distinguish the truncations of the function θ in the variable x from the ones in the variable t (see Notation 3) we write θ = θ • k + θ • * , where θ • k := k j=0 q j(j+1)/2 x j and θ • * := ∞ j=k+1 q j(j+1)/2 x j , i. e. we use the superscript "bullet" when in the variable x (no index k is added to θ • * ). No superscript is used for the truncations of θ(q, −t + wi) and of G. (2) We set Remark 5. In the proofs we use the convergence of the series (1) when the parameter q belongs to an interval of the form , a ∈ (0, 1). When we need to deal with intervals of the form , we use the equalities (3) in which the modulus of the term Θ * tends to 0 as q tends to 1 − while the series of G converges uniformly for |x| ∈ . There exists an increasing and tending to 1 − sequence of spectral valuesq j of q such that θ(q j , .) has a multiple (more exactly double) real zero, see . The 6-digit truncations of the first 6 spectral values are: When q passes fromq − j toq + j , the rightmost two of the real zeros of θ coalesce and then form a complex conjugate pair. All other real zeros of θ remain negative and distinct, see Theorem 1 in , the function θ is the product of a real polynomial of degree 2j without real zeros and a function of the class L − PI. See the details in . Spectral values exist also for q ∈ (−1, 0), see . The existence of spectral values for complex values of q is proved in , see Proposition 8 therein. Using the above notation and (4) one can write To prove the latter inequality one has to observe that the numbers q m corresponding to factors |K(q m )| from the set Σ (1/3. (see the equalities and inequalities (5) and (4)) and one concludes that ℓ 3 ≤ m 3 + 6. The factors |K(q m )| which have not been mentioned up to now are all of modulus < 1; the corresponding numbers q m belong to the intervals (0, d ′ ) and (t ′′ , u ′′ ). Thus ∞ m=1 |K(q m )| < 2 6 . At the same time This shows that |Θ * (q, −5)| < 10 −4 < 4/25 < | − G(q, −5)| from which the proposition follows. For q fixed, these quantities are decreasing in ϕ, because such is cos ϕ. Set cos ϕ := − √ 2/2, |x| := 3. The displayed formulas show that from which one deduces the last two claims of the lemma. In the proofs we need some properties of the functions M := |(1 + qx)(1 + q/x)| and M 0 := (1 − q)M . We remind that we set x = −t + wi, t ∈ , w = 3/ √ 2. Proof. It suffices to prove the claims of the lemma about the function M . One checks directly for the square of M that One verifies straightforwardly that The discriminant of the trinomial 36(qt) 2 − 149qt + 198 is negative, so this trinomial is positivevalued. For the remaining terms of P , for t ∈ (hence t 2 ≤ 9/2), one obtains −18qt 3 + 198q 2 + 36t 2 ≥ −81qt + 198q 2 + 36t 2 which is again a trinomial with negative discriminant. Thus P > 0 and M 2 − M 2 | t=0 ≤ 0 with equality only for t = 0 which proves the first claim of the lemma. To prove its second statement we consider the difference The polynomial V 2 q 2 +V 1 q+V 0 has no crfitical points for (q, t) ∈ × , there is exactly one such pair. From now on we assume that q ∈ will be subdivided in two cases: We use the fact that |θ • 4 | ≥ max(|Re(θ • 4 )|, |Im(θ • 4 )|) =: µ. Neither of the functions G R and G I has a critical point with q ∈ I 0 , so G R (resp. G I ) attains its maximal and its minimal value when one of the following conditions takes place: t = 0, t = 3, q = 0 or q = 0.5.
def randbool(n=8): return randint(0, n*n-1) % n == 0
<filename>backend/core/src/main/java/com/github/thiagogarbazza/training/springangular/core/cliente/impl/ClienteRepositoryCustom.java<gh_stars>0 package com.github.thiagogarbazza.training.springangular.core.cliente.impl; import com.github.thiagogarbazza.training.springangular.core.cliente.Cliente; import java.util.Collection; interface ClienteRepositoryCustom { Collection<Cliente> pesquisar(); }
Pep Guardiola says Manchester City are unlikely to be spending big in the January transfer window and would be happy to complete the season with the present squad. “I’m happy with what we have, I have confidence in the players,” the City manager said. “I’m not saying we won’t do anything in the window, you never know what might happen in a week or two, but at the moment we have no plans for a major signing. We can work with what we have and if we finish the season with these players that will be good.” City travel to Hull City on Boxing Day, something of a novelty for a manager used to winter breaks. “This will be my first time playing through Christmas, I haven’t been able to sleep,” Guardiola joked. “Now we have put a couple of wins together we need to try and keep the run going, though of course all the other teams in the Premier League will feel the same. This is an important stage of the season.” Leicester are struggling but Manchester City wrote the book on bad title defences | Jonathan Wilson Read more City are seven points behind Chelsea, with the manager envious of the leaders’ consistency. “There is no secret about why they are so far ahead,” he said. “If you win 11 games in a row, take 33 points from 33, that is what will happen,” he said. “They take their chances, in the right moment they are there. When they played us we did not allow them too many chances, but they took them all and won. Our problem has been not creating enough chances. We have been dominating games but have had difficulty making openings and scoring goals.” Bottom-of-the-table Hull represent a different challenge. Guardiola has been talking to some of his players about what to expect at the KC Stadium, but the coach has seen enough of lower table sides to imagine he will be in for a tough game. “What I have learned in my short time in England is that the gap between the clubs in the top half of the table and those at the bottom is not all that great. We will have to be prepared. I am not expecting an easy game.” Fernandinho is back from suspension for the visit to the east coast, Sergio Agüero completes the last match of his ban, and Pablo Zabaleta will have a late fitness test.
import * as Vector2D from "./vector-2d"; export interface ControlLine { readonly length: number; readonly angle: number; } export interface VertexProperty { readonly point: Vector2D.Unit; readonly controlLine: ControlLine; } export interface PathSegment { readonly controlPoint1: Vector2D.Unit; readonly controlPoint2: Vector2D.Unit; readonly targetPoint: Vector2D.Unit; } export interface Curve { readonly startPoint: Vector2D.Unit; readonly paths: readonly PathSegment[]; } export const createCurve = ( vertexPropertyList: readonly VertexProperty[] ): Curve => { const paths: PathSegment[] = []; const len = vertexPropertyList.length; let previousVertex = vertexPropertyList[0]; let previousControlLine = previousVertex.controlLine; for (let i = 1; i < len; i += 1) { const currentVertex = vertexPropertyList[i]; const currentControlLine = currentVertex.controlLine; paths.push({ controlPoint1: Vector2D.addPolar( previousVertex.point, 0.5 * previousControlLine.length, previousControlLine.angle ), controlPoint2: Vector2D.subtractPolar( currentVertex.point, 0.5 * currentControlLine.length, currentControlLine.angle ), targetPoint: currentVertex.point, }); previousVertex = currentVertex; previousControlLine = currentControlLine; } return { startPoint: vertexPropertyList[0].point, paths, }; };
def restart_workers_signal_callback(sender, instance, field_name, **kwargs): if settings.DEBUG: return prev = getattr(instance, "_original_{}".format(field_name)) curr = getattr(instance, "{}".format(field_name)) if field_name == "evaluation_script": instance._original_evaluation_script = curr elif field_name == "test_annotation": instance._original_test_annotation = curr if prev != curr: challenge = None if field_name == "test_annotation": challenge = instance.challenge else: challenge = instance response = restart_workers([challenge]) count, failures = response["count"], response["failures"] logger.info( "The worker service for challenge {} was restarted, as {} was changed.".format( challenge.pk, field_name ) ) if count != 1: logger.warning( "Worker(s) for challenge {} couldn't restart! Error: {}".format( challenge.id, failures[0]["message"] ) ) else: challenge_url = "https://{}/web/challenges/challenge-page/{}".format( settings.HOSTNAME, challenge.id ) challenge_manage_url = "https://{}/web/challenges/challenge-page/{}/manage".format( settings.HOSTNAME, challenge.id ) if field_name == "test_annotation": file_updated = "Test Annotation" elif field_name == "evaluation_script": file_updated = "Evaluation script" template_data = { "CHALLENGE_NAME": challenge.title, "CHALLENGE_MANAGE_URL": challenge_manage_url, "CHALLENGE_URL": challenge_url, "FILE_UPDATED": file_updated, } if challenge.image: template_data["CHALLENGE_IMAGE_URL"] = challenge.image.url template_id = settings.SENDGRID_SETTINGS.get("TEMPLATES").get( "WORKER_RESTART_EMAIL" ) emails = challenge.creator.get_all_challenge_host_email() for email in emails: send_email( sender=settings.CLOUDCV_TEAM_EMAIL, recipient=email, template_id=template_id, template_data=template_data, )
<reponame>0xen/EnteeZ #pragma once #include <EnteeZ/EntityManager.hpp> #include <EnteeZ\TemplatePair.hpp> #include <typeindex> #include <map> #include <vector> namespace enteez { class EnteeZ { public: // Create a instance of EnteeZ (Entity Component Manager) EnteeZ(); // Handle destruction of the object ~EnteeZ(); // Get the local instance of the entity manager // Entity manager is used to create and destroy entity instances EntityManager& GetEntityManager(); template<typename T, typename V> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment -> RegisterBase<PlayerMovment, Movment>(); void RegisterBase(); template<typename T, typename A, typename B, typename... bases> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment, public KeyboardHandler -> RegisterBase<PlayerMovment, Movment, KeyboardHandler>(); void RegisterBase(); // Allow entity manager access to our private members friend class EntityManager; private: template<typename T> // Get component index using x index storage map unsigned int GetIndex(std::map<std::type_index, unsigned int>& map); // Stores objects that are inherited from a component std::map<std::type_index, unsigned int> m_base_indexs; // Used to store the top level component std::map<std::type_index, unsigned int> m_component_indexs; // Stores What classes a component inherits std::map<unsigned int, std::vector<unsigned int>> m_component_bases; // Stores all the casting information required to cast void* to base class whilest retaining the top level inheritance std::map<unsigned int, std::map<unsigned int, TemplateBase*>> m_component_base_templates; // Local instance of the entity manager EntityManager m_entity_manager; }; template<typename T, typename V> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment -> RegisterBase<PlayerMovment, Movment>(); inline void EnteeZ::RegisterBase() { unsigned int component_index = GetIndex<T>(m_component_indexs); unsigned int base_index = GetIndex<V>(m_base_indexs); m_component_base_templates[component_index][base_index] = new TemplatePair<T, V>(); auto it = std::find(m_component_bases[base_index].begin(), m_component_bases[base_index].end(), component_index); if (it == m_component_bases[base_index].end()) { m_component_bases[base_index].push_back(component_index); } } template<typename T, typename A, typename B, typename... bases> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment, public KeyboardHandler -> RegisterBase<PlayerMovment, Movment, KeyboardHandler>(); inline void EnteeZ::RegisterBase() { // Extract the first component that is inherited and store it RegisterBase<T, A>(); // Call itself if there are 2+ base classes left or add if 1 left (as 'bases' will be 0 and we will be calling <T, B>) RegisterBase<T, B, bases...>(); } template<typename T> // Get component index using x index storage map inline unsigned int EnteeZ::GetIndex(std::map<std::type_index, unsigned int>& map) { auto found = map.find(std::type_index(typeid(T))); // If the component was not found if (found == map.end()) { // Add component to the map map[(std::type_index)std::type_index(typeid(T))] = (unsigned int)map.size(); return (unsigned int)map.size() - 1; } // Return the component index return found->second; } }
<gh_stars>10-100 package xyz.belvi.permissiondialog.Rationale; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import java.util.ArrayList; import xyz.belvi.permissiondialog.Permission.SmoothPermission; import static xyz.belvi.permissiondialog.Rationale.RationaleDialog.SMOOTH_PERMISSIONS; /** * Created by zone2 on 1/20/17. */ public class Rationale implements RationaleBuilder.PermissionBuild, RationaleBuilder.PermissionInit { private RationaleDialogBuilder permissionDialogBuilder; private Rationale(Activity activity) { permissionDialogBuilder = new RationaleDialogBuilder(activity); } private Rationale(Fragment fragment) { permissionDialogBuilder = new RationaleDialogBuilder(fragment); } /** * launching with a an activity * @param activity - activity to return response via onActivityResult */ public static RationaleBuilder.PermissionInit withActivity(Activity activity) { return new Rationale(activity); } /** * launching with a fragment * @param fragment - fragment to return response via onActivityResult */ public static RationaleBuilder.PermissionInit withFragment(Fragment fragment) { return new Rationale(fragment); } /** * add of permissions to run Rationale on * @param smoothPermission - list of permission * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit addSmoothPermission(SmoothPermission... smoothPermission) { permissionDialogBuilder.addSmoothPermission(smoothPermission); return this; } /** * add of permissions to run Rationale on * @param smoothPermission - arraylist of permission * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit addSmoothPermission(ArrayList<SmoothPermission> smoothPermission) { permissionDialogBuilder.addSmoothPermission(smoothPermission); return this; } /** * set request code to mark response from Rationale * @param requestCode - request code to to start Rationale and return via onActivityResult * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit requestCode(int requestCode) { permissionDialogBuilder.requestCode(requestCode); return this; } /** * style the Rationale Dialog with @styleRes * @param styleRes - styleRes id * @return PermissionBuild */ @Override public RationaleBuilder.PermissionBuild includeStyle(int styleRes) { permissionDialogBuilder.includeStyle(styleRes); return this; } /** * set list of permissions to run Rationale on * @param smoothPermission - list of permissions * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit setPermission(SmoothPermission... smoothPermission) { permissionDialogBuilder.setSmoothPermission(smoothPermission); return this; } /** * set list of permissions to run Rationale on * @param smoothPermission - arraylist of permissions * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit setPermission(ArrayList<SmoothPermission> smoothPermission) { permissionDialogBuilder.setSmoothPermission(smoothPermission); return this; } /** * * @param buildAnyway - true if the Rationale should show permissions that not not been permanently denied. */ @Override public void build(boolean buildAnyway) { permissionDialogBuilder.build(buildAnyway); } public static Bundle bundleResponse(ArrayList<SmoothPermission> smoothPermissions, boolean userDecline) { Bundle bundle = new Bundle(); bundle.putParcelable(SMOOTH_PERMISSIONS, new RationaleResponse(smoothPermissions, smoothPermissions.size() > 0 && !userDecline, userDecline)); return bundle; } public static boolean isResultFromRationale(int requestCode, int expectedCode) { return requestCode == expectedCode; } public static boolean permissionResolved(Intent intent) { return intent.getIntExtra(RationaleBase.RESULT_TYPE, -1) == RationaleDialog.PERMISSION_RESOLVE; } public static boolean noAction(Intent intent) { return intent.getIntExtra(RationaleBase.RESULT_TYPE, -1) == RationaleDialog.NO_ACTION; } public static RationaleResponse getRationaleResponse(Intent intent) { if (permissionResolved(intent) || noAction(intent)) { RationaleResponse rationaleResponse = getResponse(intent); if (rationaleResponse != null) return rationaleResponse; } return null; } private static RationaleResponse getResponse(Intent intent) { Bundle bundle = intent.getBundleExtra(RationaleBase.RESULT_DATA); if (bundle != null) { RationaleResponse rationaleResponse = bundle.getParcelable(SMOOTH_PERMISSIONS); return rationaleResponse; } return null; } }
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_LINALG_FUNCTIONS_GENERAL_SQRTM_HPP_INCLUDED #define NT2_LINALG_FUNCTIONS_GENERAL_SQRTM_HPP_INCLUDED #include <nt2/linalg/functions/sqrtm.hpp> #include <nt2/core/container/table/table.hpp> #include <nt2/include/functions/tofloat.hpp> #include <nt2/include/functions/sqrt.hpp> #include <nt2/include/functions/diag_of.hpp> #include <nt2/include/functions/from_diag.hpp> #include <nt2/include/functions/isdiagonal.hpp> #include <nt2/include/functions/schur.hpp> #include <nt2/include/functions/mtimes.hpp> #include <nt2/include/functions/globalsum.hpp> #include <nt2/include/functions/zeros.hpp> #include <nt2/include/functions/eye.hpp> #include <nt2/include/functions/length.hpp> #include <nt2/include/functions/transpose.hpp> #include <nt2/include/functions/conj.hpp> #include <nt2/include/functions/real.hpp> #include <nt2/include/functions/colvect.hpp> #include <nt2/include/functions/cast.hpp> #include <complex> namespace nt2{ namespace ext { BOOST_DISPATCH_IMPLEMENT ( sqrtm_, tag::cpu_ , (A0) , ((ast_<A0, nt2::container::domain>)) ) { typedef typename A0::value_type value_type; typedef typename A0::index_type index_type; typedef table<value_type, index_type> result_type; NT2_FUNCTOR_CALL(1) { return doit(a0, typename meta::is_complex<value_type>::type()); } private : result_type doit(const A0 & a0, boost::mpl::false_ const &) const { typedef typename std::complex<value_type> cmplx_type; typedef nt2::table<cmplx_type, nt2::_2D> ctab_t; size_t n = length(a0); ctab_t q, t, r; tie(q, t) = schur(a0, nt2::cmplx_); compute(n, t, r); ctab_t x = nt2::mtimes( nt2::mtimes(q, r), nt2::trans(nt2::conj(q))); return nt2::real(x); //bool nzeig = any(diag_of(t)(_))(1); // if nzeig // warning(message('sqrtm:SingularMatrix')) // end } result_type doit(const A0 & a0, boost::mpl::true_ const &) const { typedef nt2::table<value_type, nt2::_2D> tab_t; size_t n = length(a0); tab_t q, t, r; tie(q, t) = schur(a0, nt2::cmplx_); compute(n, t, r); return nt2::mtimes( nt2::mtimes(q, r), nt2::trans(nt2::conj(q))); //bool nzeig = any(diag_of(t)(_))(1); // if nzeig // warning(message('sqrtm:SingularMatrix')) // end } template < class S > void compute(const size_t & n, const S& t, S& r) const { typedef typename S::value_type v_type; if (nt2::isdiagonal(t)) { r = nt2::from_diag(nt2::sqrt(nt2::diag_of(t))); } else { // Compute upper triangular square root R of T, a column at a time. r = nt2::zeros(n, n, meta::as_<v_type>()); for (size_t j=1; j <= n; ++j) { r(j,j) = nt2::sqrt(t(j,j)); for (size_t i=j-1; i >= 1; --i) { //itab_ k = _(i+1, j-1); v_type s = nt2::globalsum(nt2::multiplies(colvect(r(i,_(i+1, j-1))), colvect(r(_(i+1, j-1),j)))); // value_type s = nt2::mtimes(r(i,_(i+1, j-1)), r(_(i+1, j-1),j)); r(i,j) = (t(i,j) - s)/(r(i,i) + r(j,j)); } } } } }; BOOST_DISPATCH_IMPLEMENT ( sqrtm_, tag::cpu_ , (A0) , (scalar_<fundamental_<A0> >) ) { typedef A0 result_type; NT2_FUNCTOR_CALL(1) { return nt2::sqrt(a0); } }; } } #endif
The NFLPA has released its latest cap figures for the 2017 offseason, and the Eagles have a little less money than expected According to the NFLPA, the Eagles will carry over $7.9 million in cap space from 2016 into 2017, which is slightly less than the $8.25 million they were projected to carry over. Any money not spent in the 2016 season is allowed to be moved over to the 2017 payroll, giving teams more money and cap space. Here is a complete look at the Eagles' cap situation, and how the $7.9 million in carry over in cap space from 2016 will impact 2017. Projected Cap: Somewhere between $170 to $166 million. For this article, we will use $168 million. Roll Over: According to the NFLPA, the Eagles are set to roll over $7.9 million in cap space from the 2016 season to the 2017 offseason. Dead Money: The Eagles have $6.8 million in dead money on their books -- $5.5 million from Sam Bradford, and $904,000 from Eric Rowe. 10 steps to a perfect Eagles' offseason Contracts: The Eagles currently have $158 million in committed contracts for the 2017 season. They can release players to lower that number, but as of now, they enter the offseason with $158 million committed to next season. Cap Space: Using $168 million as the NFL cap, the Eagles have around $12 million in cap space ($168 million cap - $158 million in contracts - $6.8 million in dead money + $7.9 million in carry over) Rookies: The Eagles will have to budget around $5 million for their 2017 rookie class, which comes out of the $12 million cap space. That brings the Eagles down to $7 million. Free Agents: The following players are set to become free agents: LB Stephen Tulloch, CB Nolan Carroll, OL Stefen Wisniewski, DE Bryan Braman, DL Bennie Logan, LB Najee Goode, S Jaylen Watkins, RB Kenjon Barner, TE Trey Burton Biggest Cap Hits: The top five cap hits for next season are OT Jason Peters ($11.2 million), OT Lane Johnson ($10 million), DE Fletcher Cox ($9.4 million), DE Vinny Curry ($9 million) and DE Connor Barwin ($8.3 million) Possible Cap Casualties: Jason Peters: Cutting Peters would save $9.2 million, leave $2 million in dead cap Connor Barwin: Cutting Barwin would save $7.75 million, leave $600,000 in dead cap Ryan Mathews: Cutting Mathews would save $4 million, leave $1 million in dead cap Leodis McKelvin: Cutting McKelvin would save $3 million, leave $200,000 in dead cap Darren Sproles: Cutting Sproles would save $4 million, leave $0 in dead cap Realistic space: If the Eagles do move on from Barwin, Mathews, McKelvin and Sproles, the team would add an additional $18.75 million in cap space. Outside of Sproles, the team could move on from those players even if there wasn't cap incentives. It is also very possible the team could re-do the deals of Peters to lower his cap hit. If you add the possible money gained by releasing players, plus the $7 million they already have, the Eagles could go into the 2017 offseason with around $25 million in cap space. THE NO-HUDDLE SHOW: Are we still all-in on Carson Wentz? Eliot Shorr-Parks may be reached at eshorrpa@njadvancemedia.com. Follow him on Twitter @EliotShorrParks. Find NJ.com Eagles on Facebook.
/** * Adds <i>append</i> to <i>string</i> if <i>string</i> does not end with <i>append</i>. * @param string * @param append * @return */ @NotNull public static String appendIfNotPresent(@NotNull final String string, @NotNull final String append) { Objects.requireNonNull(string, "Provided string is null"); Objects.requireNonNull(append, "Append string is null"); if (string.endsWith(append)) { return string; } else { return string + append; } }
<reponame>sasigume/manoikura interface PostJsonData { slug: string; modified_gmt: string; // パース時にnullになる acf: { fetch_on_build?: boolean | null; }; } export type { PostJsonData };
HOST-PATHOGEN INTERACTION IN INFECTIONS DUE TO STAPHYLOCOCCUS AUREUS. STAPHYLOCOCCUS AUREUS VIRULENCE FACTORS. Staphylococcus aureus (S. aureus) is a major cause of hospital-acquired (HA-SA) and community-acquired (CA-SA) infections worldwide. It is isolated from many human body sites, from animals and from foods, from the environment. Pathogenesis is caused by many virulence factors and antibiotic resistance. The host immune system tries to keep under control this pathogen, but many virulence factors produced by this under the regulatory systems control attack the immune system. The epidemiology of S. aureus is in permanent dynamic and is changing quickly. Therefore, it is necessary to monitor infections, to find new effective molecules and vaccines against this pathogen. In order to reduce this problem which affects public health as a whole, the search for new therapeutic alternatives must be associated with policies to control antibiotic use. Community-acquired and hospital-acquired infections epidemiological surveillance guided by scientific studies should be constant habits among health professionals and hospitals.
<reponame>surgelt/sptingboot-cloud-st package com.ggj.encrypt.modules.base.controller; import java.util.Date; import com.ggj.encrypt.common.exception.BizException; import com.ggj.encrypt.common.utils.DateUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * @author:gaoguangjin * @Description: * @Email:<EMAIL> * @Date 2016/4/25 13:54 */ @RestController @RequestMapping("/test") @Slf4j public class RestTemplateController extends BaseController{ @RequestMapping("{sign}/{id}") public String restTemplateClient(@PathVariable("sign") String sign,@PathVariable("id") String id) { return sign+id; } @RequestMapping("/exception/{type}") public String testException(@PathVariable("type")int type) throws Exception { if(type==1) { throw new Exception("异常"); }else{ throw new BizException("111","测试BizException"); } } // public static void main(String[] args) { // // String date= DateUtils.formatDate(new Date((System.currentTimeMillis())),"yyyy-MM-dd HH:mm:ss"); // String date= DateUtils.formatDate(new Date(1425860757000l),"yyyy-MM-dd HH:mm:ss"); // System.out.println(date); // } }
import { TestBed } from '@angular/core/testing'; import { TodosApi } from './todos.api'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { mockTodo, mockAllTodos } from '../mocks/todos.mock'; import { environment } from 'src/environments/environment'; describe('TodosApi', () => { let service: TodosApi; let httpTestingController: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [TodosApi], imports: [HttpClientTestingModule] }); }); beforeEach(() => { service = TestBed.inject(TodosApi); httpTestingController = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTestingController.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('#list', () => { it('returned Observable should match the right data', () => { const searchQuery = 'search'; service.list(searchQuery) .subscribe(todos => { expect(todos[0].title).toEqual(mockAllTodos[0].title); expect(todos[1].title).toEqual(mockAllTodos[1].title); }); const req = httpTestingController .expectOne(`${environment.apiBaseUrl}/todos?search=${searchQuery}`); expect(req.request.method).toEqual('GET'); req.flush(mockAllTodos); }); }); describe('#create', async () => { it('returned Observable should match the right data', () => { service.create(mockTodo) .subscribe(todo => { expect(todo.title).toEqual(mockTodo.title); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos`); expect(req.request.method).toEqual('POST'); req.flush(mockTodo); }); }); describe('#remove', async () => { it('returned Observable should match the right data', () => { service.remove(mockTodo.id) .subscribe(todo => { expect(todo).toEqual(mockTodo); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos/${mockTodo.id}`); expect(req.request.method).toEqual('DELETE'); req.flush(mockTodo); }); }); describe('#toggleCompleted', async () => { it('returned Observable should match the right data', () => { service.toggleCompleted(mockTodo.id, true) .subscribe(todo => { expect(todo.id).toEqual(mockTodo.id); expect(todo.isCompleted).toEqual(true); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos/${mockTodo.id}`); expect(req.request.method).toEqual('PUT'); req.flush({ ...mockTodo, isCompleted: true}); }); }); });
/** * @author Andrea Schweer schweer@waikato.ac.nz for the LCoNZ Institutional Research Repositories */ public class SolrStorageService { private static final DateFormat ISO_DATE_FORMAT; static { ISO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); ISO_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final SolrServer solr; static { String solrUrl = "http://localhost:8080/solr/altmetrics"; solr = new HttpSolrServer(solrUrl); } public static final int COMMIT_DELAY = 500; public static void addOrUpdate(ProviderMetrics providerMetrics) throws StorageException { try { SolrInputDocument solrDoc = toSolrDoc(providerMetrics); if (solrDoc != null) { solr.add(solrDoc, COMMIT_DELAY); } } catch (IOException | SolrServerException e) { throw new StorageException("Problem saving metrics", e); } } public static ProviderMetrics findByHandleAndProvider(String handle, String provider) throws StorageException { NamedList<String> queryParams = new NamedList<>(); queryParams.add("q", String.format("handle:%s AND provider:%s", wildcardOrEscape(handle), wildcardOrEscape(provider))); queryParams.add("sort", "last-updated DESC"); queryParams.add("rows", "1"); try { QueryResponse response = solr.query(SolrParams.toSolrParams(queryParams)); SolrDocumentList results = response.getResults(); for (SolrDocument result : results) { ProviderMetrics metrics = fromSolrDoc(result); if (metrics != null) { return metrics; // return first non-null result } } return null; } catch (SolrServerException e) { throw new StorageException("Could not do query", e); } } static SolrInputDocument toSolrDoc(ProviderMetrics metrics) { if (metrics == null) { return null; } SolrInputDocument doc = new SolrInputDocument(); doc.setField("provider", metrics.getProvider()); doc.setField("handle", metrics.getHandle()); doc.setField("last-updated", metrics.getLastUpdated()); doc.setField("id", metrics.getProvider() + "-" + metrics.getHandle()); for (String key : metrics.getMetrics().keySet()) { Object value = metrics.getMetrics().get(key); if (value instanceof Integer) { doc.setField(key + "_i_metric", value); } else { doc.setField(key + "_s_metric", Objects.toString(value, "")); } } return doc; } static ProviderMetrics fromSolrDoc(SolrDocument doc) { if (doc == null) { return null; } ProviderMetrics metrics = new ProviderMetrics(); metrics.setProvider(Objects.toString(doc.getFieldValue("provider"), "")); metrics.setHandle(Objects.toString(doc.getFieldValue("handle"), "")); try { metrics.setLastUpdated((Date) doc.getFieldValue("last-updated")); } catch (ClassCastException e) { // ignore } Collection<String> fieldNames = doc.getFieldNames(); for (String fieldName : fieldNames) { if (fieldName.endsWith("_i_metric")) { String key = StringUtils.removeEnd(fieldName, "_i_metric"); Integer value; try { value = (Integer) doc.getFieldValue(fieldName); metrics.putMetric(key, value); } catch (ClassCastException e) { // ignore } } else if (fieldName.endsWith("_s_metric")) { String key = StringUtils.removeEnd(fieldName, "_s_metric"); Object value = doc.getFieldValue(fieldName); metrics.putMetric(key, Objects.toString(value, "")); } } return metrics; } public static void deleteLastUpdatedBefore(Date cutOff) throws StorageException { if (cutOff == null || cutOff.before(new Date())) { throw new StorageException("Cut-off needs to be non-null date in the past, is " + cutOff); } try { solr.deleteByQuery(String.format("last-updated:[* TO %s]", ISO_DATE_FORMAT.format(cutOff))); } catch (SolrServerException | IOException e) { throw new StorageException("Could not delete older than cut-off", e); } } public static void deleteByHandleAndProvider(String handle, String provider) throws StorageException { handle = wildcardOrEscape(handle); provider = wildcardOrEscape(provider); try { solr.deleteByQuery(String.format("handle:%s AND provider:%s", handle, provider), COMMIT_DELAY); } catch (SolrServerException | IOException e) { throw new StorageException("Could not delete by handle/provider", e); } } private static String wildcardOrEscape(String string) { if (StringUtils.isBlank(string)) { string = "*"; } else { string = ClientUtils.escapeQueryChars(string); } return string; } }
// CreateUser creates a new org based on seed data in the POST body func (srv Instance) CreateUser(w http.ResponseWriter, r *http.Request) { ctx := r.Context() defer srv.ST.L.Sync() sugar := srv.ST.L.Sugar() authLevel, ok := ctx.Value(authLevelCtxKey).(int) if !ok { panic("auth missing") } if authLevel == AuthUser { http.Error(w, "auth inadequate", http.StatusForbidden) return } body, err := io.ReadAll(r.Body) if err != nil { sugar.Debugw("read body", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } var m CreateUserMsg err = json.Unmarshal(body, &m) if err != nil { http.Error(w, "malformed user create", http.StatusBadRequest) return } derived, err := security.DerivePassword(m.Password, srv.ST.Argon2Cfg) if err != nil { sugar.Debugw("derive password", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } if m.Org == srv.ST.RootOrg { http.Error(w, "malformed user args", http.StatusForbidden) return } u, err := user.New(m.DisplayName, m.Email, m.Org, derived) if err != nil { http.Error(w, "malformed user args", http.StatusBadRequest) return } if authLevel == AuthOrg { session, ok := ctx.Value(sessionCtxKey).(Session) if !ok { panic("session missing") } if session.Org.ID != m.Org { http.Error(w, "not a member of requested org", http.StatusForbidden) return } } err = u.Insert(ctx, srv.ST.Master, srv.ST.Key) if err != nil { if err == models.ErrConflict { http.Error(w, "duplicate user args", http.StatusConflict) return } sugar.Debugw("insert user", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } w.Header().Set("location", UserRoute+"/"+u.ID) w.WriteHeader(http.StatusCreated) }
MOD = 10 ** 9 + 7 MAXN = 10 ** 5 + 123 MAXK = 22 fact = [1] inv = [1] s = [[ 0 for i in range(MAXK)] for j in range(MAXK)] s[0][0] = 1 for n in range(1, MAXK): for k in range(1, n + 1): s[n][k] = (s[n - 1][k - 1] + k * s[n - 1][k]) % MOD for i in range(1, MAXN): fact.append(fact[-1] * i % MOD) inv.append(pow(fact[-1], MOD - 2, MOD)) for _ in range(int(input())): n, k = map(int, input().split()) ans = 0 for parts in range(1, min(n, k) + 1): mult = s[k][parts] cur = fact[n] * inv[n - parts] * mult ans = (ans + cur) % MOD print(ans)
/** * retourne la distance en micro-seconde de l'obstacle a droite * (retourne 0 si aucun obstacle n'a ete detecte) * @return la distance en micro-seconde */ int detecteDroite() { int counter = 0; while (!(PINA & (1 << PA2))) { } while ((PINA & (1 << PA2)) != 0) { counter++; _delay_us(DELAI); if (counter > 3600) { return 0; } } return counter; }
def load_github_owners(neo4j_session: neo4j.Session, update_tag: int, repo_owners: List[Dict]) -> None: for owner in repo_owners: ingest_owner_template = Template(""" MERGE (user:$account_type{id: {Id}}) ON CREATE SET user.firstseen = timestamp() SET user.username = {UserName}, user.lastupdated = {UpdateTag} WITH user MATCH (repo:GitHubRepository{id: {RepoId}}) MERGE (user)<-[r:OWNER]-(repo) ON CREATE SET r.firstseen = timestamp() SET r.lastupdated = {UpdateTag}""") account_type = {'User': "GitHubUser", 'Organization': "GitHubOrganization"} neo4j_session.run( ingest_owner_template.safe_substitute(account_type=account_type[owner['type']]), Id=owner['owner_id'], UserName=owner['owner'], RepoId=owner['repo_id'], UpdateTag=update_tag, )
// IsSubscriptionActivated checks if the subscription is active or not. func IsSubscriptionActivated(sub *kymaeventingv1alpha1.Subscription) bool { eventActivatedCondition := kymaeventingv1alpha1.SubscriptionCondition{Type: kymaeventingv1alpha1.EventsActivated, Status: kymaeventingv1alpha1.ConditionTrue} knSubReadyCondition := kymaeventingv1alpha1.SubscriptionCondition{Type: kymaeventingv1alpha1.SubscriptionReady, Status: kymaeventingv1alpha1.ConditionTrue} return sub.HasCondition(eventActivatedCondition) && sub.HasCondition(knSubReadyCondition) }
// ----------------------------------------------------------------------------------- // lossflag - return true if loss calculation required // metrics - given input(s), target(s) & model output for the batch, calculate metrics // ----------------------------------------------------------------------------------- static bool lossflag(const Metrics& m) { for(auto k:m) if(k==Metric::loss || k==Metric::batchloss) return true; return false; }
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card