hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
e782c500fe01541a79d45d0301c8a93428835636
77
php
PHP
spec/.test/classes.php
quantaphp/array-type-check
17a233857d6d77c4143677a5a523eaa4ea7c89cc
[ "MIT" ]
null
null
null
spec/.test/classes.php
quantaphp/array-type-check
17a233857d6d77c4143677a5a523eaa4ea7c89cc
[ "MIT" ]
null
null
null
spec/.test/classes.php
quantaphp/array-type-check
17a233857d6d77c4143677a5a523eaa4ea7c89cc
[ "MIT" ]
null
null
null
<?php namespace Test; interface SomeInterface {} final class SomeClass {}
9.625
26
0.74026
a3c2f4946e0786dc428dac148f7978470659318f
35,914
java
Java
warehouse/ingest-core/src/main/java/datawave/ingest/mapreduce/handler/tokenize/ExtendedContentIndexingColumnBasedHandler.java
matthpeterson/datawave
b8758ba2d5d18f1eba0e1fad63b35bb806998955
[ "Apache-2.0" ]
null
null
null
warehouse/ingest-core/src/main/java/datawave/ingest/mapreduce/handler/tokenize/ExtendedContentIndexingColumnBasedHandler.java
matthpeterson/datawave
b8758ba2d5d18f1eba0e1fad63b35bb806998955
[ "Apache-2.0" ]
null
null
null
warehouse/ingest-core/src/main/java/datawave/ingest/mapreduce/handler/tokenize/ExtendedContentIndexingColumnBasedHandler.java
matthpeterson/datawave
b8758ba2d5d18f1eba0e1fad63b35bb806998955
[ "Apache-2.0" ]
null
null
null
package datawave.ingest.mapreduce.handler.tokenize; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.zip.GZIPOutputStream; import datawave.ingest.data.RawRecordContainer; import datawave.ingest.data.config.NormalizedContentInterface; import datawave.ingest.data.config.NormalizedFieldAndValue; import datawave.ingest.data.config.ingest.AccumuloHelper; import datawave.ingest.data.tokenize.DefaultTokenSearch; import datawave.ingest.data.tokenize.TokenSearch; import datawave.ingest.data.tokenize.TokenizationHelper; import datawave.ingest.mapreduce.ContextWrappedStatusReporter; import datawave.ingest.mapreduce.handler.DataTypeHandler; import datawave.ingest.mapreduce.handler.ExtendedDataTypeHandler; import datawave.ingest.mapreduce.handler.shard.AbstractColumnBasedHandler; import datawave.ingest.mapreduce.handler.shard.ShardedDataTypeHandler; import datawave.ingest.mapreduce.handler.shard.content.BoundedOffsetQueue; import datawave.ingest.mapreduce.handler.shard.content.BoundedOffsetQueue.OffsetList; import datawave.ingest.mapreduce.handler.shard.content.ContentIndexCounters; import datawave.ingest.mapreduce.handler.shard.content.OffsetQueue; import datawave.ingest.mapreduce.handler.shard.content.TermAndZone; import datawave.ingest.mapreduce.job.BulkIngestKey; import datawave.ingest.mapreduce.job.writer.ContextWriter; import datawave.ingest.protobuf.TermWeight; import datawave.ingest.protobuf.Uid; import datawave.util.TextUtil; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.ColumnVisibility; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.StatusReporter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.TaskInputOutputContext; import org.apache.hadoop.util.bloom.BloomFilter; import org.apache.log4j.Logger; import org.apache.lucene.analysis.util.CharArraySet; import org.infinispan.commons.util.Base64; import com.google.common.collect.Multimap; /** * <p> * Calling the process method on this DataTypeHandler creates fields representing the tokenized content for text indexing. The process method also calls the * processBulk method on the {@link ShardedDataTypeHandler} to create the expected fields for the current {@link RawRecordContainer} object. * </p> * * <p> * This class creates the following Mutations or Key/Values in addition to those created by the {@link ShardedDataTypeHandler}: <br> * <br> * <table border="1" summary=""> * <tr> * <th>Schema Type</th> * <th>Use</th> * <th>Row</th> * <th>Column Family</th> * <th>Column Qualifier</th> * <th>Value</th> * </tr> * <tr> * <td>Shard</td> * <td>Event Data</td> * <td>ShardId</td> * <td>DataType\0UID</td> * <td>TERM_ZONE\0TERM</td> * <td>NULL</td> * </tr> * <tr> * <td>Shard</td> * <td>Document content</td> * <td>ShardId</td> * <td>#ExtendedDataTypeHandler.FULL_CONTENT_COLUMN_FAMILY</td> * <td>DataType\0UID</td> * <td>Base64 encoded, GZIPed document</td> * </tr> * </table> * * <p> * The document is not placed into the RawRecordContainer object with the rest of the fields in an attempt to prevent any slow-downs when scanning over the * RawRecordContainer objects. Placing them into their own column family also allows a locality group to be set so that they will all be located within the same * RFiles and not add additional bloat to the RFiles containing the rest of the shard table. * * @param <KEYIN> * @param <KEYOUT> * @param <VALUEOUT> */ public abstract class ExtendedContentIndexingColumnBasedHandler<KEYIN,KEYOUT,VALUEOUT> extends AbstractColumnBasedHandler<KEYIN> implements ExtendedDataTypeHandler<KEYIN,KEYOUT,VALUEOUT> { /* * "Offline" mode allows for documents to be written to the context rather than directly to Accumulo. This allows content indexing to run without needing to * connect to an active Accumulo instance. */ public static final String OPT_OFFLINE = "content.ingest.documents.offline"; /* * Disabling D column output will prevent document content from being written out in the context or to accumulo. */ public static final String OPT_NO_D_COL = "content.ingest.documents.disable"; /* * base64.dcolumn allows you to turn off base64 gzipped content and store gzipped bytes. If not set, base64 encoding is on by default. */ public static final String OPT_BASE64 = "content.ingest.base64.dcolumn"; private static final Logger log = Logger.getLogger(ExtendedContentIndexingColumnBasedHandler.class); protected static final String SPACE = " "; protected ExtendedContentIngestHelper ingestHelper = null; protected ExtendedContentDataTypeHelper dataTypeHelper = null; protected ContentIndexCounters counters = null; protected OffsetQueue<Integer> tokenOffsetCache = null; protected Set<String> zones = new HashSet<>(); protected boolean eventReplaceMalformedUTF8 = false; protected String eventDataTypeName = null; protected String eventUid = null; protected byte[] shardId = null; protected boolean offlineDocProcessing = true; protected boolean disableDCol = false; protected ExecutorService docWriterService; protected BatchWriter docWriter; protected boolean tokenizerTimeWarned = false; protected boolean useBase64Encoding = true; protected Set<String> termTypeBlacklist = Collections.emptySet(); protected TokenSearch searchUtil; protected CharArraySet stopWords; protected Configuration conf; protected TokenizationHelper tokenHelper = null; @Override public void setup(TaskAttemptContext context) { super.setup(context); conf = context.getConfiguration(); tokenHelper = new TokenizationHelper(helper, conf); termTypeBlacklist = new HashSet<>(Arrays.asList(tokenHelper.getTermTypeBlacklist())); counters = new ContentIndexCounters(); offlineDocProcessing = conf.getBoolean(OPT_OFFLINE, true); useBase64Encoding = conf.getBoolean(OPT_BASE64, true); disableDCol = conf.getBoolean(OPT_NO_D_COL, false); if (disableDCol) { // set this to true so we don't spin up a thread we don't need... offlineDocProcessing = true; log.info("D Column content storage disabled."); } if (!offlineDocProcessing) { docWriterService = Executors.newSingleThreadExecutor(); try { AccumuloHelper accumuloHelper = new AccumuloHelper(); accumuloHelper.setup(conf); log.debug("Attempting to create Accumulo connection."); docWriter = accumuloHelper.getConnector().createBatchWriter(conf.get("shard.table.name"), new BatchWriterConfig().setMaxLatency(60, TimeUnit.SECONDS).setMaxMemory(100000000L).setMaxWriteThreads(10)); log.debug("Created connection to Accumulo for asynchronous document storage."); } catch (Exception e) { log.warn("No document payloads will be written to Accumulo.", e); // giving a stub batchwriter means I don't have a bunch of "if(writer != null)"s lying around docWriter = new BatchWriter() { @Override public void addMutation(Mutation m) {} @Override public void addMutations(Iterable<Mutation> iterable) throws MutationsRejectedException {} @Override public void flush() throws MutationsRejectedException {} @Override public void close() throws MutationsRejectedException {} }; } } // The tokens offsets queue is a bounded priority queue that will allow us to cache the // highest cardinality offsets up to a predetermined max size tokenOffsetCache = new BoundedOffsetQueue<>(tokenHelper.getTokenOffsetCacheMaxSize()); stopWords = tokenHelper.getStopWords(); // TODO: refactor explicit DefaultTokenSearch usage here and get class from config searchUtil = TokenSearch.Factory.newInstance(DefaultTokenSearch.class.getCanonicalName(), stopWords, false); tokenHelper.configureSearchUtil(searchUtil); log.info("ExtendedContentIndexingColumnBasedHandler configured."); } /** * This method will block until all of the documents have been written to Accumulo, or a timeout has been reached. * * TODO make the timeout configurable */ @Override public void close(TaskAttemptContext context) { super.close(context); if (!offlineDocProcessing) { try { log.info("Attempting to flush document writer."); this.docWriterService.shutdown(); this.docWriterService.awaitTermination(1, TimeUnit.MINUTES); this.docWriter.close(); } catch (InterruptedException | MutationsRejectedException e) { log.error("Unable to terminate document writing service!", e); } } } @Override public long process(KEYIN key, RawRecordContainer event, Multimap<String,NormalizedContentInterface> eventFields, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, ContextWriter<KEYOUT,VALUEOUT> contextWriter) throws IOException, InterruptedException { // Hold some event-specific variables to avoid re-processing this.shardId = getShardId(event); if (tokenHelper.isVerboseShardCounters()) { context.getCounter("EVENT_SHARD_ID", new String(this.shardId)).increment(1); } this.eventDataTypeName = event.getDataType().outputName(); this.eventUid = event.getId().toString(); // write the standard set of keys Multimap<BulkIngestKey,Value> keys = super.processBulk(key, event, eventFields, new ContextWrappedStatusReporter(context)); long count = keys.size(); contextWriter.write(keys, context); StatusReporter reporter = new ContextWrappedStatusReporter(context); // gc before we get into the tokenization piece keys = null; // stream the tokens to the context writer here count += tokenizeEvent(event, context, contextWriter, reporter); // return the number of records written return count; } public boolean isTokenizerTimeWarned() { return tokenizerTimeWarned; } /** * Tokenize the event, and write all of the shard, shardIndex, and shardReverseIndex keys out to the context * * @param event * @param context * @param contextWriter * @return * @throws IOException * @throws InterruptedException */ protected abstract long tokenizeEvent(RawRecordContainer event, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, ContextWriter<KEYOUT,VALUEOUT> contextWriter, StatusReporter reporter) throws IOException, InterruptedException; /** * Process a term and zone by writting all applicable keys to the context. * * @param event * @param position * @param termAndZone * @param alreadyIndexedTerms * @param context * @param contextWriter * @param reporter * @throws IOException * @throws InterruptedException */ private void processTermAndZone(RawRecordContainer event, int position, TermAndZone termAndZone, BloomFilter alreadyIndexedTerms, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, ContextWriter<KEYOUT,VALUEOUT> contextWriter, StatusReporter reporter) throws IOException, InterruptedException { // Make sure the term length is greater than the minimum allowed length if (termAndZone.term.length() < tokenHelper.getTermLengthMinimum()) { log.debug("Ignoring token of length " + termAndZone.term.length() + " because it is too short"); counters.increment(ContentIndexCounters.TOO_SHORT_COUNTER, reporter); return; } // Track all tokens (including synonyms) processed counters.increment(ContentIndexCounters.ALL_PROCESSED_COUNTER, reporter); // Normalize the term since it won't be auto-normalized through the eventFields map NormalizedFieldAndValue normFnV = new NormalizedFieldAndValue(termAndZone.zone, termAndZone.term); Set<NormalizedContentInterface> ncis = this.ingestHelper.normalize(normFnV); // nfv = (NormalizedFieldAndValue) this.ingestHelper.normalize(nfv); for (NormalizedContentInterface nci : ncis) { if (!(nci instanceof NormalizedFieldAndValue)) { log.warn("Can't handle a " + nci.getClass() + "; must be a NormalizedFieldAndValue."); } NormalizedFieldAndValue nfv = (NormalizedFieldAndValue) nci; byte[] fieldVisibility = getVisibility(event, nfv); // Build the event column key/value createShardEventColumn(event, contextWriter, context, nfv, this.shardId, fieldVisibility); // Create a index normalized variant of the term and zone for indexing purposes TermAndZone indexedTermAndZone = new TermAndZone(nfv.getIndexedFieldValue(), nfv.getIndexedFieldName()); org.apache.hadoop.util.bloom.Key alreadySeen = null; if ((alreadyIndexedTerms != null) && alreadyIndexedTerms.membershipTest(alreadySeen = new org.apache.hadoop.util.bloom.Key(indexedTermAndZone.getToken().getBytes()))) { if (log.isDebugEnabled()) { log.debug("Not creating index mutations for " + termAndZone + " as we've already created mutations for it."); } counters.increment(ContentIndexCounters.BLOOM_FILTER_EXISTS, reporter); } else if ((tokenOffsetCache != null) && tokenOffsetCache.containsKey(indexedTermAndZone)) { if (log.isDebugEnabled()) { log.debug("Not creating index mutations for " + termAndZone + " as we've already created mutations for it."); } counters.increment(ContentIndexCounters.TOKEN_OFFSET_CACHE_EXISTS, reporter); } else { // create the index createShardIndexColumns(event, contextWriter, context, nfv, this.shardId, fieldVisibility); if (alreadyIndexedTerms != null) { alreadyIndexedTerms.add(alreadySeen); counters.increment(ContentIndexCounters.BLOOM_FILTER_ADDED, reporter); } } // Now add the offset to the token offset queue, and if we overflow then output the overflow if (tokenOffsetCache != null) { OffsetList<Integer> overflow = tokenOffsetCache.addOffset(indexedTermAndZone, position); if (overflow != null) { // no need to normalize as that was already done upon insertion into the token offset cache NormalizedFieldAndValue overflowNfv = new NormalizedFieldAndValue(overflow.termAndZone.zone, overflow.termAndZone.term); byte[] overflowFieldVisibility = getVisibility(event, overflowNfv); // Build the field index key/value createTermFrequencyIndex(event, contextWriter, context, this.shardId, overflowNfv, overflow.offsets, overflowFieldVisibility, this.ingestHelper.getDeleteMode()); counters.increment(ContentIndexCounters.TOKENIZER_OFFSET_CACHE_OVERFLOWS, reporter); counters.incrementValue(ContentIndexCounters.TOKENIZER_OFFSET_CACHE_POSITIONS_OVERFLOWED, overflow.offsets.size(), reporter); } } else { createTermFrequencyIndex(event, contextWriter, context, this.shardId, nfv, Arrays.asList(position), fieldVisibility, this.ingestHelper.getDeleteMode()); } } } protected void buildAllPhrases(ArrayList<Collection<String>> terms, String zone, RawRecordContainer event, int position, BloomFilter alreadyIndexedTerms, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, ContextWriter<KEYOUT,VALUEOUT> contextWriter, StatusReporter reporter) throws IOException, InterruptedException { if (terms.size() < 2) { // An empty list has no tokens/phrases to emit and phrases of length one // were already handled return; } StringBuilder sb = new StringBuilder(); for (String term : terms.get(0)) { if (term.length() <= tokenHelper.getTermLengthMinimum()) { continue; } sb.append(term); // Need to move the position pointer back by the amount of the phrase lengths // accounting for zero-indexing completePhrase(sb, terms.subList(1, terms.size()), zone, event, position - (terms.size() - 1), alreadyIndexedTerms, context, contextWriter, reporter); sb.setLength(0); } } private void completePhrase(StringBuilder baseTerm, List<Collection<String>> terms, String zone, RawRecordContainer event, int position, BloomFilter alreadyIndexedTerms, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, ContextWriter<KEYOUT,VALUEOUT> contextWriter, StatusReporter reporter) throws IOException, InterruptedException { if (terms.isEmpty()) { return; } for (String term : terms.get(0)) { if (term == null) { continue; } boolean properLen = term.length() >= tokenHelper.getTermLengthMinimum(); // Add the current term and emit the phrase if the current term isn't empty if (properLen) { baseTerm.append(SPACE).append(term); counters.increment(ContentIndexCounters.PHRASES_PROCESSED_COUNTER, reporter); processTermAndZone(event, position, new TermAndZone(baseTerm.toString(), zone), alreadyIndexedTerms, context, contextWriter, reporter); } // If we have more terms to add to this phrase, recurse if (terms.size() > 1) { completePhrase(baseTerm, terms.subList(1, terms.size()), zone, event, position, alreadyIndexedTerms, context, contextWriter, reporter); } // Only remove the space and term if we actually added one if (properLen) { // Remove the space and the token we appended last baseTerm.setLength(baseTerm.length() - 1 - term.length()); } } } static final Pattern EMPTY_PATTERN = Pattern.compile("\\s*"); /** * Return true if this term appears to be empty (all spaces) * * @param term * @return true if term is zero or more spaces */ protected static boolean isEmptyTerm(String term) { return ((term.length() == 0) || EMPTY_PATTERN.matcher(term).matches()); } /** * Creates and writes the BulkIngestKey for the event's field/value to the ContextWriter (instead of the Multimap that the {@link ShardedDataTypeHandler} * uses). * * @param event * @param contextWriter * @param context * @param nFV * @param shardId * @param visibility * @throws IOException * @throws InterruptedException */ protected void createShardEventColumn(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, NormalizedContentInterface nFV, byte[] shardId, byte[] visibility) throws IOException, InterruptedException { String fieldName = nFV.getEventFieldName(); String fieldValue = nFV.getEventFieldValue(); if (this.ingestHelper.isIndexOnlyField(fieldName) || this.ingestHelper.isCompositeField(fieldName)) return; if (StringUtils.isEmpty(fieldValue)) return; Text colf = new Text(event.getDataType().outputName()); TextUtil.textAppend(colf, event.getId().toString(), this.eventReplaceMalformedUTF8); Text colq = new Text(fieldName); TextUtil.textAppend(colq, fieldValue, this.ingestHelper.getReplaceMalformedUTF8()); Key k = createKey(shardId, colf, colq, visibility, event.getDate(), this.ingestHelper.getDeleteMode()); BulkIngestKey bKey = new BulkIngestKey(new Text(this.getShardTableName()), k); contextWriter.write(bKey, DataTypeHandler.NULL_VALUE, context); } /** * Creates and writes the BulkIngestKey for the event's field and global indexes to the ContextWriter * * @param event * @param contextWriter * @param context * @param nFV * @param shardId * @param fieldVisibility * @throws IOException * @throws InterruptedException */ protected void createShardIndexColumns(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, NormalizedContentInterface nFV, byte[] shardId, byte[] fieldVisibility) throws IOException, InterruptedException { if (log.isDebugEnabled()) { log.debug("Creating a mutation for " + nFV.getIndexedFieldValue() + ':' + nFV.getIndexedFieldName()); } // Still need the field index record for the token createShardFieldIndexColumn(event, contextWriter, context, nFV, shardId, null, fieldVisibility, this.ingestHelper.getReplaceMalformedUTF8(), this.ingestHelper.getDeleteMode()); // If we're creating index terms if ((null != this.getShardIndexTableName()) && this.ingestHelper != null) { if (this.ingestHelper.isIndexedField(nFV.getIndexedFieldName())) { // Throw it into the index createIndexColumn(event, contextWriter, context, nFV, shardId, this.getShardIndexTableName(), fieldVisibility, this.ingestHelper.getReplaceMalformedUTF8(), this.ingestHelper.getDeleteMode()); } } // If we're creating reverse index terms if ((null != this.getShardReverseIndexTableName()) && this.ingestHelper != null) { if (this.ingestHelper.isReverseIndexedField(nFV.getIndexedFieldName())) { // Throw the reversed term into the reverse index NormalizedContentInterface reverseNfv = new NormalizedFieldAndValue(nFV); reverseNfv.setIndexedFieldValue(new StringBuilder(nFV.getIndexedFieldValue()).reverse().toString()); createIndexColumn(event, contextWriter, context, reverseNfv, shardId, this.getShardReverseIndexTableName(), fieldVisibility, this.ingestHelper.getReplaceMalformedUTF8(), this.ingestHelper.getDeleteMode()); } } } /** * Writes the document's content into the {@link #FULL_CONTENT_COLUMN_FAMILY} column family. The data is compressed (GZIP) and Base64 encoded before being * placed into the value. * * @param event * @param contextWriter * @param context * @param reporter * @param uid * @param visibility * @param shardId * @param rawValue * @throws IOException * @throws InterruptedException * @throws MutationsRejectedException */ protected void createContentRecord(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, StatusReporter reporter, Text uid, byte[] visibility, byte[] shardId, byte[] rawValue) throws IOException, InterruptedException, MutationsRejectedException { Key k = createKey(shardId, new Text(ExtendedDataTypeHandler.FULL_CONTENT_COLUMN_FAMILY), uid, visibility, event.getDate(), this.ingestHelper.getDeleteMode()); ByteArrayOutputStream baos = null; Base64.OutputStream b64os = null; GZIPOutputStream gzos = null; Value value = null; try { baos = new ByteArrayOutputStream(Math.max(rawValue.length / 2, 1024)); if (useBase64Encoding) { b64os = new Base64.OutputStream(baos, Base64.ENCODE); } gzos = new GZIPOutputStream(useBase64Encoding ? b64os : baos); gzos.write(rawValue); } finally { closeOutputStreams(gzos, b64os, baos); if (baos != null) { value = new Value(baos.toByteArray()); } gzos = null; b64os = null; baos = null; } counters.increment(ContentIndexCounters.CONTENT_RECORDS_CREATED, reporter); if (!disableDCol) { if (offlineDocProcessing) { BulkIngestKey bKey = new BulkIngestKey(new Text(this.getShardTableName()), k); contextWriter.write(bKey, value, context); } else { DocWriter dw = new DocWriter(); dw.k = k; dw.shardId = shardId; dw.visibility = visibility; dw.event = event; dw.value = value; this.docWriterService.execute(dw); } } } /** * Ensures all of the output streams are closed * * @param streams * order to attempt closing: outermost first, innermost last */ public static void closeOutputStreams(OutputStream... streams) { for (OutputStream stream : streams) { if (null != stream) { try { stream.close(); return; // if outermost one closed, then we can stop } catch (IOException e) { log.trace("Failed to close stream: " + stream.getClass().getCanonicalName(), e); } } } } /** * Used to track tokenization execution time. It's too expensive to perform a call to System.currentTimeMillis() each time we produce a new token, so spawn * a thread that increments a counter every 500ms. * <p> * The main thread will check the counter value each time it produces a new token and thus track the number of ticks that have elapsed. */ protected static class HeartBeatThread extends Thread { public static final long INTERVAL = 500; // half second resolution public static volatile int counter = 0; public static long lastRun; static { new HeartBeatThread().start(); } private HeartBeatThread() { super("HeartBeatThread"); setDaemon(true); } public void run() { while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { throw new RuntimeException(e); } // verify that we're exeuting in a timely fashion // ..if not warn. long currentRun = System.currentTimeMillis(); long delta = currentRun - lastRun; if (delta > (INTERVAL * 1.5)) { log.warn("HeartBeatThread starved for cpu, " + "should execute every " + INTERVAL + " ms, " + "latest: " + delta + " ms."); } lastRun = currentRun; counter++; } } } private class DocWriter implements Runnable { Key k; byte[] shardId; byte[] visibility; RawRecordContainer event; Value value; @Override public void run() { log.debug("Writing out a document of size " + value.get().length + " bytes."); Mutation m = new Mutation(new Text(shardId)); m.put(k.getColumnFamily(), k.getColumnQualifier(), new ColumnVisibility(visibility), event.getDate(), value); try { docWriter.addMutation(m); } catch (MutationsRejectedException e) { log.error("Could not write document payload to Accumulo!", e); } } } // Used to indicate that there was a case where the tokenizer took too // long. public static class TokenizerTimeoutException extends IOException { private static final long serialVersionUID = 2307696490675641276L; public TokenizerTimeoutException(String message) { super(message); } } /** * Creates and writes the BulkIngestKey for the field index to the ContextWriter (instead of the Multimap that the {@link ShardedDataTypeHandler} uses). * * @param event * @param contextWriter * @param context * @param nFV * @param shardId * @param value * @param visibility * @param replaceMalformedUTF8 * @param deleteMode * @throws IOException * @throws InterruptedException */ protected void createShardFieldIndexColumn(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, NormalizedContentInterface nFV, byte[] shardId, Value value, byte[] visibility, boolean replaceMalformedUTF8, boolean deleteMode) throws IOException, InterruptedException { Text colf = new Text("fi"); TextUtil.textAppend(colf, nFV.getIndexedFieldName(), replaceMalformedUTF8); Text colq = new Text(nFV.getIndexedFieldValue()); TextUtil.textAppend(colq, this.eventDataTypeName, replaceMalformedUTF8); TextUtil.textAppend(colq, this.eventUid, replaceMalformedUTF8); if (value == null) { value = DataTypeHandler.NULL_VALUE; } Key k = createKey(shardId, colf, colq, visibility, event.getDate(), deleteMode); BulkIngestKey bKey = new BulkIngestKey(new Text(this.getShardTableName()), k); contextWriter.write(bKey, value, context); } /** * Creates a Term Frequency index key in the "tf" column family. * * @param event * @param contextWriter * @param context * @param shardId * @param nfv * @param offsets * @param visibility * @param deleteMode * @throws IOException * @throws InterruptedException */ protected void createTermFrequencyIndex(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, byte[] shardId, NormalizedFieldAndValue nfv, List<Integer> offsets, byte[] visibility, boolean deleteMode) throws IOException, InterruptedException { TermWeight.Info.Builder builder = TermWeight.Info.newBuilder(); for (Integer offset : offsets) { builder.addTermOffset(offset); } Value value = new Value(builder.build().toByteArray()); StringBuilder colq = new StringBuilder(this.eventDataTypeName.length() + this.eventUid.length() + nfv.getIndexedFieldName().length() + nfv.getIndexedFieldValue().length() + 3); colq.append(this.eventDataTypeName).append('\u0000').append(this.eventUid).append('\u0000').append(nfv.getIndexedFieldValue()).append('\u0000') .append(nfv.getIndexedFieldName()); BulkIngestKey bKey = new BulkIngestKey(new Text(this.getShardTableName()), new Key(shardId, ExtendedDataTypeHandler.TERM_FREQUENCY_COLUMN_FAMILY.getBytes(), colq.toString().getBytes(), visibility, event.getDate(), deleteMode)); contextWriter.write(bKey, value, context); } /** * Creates and writes the BulkIngestKey for the global (reverse) index to the ContextWriter (instead of the Multimap that the {@link ShardedDataTypeHandler} * uses). * * @param event * @param contextWriter * @param context * @param nFV * @param shardId * @param tableName * @param visibility * @param replacedMalformedUTF8 * @param deleteMode * @throws IOException * @throws InterruptedException */ protected void createIndexColumn(RawRecordContainer event, ContextWriter<KEYOUT,VALUEOUT> contextWriter, TaskInputOutputContext<KEYIN,? extends RawRecordContainer,KEYOUT,VALUEOUT> context, NormalizedContentInterface nFV, byte[] shardId, Text tableName, byte[] visibility, boolean replacedMalformedUTF8, boolean deleteMode) throws IOException, InterruptedException { // Shard Global Index Table Structure // Row: Field Value // Colf: Field Name // Colq: Shard Id : DataType // Value: UID Text colf = new Text(nFV.getIndexedFieldName()); Text colq = new Text(shardId); TextUtil.textAppend(colq, this.eventDataTypeName, replacedMalformedUTF8); Key k = this.createIndexKey(nFV.getIndexedFieldValue().getBytes(), colf, colq, visibility, event.getDate(), deleteMode); // Create a UID object for the Value Uid.List.Builder uidBuilder = Uid.List.newBuilder(); uidBuilder.setIGNORE(false); if (!deleteMode) { uidBuilder.setCOUNT(1); uidBuilder.addUID(this.eventUid); } else { uidBuilder.setCOUNT(-1); uidBuilder.addUID(this.eventUid); } Uid.List uidList = uidBuilder.build(); Value val = new Value(uidList.toByteArray()); BulkIngestKey bKey = new BulkIngestKey(tableName, k); contextWriter.write(bKey, val, context); } }
45.403287
162
0.645459
937501f54199d51db412b4863fcc4fbdc8751f14
1,285
cs
C#
src/spa/EmployeeDashboard/EmployeeDashboard/Models/Responses/ApiOkResponse.cs
manju064/employee-dashboard
de57fb4f115626e7c2091bfc24a1ec17fa5ee389
[ "MIT" ]
1
2019-01-22T22:04:08.000Z
2019-01-22T22:04:08.000Z
src/spa/EmployeeDashboard/EmployeeDashboard/Models/Responses/ApiOkResponse.cs
manju064/employee-dashboard
de57fb4f115626e7c2091bfc24a1ec17fa5ee389
[ "MIT" ]
null
null
null
src/spa/EmployeeDashboard/EmployeeDashboard/Models/Responses/ApiOkResponse.cs
manju064/employee-dashboard
de57fb4f115626e7c2091bfc24a1ec17fa5ee389
[ "MIT" ]
null
null
null
// <copyright file="ApiOkResponse.cs" company="Manjunath Keshava"> // Manjunath Keshava Copyright (c) 2018 // </copyright> using System.Net; using EmployeeDashboard.Resource; namespace EmployeeDashboard.Models.Responses { /// <summary> /// Object for sending sucessfull message /// </summary> /// <typeparam name="T">data</typeparam> public class ApiOkResponse<T> : ApiResponse { /// <summary> /// Initializes a new instance of the <see cref="ApiOkResponse{T}"/> class. /// </summary> /// <param name="data">Generica type data</param> public ApiOkResponse(T data) : base(HttpStatusCode.OK, Global.SuccessMessage) { this.Data = data; } /// <summary> /// Initializes a new instance of the <see cref="ApiOkResponse{T}"/> class with HttpStatusCode. /// </summary> /// <param name="statusCode">HttpStatusCode</param> /// <param name="data">Generica type data</param> public ApiOkResponse(HttpStatusCode statusCode, T data) : base(statusCode, Global.SuccessMessage) { this.Data = data; } /// <summary> /// Gets Data /// </summary> public T Data { get; } } }
29.883721
103
0.584436
6b758df8f5da3847316c645bd8dcd4fe2cd37d71
417
js
JavaScript
JavaScript/M03_JavaScriptAdvanced/L06_AdvancedFunctions/Exercises/P01_SortArray.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
3
2021-04-06T21:35:50.000Z
2021-08-07T09:51:58.000Z
JavaScript/M03_JavaScriptAdvanced/L06_AdvancedFunctions/Exercises/P01_SortArray.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
JavaScript/M03_JavaScriptAdvanced/L06_AdvancedFunctions/Exercises/P01_SortArray.js
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
1
2021-12-02T13:58:21.000Z
2021-12-02T13:58:21.000Z
function sortArr(arr, sortType) { let sortFunction = { asc: function (arr) { return arr.sort((a, b) => a - b); }, desc: function (arr) { return arr.sort((a, b) => b - a); } } let func = sortFunction[sortType]; return func(arr); // modification // return sortType === 'asc' ? arr.sort((a, b) => a - b) : arr.sort((a, b) => b - a); }
20.85
89
0.467626
745e45bbfc1109f29ccea1a9762cef9e5bdfc717
20,764
css
CSS
css/style.css
Marmik198/Travellicious
17d98562ae1713b963326f4571cd3062d39bae4c
[ "MIT" ]
1
2021-12-02T14:11:43.000Z
2021-12-02T14:11:43.000Z
css/style.css
Marmik198/Travel-Website
0403ac596cb9b46bd1a027447c36e36020595e06
[ "MIT" ]
null
null
null
css/style.css
Marmik198/Travel-Website
0403ac596cb9b46bd1a027447c36e36020595e06
[ "MIT" ]
null
null
null
/*-----Basics-----*/ :root { --cyan: #00d2be; --black: #000; --white: #fff; --linkred: #eb5424; --facebook: #3b5998; --twitter: #4099ff; --googleplus: #d34836; --linkedin: #00a0dc; } body { padding: 0; margin: 0; background: var(--white); font-family: 'Open Sans', sans-serif; overflow-x: hidden; } body a { text-decoration: none; } body a:focus, a:hover { text-decoration: none; outline: none; } input[type="button"], input[type="submit"] { transition: 0.5s all; -webkit-transition: 0.5s all; } h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; font-family: 'Noto Sans', sans-serif; font-weight: normal; } p, label { margin: 0; } ul { margin: 0; padding: 0; } img { vertical-align: middle; width: 100%; } /*-----Navbar-----*/ .main-section { z-index: 999; width: 100%; position: absolute; } .banner-nav { padding: .5em; } .navbar { border-radius: 0; margin-bottom: 0; min-height: 45px; } .navbar-default { border: none; background: none; } .navbar-default .navbar-brand, .navbar-default .navbar-brand:hover, .navbar-default .navbar-brand:focus { color: var(--white); } .navbar-default .navbar-nav > li > a:hover { color: var(--cyan); } .navbar-brand { padding: 0; font-size: .8em; line-height: 40px; height: 45px; letter-spacing: 2px; } .navbar-brand p { font-family: 'Open Sans', sans-serif; display: inline-block; font-size: 2em; color: var(--cyan); vertical-align: top; font-weight: 800; } .navbar-collapse { padding: 0; } .navbar-right { margin-right: 0; width: 77%; } .navbar-nav > li > a { text-transform: uppercase; padding: 5px 15px; font-weight: 500; font-size: 15px; } .navbar-default .navbar-nav > li > a { color: var(--white); } .navbar-nav { margin: 1em 0 0; } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:hover, .navbar-default .navbar-nav > .open > a:focus { color: #212121; background: transparent; } .navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus { color: var(--white); background-color: var(--cyan); } .navbar-nav > li { margin: 0 2px; } /*--Hover Effect on Links--*/ .menu_list { position: relative; list-style: none; } .menu .menu_item { margin: 0 0.9em 0 0; } .menu .menu_link { position: relative; text-align: center; color: #b5b5b5; -webkit-transition: color 0.3s; transition: color 0.3s; } .menu .menu_link::before, .menu .menu_link::after { content: ''; position: absolute; width: 10px; height: 10px; opacity: 0; border: 2px solid var(--cyan); transition: transform 0.3s, opacity 0.3s; } .menu .menu_link::before { top: 0; left: 0; border-width: 2px 0 0 2px; -webkit-transform: translate3d(10px, 10px, 0); transform: translate3d(10px, 10px, 0); } .menu .menu_link::after { bottom: 0; right: 0; border-width: 0 2px 2px 0; -webkit-transform: translate3d(-10px, -10px, 0); transform: translate3d(-10px, -10px, 0); } .menu .menu_link:hover::before, .menu .menu_link:hover::after { opacity: 1; -webkit-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0) } /*--Social Icons in Nav--*/ .social_icons a { font-size: 1.3em; color: var(--white); margin: 1em 1.5em 0 0; display: inline-block; text-align: center; } .social_icons { float: right; } .social_icons a:hover { color: var(--cyan); -webkit-transform: scale(1.3); transform: scale(1.3); } /*-----Banner SlideShow-----*/ .banner-slider1 { background: url('../image/banner1.jpg') no-repeat 0px 0px; background-size: cover; min-height: 780px; } .banner-slider2 { background: url('../image/banner2.jpg') no-repeat 0px 0px; background-size: cover; min-height: 780px; } .banner-slider3 { background: url('../image/banner3.jpg') no-repeat 0px 0px; background-size: cover; min-height: 780px; } .banner-info { padding-top: 22em; text-align: center; color: var(--white); } .banner-info h3 { text-transform: uppercase; font-size: 4em; margin-bottom: 0.2em; text-shadow: 1px 1px 2px rgb(12, 12, 12); } .banner-info p { font-size: 1.1em; line-height: 1.9em; letter-spacing: 9px; font-weight: 600; } /*-----About-----*/ #about { padding: 5em 0; } .about h5 { text-transform: uppercase; color: var(--cyan); font-size: 20px; font-weight: 520; } .about h2.abtsubhead { text-transform: capitalize; color: var(--black); font-size: 40px; margin: 0.3em 0; } .about p { font-size: 15px; color: var(--black); line-height: 1.8em; font-weight: 300; } .abouthead { width: 35%; text-align: center; margin: 0 auto 4em; padding: 0 2em; border-left: 2px solid var(--black); border-right: 2px solid var(--black); } .aboutleft h4 { text-transform: uppercase; color: var(--cyan); font-size: 20px; margin-bottom: .5em; } .aboutleft h3, .aboutright h3 { text-transform: uppercase; color: var(--black); font-size: 25px; margin: 0 0 1em; } .aboutleft p { margin: 0 0 1em; font-size: 14.5px; } /*--Accordian--*/ .panel-default > .panel-heading { color: #eee; background-color: var(--cyan); } .panel-heading { padding: 12px 20px; border: 1px solid transparent; border-top-left-radius: 0; border-bottom-right-radius: 0; } .panel-title { color: inherit; font-size: 16px; text-transform: capitalize; margin-top: 0; margin-bottom: 0; } .panel-group { margin-bottom: 0; } .panel-body { background-color: #232323; color: var(--white); letter-spacing: 1px; line-height: 1.8em; padding: 15px; } /*--Count--*/ .count-grids { margin-top: 2em; background-color: #232323; } .count { padding: 40px; border: 1px solid #999; text-align: center; } hr.divider { background-color: var(--cyan); margin: 0 auto; width: 65px; height: 2px; border: none; } .count h5 { color: #c3c3c3; font-size: 1.2em; margin-top: 1em; text-transform: uppercase; font-weight: 400; } .numscroller { font-size: 3em; color: var(--white); font-family: 'Noto Sans', sans-serif; padding: 0.3em 0; } #stats { border-radius: 3px 3px 0 0; overflow: hidden; } /*-----Video-----*/ .center-container { background: rgba(0, 0, 0, 0.45); } .video { text-align: center; padding: 100px; } .video h3.video-head { font-size: 2.5em; color: var(--white); text-transform: capitalize; line-height: 1.5em; } .video p { color: var(--white); margin: 20px auto; width: 60%; font-size: 14px; line-height: 28px; letter-spacing: 1px; } /*-----Team-----*/ #team { padding: 5em 0; } .team h3.team-head { color: var(--black); text-transform: uppercase; text-align: center; font-size: 2.5em; margin-bottom: 1.5em; } .team-grid-left { width: 35%; padding: 0; transition: 0.5s all; -webkit-transition: 0.5s all; } .team-grid-left img.img-responsive { width: 100%; } .team-grid:hover .team-grid-left { box-shadow: 0 0 9px 1px #484848; -webkit-box-shadow: 0 0 9px 1px #484848; } .team-grid-right { width: 65%; } .team-grid-right h4 { color: var(--cyan); margin: 0; text-transform: capitalize; font-size: 1.6em; font-weight: 500; } .team-grid-right h5 { color: var(--black); text-transform: capitalize; margin: .5em 0 0; letter-spacing: 2px; font-size: 17px; } .team-grid-right p { color: var(--black); margin: 2em 0 1em; font-size: 15px; line-height: 28px; } .team-row { margin: 4em 0; } /*--Social Icons--*/ .team-social ul li { display: inline-block; text-align: center; } .team-social ul li a.fa { font-size: .9em; color: var(--white); line-height: 2.8em; width: 35px; height: 35px; transition: .5s all; -webkit-transition: .5s all; } .icon { position: relative; } .icon-border { vertical-align: top; overflow: hidden; width: 30px; height: 30px; margin: 0 4px; } .icon-border::after, .icon-border::before { display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; border-radius: 50%; content=""; } .icon-border::before { z-index: 1; transition: box-shadow .3s; } .team-social ul li a.facebook:hover { color: var(--facebook); } .team-social ul li a.twitter:hover { color: var(--twitter); } .team-social ul li a.googleplus:hover { color: var(--googleplus); } .icon-border.facebook::before { box-shadow: inset 0 0 0 48px var(--facebook); } .icon-border.facebook:hover::before { box-shadow: inset 0 0 0 2px var(--facebook); } .icon-border.twitter::before { box-shadow: inset 0 0 0 48px var(--twitter); } .icon-border.twitter:hover::before { box-shadow: inset 0 0 0 2px var(--twitter); } .icon-border.googleplus::before { box-shadow: inset 0 0 0 48px var(--googleplus); } .icon-border.googleplus:hover::before { box-shadow: inset 0 0 0 2px var(--googleplus); } /*-----Gallery-----*/ #gallery { padding: 5em 0; } .gallery h3.gallery-head { color: var(--black.); text-transform: uppercase; text-align: center; font-size: 2.5em; margin-bottom: 1.5em; } .gallery-grid { padding: .5em .5em 0; } .hinge { position: relative; display: inline-block; background-color: #232323; cursor: pointer; margin: 0; backface-visibility: hidden; transform: rotateZ(0); overflow: hidden; max-width: 100%; } .hinge > img { vertical-align: top; max-width: 100%; transform-origin: 100% 50%; } .hinge > .figure-caption { background-color: var(--cyan); color: #212121; text-align: center; padding: 4.5em; position: absolute; top: 0; bottom: 0; left: 0; right: 0; opacity: 0; z-index: 1; transform: rotateY(90deg); transform-origin: 0 50%; } .hinge > .figure-caption h4 { font-size: 2em; margin-bottom: .5em; } .hinge > .figure-caption p { color: var(--white); line-height: 2em; } .hinge, .hinge::after, .hinge::before, .hinge *, .hinge *::after, .hinge *::before { box-sizing: border-box; transition: 0.35s all ease; } .hinge { perspective: 50em; } .hinge:hover img { opacity: 0; transform: rotateY(-90deg); } .hinge:hover .figure-caption { opacity: 1; transition-delay: 0.21s; transform: rotateY(0deg); } /*-----Testimonials-----*/ #testimonials { background: url('../image/testimonial.jpg') no-repeat 0 0; background-size: cover; margin-top: 40px; height: 400px; padding: 5em 0; } .testimonials .testimonials-head { color: var(--white); margin-bottom: 1em; text-transform: uppercase; text-align: center; font-size: 2.5em; } .flexslider .slides > li { display: block; } .test-info { height: 400px; position: relative; } .flexslider .slides img { position: absolute; background: #999; width: 160px; height: 160px; border-radius: 50%; margin: 0 auto; bottom: 19%; left: 79%; } .test-grid-2 { text-align: right; margin: 0 20em 0 2em; } .test-info h4 { font-size: 30px; color: #eee; } .test-info h5 { font-size: 16px; color: #d2d2d2; text-transform: capitalize; margin-top: 10px; } .test-info p { letter-spacing: 1px; line-height: 28px; font-size: 16px; color: var(--white); margin-bottom: 20px; } /*----Blog---*/ #blog { padding: 8em 0 5em; } .blog .blog-head { color: var(--black); margin-bottom: 1.5em; text-transform: uppercase; text-align: center; font-size: 2.5em; } .blog-grids { margin-bottom: 5em; } .blog-post { position: relative; } .post-img a { min-height: 300px; display: block; } .post-img-1 a { background: url('../image/blog1.jpg') no-repeat 0 0; background-size: cover; } .post-img-2 a { background: url('../image/blog2.jpg') no-repeat 0 0; background-size: cover; } .post-img-3 a { background: url('../image/blog3.jpg') no-repeat 0 0; background-size: cover; } .post-img-4 a { background: url('../image/blog4.jpg') no-repeat 0 0; background-size: cover; } .post-info h4 { margin: 1.5em 0 .5em 0; } .post-info h4 a { color: var(--black); font-size: .9em; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; margin-top: 1em; } .post-info h4 a:hover { color: var(--linkred); } .post-info p { color: #545454; letter-spacing: .5px; margin: 1em 0; font-size: 1em; line-height: 1.9em; } .post-info ul { padding: 0; margin 0; list-style-type: none; } .post-info ul li { display: inline-block; letter-spacing: 1px; font-size: 1em; font-style: italic; color: var(--black); } .post-info ul li a { color: #999999; } .post-info ul li a:hover { color: var(--cyan); transition: .3s all; } .blog-post i.fa.fa-search-plus { position: absolute; bottom: 30%; right: 8%; border-radius: 50%; background-color: var(--cyan); color: var(--white); font-size: 20px; padding: 1em; text-align: center; } .blog-post i.fa.fa-search-plus.searchplus { position: absolute; bottom: 10%; right: 48%; } /*-----Newsletter-----*/ .newsletter { background-color: var(--cyan); text-align: center; padding: 4em 0; } .newsletter h3.news-head { color: var(--white); text-transform: uppercase; font-size: 40px; text-align: center; margin-bottom: 1em; } .subscribe { width: 75%; margin: 0 auto; } .subscribe input { display: inline-block; background: var(--white); border: 1px solid var(--white); width: 50%; color: #999999; padding: 1em; font-size: 1em; outline: none; letter-spacing: 1px; } .subscribe .subs-btn { color: var(--white); background-color: #232323; font-size: 1.2em; border: 1px solid #232323; width: 70px; height: 49px; text-align: center; text-decoration: none; transition: 0.5s all; } .subscribe .subs-btn:hover { background-color: #ccc; color: #232323; } .subscribe .subs-btn:hover i.fa.fa-paper-plane-o { transform: scale(1.3); } /*-----Contact-----*/ #contact { padding: 5em 0; } .contact h3.contact-head { color: var(--black); margin-bottom: 1.5em; text-transform: uppercase; text-align: center; font-size: 2.5em; } .form-left { padding-right: 10em; } .form-top h3, .social-form h3 { text-transform: uppercase; color: var(--black); font-size: 1.5em; margin-bottom: 1em; letter-spacing: 1px; } .form-top p { color: #333; margin-top: 1em; line-height: 1.9em; letter-spacing: .5px; font-size: 1em; } .social-form { margin-top: 3em; } .social-media ul li { list-style-type: none; display: inline-block; } .social-media a.fa { color: var(--white); font-size: 17px; width: 38px; height: 38px; line-height: 38px; text-align: center; } .social-media a.fa.fa-facebook { background: var(--facebook); } .social-media a.fa.fa-twitter { background: var(--twitter); } .social-media a.fa.fa-google-plus { background: var(--googleplus); } .social-media a.fa.fa-linkedin { background: var(--linkedin); } .social-media a.fa.fa-facebook:hover { color: var(--facebook); background-color: var(--white); border: 1px solid var(--facebook); transition: 0.3s all; } .social-media a.fa.fa-twitter:hover { color: var(--twitter); background-color: var(--white); border: 1px solid var(--twitter); transition: 0.3s all; } .social-media a.fa.fa-google-plus:hover { color: var(--googleplus); background-color: var(--white); border: 1px solid var(--googleplus); transition: 0.3s all; } .social-media a.fa.fa-linkedin:hover { color: var(--linkedin); background-color: var(--white); border: 1px solid var(--linkedin); transition: 0.3s all; } .contact-form form input, textarea { display: inline-block; border: none; outline: none; border-bottom: 1px solid var(--black); padding: 10px 15px 10px 0; font-size: 1em; color: #232323; margin-bottom: 1.5em; } .contact-form form input[type="text"] { float: left; width: 47%; } .contact-form form input[type="email"] { width: 100%; } .contact-form form textarea { margin-bottom: 1em; width: 100%; display: block; resize: none; height: 150px; } .contact-form form input[type="text"]:nth-child(1) { margin-right: 1.7em; } .contact-btn { background: var(--cyan); color: var(--white); text-transform: uppercase; letter-spacing: 1px; outline: none; padding: .5em 2em; font-size: 1em; border: 1px solid var(--cyan); transition: 0.5s all; text-decoration: none; text-align: center; } /*-----Map-----*/ .map > iframe { border: none; min-height: 300px; width: 100%; } /*Footer*/ .footer { padding: 1em 0; background: #232323; } .footer p { padding: 1em 0; text-align: center; color: #BBBBBB; margin: 0; text-transform: capitalize; font-size: 17px; line-height: 28px; letter-spacing: 1px; } .copyright a { color: #BBBBBB; } .copyright a:hover, .footer-social i.fa:hover { color: var(--cyan); transition: 1s all; } .copyright { float: left; } .footer-social { float: right; } .footer-social i.fa { font-size: 25px; padding-right: 5px; color: #BBBBBB; } /*-----Blog Modal-----*/ .modal-header { border-bottom: none; } .modal-body { background: var(--white); } .modal-body p { color: #383535; text-align: left; padding: 2em 1em 1em; margin: 0; line-height: 2em; } .modal-body p i { display: block; margin-top: 1em; color: var(--cyan); letter-spacing: 1px; font-size: 14px; } .modal-content { border-radius: 0; border: none; } button.close { font-size: 1em; color: #383535; outline: none; opacity: 1; } .modal-body h5 { font-weight: 700; margin-bottom: 1em; text-transform: uppercase; letter-spacing: 1px; text-align: center; font-size: 1.4em; color: var(--black); } /*----Move To Top Button----*/ .scrollUpButton { opacity: 1; position: fixed; bottom: 20px; right: 2%; width: 40px; height: 40px; display: none; background: url('../image/arrow.png') no-repeat 0 0; outline: none; z-index: 999; } .scrollUpButton:hover, .scrollUpButton:focus { outline: none; opacity: 0.7; transition: .75s; } /*-----Selection-----*/ ::selection { color: white; background: var(--cyan); } /*-----ScrollBar-----*/ ::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { background: transparent; } ::-webkit-scrollbar-thumb { background: #555; } ::-webkit-scrollbar-thumb:hover { background: #000; }
16.6245
63
0.556781
58b2e45ba61ccee10f346d404a990a7b9d070d87
999
css
CSS
src/assets/css/style.css
bikingbadger/bikepacking.hiltonmeyer.com
d4de6c84dfe197842b4da55f53af06413c9b0e02
[ "MIT" ]
1
2020-10-20T13:49:47.000Z
2020-10-20T13:49:47.000Z
src/assets/css/style.css
bikingbadger/bikepacking.hiltonmeyer.com
d4de6c84dfe197842b4da55f53af06413c9b0e02
[ "MIT" ]
18
2020-01-08T03:44:23.000Z
2021-07-26T03:22:32.000Z
src/assets/css/style.css
bikingbadger/bikingbadger.com
d4de6c84dfe197842b4da55f53af06413c9b0e02
[ "MIT" ]
null
null
null
:root { /* --background-body: #fff; */ /* --background: #efefef; */ /* --background-alt: #f7f7f7; */ /* --selection: #9e9e9e; */ --text-main: #293748; --text-bright: #293748; /* --text-muted: #70777f; */ /* --links: #0076d1; */ /* --focus: #0096bfab; */ /* --border: #dbdbdb; */ --code: #293748; /* --animation-duration: 0.1s; */ /* --button-hover: #ddd; */ /* --scrollbar-thumb: color-mod(var(--button-hover) lightness(-3%)); */ /* --scrollbar-thumb-hover: color-mod(var(--button-hover) lightness(-10%)); */ /* --form-placeholder: #949494; */ --form-text: #293748; /* --variable: #39a33c; */ /* --highlight: #ff0; */ /* --select-arrow: svg-load('./assets/select-arrow.svg', fill: #161f27); */ } p { max-width: min(70ch, 100%); align-self: center; } #mapid { height: 70vh; } header { display: grid; grid-template-columns: 1fr 7fr; align-items: center; justify-items: center; gap: 1rem; } nav { display: grid; grid-auto-flow: column; }
22.2
80
0.567568
cda6dd2689f1ee57bf4c6c09dcd32700c02c8df2
11,743
ps1
PowerShell
setup/steps/ingress.ps1
codedx/codedx-kubernetes
759cd1083d0fe39a84e93da93e06ee287ce0458b
[ "Apache-2.0" ]
5
2021-08-09T14:49:57.000Z
2022-03-29T17:34:02.000Z
setup/steps/ingress.ps1
codedx/codedx-kubernetes
759cd1083d0fe39a84e93da93e06ee287ce0458b
[ "Apache-2.0" ]
5
2018-12-21T17:36:42.000Z
2021-12-19T09:53:48.000Z
setup/steps/ingress.ps1
codedx/codedx-kubernetes
759cd1083d0fe39a84e93da93e06ee287ce0458b
[ "Apache-2.0" ]
3
2018-12-20T19:57:41.000Z
2022-02-09T03:08:08.000Z
'./step.ps1', '../core/common/input.ps1' | ForEach-Object { Write-Debug "'$PSCommandPath' is including file '$_'" $path = join-path $PSScriptRoot $_ if (-not (Test-Path $path)) { Write-Error "Unable to find file script dependency at $path. Please download the entire codedx-kubernetes GitHub repository and rerun the downloaded copy of this script." } . $path | out-null } class IngressKind : Step { static [string] hidden $description = @' Specify the the type of ingress you want to use. '@ static [string] hidden $nginxDescription = @' If you select the 'NGINX and Cert Manager with Let's Encrypt' option, you will install the Let's Encrypt Cert Manager. You should not run more than one copy of Cert Manager on your cluster. '@ static [string] hidden $openshiftDescription = @' The Guided Setup does not include support for creating OpenShift routes. If you plan to use routes, configure your routes after installing Code Dx. '@ IngressKind([ConfigInput] $config) : base( [IngressKind].Name, $config, 'Ingress Type', [IngressKind]::description, 'What type of ingress do you want to use?') {} [string]GetMessage() { $message = [IngressKind]::description if ($this.config.k8sProvider -eq [ProviderType]::OpenShift) { $message += [IngressKind]::openshiftDescription } else { $message += [IngressKind]::nginxDescription } return $message } [IQuestion]MakeQuestion([string] $prompt) { $choices = @( [tuple]::create('None', 'Do not configure any type of ingress (use port-forward or something else to access Code Dx)'), [tuple]::create('Load Balancer', 'Configure the Code Dx Kubernetes service as a LoadBalancer service type'), [tuple]::create('External Ingress Controller', 'Create ingress resource for use with an ingress controller you installed separately'), [tuple]::create('External NGINX Ingress Controller', 'Create ingress resource for use with an NGINX ingress controller you installed separately') ) if ($this.config.k8sProvider -ne [ProviderType]::OpenShift) { $choices += @( [tuple]::create('NGINX and Let''s Encrypt', 'Install and use NGINX with Let''s Encrypt Cert Manager'), [tuple]::create('NGINX and Let''s Encrypt (with Load Balancer IP)', 'Install and use NGINX with Let''s Encrypt Cert Manager with a specified Load Balancer IP address') ) } if ($this.config.k8sProvider -eq [ProviderType]::Eks) { $choices += [tuple]::create('AWS Classic Load Balancer with Certificate Manager', 'Use AWS Classic Load Balancer') $choices += [tuple]::create('AWS Network Load Balancer with Certificate Manager', 'Use AWS Network Load Balancer') $choices += [tuple]::create('Internal AWS Classic Load Balancer with Certificate Manager', 'Use Internal AWS Classic Load Balancer') } return new-object MultipleChoiceQuestion($prompt, $choices, -1) } [bool]HandleResponse([IQuestion] $question) { switch (([MultipleChoiceQuestion]$question).choice) { 0 { $this.config.ingressType = [IngressType]::None } 1 { $this.config.ingressType = [IngressType]::LoadBalancer } 2 { $this.config.ingressType = [IngressType]::ExternalIngressController } 3 { $this.config.ingressType = [IngressType]::ExternalNginxIngressController } 4 { $this.config.ingressType = [IngressType]::NginxLetsEncrypt } 5 { $this.config.ingressType = [IngressType]::NginxLetsEncryptWithLoadBalancerIP } 6 { $this.config.ingressType = [IngressType]::ClassicElb } 7 { $this.config.ingressType = [IngressType]::NetworkElb } 8 { $this.config.ingressType = [IngressType]::InternalClassicElb } } $this.config.skipNginxIngressControllerInstall = -not $this.config.HasNginxIngress() $this.config.skipLetsEncryptCertManagerInstall = $this.config.skipNginxIngressControllerInstall $this.config.skipIngressEnabled = $this.config.skipNginxIngressControllerInstall -and $this.config.ingressType -ne [IngressType]::ExternalIngressController -and $this.config.ingressType -ne [IngressType]::ExternalNginxIngressController $this.config.skipIngressAssumesNginx = $this.config.skipNginxIngressControllerInstall -and $this.config.ingressType -ne [IngressType]::ExternalNginxIngressController $isElb = $this.config.IsElbIngress() $this.config.ingressAnnotationsCodeDx = @{} $this.config.serviceTypeCodeDx = ($this.config.ingressType -eq [IngressType]::LoadBalancer -or $isElb) ? 'LoadBalancer' : '' if ($isElb) { $this.config.codeDxTlsServicePortNumber = 443 } return $true } [void]Reset(){ $this.config.skipNginxIngressControllerInstall = $false $this.config.skipLetsEncryptCertManagerInstall = $false $this.config.skipIngressEnabled = $false $this.config.skipIngressAssumesNginx = $false $this.config.ingressAnnotationsCodeDx = @{} $this.config.serviceTypeCodeDx = '' $this.config.codeDxTlsServicePortNumber = [ConfigInput]::codeDxTlsServicePortNumberDefault } } class NginxIngressNamespace : Step { static [string] hidden $description = @' Specify the Kubernetes namespace where Nginx components will be installed. For example, to install components in a namespace named 'nginx', enter that name here. The namespace will be created if it does not already exist. '@ NginxIngressNamespace([ConfigInput] $config) : base( [NginxIngressNamespace].Name, $config, 'NGINX Namespace', [NginxIngressNamespace]::description, 'Enter namespace') {} [bool]HandleResponse([IQuestion] $question) { $this.config.nginxIngressControllerNamespace = ([Question]$question).response return $true } [void]Reset(){ $this.config.nginxIngressControllerNamespace = 'nginx' } [bool]CanRun() { return $this.config.HasNginxIngress() } } class NginxIngressAddress : Step { static [string] hidden $description = @' Specify an existing IP address to associate with the Code Dx ingress resource. '@ NginxIngressAddress([ConfigInput] $config) : base( [NginxIngressAddress].Name, $config, 'NGINX Ingress IP Address', [NginxIngressAddress]::description, 'Enter IP address') {} [IQuestion]MakeQuestion([string] $prompt) { $question = new-object Question('Enter IP address') $question.validationExpr = '^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' return $question } [bool]HandleResponse([IQuestion] $question) { $this.config.nginxIngressControllerLoadBalancerIP = ([Question]$question).response return $true } [void]Reset(){ $this.config.nginxIngressControllerLoadBalancerIP = '' } [bool]CanRun() { return $this.config.ingressType -eq [IngressType]::NginxLetsEncryptWithLoadBalancerIP } } class LetsEncryptNamespace : Step { static [string] hidden $description = @' Specify the Kubernetes namespace where the Let's Encrypt components will be installed. For example, to install components in a namespace named 'nginx', enter that name here. The namespace will be created if it does not already exist. '@ LetsEncryptNamespace([ConfigInput] $config) : base( [LetsEncryptNamespace].Name, $config, 'Let''s Encrypt Namespace', [LetsEncryptNamespace]::description, 'Enter the Let''s Encrypt k8s namespace') {} [bool]HandleResponse([IQuestion] $question) { $this.config.letsEncryptCertManagerNamespace = ([Question]$question).response return $true } [void]Reset(){ $this.config.letsEncryptCertManagerNamespace = 'cert-manager' } [bool]CanRun() { return $this.config.HasNginxIngress() } } class LetsEncryptIssuer : Step { static [string] hidden $description = @' Specify the name of the Let's Encrypt Issuer you want to use. The setup script will create two Issuer resources, one for staging and one for production use. The staging configuration will be generated as a Issuer resource named letsencrypt-staging, and the production issuer will be named letsencrypt-prod. Use the staging version first. When everything is working correctly, run the setup again replacing the letsencrypt-staging parameter with letsencrypt-prod. '@ LetsEncryptIssuer([ConfigInput] $config) : base( [LetsEncryptIssuer].Name, $config, 'Let''s Encrypt Issuer', [LetsEncryptIssuer]::description, 'Do you want to use the staging issuer for Let''s Encrypt?') {} [IQuestion]MakeQuestion([string] $prompt) { return new-object YesNoQuestion($prompt, 'Yes, use the letsencrypt-staging issuer.', 'No, use the letsencrypt-prod issuer.', -1) } [bool]HandleResponse([IQuestion] $question) { $this.config.letsEncryptCertManagerIssuer = ([YesNoQuestion]$question).choice -eq 0 ? 'letsencrypt-staging' : 'letsencrypt-prod' return $true } [void]Reset(){ $this.config.letsEncryptCertManagerNamespace = 'letsencrypt-staging' } [bool]CanRun() { return $this.config.HasNginxIngress() } } class LetsEncryptEmail : Step { static [string] hidden $description = @' Specify an email address to associate with the Let's Encrypt registration. '@ LetsEncryptEmail([ConfigInput] $config) : base( [LetsEncryptEmail].Name, $config, 'Let''s Encrypt Email Contact', [LetsEncryptEmail]::description, 'Enter your registration email address') {} [IQuestion]MakeQuestion([string] $prompt) { return new-object EmailAddressQuestion($prompt, $false) } [bool]HandleResponse([IQuestion] $question) { $this.config.letsEncryptCertManagerRegistrationEmailAddress = ([Question]$question).response return $true } [void]Reset(){ $this.config.letsEncryptCertManagerRegistrationEmailAddress = '' } [bool]CanRun() { return $this.config.HasNginxIngress() } } class IngressCertificateArn : Step { static [string] hidden $description = @' Specify the Amazon Resource Name (ARN) for the certificate you want to use with the Code Dx EKS service. You can create a new certificate using the AWS Certificates console. '@ IngressCertificateArn([ConfigInput] $config) : base( [IngressCertificateArn].Name, $config, 'AWS Certificate ARN', [IngressCertificateArn]::description, 'Enter your certificate ARN') {} [bool]HandleResponse([IQuestion] $question) { $certArn = ([Question]$question).response $isNetworkElb = $this.config.ingressType -eq [IngressType]::NetworkElb $backendProtocol = 'http' if (-not $this.config.skipTLS) { $backendProtocol = $isNetworkElb ? 'ssl' : 'https' } $this.config.serviceAnnotationsCodeDx = @{ 'service.beta.kubernetes.io/aws-load-balancer-backend-protocol' = $backendProtocol 'service.beta.kubernetes.io/aws-load-balancer-ssl-ports' = 'https' 'service.beta.kubernetes.io/aws-load-balancer-ssl-cert' = $certArn } if ($isNetworkElb) { $this.config.serviceAnnotationsCodeDx['service.beta.kubernetes.io/aws-load-balancer-type'] = 'nlb' } if ($this.config.IsElbInternalIngress()) { $this.config.serviceAnnotationsCodeDx['service.beta.kubernetes.io/aws-load-balancer-internal'] = 'true' } return $true } [void]Reset(){ $this.config.serviceAnnotationsCodeDx = @{} } [bool]CanRun() { return $this.config.IsElbIngress() } } class DnsName : Step { static [string] hidden $description = @' Specify the DNS name to associate with the Code Dx web application. This can be the hostname in lowercase letters when running on minikube or the server name of a host you will access over the network using a DNS registration. '@ DnsName([ConfigInput] $config) : base( [DnsName].Name, $config, 'Code Dx DNS Name', [DnsName]::description, 'Enter DNS name') {} [bool]HandleResponse([IQuestion] $question) { $this.config.codeDxDnsName = ([Question]$question).response return $true } [void]Reset(){ $this.config.codeDxDnsName = '' } [bool]CanRun() { return -not $this.config.skipIngressEnabled } }
33.078873
237
0.729456
9e2ae99dccd792a92f6b43caaa553be60d562902
6,242
cs
C#
GanttChartWebLibraryDemos/Demos/Samples/CSharp/ScheduleChartView/ResourceStatus/Index.aspx.cs
DlhSoftTeam/GanttChartWebLibrary-Demos
9798786ee55be6ca05eb1e24d3d71335c653e22a
[ "MIT" ]
1
2020-06-02T19:40:55.000Z
2020-06-02T19:40:55.000Z
GanttChartWebLibraryDemos/Demos/Samples/CSharp/ScheduleChartView/ResourceStatus/Index.aspx.cs.txt
DlhSoftTeam/GanttChartWebLibrary-Demos
9798786ee55be6ca05eb1e24d3d71335c653e22a
[ "MIT" ]
null
null
null
GanttChartWebLibraryDemos/Demos/Samples/CSharp/ScheduleChartView/ResourceStatus/Index.aspx.cs.txt
DlhSoftTeam/GanttChartWebLibrary-Demos
9798786ee55be6ca05eb1e24d3d71335c653e22a
[ "MIT" ]
1
2020-10-22T19:37:06.000Z
2020-10-22T19:37:06.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DlhSoft.Web.UI.WebControls; using System.Drawing; using DlhSoft.Windows.Data; namespace Demos.Samples.CSharp.ScheduleChartView.ResourceStatus { public partial class Index : System.Web.UI.Page { private static readonly DateTime date = DateTime.Today; private static readonly int year = date.Year, month = date.Month; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var items = new List<ScheduleChartItem> { new ScheduleChartItem { Content = "Resource 1", GanttChartItems = new List<GanttChartItem> { new GanttChartItem { Content = "Resource 1: started", Start = new DateTime(year, month, 2, 8, 0, 0), Finish = new DateTime(year, month, 8, 16, 0, 0), BarCssClass = "startedStatusBar" }, new GanttChartItem { Content = "Resource 1: maintenance", Start = new DateTime(year, month, 9, 8, 0, 0), Finish = new DateTime(year, month, 9, 16, 0, 0), BarCssClass = "maintenanceStatusBar" }, new GanttChartItem { Content = "Resource 1: started", Start = new DateTime(year, month, 10, 8, 0, 0), Finish = new DateTime(year, month, 13, 16, 0, 0), BarCssClass = "startedStatusBar" }, new GanttChartItem { Content = "Resource 1: issues", Start = new DateTime(year, month, 14, 8, 0, 0), Finish = new DateTime(year, month, 14, 16, 0, 0), BarCssClass = "issuesStatusBar" }, new GanttChartItem { Content = "Resource 1: maintenance", Start = new DateTime(year, month, 15, 8, 0, 0), Finish = new DateTime(year, month, 15, 16, 0, 0), BarCssClass = "maintenanceStatusBar" }, new GanttChartItem { Content = "Resource 1: started", Start = new DateTime(year, month, 16, 8, 0, 0), Finish = new DateTime(year, month, 22, 16, 0, 0), BarCssClass = "startedStatusBar" } } }, new ScheduleChartItem { Content = "Resource 2", GanttChartItems = new List<GanttChartItem> { new GanttChartItem { Content = "Resource 2: started", Start = new DateTime(year, month, 2, 8, 0, 0), Finish = new DateTime(year, month, 8, 16, 0, 0), BarCssClass = "startedStatusBar" }, new GanttChartItem { Content = "Resource 2: issues", Start = new DateTime(year, month, 9, 8, 0, 0), Finish = new DateTime(year, month, 12, 16, 0, 0), BarCssClass = "issuesStatusBar" }, new GanttChartItem { Content = "Resource 2: maintenance", Start = new DateTime(year, month, 13, 8, 0, 0), Finish = new DateTime(year, month, 14, 16, 0, 0), BarCssClass = "maintenanceStatusBar" }, new GanttChartItem { Content = "Resource 2: started", Start = new DateTime(year, month, 15, 8, 0, 0), Finish = new DateTime(year, month, 22, 16, 0, 0), BarCssClass = "startedStatusBar" } } }, new ScheduleChartItem { Content = "Resource 3", GanttChartItems = new List<GanttChartItem> { new GanttChartItem { Content = "Resource 3: started", Start = new DateTime(year, month, 2, 8, 0, 0), Finish = new DateTime(year, month, 22, 16, 0, 0), BarCssClass = "startedStatusBar" } } } }; for (int i = 4; i <= 16; i++) { items.Add(new ScheduleChartItem { Content = "Resource " + i, GanttChartItems = new List<GanttChartItem> { new GanttChartItem { Content = "Resource " + i + ": started", Start = new DateTime(year, month, 2, 8, 0, 0), Finish = new DateTime(year, month, 5, 16, 0, 0), BarCssClass = "startedStatusBar" }, new GanttChartItem { Content = "Resource " + i + ": issues", Start = new DateTime(year, month, 6, 8, 0, 0), Finish = new DateTime(year, month, 6, 16, 0, 0), BarCssClass = "issuesStatusBar" }, new GanttChartItem { Content = "Resource " + i + ": maintenance", Start = new DateTime(year, month, 7, 8, 0, 0), Finish = new DateTime(year, month, 7, 16, 0, 0), BarCssClass = "maintenanceStatusBar" }, new GanttChartItem { Content = "Resource " + i + ": started", Start = new DateTime(year, month, 8, 8, 0, 0), Finish = new DateTime(year, month, 15, 16, 0, 0), BarCssClass = "startedStatusBar" }, new GanttChartItem { Content = "Resource " + i + ": issues", Start = new DateTime(year, month, 16, 8, 0, 0), Finish = new DateTime(year, month, 16, 16, 0, 0), BarCssClass = "issuesStatusBar" }, new GanttChartItem { Content = "Resource " + i + ": started", Start = new DateTime(year, month, 17, 8, 0, 0), Finish = new DateTime(year, month, 22, 16, 0, 0), BarCssClass = "startedStatusBar" } } }); } ScheduleChartView.Items = items; ScheduleChartView.DisplayedTime = new DateTime(year, month, 1); ScheduleChartView.CurrentTime = new DateTime(year, month, 2, 12, 0, 0); ScheduleChartView.IsReadOnly = true; ScheduleChartView.IsTaskCompletedEffortVisible = false; ScheduleChartView.WorkingWeekStart = DayOfWeek.Sunday; ScheduleChartView.WorkingWeekFinish = DayOfWeek.Saturday; // Optionally, initialize custom themes (themes.js). ScheduleChartView.InitializingClientCode = @"initializeScheduleChartTheme(control.settings, theme);"; } } } }
70.134831
229
0.546139
cc80400f3cf3a902ab41a3ee51066a521b31ce63
37
rb
Ruby
app/helpers/projects_tools_helper.rb
jeanettepayne/lettering-project-tracker
df773820c605c90381ea50b37d489ae7bd230029
[ "MIT" ]
2
2021-01-26T23:30:58.000Z
2021-03-07T21:08:53.000Z
app/helpers/projects_tools_helper.rb
jeanettepayne/lettering-project-tracker
df773820c605c90381ea50b37d489ae7bd230029
[ "MIT" ]
null
null
null
app/helpers/projects_tools_helper.rb
jeanettepayne/lettering-project-tracker
df773820c605c90381ea50b37d489ae7bd230029
[ "MIT" ]
1
2021-03-02T14:54:56.000Z
2021-03-02T14:54:56.000Z
module ProjectsToolsHelper end
7.4
26
0.756757
23a989d76985e7b482721835cda6a02c4edc3867
2,328
js
JavaScript
index.js
Knightron1/Week-7
61ecbbe956774e6c7d8ca65bcdaa71a1d1ec93e2
[ "MIT" ]
null
null
null
index.js
Knightron1/Week-7
61ecbbe956774e6c7d8ca65bcdaa71a1d1ec93e2
[ "MIT" ]
null
null
null
index.js
Knightron1/Week-7
61ecbbe956774e6c7d8ca65bcdaa71a1d1ec93e2
[ "MIT" ]
null
null
null
function addTwoNumbers(x, y) { return x+y } console.log(addTwoNumbers(44, 29)); const add = function(a, b){ return a+b } // This is another way of declaring a function in javascript console.log(add(12, 14)) // Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. function myFunc(){ anotherFunc() function anotherFunc(){ return console.log("hello") } } console.log(myFunc()) var arr = [1, 2, 3, 4, 5] console.log(arr) console.log(arr[4]) arr[3] = "x" arr console.log(arr.length) // This is a method to determine the length of the array const arr1 = ['name', 'lastName', 'DOB', 'Gender'] console.log(arr1.length) console.log(1 in arr) // This checks whether or not there is a value in that position in the array console.log(6 in arr) var exampleArray = [] exampleArray.test = 111 exampleArray.test1 = 222 console.log(exampleArray); console.log(arr.slice(1,4)) // slice takes a segment of the array from position (x) to position (y) console.log(arr.slice(0,3)) console.log(arr.pop()) // pop takes the last value of an array and seperates it from the array console.log(arr) console.log(arr.push(12)) // push adds a value to the end of the array console.log(arr) console.log(arr.concat(exampleArray.test, exampleArray.test1)) // concat (short for concatenate) can be used to merge multiple arrays arr.forEach(arr => console.log(arr)) // This prints each value of the array on a seperate line in output const firstValue = arr.shift() // This removes the first value of an array and stores it as the constant 'firstValue' console.log(firstValue) console.log(arr) console.log(arr.unshift(1)) // unshift will add the value in the brackets to the start of the array console.log(arr) console.log(arr.reverse()) // .reverse does as implied and reverses the called array console.log(arr) console.log(arr.reverse()) // var RRR = arr.reverse() // console.log(RRR); console.log(arr.join('-')) // join will return the values of the array with the value in the brackets (-) in between console.log(arr.join()) // without a value in the brackets it will return the values with commas in between const newArr = arr.map(num => num*4) console.log(newArr) var arr2 = [2,4,6,8] console.log(arr2.reduce(x => x+1))
24.25
138
0.719072
4e4a89fdaf9d4c0182473d5646e42fc669b17c3e
187
dart
Dart
security_repository/lib/src/security/user_permission_set.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
security_repository/lib/src/security/user_permission_set.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
security_repository/lib/src/security/user_permission_set.dart
kevmoo/dart_framework
e8a6fcedb7596f706c0abcdd72d016d864235298
[ "MIT" ]
null
null
null
class UserPermissionSet { final List<String> permissions; final bool isAdministrator; UserPermissionSet({ required this.permissions, required this.isAdministrator, }); }
18.7
34
0.743316
1a98a9cfc6c4bae0cb2914f737a3e593898e57fa
25
py
Python
python/testData/quickFixes/PyRenameElementQuickFixTest/renameAwaitClassInPy36_after.py
fduminy/intellij-community
fe13dc9ddb7f0f65397325ded25ecb239675eb59
[ "Apache-2.0" ]
2
2018-12-29T09:53:39.000Z
2018-12-29T09:53:42.000Z
python/testData/quickFixes/PyRenameElementQuickFixTest/renameAwaitClassInPy36_after.py
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
null
null
null
python/testData/quickFixes/PyRenameElementQuickFixTest/renameAwaitClassInPy36_after.py
tnorbye/intellij-community
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
[ "Apache-2.0" ]
1
2022-01-02T19:58:08.000Z
2022-01-02T19:58:08.000Z
class a(object): pass
12.5
16
0.64
8c1dae0d5996846ea6c3698bd35703d9d9fcc4c0
386
cs
C#
teaching-c/teaching-c/AbstractSyntaxTree/Character.cs
FayzSa/teaching-c
06505a8eabb4ff670c3dca1a464211da7560fddc
[ "MIT" ]
3
2019-11-16T11:56:22.000Z
2022-03-23T11:18:41.000Z
teaching-c/teaching-c/AbstractSyntaxTree/Character.cs
FayzSa/teaching-c
06505a8eabb4ff670c3dca1a464211da7560fddc
[ "MIT" ]
null
null
null
teaching-c/teaching-c/AbstractSyntaxTree/Character.cs
FayzSa/teaching-c
06505a8eabb4ff670c3dca1a464211da7560fddc
[ "MIT" ]
1
2019-11-16T11:56:18.000Z
2019-11-16T11:56:18.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace teaching_c.AbstractSyntaxTree { class Character : AbstractSyntaxTree { public object Value { get; set; } public Character(Token Token) { this.Token = Token; this.Value = Token.Value; } } }
19.3
41
0.634715
d4115759b959436aad9cec6b1ad256874002207e
10,734
cc
C++
src/conv_common.cc
TUD-UCB-Boda/tud_boda
aa52c85aa0af1110f6f1f5a50c71bb37994b332a
[ "BSD-2-Clause" ]
62
2015-03-19T09:55:50.000Z
2022-02-27T19:06:52.000Z
src/conv_common.cc
moskewcz/boda
27ec86e03ad004ad8beac7f7d74a5b0ef7676ef6
[ "BSD-2-Clause" ]
31
2015-12-02T23:36:06.000Z
2019-04-17T20:11:28.000Z
src/conv_common.cc
TUD-UCB-Boda/tud_boda
aa52c85aa0af1110f6f1f5a50c71bb37994b332a
[ "BSD-2-Clause" ]
24
2015-05-20T14:33:15.000Z
2021-04-25T01:08:36.000Z
// Copyright (c) 2013-2014, Matthew W. Moskewicz <moskewcz@alumni.princeton.edu>; part of Boda framework; see LICENSE #include"boda_tu_base.H" #include"conv_common.H" #include"str_util.H" namespace boda { // conversion functions for image<-->feature space // handle scales / placements // valid: any returned output is computed using *only* values in the input value. that is, the // full support region of all returned outputs are fully contained in the input region. // any_valid: the returned output consists of all outputs that using *any* of the input values (but may // also use padding or even garbage when the padding is anti-convervative ) // core_valid: like 'valid', but only requires that a central core region of each returned // output's support region be contained in the input region. thus, it returns a larger area than // the 'valid' mode. the size of the core region is equal to the support stride of the output, // such that the core regions of the output tile to cover the input without overlaps or gaps. // note: in core_valid mode, if there is an odd/even mismatch between the support stride and the // support size (per dim) then the boundaries of the core region will not align to the input // grid. in this case, the core is shifted by +.5 pixels (per dim) to align to the input grid. // note: in the case where the stride=1, and the support size is odd, and there is sufficient // effective total support padding, then 'core_valid' mode yields an output area equal to the // input area, like the 'same' mode of matlab's 2D convolution. if the support size is even, the // shifting of the core as above should match the arbitrary choice of matlab's 'same' mode to // still return an output of the same size as the input by favoring keeping - outputs (due to the // +.5 shifting of the core) when clipping the central region. // note: for strides > 1, the 'any_valid' and 'valid' cases are still sensible. however, the // 'core_valid' case is a bit more problematic. the returned size will be approximately the input // size / the stride, and hopefully the overall behavior is still sensible, but the semantics of // the boundary/edge cases are a bit unclear/aribitrary (but are (intended to be) exactly as // described above). // notes on padding: (1) for the 'valid' mode, the amount of padding will not effect the returned // size of out_box or even the set of descriptors that it contains. however, since the padding // may/will create additional outputs on the - edge of the output space, out_box will shift in the // + direction for a given input window as padding increases. (2) for the 'core_valid' mode, there // may be descriptors that need to use padding. thus, a lack of sufficient padding will cause // descriptors that should be associated with some valid core support region in the input to not // exist. // we define the 'base' output support as the support of the single 'first' output pixel from // (0,0),(1,1). based on core_only, we return either the entire support or only the 'core' support // as per the above definition. the cores are centered in the full support (i.e. are of size // csi.support_stride) and tile to cover in the input space with no gaps or overlap between the // cores of adjacent output pixels. note that the tiled cores may/will not extend to the borders // of the input. i32_box_t get_base_out_support( conv_support_info_t const & csi, bool const core_only ) { assert( csi.support_sz.both_dims_non_zero() ); if( !core_only ) { return i32_box_t( i32_pt_t(), u32_to_i32( csi.support_sz ) ); } else { i32_pt_t const support_core_ub = u32_to_i32( ( csi.support_sz + csi.support_stride + u32_pt_t( 1, 1 ) ) >> 1 ); return i32_box_t( support_core_ub - u32_to_i32( csi.support_stride ), support_core_ub ); } } void in_box_to_out_box( i32_box_t & out_box, u32_box_t const & in_box, conv_mode_t const mode, conv_support_info_t const & csi ) { // shift input region to be in an input space that included the total effective input padding i32_box_t const in_pel = u32_to_i32(in_box + csi.eff_tot_pad); assert_st( in_pel.is_strictly_normalized() ); // choose which type support region we wish to use based on the mode if( mode == cm_any_valid ) { i32_box_t const support = get_base_out_support( csi, 0 ); out_box.p[0] = ceil_div( in_pel.p[0] + i32_pt_t(1,1) - support.p[1], csi.support_stride ); out_box.p[1] = floor_div( in_pel.p[1] - i32_pt_t(1,1) - support.p[0], csi.support_stride ); } else if( mode == cm_valid || mode == cm_core_valid ) { i32_box_t const support = get_base_out_support( csi, ( mode == cm_core_valid ) ); // note: zero area is okay. if denormalized, though, there will no output area (closed out_box // will be denormal and the final open out_box will not be strictly normal. i32_box_t const in_pel_shrunk = in_pel - support; out_box = i32_box_t{ ceil_div( in_pel_shrunk.p[0], csi.support_stride ), floor_div( in_pel_shrunk.p[1], csi.support_stride ) }; // out_box is closed here // check that out_valid is correct: it is valid, and minimal/maximal (one less/more in either dim is not valid) i32_box_t const in_used_pel = support + ( out_box * u32_to_i32(csi.support_stride) ); //printf( "in_pel=%s support=%s in_used_pel=%s out_box=%s\n", // str(in_pel).c_str(), str(support).c_str(), str(in_used_pel).c_str(), str(out_box).c_str() ); // FIXME: the first (and other?) assert fails (as one might expect) if out_box is not // normalized ('negative'/no output area case). skip the asserts in that case? assert_st( in_used_pel.is_strictly_normalized() ); assert_st( in_pel.contains( in_used_pel ) ); // valid check assert_st( in_used_pel.p[0].both_dims_lt( in_pel.p[0] + u32_to_i32(csi.support_stride) ) ); // minimal check assert_st( in_used_pel.p[1].both_dims_gt( in_pel.p[1] - u32_to_i32(csi.support_stride) ) ); // maximal check } else { assert(!"unknown mode"); } // convert the output space box from closed [] to half-open [) pixel coverage semantics. after // the conversion, the box area (as returned by box.get_area()) == the covered pixels. that is, // the box corners/edges are 'between' pixels. out_box.p[1] += i32_pt_t(1,1); // note1: at this point, out_box may not be strictly normalized (even after the []->[) adj.). if // it is not, it means the given input box doesn't have any valid output features for the given // mode. note2: out_box may extend outside the boundaries of the output space. in that case, it // means that the given output pixels were not calculated even though the input region covered // the requested support (sub-)region. this can only occur if the mode is 'core_valid' and if // there is less than a certain amount of padding/garbage in the input space. generally // speaking, care must be taken when using 'core_valid' mode to avoid using 'bad' parts of the // input space. } // return the input-space support of the given out_box (which must be strictly normalized). the // 'unchecked_' means that no clipping/checking of either out_box or in_box to any notion of a // 'valid' input or output space is performed by this function. also, note that there might be // multiple in_boxes that yield the same out_box due to non-unit strides. the details of which // sets of in_boxes can map to the same out_box and which in_box is returned by this function for // a out_box vary by mode; see the per-case comments. void unchecked_out_box_to_in_box( i32_box_t & in_box, i32_box_t const & out_box, conv_mode_t const mode, conv_support_info_t const & csi ) { assert_st( out_box.is_strictly_normalized() ); assert_st( !csi.support_sz.is_zeros() ); i32_box_t out_box_closed( out_box.p[0], out_box.p[1] - i32_pt_t(1,1) ); if( mode == cm_any_valid ) { // for the 'any_valid' mode, the returned in_box is minimal: any smaller box would map to a // smaller out_box. [TODO: CHECK: thus, the returned in_box box can be grown by up to // (stride-1) in any combination of edges and will still yield the same out_box. ] note: some // out_boxes are too small to map to any in_box in any_valid mode; i.e. they are smaller than // the out_box that would be returned from a single pixel of input space. we return a // denormalized in_box in this case, but it's unclear if that makes sense / is useful. i32_box_t const support = get_base_out_support( csi, 0 ); // lb of in_box is -corner of +most (full) support pixel in -most output pixel in_box.p[0] = support.p[1] - i32_pt_t(1,1) + out_box_closed.p[0] * u32_to_i32(csi.support_stride); // ub of in_box is +corner of -most (full) support pixel in +most output pixel in_box.p[1] = support.p[0] + i32_pt_t(1,1) + out_box_closed.p[1] * u32_to_i32(csi.support_stride); } else if( mode == cm_valid || mode == cm_core_valid ) { // for 'valid' and 'core_valid' modes, the returned support is exactly the union of the // support of each pixel in the out_box, based on the above definitions of the supporting // region. thus it is the minimal in_box that maps to this out_box. [TODO: CHECK: if the // resultant in_box is expanded by up to (csi.support_stride-1) on any combination of edges, // it will yield the same out_box. thus, if the stride is 1, the retured in_box is a unique // mapping for this out_box. ] i32_box_t const support = get_base_out_support( csi, ( mode == cm_core_valid ) ); in_box = support + ( out_box_closed * u32_to_i32(csi.support_stride) ); } else { assert(!"unknown mode"); } in_box = in_box - u32_to_i32(csi.eff_tot_pad); // adjust for padding } // this wrapper: (1) includes a special case to handle when global pooling is involved, and thus must take the // full input size so it can be returned in that case. (2) returns valid and core_valid boxes (in one call) void unchecked_out_box_to_in_boxes( i32_box_t & valid_in_box, i32_box_t & core_valid_in_box, i32_box_t const & out_box, conv_support_info_t const & csi, u32_pt_t const & full_in_sz ) { if( !csi.support_sz.is_zeros() ) { unchecked_out_box_to_in_box( valid_in_box, out_box, cm_valid, csi ); unchecked_out_box_to_in_box( core_valid_in_box, out_box, cm_core_valid, csi ); } else { valid_in_box = core_valid_in_box = i32_box_t{u32_to_i32(csi.eff_tot_pad).scale(-1), u32_to_i32(full_in_sz+csi.eff_tot_pad)}; // whole image } } }
67.0875
117
0.709707
b9df1e1dee4c0fad97fc53f19f18a5eb68c2b331
965
lua
Lua
Mods ChoGGi/Find Map Locations/metadata.lua
ChoGGi/SurvivingMars_CheatMods
a84f54572c9f73c671c94a9384fd58a9ffee7cd0
[ "MIT" ]
64
2018-03-27T02:05:29.000Z
2022-02-28T09:44:22.000Z
Mods ChoGGi/Find Map Locations/metadata.lua
ChoGGi/SurvivingMars_CheatMods
a84f54572c9f73c671c94a9384fd58a9ffee7cd0
[ "MIT" ]
50
2018-03-23T09:43:21.000Z
2022-03-27T02:48:04.000Z
Mods ChoGGi/Find Map Locations/metadata.lua
ChoGGi/SurvivingMars_CheatMods
a84f54572c9f73c671c94a9384fd58a9ffee7cd0
[ "MIT" ]
54
2018-03-25T23:12:12.000Z
2022-03-02T15:10:20.000Z
return PlaceObj("ModDef", { "dependencies", { PlaceObj("ModDependency", { "id", "ChoGGi_Library", "title", "ChoGGi's Library", "version_major", 10, "version_minor", 5, }), PlaceObj("ModDependency", { "id", "ChoGGi_MapImagesPack", "title", "Map Images Pack", "version_major", 0, "version_minor", 2, }), }, "title", "Find Map Locations", "id", "ChoGGi_FindMapLocations", "pops_any_uuid", "b97dbd4e-71cf-4e82-80a0-46dd104133bc", "steam_id", "2453011286", "lua_revision", 1007000, -- Picard "version", 7, "version_major", 0, "version_minor", 7, "image", "Preview.jpg", "author", "ChoGGi", "code", { "Code/Script.lua", }, "TagTools", true, "description", [[ Find landing spots with/without a combination of breakthroughs (Extractor AI), resources (metals2), threats(dust_devils4), etc. Left click an item to move the globe to it. For something easier to use: [url=https://survivingmaps.com/]Surviving Maps[/url] ]], })
26.081081
127
0.665285
5812e99e1670bbcc7a91d2e40da62de0e9f38112
9,932
css
CSS
GitHub/profile_style.css
vorobyovvitaliy/Web
06e40635f2f38d7aee2eb28336b366ac39e41e50
[ "MIT" ]
null
null
null
GitHub/profile_style.css
vorobyovvitaliy/Web
06e40635f2f38d7aee2eb28336b366ac39e41e50
[ "MIT" ]
null
null
null
GitHub/profile_style.css
vorobyovvitaliy/Web
06e40635f2f38d7aee2eb28336b366ac39e41e50
[ "MIT" ]
null
null
null
body { font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol; } * { margin: 0; padding: 0; } #main-header { height: 60px; background-color: #24292e; display: flex; justify-content: space-between; padding: 0 16px; } #main-header > div { display: flex; align-items: center; } #main-header > div > a { margin-right: 13px; } #main-header > div > a:before { content: ""; width: 32px; height: 32px; display: block; background: url("images/GitHubIcon.svg") no-repeat; margin-top: -4px; } #main-header > div form input { width: 300px; height: 30px; border: none; border-radius: 3px; background-color: hsla(0,0%,100%,.125); padding: 0 8px; color: #cdcdcd; font-weight: 400; font-size: 13px; } #main-header > div form { width: 300px; height: 30px; display: flex; align-items: center; } #main-header > div form img { margin-left: -25px; height: 18px; } .main-nav { margin-left: 16px; margin-top: 3px; } .main-nav a { color: #FFF; text-decoration: none; font-weight: 600; font-size: 14px; margin-right: 12px; } .main-nav a:hover { color: hsla(0,0%,100%,.75); } .secondary-nav { width: 116px; display: flex; align-items: center; justify-content: space-around; } .secondary-nav a::before { content: ""; width: 16px; height: 16px; display: block; margin-top: -1px; background: url("images/bell.svg") no-repeat; } .plus-button { width: 17px; height: 17px; margin-top: 3px; margin-right: 7px; background: url("images/plus.svg") no-repeat; border: none; cursor: pointer; } .plus-button::after { content: ""; width: 8px; height: 8px; display: block; margin-left: 18px; position: relative; cursor: pointer; background: url("images/dropdown.svg"); } .profile-button { width: 20px; height: 20px; margin-top: 4px; border-radius: 3px; margin-right: 4px; background: url("images/avatar.jpg") no-repeat; background-size: cover; border: none; cursor: pointer; } .profile-button::after { content: ""; width: 8px; height: 8px; display: block; margin-left: 24px; position: relative; cursor: pointer; background: url("images/dropdown.svg") } main { width: 980px; height: auto; margin: 24px auto auto; } main aside { width: 229px; height: auto; display: inline-block; float: left; } main aside > img:nth-child(1) { height: 229px; width: 227px; border-radius: 3px 3px 0 0; border: 1px solid #e1e4e8; border-bottom: 0; } #avatar-footer { width: 227px; height: 49px; margin-top: -6px; border-bottom: 1px solid #e1e4e8; border-radius: 0 0 3px 3px; border-left: 1px solid #e1e4e8; border-right: 1px solid #e1e4e8; } #avatar-footer div { border-radius: 50%; display: flex; background-color: #FFF; position: absolute; width: 28px; height: 28px; align-items: center; justify-content: center; border: none; margin-top: -14px; margin-left: 15px; } #avatar-footer div img { width: 18px; height: 18px; } #avatar-footer a { color: #24292e; position: absolute; font-size: 12px; margin-top: 24px; margin-left: 12px; text-decoration: none; } #avatar-footer a:hover { color: cornflowerblue; } aside > h1 { margin-top: 16px; color: #24292e; font-size: 26px; font-weight: 600; } aside > h2 { color: #6a737d; font-size: 20px; font-weight: 300; } aside > hr { margin-top: 16px; margin-bottom: 18px; border: 0; height: 1px; background: #ddd; } .star { width: 14px; height: 16px; display: inline-block; } .pro { margin-left: 12px; color: #FFF; box-shadow: inset 0 -1px 0 rgba(27,31,35,.12); border-radius: 2px; display: inline-block; font-size: 12px; font-weight: 600; line-height: 1; padding: 3px 4px; background-color: #6f42c1; } aside > p { margin: 15px 0 23px 0; color: #24292e; font-size: 14px; line-height: 1.5; } aside > address:before { content: ""; width: 16px; height: 16px; display: block; background: url("images/geo.svg") no-repeat; float: left; position: relative; visibility: visible; } aside > address { color: #24292e; font-size: 14px; font-style: normal; } aside > a { text-decoration: none; color: cornflowerblue; display: block; } .mail:before { content: ""; width: 16px; height: 16px; display: block; background: url("images/mail.svg") no-repeat; float: left; position: relative; visibility: visible; } .contact { text-overflow: ellipsis; overflow: hidden; width: 160px; height: 1.2em; white-space: nowrap; } .contact:before { content: ""; width: 16px; height: 16px; display: block; background: url("images/contact.svg") no-repeat; float: left; position: relative; visibility: visible; } aside > button { width: 229px; height: 28px; border: 1px solid #bbb; background-color: #eff3f6; border-radius: 3px; font-weight: 600; font-size: 12px; margin-top: 20px; cursor: pointer; } .main-content { width: 727px; height: auto; float: right; } .main-content > header { width: 727px; height: 55px; border-bottom: 1px solid #d1d5da; box-sizing: border-box; background-color: #FFF; z-index: 1; position: sticky; top: 0; } .main-content > header > div { display: flex; align-items: center; justify-content: space-between; } .main-content > header > div a { height: 55px; text-decoration: none; color: #6a737d; font-size: 14px; padding: 18px 8px; margin-right: 16px; box-sizing: border-box; border-bottom: 2px solid transparent; } .main-content > header > div a:hover { border-bottom-color: #d1d5da; } .main-content > header > div a span { background-color: rgba(27,31,35,.08); border-radius: 20px; color: #586069; display: inline-block; font-size: 12px; font-weight: 600; line-height: 1; padding: 2px 5px; } .main-content > header > div a:nth-child(1) { border-bottom-color: #e36209; color: #24292e; font-weight: 600; } .pinned-repositories { width: 727px; height: 374px; margin-top: 24px; } .pinned-repositories h2 { width: 500px; font-size: 16px; font-weight: 400; color: #6a737d; float: left; line-height: 1.5; margin-bottom: 8px; } .pinned-repositories button { border: none; background: none; color: #586069; float: right; font-size: 13px; line-height: 1.5; margin-top: 4px; } .pinned-repositories button:hover { color: #0366d6; cursor: pointer; } .pinned-repositories article { width: 325px; height: 64px; border: 1px solid #e1e4e8; display: inline-block; position: relative; border-radius: 3px; padding: 16px; margin-bottom: 16px; } .pinned-repositories article:nth-child(2n) { float: right; } .pinned-repositories article a { color: #0366d6; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol;; font-size: 14px; line-height: 1.5; font-weight: 600; text-decoration: none; } .pinned-repositories article a:hover { text-decoration: underline; } .pinned-repositories article a::before { width: 8px; height: 16px; content: ""; display: block; float: left; padding: 1px 8px 0 0; margin-top: 3px; background: url("images/menu.svg") no-repeat; cursor: grabbing; } .pinned-repositories article p { margin-top: 26px; font-size: 12px; color: #586069; } .pinned-repositories article p::before { content: ""; display: block; float: left; width: 12px; height: 12px; margin-top: 1px; margin-right: 4px; border-radius: 50%; } .main-content > section article p::before { background-color: #3572A5; } .contributions { width: 727px; height: auto; margin-top: 24px; } .contributions > section { width: 605.833px; } .contributions > section h2 { font-weight: 400; font-size: 16px; color: #24292e; margin-bottom: 8px; line-height: 1.5; display: inline-block; } .contributions > section button { border: none; background: none; color: #586069; float: right; font-size: 13px; line-height: 1.5; margin-top: 4px; } .contributions > section button::after { content: ""; width: 8px; height: 8px; display: block; margin-left: 4px; margin-top: 5px; position: relative; cursor: pointer; float: right; background: url("images/dropdown.svg"); } .contributions > section button:hover { color: #0366d6; } .contributions-table { width: 100%; height: 122.5px; padding: 8px 0; border-top-left-radius: 3px; border-top-right-radius: 3px; border: 1px solid #d1d5da; } .contributions-activity { width: 100%; height: 157px; padding: 16px 0; border-left: 1px solid #d1d5da; border-right: 1px solid #d1d5da; border-bottom: 1px solid #d1d5da; border-bottom-left-radius: 3px; border-bottom-right-radius: 3px; margin-bottom: 32px; } /*footer {*/ /*width: 100%;*/ /*height: 115px;*/ /*display: flex;*/ /*justify-content: center;*/ /*}*/ /*footer::before {*/ /*content: "";*/ /*position: absolute;*/ /*width: 900px;*/ /*border: 1px solid rgb(88, 96, 105);*/ /*}*/ /*footer a {*/ /*color: rgb(88, 96, 105);*/ /*}*/ /*footer a:hover {*/ /*}*/
18.157221
144
0.606524
dc1b2492905658e1a56d039b8babfb08d612b548
1,511
lua
Lua
SafeLuaAPI.lua
drbo/safer-lua-api
cacfad7d3453cb84fe3a4c8e3f7865e634210c18
[ "Apache-2.0", "MIT" ]
2
2017-06-22T09:14:53.000Z
2018-09-24T17:15:00.000Z
SafeLuaAPI.lua
DemiMarie/safer-lua-api
cacfad7d3453cb84fe3a4c8e3f7865e634210c18
[ "Apache-2.0", "MIT" ]
2
2016-05-02T00:24:37.000Z
2016-05-02T02:12:46.000Z
SafeLuaAPI.lua
DemiMarie/safer-lua-api
cacfad7d3453cb84fe3a4c8e3f7865e634210c18
[ "Apache-2.0", "MIT" ]
null
null
null
--- -- @author Demi Marie Obenour -- @module SafeLuaAPI -- @license MIT/X11 -- @license Apache 2.0 -- @copyright 2016 local SafeLuaAPI = {} local string, assert, io, require, arg, print, os, pcall = string, assert, io, require, arg, print, os, pcall local generator = require 'SafeLuaAPI/generator' local functions = require 'SafeLuaAPI/functions' local finally = require 'SafeLuaAPI/finally' pcall(require, 'pl/strict') local function do_it(handle, header_handle) handle:write[[ /* THIS IS A GENERATED FILE. DO NOT EDIT. */ #include <luajit-2.0/lua.h> #include <luajit-2.0/lauxlib.h> #include "../template.h" #include "bindings.h" ]] header_handle:write[[ /* THIS IS A GENERATED FILE. DO NOT EDIT. */ #ifndef SAFE_LUA_API_H_INCLUDED #define SAFE_LUA_API_H_INCLUDED SAFE_LUA_API_H_INCLUDED ]] assert(header_handle) local c_code_emitter = generator.new(handle, header_handle) c_code_emitter:generate(functions.api_functions_needing_wrappers) --generator.generate(handle, functions.auxlib_functions_needing_wrappers) --generator.generate(handle, functions.debug_functions_needing_wrappers) header_handle:write '#endif // !defined(SAFE_LUA_API_H_INCLUDED)\n' end local handle, err = io.open(arg[1], 'w') if handle then local header_handle header_handle, err = io.open(string.gsub(arg[1], '%.c$', '.h'), 'w') if not header_handle then print(err) os.exit(1) end do_it(handle, header_handle) io.close(handle) else print(err) os.exit(1) end
26.508772
76
0.724686
20ba953b802f47c9fb924d658fe7172aaf436c99
1,748
py
Python
setup.py
vndmtrx/flask-staticsite
a1d80578b810088ce29fa48aa73a84aac178f248
[ "Apache-2.0" ]
2
2018-10-21T18:17:20.000Z
2021-11-27T12:25:17.000Z
setup.py
vndmtrx/flask-staticsite
a1d80578b810088ce29fa48aa73a84aac178f248
[ "Apache-2.0" ]
null
null
null
setup.py
vndmtrx/flask-staticsite
a1d80578b810088ce29fa48aa73a84aac178f248
[ "Apache-2.0" ]
null
null
null
import os import re import sys from setuptools import setup, find_packages DIRNAME = os.path.abspath(os.path.dirname(__file__)) rel = lambda *parts: os.path.abspath(os.path.join(DIRNAME, *parts)) README = open(rel('README.md')).read() INIT_PY = open(rel('flask_staticsite', '__init__.py')).read() VERSION = re.search("__version__ = '([^']+)'", INIT_PY).group(1) setup( name='Flask-StaticSite', version=VERSION, url='https://github.com/vndmtrx/Flask-StaticSite', license='Apache', author='Eduardo Rolim', author_email='vndmtrx@gmail.com', description='Provides static pages to a Flask application.', long_description=README, packages=find_packages(exclude=["tests", "examples"]), zip_safe=False, include_package_data=True, platforms='any', install_requires=[ 'Flask>=1.0.2', 'PyYAML>=3.13', 'six>=1.11.0', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: Portuguese (Brazilian)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Indexing', 'Topic :: Utilities', 'Framework :: Flask', ] )
33.615385
71
0.621854
ed3759f1606c2cf4d082a7227a9321f4206f69d7
18
h
C
source/pcemu/src/jim.h
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-11-20T22:46:39.000Z
2021-11-20T22:46:39.000Z
source/pcemu/src/jim.h
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
source/pcemu/src/jim.h
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
void jim_init();
9
17
0.666667
2c515873423c6d4aa774694860058b0149bf6abb
1,645
py
Python
augly/video/augmenters/ffmpeg/color_jitter.py
Adib234/AugLy
35a6a5de07e64f465b8979e3257218551929e57a
[ "MIT" ]
null
null
null
augly/video/augmenters/ffmpeg/color_jitter.py
Adib234/AugLy
35a6a5de07e64f465b8979e3257218551929e57a
[ "MIT" ]
null
null
null
augly/video/augmenters/ffmpeg/color_jitter.py
Adib234/AugLy
35a6a5de07e64f465b8979e3257218551929e57a
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from typing import Tuple, Dict from augly.video.augmenters.ffmpeg.base_augmenter import BaseFFMPEGAugmenter from ffmpeg.nodes import FilterableStream class VideoAugmenterByColorJitter(BaseFFMPEGAugmenter): def __init__( self, brightness_level: float, contrast_level: float, saturation_level: float ): assert ( -1.0 <= brightness_level <= 1.0 ), "Brightness factor must be a value in the range [-1.0, 1.0]" assert ( -1000.0 <= contrast_level <= 1000.0 ), "Contrast factor must be a value in the range [-1000, 1000]" assert ( 0.0 <= saturation_level <= 3.0 ), "Saturation factor must be a value in the range [0.0, 3.0]" self.brightness_level = brightness_level self.contrast_level = contrast_level self.saturation_level = saturation_level def add_augmenter( self, in_stream: FilterableStream, **kwargs ) -> Tuple[FilterableStream, Dict]: """ Color jitters the video @param in_stream: the FFMPEG object of the video @returns: a tuple containing the FFMPEG object with the augmentation applied and a dictionary with any output arguments as necessary """ return ( in_stream.video.filter( "eq", **{ "brightness": self.brightness_level, "contrast": self.contrast_level, "saturation": self.saturation_level, } ), {}, )
32.9
85
0.598784
e2c7e1f55b6f31e369d4b927d81360a998dbb4f8
2,181
py
Python
src/api/admin_estacio_api.py
BoaVaga/boavaga_server
7d25a68832d3b9f4f5666d0a3d55c99025498511
[ "MIT" ]
null
null
null
src/api/admin_estacio_api.py
BoaVaga/boavaga_server
7d25a68832d3b9f4f5666d0a3d55c99025498511
[ "MIT" ]
null
null
null
src/api/admin_estacio_api.py
BoaVaga/boavaga_server
7d25a68832d3b9f4f5666d0a3d55c99025498511
[ "MIT" ]
null
null
null
import logging import flask from ariadne import convert_kwargs_to_snake_case from dependency_injector.wiring import Provide, inject from sqlalchemy.orm import Session from src.api.base import BaseApi from src.container import Container from src.repo import AdminSistemaRepo, RepoContainer, AdminEstacioRepo from src.services import Cached class AdminEstacioApi(BaseApi): ERRO_DESCONHECIDO = 'erro_desconhecido' @inject def __init__(self, admin_estacio_repo: AdminEstacioRepo = Provide[RepoContainer.admin_estacio_repo], cached: Cached = Provide[Container.cached]): self.repo = admin_estacio_repo self.cached = cached queries = {} mutations = { 'createAdminEstacio': self.create_admin_resolver, 'addAdminToEstacio': self.add_to_estacio_resolver } super().__init__(queries, mutations) @convert_kwargs_to_snake_case def create_admin_resolver(self, _, info, email: str, senha: str): sess: Session = flask.g.session try: success, error_or_admin = self.repo.create_admin(sess, email, senha) except Exception as ex: logging.getLogger(__name__).error('Error on create_admin_resolver', exc_info=ex) success, error_or_admin = False, self.ERRO_DESCONHECIDO if success: payload = { 'success': True, 'admin_estacio': error_or_admin } else: payload = { 'success': False, 'error': error_or_admin } return payload @convert_kwargs_to_snake_case def add_to_estacio_resolver(self, _, info, email: str): sess: Session = flask.g.session user_sess = self.get_user_session(sess, self.cached, info) try: success, error = self.repo.add_to_estacio(user_sess, sess, email) except Exception as ex: logging.getLogger(__name__).error('Error on add_to_estacio_resolver', exc_info=ex) success, error = False, self.ERRO_DESCONHECIDO return { 'success': success, 'error': error }
31.608696
104
0.646492
f89e93ac48d6330a5fd84ab0b1a1597836cff797
444
dart
Dart
lib/device/theme/myColors.dart
Usta66/karakok_uygulama_2022
a63beacb022fcafeccc6a8e11639eb30d287228b
[ "MIT" ]
null
null
null
lib/device/theme/myColors.dart
Usta66/karakok_uygulama_2022
a63beacb022fcafeccc6a8e11639eb30d287228b
[ "MIT" ]
null
null
null
lib/device/theme/myColors.dart
Usta66/karakok_uygulama_2022
a63beacb022fcafeccc6a8e11639eb30d287228b
[ "MIT" ]
null
null
null
// ignore_for_file: file_names import 'package:flutter/material.dart'; class MyColors { static MyColors? _instance; static MyColors? get instance { return _instance ??= MyColors._init(); } MyColors._init(); Color seciliRenk = const Color(0xFFC5CAE9); Color normal = const Color(0xFFB2DFDB); Color dogru = const Color(0xFF4caf50); Color yanlis = const Color(0xFFb71c1c); Color zamanVeSkor = const Color(0xFFFFD900); }
22.2
46
0.725225
cdc43d7e80c49465a723c604a6c49b6b367684b3
6,439
cs
C#
src/Enterspeed.Source.Sdk/Domain/Services/EnterspeedIngestService.cs
msoelvsteen/enterspeed-sdk-dotnet
a8e77a78d97bfeea42de64252e3f94c41f6ce8e4
[ "MIT" ]
null
null
null
src/Enterspeed.Source.Sdk/Domain/Services/EnterspeedIngestService.cs
msoelvsteen/enterspeed-sdk-dotnet
a8e77a78d97bfeea42de64252e3f94c41f6ce8e4
[ "MIT" ]
3
2021-04-21T19:54:31.000Z
2022-03-18T10:10:08.000Z
src/Enterspeed.Source.Sdk/Domain/Services/EnterspeedIngestService.cs
msoelvsteen/enterspeed-sdk-dotnet
a8e77a78d97bfeea42de64252e3f94c41f6ce8e4
[ "MIT" ]
1
2022-03-14T09:00:42.000Z
2022-03-14T09:00:42.000Z
using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Enterspeed.Source.Sdk.Api.Connection; using Enterspeed.Source.Sdk.Api.Models; using Enterspeed.Source.Sdk.Api.Providers; using Enterspeed.Source.Sdk.Api.Services; using Enterspeed.Source.Sdk.Domain.Connection; namespace Enterspeed.Source.Sdk.Domain.Services { public class EnterspeedIngestService : IEnterspeedIngestService { private readonly IEnterspeedConnection _connection; private readonly IJsonSerializer _jsonSerializer; private readonly string _ingestEndpoint; public EnterspeedIngestService( IEnterspeedConnection connection, IJsonSerializer jsonSerializer, IEnterspeedConfigurationProvider configurationProvider) { _connection = connection; _jsonSerializer = jsonSerializer; _ingestEndpoint = $"/ingest/v{configurationProvider.Configuration.IngestVersion}"; } public Response Save(IEnterspeedEntity entity) { if (entity == null) { return new Response { Success = false, Exception = new ArgumentNullException(nameof(entity)), Message = "Missing entity" }; } HttpResponseMessage response = null; IngestResponse ingestResponse = null; string responseContentAsString = null; try { var content = _jsonSerializer.Serialize(entity); var buffer = Encoding.UTF8.GetBytes(content); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = _connection.HttpClientConnection.PostAsync(_ingestEndpoint, byteContent) .ConfigureAwait(false) .GetAwaiter() .GetResult(); responseContentAsString = response?.Content .ReadAsStringAsync() .ConfigureAwait(false) .GetAwaiter() .GetResult(); if (!string.IsNullOrWhiteSpace(responseContentAsString)) { ingestResponse = _jsonSerializer.Deserialize<IngestResponse>(responseContentAsString); } } catch (Exception e) { return new Response { Success = false, Status = response?.StatusCode ?? HttpStatusCode.BadRequest, Exception = e, Content = responseContentAsString }; } if (response == null) { return new Response { Success = false, Exception = new Exception("Failed sending data") }; } var statusCode = ingestResponse?.Status ?? response.StatusCode; return new Response { Message = ingestResponse?.Message, Errors = ingestResponse?.Errors, ErrorCode = ingestResponse?.ErrorCode, Status = statusCode, Success = response.IsSuccessStatusCode, Content = responseContentAsString }; } public Response Delete(string id) { if (string.IsNullOrWhiteSpace(id)) { return new Response { Success = false, Exception = new ArgumentNullException(nameof(id)), Message = "Missing entity" }; } HttpResponseMessage response = null; try { response = _connection.HttpClientConnection .DeleteAsync($"{_ingestEndpoint}?id={id}") .ConfigureAwait(false) .GetAwaiter() .GetResult(); } catch (Exception e) { return new Response { Success = false, Status = response?.StatusCode ?? HttpStatusCode.BadRequest, Exception = e }; } if (response == null) { return new Response { Success = false, Exception = new Exception("Failed deleting data") }; } return new Response { Message = response.Content .ReadAsStringAsync() .ConfigureAwait(false) .GetAwaiter() .GetResult(), Status = response.StatusCode, Success = response.IsSuccessStatusCode }; } public Response Test() { HttpResponseMessage response = null; try { var buffer = Encoding.UTF8.GetBytes("{}"); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = _connection.HttpClientConnection .PostAsync(_ingestEndpoint, byteContent) .ConfigureAwait(false) .GetAwaiter() .GetResult(); } catch (Exception e) { return new Response { Success = false, Status = response?.StatusCode ?? HttpStatusCode.BadRequest, Exception = e }; } if (response == null) { return new Response { Success = false, Exception = new Exception("Failed testing endpoint") }; } var statusCode = response.StatusCode; return new Response { Status = statusCode, Success = response.IsSuccessStatusCode }; } } }
33.020513
106
0.491691
cb36ae11822362749fe190cdef2bc065b1f7fa7d
2,457
sh
Shell
gotolong/chealth/chealth_invoke.sh
ParikhKadam/gotolong
839beb8aa37055a2078eaa289b8ae05b62e8905e
[ "BSD-2-Clause", "BSD-3-Clause" ]
15
2019-12-06T16:19:45.000Z
2021-08-20T13:22:22.000Z
gotolong/chealth/chealth_invoke.sh
ParikhKadam/gotolong
839beb8aa37055a2078eaa289b8ae05b62e8905e
[ "BSD-2-Clause", "BSD-3-Clause" ]
14
2020-12-08T10:45:05.000Z
2021-09-21T17:23:45.000Z
gotolong/chealth/chealth_invoke.sh
ParikhKadam/gotolong
839beb8aa37055a2078eaa289b8ae05b62e8905e
[ "BSD-2-Clause", "BSD-3-Clause" ]
9
2020-01-01T03:04:29.000Z
2021-04-18T08:42:30.000Z
#!/bin/sh DEBUG_LEVEL=1 CONFIG_GLOBAL_DATA_LOC=`python -m gotolong.config.config_ini global_data` CONFIG_GLOBAL_REPORTS_LOC=`python -m gotolong.config.config_ini global_reports` CONFIG_PROFILE_DATA_LOC=`python -m gotolong.config.config_ini profile_data` CONFIG_PROFILE_REPORTS_LOC=`python -m gotolong.config.config_ini profile_reports` MODULE=chealth # equity user for EUSER in index_nifty index_nse500 demat_idirect demat_zerodha user_normal do echo "generating reports for equity user ${EUSER}" EUDIR=${EUSER} if test "${EUSER}" == "demat_idirect" -o "${EUSER}" == "demat_zerodha" then if test "${EUSER}" == "demat_idirect" then BROKER=icicidirect elif test "${EUSER}" == "demat_zerodha" then BROKER=zerodha else echo "wrong broker : $EUSER" exit 1 fi IN_FILE_1=$CONFIG_PROFILE_REPORTS_LOC/demat-reports/${BROKER}/demat-summary-ticker-only.csv else IN_FILE_1=$CONFIG_PROFILE_DATA_LOC/${MODULE}-data/${EUDIR}/${EUDIR}-ticker-list.csv fi IN_FILE_2=$CONFIG_GLOBAL_REPORTS_LOC/screener-reports/screener-reports-fltr-buy-ticker-only.csv IN_FILE_3=$CONFIG_GLOBAL_REPORTS_LOC/screener-reports/screener-reports-fltr-hold-ticker-cause.csv IN_FILE_4=$CONFIG_GLOBAL_REPORTS_LOC/screener-reports/screener-reports-fltr-sale-ticker-cause.csv OUT_DIR=$CONFIG_PROFILE_REPORTS_LOC/${MODULE}-reports/${EUDIR}/ mkdir -p ${OUT_DIR} # present in file 1 (ticker list) only - (not in screener - hold and buy ) recommendation - drop from portfolio OUT_FILE_1=${OUT_DIR}/reco-sale.csv # present in file 2 (screener - buy) only - recommendation - add OUT_FILE_2=${OUT_DIR}/reco-buy-new.csv # present in both file 1 and file 2 (screener - buy) - recommendation - more OUT_FILE_3=${OUT_DIR}/reco-buy-more.csv # present in both file 1 and file 2 (screener - hold) - recommendation - keep - hold OUT_FILE_4=${OUT_DIR}/reco-hold.csv # reco - none - as data missing OUT_FILE_5=${OUT_DIR}/reco-none.csv # python -m pdb weight_invoke.py ${DEBUG_LEVEL} ${IN_FILE_PLAN} ${OUT_FILE_1} ${OUT_FILE_2} ${OUT_FILE_3} ${OUT_FILE_4} ${OUT_FILE_5} python chealth.py ${DEBUG_LEVEL} ${IN_FILE_1} ${IN_FILE_2} ${IN_FILE_3} ${IN_FILE_4} ${OUT_FILE_1} ${OUT_FILE_2} ${OUT_FILE_3} ${OUT_FILE_4} ${OUT_FILE_5} echo "generated reports for equity user ${EUSER}" done
36.671642
158
0.703704
c4b686e364cd0d9b86a354df6e64cbbb8ab96071
343
hpp
C++
src/framework/forms/input/input.hpp
kevinaud/asm-dom-OO-counters
58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6
[ "MIT" ]
9
2018-06-07T00:39:45.000Z
2021-06-28T18:26:51.000Z
src/framework/forms/input/input.hpp
kevinaud/asm-dom-OO-counters
58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6
[ "MIT" ]
null
null
null
src/framework/forms/input/input.hpp
kevinaud/asm-dom-OO-counters
58ea010941b5e7ab860109b6ebbd6f3ca47fd4c6
[ "MIT" ]
2
2019-05-04T15:35:04.000Z
2019-09-24T12:11:45.000Z
#ifndef INPUT_H #define INPUT_H #include "../../component/component.hpp" #include "../../view-property/view-property.hpp" class Input : public Component { public: Input(Component* parent); Input(Component* parent, string initValue); VNode* render(); private: ViewProperty<string>* value; }; #endif
18.052632
51
0.641399
c2535da3e2e977798ad39ffa26703c0e13506e19
3,338
swift
Swift
src/Sources/SimpleView/ViewController.swift
vladimir-aubrecht/SimpleView
8e76d088c8f461736b9872b8db979ca886816b6c
[ "Apache-2.0" ]
null
null
null
src/Sources/SimpleView/ViewController.swift
vladimir-aubrecht/SimpleView
8e76d088c8f461736b9872b8db979ca886816b6c
[ "Apache-2.0" ]
null
null
null
src/Sources/SimpleView/ViewController.swift
vladimir-aubrecht/SimpleView
8e76d088c8f461736b9872b8db979ca886816b6c
[ "Apache-2.0" ]
null
null
null
// // ViewController.swift // SimpleView // // Created by Vladimir Aubrecht on 31/07/2017. // Copyright © 2017 Vladimir Aubrecht. All rights reserved. // import Cocoa import SwiftyBeaver import Quartz class ViewController: NSViewController { private let log = SwiftyBeaver.self @IBOutlet var OpeningLabel: NSTextField! @IBOutlet var scrollView: NSScrollView! @IBOutlet var imageCell: NSImageCell! // TODO: Think about moving fileBrowser into AppDelegate (it would removed proxy methods ...) private var fileBrowser = ImageFileBrowser(allowedExtensions: ["jpeg", "jpg", "png", "psd", "bmp", "gif", "raw"]) let zoomMultiplier : CGFloat = 1.2 public func loadPath(path: String) { self.fileBrowser.loadPathsFromPath(path: path) self.processCurrentImage() } public func deleteCurrentImage() { self.fileBrowser.deleteCurrentPath() self.processCurrentImage() } public func zoomInImage() { self.scrollView.magnification *= zoomMultiplier } public func zoomOutImage() { self.scrollView.magnification /= zoomMultiplier } public func zoomDefault() { self.scrollView.magnification = 1.0 } public func nextImage() { if (self.fileBrowser.nextPath()) { self.processCurrentImage() } else if self.fileBrowser.goToFirstPath() { self.processCurrentImage() } } public func previousImage() { if (self.fileBrowser.previousPath()) { self.processCurrentImage() } else if self.fileBrowser.goToLastPath() { self.processCurrentImage() } } public func reZoom() { let magnification = self.scrollView.magnification self.zoomDefault() self.scrollView.magnification = magnification } private func processCurrentImage() { self.imageCell.image = self.fileBrowser.getCurrentImage() self.OpeningLabel.isHidden = self.fileBrowser.getCurrentPath() != nil if let imagePath = self.fileBrowser.getCurrentPath() { self.scrollView.window!.setWindowTitleByFilename(fromPath: imagePath) self.setContentSizeByCurrentImage() } } public func setContentSizeByCurrentImage() { if self.fileBrowser.getCurrentImage() != nil { let sizeFittingWindow = self.scrollView.window!.getSizeFittingTheWindow(size: self.imageCell.image!.size) self.scrollView.documentView!.setFrameSize(sizeFittingWindow) self.zoomDefault() } } public func setWindowLayoutByCurrentImage() { if self.fileBrowser.getCurrentImage() != nil { let sizeFittingScreen = self.scrollView.window!.screen!.getSizeFittingTheScreen(size: self.imageCell.image!.size) self.scrollView.documentView!.setFrameSize(sizeFittingScreen) self.scrollView.window!.setWindowSizeWithRespectToMinimumDimension(size: sizeFittingScreen, minimalDimension: 500.0) self.scrollView.window!.positionWindowAtCenter() self.zoomDefault() } } }
26.919355
128
0.626423
dc31d95539a11a0938260bd9b85c9a42af315617
774
tsx
TypeScript
components/composite/ErrorContainer/styled.tsx
Quammsrl/commercelayer-react-checkout
830e73db210fe3286779ce39c9c70e3f56a8b23e
[ "MIT" ]
16
2021-12-22T09:01:48.000Z
2022-03-30T15:47:03.000Z
components/composite/ErrorContainer/styled.tsx
Quammsrl/commercelayer-react-checkout
830e73db210fe3286779ce39c9c70e3f56a8b23e
[ "MIT" ]
62
2021-12-29T11:20:38.000Z
2022-03-28T08:48:58.000Z
components/composite/ErrorContainer/styled.tsx
Quammsrl/commercelayer-react-checkout
830e73db210fe3286779ce39c9c70e3f56a8b23e
[ "MIT" ]
7
2021-12-23T07:07:34.000Z
2022-03-08T09:37:21.000Z
import styled from "styled-components" import tw from "twin.macro" import { Logo } from "components/ui/Footer/cl" export const Main = styled.div` ${tw`flex flex-col flex-1 justify-center items-center text-center`} ` export const Wrapper = styled.div` ${tw`flex flex-wrap justify-end items-stretch flex-col h-screen p-5 md:p-10 lg:px-20 lg:pb-10`} ` export const Text = styled.p` ${tw`p-4 text-sm font-normal text-gray-500`} ` export const Error = styled.div` ${tw`flex flex-col items-center md:(flex-row)`} ` export const ErrorCode = styled.p` ${tw`p-4 text-xl font-bold border-gray-300 text-gray-800 border-b md:(border-r border-b-0)`} ` export const LogoWrapper = styled.div` ${tw`md:max-w-xs`} ` export const FullLogo = styled(Logo)` ${tw`text-black`} `
28.666667
97
0.702842
f49dc3ac4d68a57a974ffec771e68d46503dd46a
3,326
ts
TypeScript
packages/engine/libs/services/execution.ts
jyfti/jyfti
43f03dfd9ef3410adf4a0b40d70dfef0963492c2
[ "MIT" ]
3
2020-12-27T14:20:03.000Z
2021-05-12T08:49:38.000Z
packages/engine/libs/services/execution.ts
jyfti/jyfti
43f03dfd9ef3410adf4a0b40d70dfef0963492c2
[ "MIT" ]
19
2020-08-16T20:04:53.000Z
2021-01-03T12:39:15.000Z
packages/engine/libs/services/execution.ts
jyfti/jyfti
43f03dfd9ef3410adf4a0b40d70dfef0963492c2
[ "MIT" ]
null
null
null
import { Observable, of } from "rxjs"; import { State, Workflow, Inputs, Environment, StepResult, JsonSchema, StepRequire, StepFailure, Path, } from "../types"; import { evaluate } from "./evaluation"; import { createVariableMapFromState } from "./variable-map-creation"; import { executeStep } from "../step-execution/step-execution"; import { resolveStep } from "./step-resolvement"; import { resolveEvaluation } from "./evaluation-resolvement"; import { map, catchError } from "rxjs/operators"; import { hasErrors, validateInputs } from "./validator"; export function step( workflow: Workflow, state: State, environment: Environment, outRoot: string ): Observable<StepResult> { const step = resolveStep(workflow, state.path); const localEvaluations = resolveEvaluation(state.evaluations, state.path); const variables = createVariableMapFromState(workflow, state, environment); const name = tryCatch( () => stringOrElseUndefined(evaluate(variables, step.name)), (err) => "<Name could not be evaluated> " + JSON.stringify(err) ); const path = state.path; const require = evaluate(variables, step.require); const requireResult = checkRequire(require, state.inputs, path, name); if (requireResult) { return of(requireResult); } return executeStep(step, localEvaluations, variables, outRoot).pipe( map((evaluation) => ({ name, path, evaluation })), catchError((error) => of({ name, path, error })) ); } export function checkRequire( require: unknown, inputs: Inputs, path: Path, name: string | undefined ): StepRequire | StepFailure | undefined { if (require && isJsonSchemaMap(require)) { const missingInputs = Object.keys(require).filter( (input) => !Object.keys(inputs).includes(input) ); if (missingInputs.length !== 0) { return { name, path, require: missingInputs.reduce( (acc, input) => ({ ...acc, [input]: require[input] }), {} ), }; } const requireValidation = validateInputs(inputs, require); if (hasErrors(requireValidation)) { return { name, path, error: new Error("Required inputs are given, but wrongly typed"), // TODO Improve message with actual errors }; } } return undefined; } function isJsonSchemaMap( object: unknown ): object is Record<string, JsonSchema> { // TODO Improve return typeof object === "object"; } function stringOrElseUndefined(object: unknown): string | undefined { return typeof object === "string" ? object : undefined; } function tryCatch<T>(f: () => T, catcher: (err) => T): T { try { return f(); } catch (err) { return catcher(err); } } export function toOutput( workflow: Workflow, state: State, environment: Environment ): unknown | undefined { return workflow.output ? evaluate( createVariableMapFromState(workflow, state, environment), workflow.output ) : undefined; } export function inputDefaults(workflow: Workflow): Inputs { const inputs = workflow.inputs || {}; return Object.keys(inputs) .map((fieldName) => ({ fieldName, default: inputs[fieldName].default })) .filter((input) => input.default) .reduce((acc, input) => ({ ...acc, [input.fieldName]: input.default }), {}); }
28.186441
116
0.662057
757b5687c0b0fede5a5e7eae1c098bbf9687b5b5
1,132
css
CSS
assets/stylesheet/style.css
Golder0912/homepage
555d9c65d1c740dfd7933bb350a5640b17625e3c
[ "MIT" ]
null
null
null
assets/stylesheet/style.css
Golder0912/homepage
555d9c65d1c740dfd7933bb350a5640b17625e3c
[ "MIT" ]
25
2019-05-11T16:29:31.000Z
2019-05-14T13:58:49.000Z
assets/stylesheet/style.css
vladossuper/homepage
5a2e984515fdff92102cb0dca3f44ec18bf5552a
[ "MIT" ]
null
null
null
main { background-image: url('../images/flagUSA.jpg'); background-attachment: fixed; background-repeat: no-repeat; } .new-border { border: 20px solid transparent; -moz-border-image: -moz-linear-gradient(top, #fd0101 0%, #0c0266 66%, #ffffff 100%); -webkit-border-image: -webkit-linear-gradient(top, #fd0101 0%, #0c0266 66%, #ffffff 100%); border-image: linear-gradient(to bottombottom, #fd0101 0%, #0c0266 66%, #ffffff 100%); border-image-slice: 1; } .avatar { width: 100%; border-radius: 50%; } .twitter:hover { color: #0c0266; } .instagram:hover { color: #e66465; } .hover-item:hover { background-image: linear-gradient(to right, #fd0101 0%, #0c0266 100%); -moz-background-image: -moz-linear-gradient(to right, #fd0101 0%, #0c0266 100%); -webkit-background-image: -webkit-linear-gradient(to right, #fd0101 0%, #0c0266 100%); color: #fff; box-shadow: 0 0 20px rgba(0,0,0,0.5); -webkit-box-shadow: 0 0 20px rgba(0,0,0,0.5); -moz-box-shadow: 0 0 20px rgba(0,0,0,0.5); } .hover-item:hover em { font-weight: bold; } .gif { width: 60%; }
26.952381
96
0.633392
e33b10bce196d4e6afc8b0a7cb97457dbe183a6b
571
rb
Ruby
lib/handlers/json.rb
michalkoczwara/intrigue-core
70036551215d5d125112e320ba71e28aeb5ab445
[ "BSD-3-Clause" ]
null
null
null
lib/handlers/json.rb
michalkoczwara/intrigue-core
70036551215d5d125112e320ba71e28aeb5ab445
[ "BSD-3-Clause" ]
null
null
null
lib/handlers/json.rb
michalkoczwara/intrigue-core
70036551215d5d125112e320ba71e28aeb5ab445
[ "BSD-3-Clause" ]
null
null
null
module Intrigue module Handler class Json < Intrigue::Handler::Base def self.type "json" end def process(task_result, options) ### THIS IS A HACK TO GENERATE A FILENAME ... think this through a bit more shortname = "#{task_result.task_name}-#{task_result.base_entity.name.gsub("/","")}" # Write it out File.open("#{$intrigue_basedir}/results/#{shortname}.json", "w+") do |file| file.flock(File::LOCK_EX) file.write(JSON.pretty_generate(JSON.parse(task_result.export_json))) end end end end end
23.791667
89
0.646235
dbaf9cc0c397661def5fbe7810903dcd6de89072
1,470
php
PHP
src/app/Http/routes.php
shadowbone/api.onex
9b12432ee8a7f127e2807ce360b87256f62a1761
[ "MIT" ]
null
null
null
src/app/Http/routes.php
shadowbone/api.onex
9b12432ee8a7f127e2807ce360b87256f62a1761
[ "MIT" ]
null
null
null
src/app/Http/routes.php
shadowbone/api.onex
9b12432ee8a7f127e2807ce360b87256f62a1761
[ "MIT" ]
null
null
null
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It is a breeze. Simply tell Lumen the URIs it should respond to | and give it the Closure to call when that URI is requested. | */ $app->get('/soal','ProjectsController@data'); $app->get('/',function(){ return \App\MasterSoalModel::create([ 'name' => 'Agama', 'keterangan' => 'ini adalah buku Agama', 'type' => 'Pengantar Agama Islam' ]); }); $app->get('/excel', function () use ($app) { Excel::create('Laravel Excel', function($excel) { $excel->sheet('Excel sheet', function($sheet) { $sheet->setOrientation('landscape'); }); })->export('xls'); }); $app->post('auth/login', 'AuthController@postLogin'); $app->group(['middleware' => 'auth:api'], function($app) { $app->get('/ahay', function() { return response()->json(['status' => true],200); }); }); $app->group(['prefix' => 'soal','middleware' => 'auth:api'],function($app){ $app->put('update','App\Http\Controllers\ProjectsController@update'); $app->delete('delete','App\Http\Controllers\ProjectsController@delete'); $app->post('create','App\Http\Controllers\ProjectsController@create'); $app->get('data','App\Http\Controllers\ProjectsController@data'); });
31.276596
79
0.561224
79a5a6e41bea343208e87ef1ff5652a402456fde
1,296
php
PHP
console/migrations/m211014_030420_alter_table_orders_remove_created_at_foreign_key.php
masterplan1/ishop
273877089bfafb48e848f8d1fc5f2b5e21265119
[ "BSD-3-Clause" ]
null
null
null
console/migrations/m211014_030420_alter_table_orders_remove_created_at_foreign_key.php
masterplan1/ishop
273877089bfafb48e848f8d1fc5f2b5e21265119
[ "BSD-3-Clause" ]
null
null
null
console/migrations/m211014_030420_alter_table_orders_remove_created_at_foreign_key.php
masterplan1/ishop
273877089bfafb48e848f8d1fc5f2b5e21265119
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\db\Migration; /** * Class m211014_030420_alter_table_orders_remove_created_at_foreign_key */ class m211014_030420_alter_table_orders_remove_created_at_foreign_key extends Migration { /** * {@inheritdoc} */ public function safeUp() { //drops foreign key for table `{{%user}}` $this->dropForeignKey( '{{%fk-orders-created_at}}', '{{%orders}}' ); //drops index for column `created_at` $this->dropIndex( '{{%idx-orders-created_at}}', '{{%orders}}' ); } /** * {@inheritdoc} */ public function safeDown(){ } // drops foreign key for table `{{%user}}` // $this->dropForeignKey( // '{{%fk-orders-created_at}}', // '{{%orders}}' // ); // drops index for column `created_at` // $this->dropIndex( // '{{%idx-orders-created_at}}', // '{{%orders}}' // ); /* // Use up()/down() to run migration code without a transaction. public function up() { } public function down() { echo "m211014_030420_alter_table_orders_remove_created_at_foreign_key cannot be reverted.\n"; return false; } */ }
21.245902
101
0.525463
07789268b494141562dc5f0d880dad0cb908fc71
364
css
CSS
public/mars/web-base/widgets/streetscape/view.css
2015lalala/noiCheck
0cc8d946023c34980f30faba566ecd70a15d1f86
[ "MIT" ]
null
null
null
public/mars/web-base/widgets/streetscape/view.css
2015lalala/noiCheck
0cc8d946023c34980f30faba566ecd70a15d1f86
[ "MIT" ]
4
2021-03-09T04:23:53.000Z
2022-02-26T11:01:40.000Z
public/mars/web-base/widgets/streetscape/view.css
2015lalala/noiCheck
0cc8d946023c34980f30faba566ecd70a15d1f86
[ "MIT" ]
2
2020-04-21T05:36:06.000Z
2020-12-09T08:17:23.000Z
/* 2017-9-28 13:40:41 | 修改 木遥(QQ:346819890) */ .streetscapeBar { position: absolute; right: 5px; top: 5px; z-index: 19910601; height: 50px; padding: 5px 10px 5px 10px; font-size: 14px; background-color: #ffffff; border-radius: 5px; } .dark .streetscapeBar { color: #ffffff; background-color: rgba(35, 72, 72, 0.6); }
20.222222
46
0.607143
6740b34e6ea00228ba3a4bcaa75c18a4b246e36f
1,421
rs
Rust
mapf/src/trace.rs
open-rmf/mapf
b0d99523d3514d3e6aedc819d33bb763e878bf6a
[ "Apache-2.0" ]
3
2022-03-22T16:34:51.000Z
2022-03-24T01:35:00.000Z
mapf/src/trace.rs
open-rmf/mapf
b0d99523d3514d3e6aedc819d33bb763e878bf6a
[ "Apache-2.0" ]
1
2022-03-22T16:48:39.000Z
2022-03-22T16:48:39.000Z
mapf/src/trace.rs
open-rmf/mapf
b0d99523d3514d3e6aedc819d33bb763e878bf6a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2022 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ pub trait Trace<Node>: Default { fn expanded_from(&mut self, node: &Node); fn expanded_to(&mut self, node: &Node); fn solution_found_from(&mut self, node: &Node); } #[derive(Default, Debug)] pub struct NoTrace; impl<N> Trace<N> for NoTrace { fn expanded_from(&mut self, _: &N) { } fn expanded_to(&mut self, _: &N) { } fn solution_found_from(&mut self, _: &N) { } } #[derive(Default)] pub struct TerminalTrace; impl<N: std::fmt::Debug> Trace<N> for TerminalTrace { fn expanded_from(&mut self, node: &N) { println!(" - Expanded from {:?}", node); } fn expanded_to(&mut self, node: &N) { println!(" > Expanded to {:?}", node); } fn solution_found_from(&mut self, node: &N) { println!("Solution found from {:?}", node); } }
28.42
75
0.659395
daa9a81694a773067f422784eb3418106fe08b4a
1,029
php
PHP
resources/views/servey.blade.php
sonthth1903012/Laravel
b6746a08b9a28494676722ceb73bb3a42ab769c7
[ "MIT" ]
null
null
null
resources/views/servey.blade.php
sonthth1903012/Laravel
b6746a08b9a28494676722ceb73bb3a42ab769c7
[ "MIT" ]
null
null
null
resources/views/servey.blade.php
sonthth1903012/Laravel
b6746a08b9a28494676722ceb73bb3a42ab769c7
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>List student</title> <link rel="stylesheet" href="{{asset('css/bootstrap.min.css')}}"> </head> <body> <div class="container"> <h3 style="text-decoration: underline; text-transform: uppercase">Servey</h3> <div class="py-4"> <a href="{{url('/add-servey')}}" class="btn btn-outline-danger">Add Servey</a> </div> <table class="table tables-dark"> <thead> <th>ID</th> <th>Name</th> <th>Email</th> <th>Telephone</th> <th>Feddback</th> </thead> <tbody> @foreach($list as $s) <tr> <td>{{$s->id}}</td> <td>{{$s->name}}</td> <td>{{$s->email}}</td> <td>{{$s->telephone}}</td> <td>{{$s->feedback}}</td> </tr> @endforeach </tbody> </table> </div> </body> </html>
25.725
86
0.483965
eb7c0a5905e71aa80dd5eb12e459c7ecb88e7f0a
20,239
css
CSS
public/css/verde-gourmet.webflow.css
VerdeGourmet/VG_20180704_MidoriNoYasai_Portal
4eca87617f01065dd52ad08d5a8a6dd540dd3f21
[ "MIT" ]
null
null
null
public/css/verde-gourmet.webflow.css
VerdeGourmet/VG_20180704_MidoriNoYasai_Portal
4eca87617f01065dd52ad08d5a8a6dd540dd3f21
[ "MIT" ]
null
null
null
public/css/verde-gourmet.webflow.css
VerdeGourmet/VG_20180704_MidoriNoYasai_Portal
4eca87617f01065dd52ad08d5a8a6dd540dd3f21
[ "MIT" ]
null
null
null
.hero { position: static; width: 100%; height: 100vh; background-image: url('../images/HeroLow.jpg'); background-position: 50% 58%; background-size: auto; } .titulo { position: absolute; left: 0px; top: 30%; right: 0px; text-align: center; } .titulo1 { font-family: Code, sans-serif; color: #fff; font-size: 52px; font-weight: 300; text-align: center; } .navbarlogo { width: 25%; margin-right: 30%; } .navbar { position: fixed; left: 0px; top: 0px; right: 0px; background-color: hsla(0, 0%, 100%, .7); } .navmenu { background-color: hsla(0, 0%, 100%, .8); } .menubutton { margin-left: 30%; } .navlink { display: block; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 16px; font-weight: 400; text-align: center; } .navbaricon { color: #ba3e27; } .secion1 { position: relative; z-index: 1; text-align: center; } .section2paragraph { padding-top: 50px; padding-right: 30%; padding-left: 30%; font-family: Sansation, sans-serif; color: #fff; font-size: 14px; text-align: center; } .section0 { display: none; height: 100vh; } .descubrebutton { margin-top: 50px; padding-right: 45px; padding-left: 45px; border: 2px solid #fff; background-color: transparent; font-family: Code, sans-serif; color: #fff; font-size: 20px; font-weight: 700; letter-spacing: 4px; } .toppingbox { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .textointro { position: absolute; left: 25%; top: 40%; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 3.3vw; font-style: italic; } .textointro2 { position: absolute; left: 25%; top: 47%; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 1.6vw; font-weight: 300; } .textointro3 { position: absolute; left: 25%; top: 55%; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 1.6vw; font-weight: 300; } .scroll { position: absolute; left: 48%; top: 64%; } .secciontitulo { position: relative; padding-top: 53px; background-color: #fffbe6; } .productossecciontext { margin-top: 0px; margin-bottom: 0px; font-family: Code, sans-serif; color: #ba3e27; font-size: 48px; } .productossecciontext.precio { color: #5ab447; } .ensaladastituloparrafo { margin-bottom: 10px; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 14px; font-style: normal; font-weight: 400; } .ensaladastituloparrafo.precioparrafo { color: #5ab447; } .ensaladastituloparrafo.jugostitulo { font-size: 13px; } .diagramacionensaladas { position: relative; background-color: #f4f4f4; } .columnaensalada { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; margin-bottom: 10px; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-flex-wrap: nowrap; -ms-flex-wrap: nowrap; flex-wrap: nowrap; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; text-align: center; } .imagenens { width: 50%; border-radius: 1000px; } .nombreensalada { margin-top: 5px; margin-bottom: 10px; font-family: Code, sans-serif; color: #5ab447; font-size: 24px; font-weight: 700; } .ingredientes { padding-right: 0px; padding-left: 0px; font-family: Sansation, sans-serif; color: #5ab447; font-size: 12px; } .productosseccion { margin-top: 40px; margin-right: 5%; margin-left: 5%; border-bottom: 1px solid #ba3e27; text-align: center; } .productosseccion.jugos { border-bottom-style: none; } .columnatopping { display: inline-block; width: 15%; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; text-align: center; } .imagentopping { border-radius: 500px; } .nombretopping { font-family: Code, sans-serif; color: #ba3e27; font-size: 12px; line-height: 14px; } .nombreaderezo { margin-top: 15px; margin-bottom: 10px; font-family: Code, sans-serif; color: #5ab447; font-size: 20px; line-height: 24px; } .nombreaderezo.jugonombre { margin-bottom: 0px; color: #ba3e27; font-size: 24px; } .linkeventos { position: fixed; left: 0px; top: 0px; bottom: 0px; z-index: 2; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; margin-left: 20px; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .imagenevento { border: 2px solid #5ab447; border-radius: 500px; background-color: transparent; -webkit-transition: background-color 500ms ease; transition: background-color 500ms ease; } .imagenevento:hover { background-color: #82d870; } .ingedientesaderezos { font-family: Sansation, sans-serif; color: #5ab447; font-size: 12px; line-height: 18px; } .ingedientesaderezos.jugosing { font-size: 14px; } .spacersection { position: relative; height: 30px; background-color: #fffbe6; } .spacer { height: 1px; margin-left: 35%; background-color: #ba3e27; } .secciontoppings { position: relative; padding: 30px 5%; background-color: #fffbe6; } .titulotopping { display: inline-block; } .navcont { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .columnapedido { background-color: #5ab447; } .pedidossection { height: 100vh; } .cuantocuesta { position: relative; display: none; border-top: 2px solid #5ab447; background-color: #fffbe6; } .donde { position: relative; padding: 50px 5%; background-color: #fffbe6; } .pedidos { position: relative; padding-top: 50px; background-color: #fffbe6; } .columnaprecio { padding: 2% 12%; } .preciotitulobox { padding-top: 80px; padding-left: 5%; } .raya { width: 40px; height: 10px; margin-bottom: 10px; border-bottom: 3px solid #5ab447; } .dondetitulo { margin-bottom: 15px; font-family: Code, sans-serif; color: #5ab447; text-align: right; } .dondeparrafo { margin-bottom: 15px; font-family: Sansation, sans-serif; color: grey; font-style: italic; text-align: right; } .dondelink { display: inline-block; margin-top: 10px; margin-right: 10px; font-family: Sansation, sans-serif; color: #ba3e27; font-size: 16px; font-style: italic; font-weight: 700; text-decoration: none; } .dondecolumna { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-pack: end; -webkit-justify-content: flex-end; -ms-flex-pack: end; justify-content: flex-end; -webkit-box-align: end; -webkit-align-items: flex-end; -ms-flex-align: end; align-items: flex-end; } .dondecolumna.bottom { -webkit-box-pack: end; -webkit-justify-content: flex-end; -ms-flex-pack: end; justify-content: flex-end; } .donderow { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: end; -webkit-align-items: flex-end; -ms-flex-align: end; align-items: flex-end; } .dondelinkblock { margin-bottom: 15px; text-align: right; text-decoration: none; } .footer { position: relative; padding-top: 50px; padding-bottom: 50px; background-color: #5ab447; } .footercontainer { text-align: center; } .footerlinea { display: inline-block; width: 44%; height: 10px; border-bottom: 2px solid #fffbe6; } .footerensaladabox { display: inline-block; width: 12%; text-align: center; } .footerensalada { margin-right: 10px; margin-left: 10px; } .footertexto { font-family: Sansation, sans-serif; color: #fffbe6; font-size: 14px; font-weight: 400; text-align: center; } .footerlink { font-family: Sansation, sans-serif; color: #fffbe6; font-weight: 300; text-decoration: none; } .footerfb { margin-right: 20px; margin-left: 5px; } .footerig { margin-right: 20px; margin-left: 5px; } .footerwa { margin-left: 5px; } .pedidoscol { position: relative; padding-right: 0px; padding-left: 0px; } .pedidostitulo { position: absolute; left: 0px; top: 0px; right: 0px; width: 60%; height: 30%; margin-top: 35%; margin-left: 20%; text-align: center; } .pedidostexto { margin-top: 15px; font-family: Code, sans-serif; color: #fff; font-size: 32px; font-weight: 700; text-align: center; letter-spacing: 1px; } .pedidosparrafo { display: inline-block; margin-top: 30px; font-family: Sansation, sans-serif; color: #fff; font-size: 12px; line-height: 14px; font-style: italic; } .pedidostitulo2 { font-family: Sansation, sans-serif; color: #fff; font-size: 20px; font-weight: 400; text-align: center; } .pedidosboton { border: 1px solid #fff; background-color: transparent; -webkit-transition: all 300ms ease; transition: all 300ms ease; font-family: Code, sans-serif; font-size: 22px; letter-spacing: 2px; } .pedidosboton:hover { border-color: #5ab447; background-color: #5ab447; } .preciotitulo { display: block; margin-top: 0px; margin-bottom: 0px; font-family: Code, sans-serif; color: #666; font-size: 28px; } .preciosubtexto { display: block; font-family: Sansation, sans-serif; color: #ba3e27; } .herosection { height: 80%; } .heroslider { height: 100%; } .body { height: 100%; } .heroslide1 { position: relative; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; background-image: url('../images/Verde-Gourmet-Ensaladas-Verduras-Bogota-2.jpg'); background-position: 50% 50%; background-size: cover; } .heroslider1texto { position: absolute; left: 20%; top: 43%; right: 0px; font-family: Sansation, sans-serif; color: #fff; font-size: 36px; font-weight: 300; text-align: left; } .heroslider1texto.subtexto { top: 50%; font-weight: 700; } .herosliderarrow { color: transparent; } .heroslide2 { background-image: url('../images/Verde-Gourmet-Ensaladas-Verduras-Bogota.jpg'); background-position: 50% 50%; background-size: cover; } .menuensaladas { padding-top: 35px; padding-bottom: 35px; -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; background-color: #f4f4f4; } .menupreciosbox { display: inline-block; width: 50%; margin-top: 20px; margin-bottom: 20px; border-bottom: 1px solid #ba3e27; } .menupreciosimagen { width: 100%; } .footersection { position: fixed; left: 0px; right: 0px; bottom: 0px; z-index: 2; height: 10%; background-image: -webkit-linear-gradient(90deg, #5ab447, rgba(90, 180, 71, 0)); background-image: linear-gradient(0deg, #5ab447, rgba(90, 180, 71, 0)); } .navbarsection { position: fixed; left: 0px; top: 0px; right: 0px; height: 60px; padding-right: 5%; padding-left: 5%; background-color: hsla(0, 0%, 100%, .8); } .navbarcont { height: 80%; margin-top: 6px; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; } .navbarbrand { height: 100%; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navmenucont { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; height: 100%; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbarlink { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; height: 100%; padding: 0px 15px; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; font-family: Sansation, sans-serif; color: #5ab447; font-size: 16px; font-weight: 400; } .navbarlink.invisible { display: none; } .navbarimg { height: 100%; } .navbarwathsappcont { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; height: 100%; margin-right: 80px; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .navbarwhatsapptexto { margin-top: 0px; margin-bottom: 0px; margin-left: 6px; font-family: Sansation, sans-serif; color: #5ab447; font-size: 21px; font-weight: 400; } .ataseccion { padding-right: 5%; padding-bottom: 20px; padding-left: 5%; background-color: #f4f4f4; } .atabox { display: inline-block; width: 50%; margin-bottom: 30px; } .jugoslogo { width: 25%; margin-top: 10px; margin-bottom: 10px; } html.w-mod-js *[data-ix="scroll-down-opacity"] { opacity: 0; } @media (max-width: 991px) { .navbarlogo { width: 40%; } .navlink { font-size: 14px; } .navbarmenubutton { padding: 12px; } } @media (max-width: 767px) { .hero { height: 800px; } .titulo { top: 15%; } .titulo1 { font-size: 38px; } .navbarlogo { width: 50%; margin-right: 0%; } .menubutton { margin-left: 0%; background-color: transparent; } .section2paragraph { padding-right: 15%; padding-left: 15%; } .section0 { height: 800px; } .toppingbox { display: block; width: 100%; } .textointro { left: 8%; top: 33%; font-size: 5vw; } .textointro2 { left: 8%; top: 42%; font-size: 3vw; } .textointro3 { left: 8%; font-size: 3vw; } .productoscont { display: block; width: 100%; margin-left: 0%; } .productossecciontext.topping { display: inline-block; width: 100%; font-size: 38px; } .ensaladastituloparrafo { font-size: 12px; } .ensaladastituloparrafo.toppingparrafo { display: inline-block; font-size: 12px; } .diagramacionensaladas { padding-top: 1px; } .imagenens { width: 50%; } .ingredientes { font-size: 14px; } .linea { margin-left: 25px; } .productosseccion { display: block; } .columnatopping { width: 50%; } .imagentopping { width: 50%; } .nombretopping { font-size: 11px; } .nombreaderezo { font-size: 18px; } .spacer { margin-left: 0%; } .secciontoppings { padding-right: 1%; padding-left: 1%; } .titulotopping { display: block; width: 100%; text-align: center; } .columnaprecio { padding: 5% 5% 20%; } .preciotitulobox { padding-top: 20px; } .dondecolumna { margin-top: 20px; padding-right: 0px; padding-left: 0px; } .donderow { -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .footerlinea { width: 30%; border-bottom-width: 1px; } .footerensaladabox { width: 20%; } .footerensalada { height: 40px; } .footertexto { font-size: 11px; } .footerlink { font-size: 12px; } .footerfb { margin-left: 2px; } .footerig { margin-left: 2px; } .footerwa { margin-left: 2px; } .pedidostexto { font-size: 30px; } .preciotitulo { font-size: 24px; } .heroslider1texto { left: 5%; font-size: 24px; } .menupreciosbox { width: 100%; } .navbarsection { padding-right: 2%; padding-left: 2%; } .navbarbrand { padding-left: 0px; } .atabox { width: 100%; } .aderezosrow { display: inline-block; width: 50%; } .jugoslogo { width: 50%; } } @media (max-width: 479px) { .navbarlogo { width: 70%; } .menubutton.w--open { background-color: transparent; } .section2paragraph { padding-right: 4%; padding-left: 4%; } .toppingbox { text-align: center; } .textointro { left: 2%; top: 24%; font-size: 7vw; } .textointro2 { left: 2%; top: 40%; font-size: 3.3vw; line-height: 21px; text-align: left; } .textointro3 { left: 2%; font-size: 3.3vw; } .productossecciontext { font-size: 3em; } .ensaladastituloparrafo.toppingparrafo { display: block; width: 100%; padding-right: 5%; padding-left: 5%; } .columnaensalada { padding-right: 0px; padding-left: 0px; } .linea { margin-left: 10px; } .columnatopping { display: inline-block; } .imagentopping { width: 70%; } .titulotopping { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; text-align: center; } .navcont { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .columnaprecio { padding-top: 1%; padding-right: 1%; padding-left: 1%; } .footerensaladabox { width: 30%; } .footerlink { font-size: 11px; } .footerfb { margin-right: 15px; } .footerig { margin-right: 15px; } .pedidostitulo { width: 70%; margin-top: 20%; margin-left: 15%; } .pedidostexto { font-size: 22px; } .pedidostitulo2 { font-size: 14px; } .pedidosboton { font-size: 18px; } .preciotitulo { font-size: 28px; } .preciosubtexto { font-size: 11px; } .navbarbrand { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } .navbarimg { height: 60%; } } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Bold_5.ttf') format('truetype'); font-weight: 700; font-style: normal; } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Light_5.ttf') format('truetype'); font-weight: 300; font-style: normal; } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Italic_4.ttf') format('truetype'); font-weight: 400; font-style: italic; } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Bold_Italic_4.ttf') format('truetype'); font-weight: 700; font-style: italic; } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Light_Italic_4.ttf') format('truetype'); font-weight: 300; font-style: italic; } @font-face { font-family: 'Sansation'; src: url('../fonts/Sansation_Regular_4.ttf') format('truetype'); font-weight: 400; font-style: normal; } @font-face { font-family: 'Code'; src: url('../fonts/CODE-Bold_1.otf') format('opentype'); font-weight: 700; font-style: normal; } @font-face { font-family: 'Code'; src: url('../fonts/CODE-Light_1.otf') format('opentype'); font-weight: 300; font-style: normal; }
17.268771
83
0.643263
52539b2ab6c13aca34fcbeedb59bc9fdf632c6af
135
kt
Kotlin
src/commonMain/kotlin/org/guiVista/gui/widget/display/LevelBarEvent.kt
gui-vista/guivista-gui
484e1e8437a3d57faaf5667489d622402fe7be01
[ "Apache-2.0" ]
null
null
null
src/commonMain/kotlin/org/guiVista/gui/widget/display/LevelBarEvent.kt
gui-vista/guivista-gui
484e1e8437a3d57faaf5667489d622402fe7be01
[ "Apache-2.0" ]
null
null
null
src/commonMain/kotlin/org/guiVista/gui/widget/display/LevelBarEvent.kt
gui-vista/guivista-gui
484e1e8437a3d57faaf5667489d622402fe7be01
[ "Apache-2.0" ]
null
null
null
package org.guiVista.gui.widget.display public object LevelBarEvent { public const val offsetChanged: String = "offset-changed" }
22.5
61
0.777778
444c4b7c36e28a58ff7465104c8e55466ccb9599
3,242
py
Python
torchqf/model/factor_model.py
simaki/torchqf
e4dfd154c62ccd858847048f77d8c2f82924ae80
[ "BSD-3-Clause" ]
7
2021-05-18T17:03:10.000Z
2021-12-01T07:58:41.000Z
torchqf/model/factor_model.py
vishalbelsare/torchqf
e4dfd154c62ccd858847048f77d8c2f82924ae80
[ "BSD-3-Clause" ]
27
2021-05-18T03:54:17.000Z
2022-01-31T15:16:16.000Z
torchqf/model/factor_model.py
vishalbelsare/torchqf
e4dfd154c62ccd858847048f77d8c2f82924ae80
[ "BSD-3-Clause" ]
3
2021-07-13T12:56:12.000Z
2021-12-26T23:00:06.000Z
from typing import TypeVar import torch from torch import Tensor from torch.nn import Module T = TypeVar("T") class FactorModel(Module): """Factor model. Attributes: beta (Tensor): Created after `fit`. Shape: - input: :math:`(*, A, T)` :math:`A` is the number of assets. :math:`T` is the number of time steps. - output: :math:`(*, A, T)` :math:`A` is the number of assets. :math:`T` is the number of time steps. - factor: :math:`(*, F, T)` :math:`F` is the number of assets. :math:`T` is the number of time steps. - beta: :math:`(F, A)` :math:`F` is the number of factor. :math:`A` is the number of assets. Examples: >>> import torchqf >>> from torchqf.stochastic import generate_brownian >>> _ = torch.manual_seed(42) >>> input = generate_brownian((2, 5), 0.1) >>> factor = generate_brownian((2, 5), 0.1) >>> fm = FactorModel().fit(input, factor) >>> fm(input, factor) tensor([[ 0.0032, -0.0023, -0.0046, 0.0138, -0.0099], [-0.0234, 0.0157, -0.0017, -0.0052, 0.0025]]) The method `fit_forward` fits and forwards at once. >>> fm.fit_forward(input, factor) tensor([[ 0.0032, -0.0023, -0.0046, 0.0138, -0.0099], [-0.0234, 0.0157, -0.0017, -0.0052, 0.0025]]) """ def fit(self: T, input: Tensor, factor: Tensor, enable_grad: bool = False) -> T: """Fit the model using the asset returns (`input`) and the factor returns (`factor`). Args: input (Tensor): Returns of assets. factor (Tensor): Returns of factors. enable_grad (bool, default=False): Flag whether to enable grad (True), or disable (False). Returns: FactorModel: Returns `self`. Shape: input : :math:`(*, A, T)` :math:`A` is the number of assets. :math:`T` is the number of time steps. factor : :math:`(*, F, T)` :math:`F` is the number of assets. :math:`T` is the number of time steps. beta : :math:`(*, F, A)` :math:`F` is the number of factors. :math:`A` is the number of assets. """ assert input.size(-1) == factor.size(-1), "numbers of time steps do not match" assert input.ndim == 2, "not supported" assert factor.ndim == 2, "not supported" with torch.set_grad_enabled(mode=enable_grad): tensor_x = factor.t() # shape : (T, F) tensor_y = input.transpose(-2, -1) # shape : (T, A) # Compute beta : (F, T) @ (T, A) = (F, A) self.beta = torch.mm(torch.linalg.pinv(tensor_x), tensor_y) return self def forward(self, input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor: factor_return = torch.mm(self.beta.t(), factor) # shape : (*, A, T) return input - factor_return def fit_forward(self, input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor: return self.fit(input, factor, enable_grad=True)(input, factor)
34.489362
93
0.534855
ec5e03f31ddf519345a4e3b3fdc7a8b6d39c88f4
1,298
swift
Swift
ios/Common/React/MixerReactModule.swift
Freeway1979/ReactNativeApp
e3ccf1b54c3d53ef94e62563a990e244f0fd08b2
[ "MIT" ]
null
null
null
ios/Common/React/MixerReactModule.swift
Freeway1979/ReactNativeApp
e3ccf1b54c3d53ef94e62563a990e244f0fd08b2
[ "MIT" ]
null
null
null
ios/Common/React/MixerReactModule.swift
Freeway1979/ReactNativeApp
e3ccf1b54c3d53ef94e62563a990e244f0fd08b2
[ "MIT" ]
null
null
null
// // MixerReactModule.swift // ReactNativeApp // // Created by Andy Liu on 2020/9/19. // Copyright © 2020 Study. All rights reserved. // import Foundation class MixerReactModule: NSObject { static let shared = MixerReactModule() var bridge: RCTBridge? func createBridgeIfNeeded() -> RCTBridge { if bridge == nil { bridge = RCTBridge(delegate: self, launchOptions: nil) } return bridge! } func viewForModule(_ moduleName: String, initProps: [String: Any]?) -> RCTRootView { let viewBridge = createBridgeIfNeeded() let rootView = RCTRootView(bridge: viewBridge, moduleName: moduleName, initialProperties: initProps) return rootView } } extension MixerReactModule: RCTBridgeDelegate { func sourceURL(for bridge: RCTBridge!) -> URL! { #if DEBUG print("running in debug mode") return RCTBundleURLProvider.sharedSettings()?.jsBundleURL(forBundleRoot: "index", fallbackResource: "main") #else print("running in release mode") return Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } }
28.217391
91
0.590139
a00591089dc3afb2e0e6546f440e08f652868b71
1,013
ts
TypeScript
app/core/service/TopicService.ts
thonatos/tegg-cnode
f24cb4226e644e97872a7e062c54bf9430ce7258
[ "MIT" ]
1
2022-01-10T10:33:57.000Z
2022-01-10T10:33:57.000Z
app/core/service/TopicService.ts
thonatos/tegg-cnode
f24cb4226e644e97872a7e062c54bf9430ce7258
[ "MIT" ]
1
2022-01-23T07:47:11.000Z
2022-01-23T07:47:11.000Z
app/core/service/TopicService.ts
thonatos/tegg-cnode
f24cb4226e644e97872a7e062c54bf9430ce7258
[ "MIT" ]
1
2022-01-18T12:57:32.000Z
2022-01-18T12:57:32.000Z
import { AccessLevel, ContextProto, Inject } from '@eggjs/tegg'; import { AbstractService } from './AbstractService'; import { Topic } from '@/app/model/Topic'; import { TopicRepository } from '../../repository/TopicRepository'; import { FilterQuery, QueryOptions } from 'mongoose'; const defaltProjection = []; @ContextProto({ accessLevel: AccessLevel.PUBLIC, }) export class TopicService extends AbstractService { @Inject() private readonly topicRepository: TopicRepository; async getById(id: string, projection?: any) { return this.topicRepository.read(id, projection || defaltProjection); } async create(model: Partial<Topic>) { return this.topicRepository.create(model); } async update(id: string, model: Partial<Topic>, filter?: any) { return this.topicRepository.update(id, model, filter); } async query(query: FilterQuery<Topic>, projection?: any, options?: QueryOptions) { return this.topicRepository.query(query, projection || defaltProjection, options); } }
31.65625
86
0.728529
f52e6164147c5029e3ef2d61fe4b8ef3bfab0333
4,172
go
Go
vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go
erikvanbrakel/terraform-provider-cloudconformity
81ab817a6dc1ce7e3b414f4861df205b8764974a
[ "MIT" ]
5
2018-07-15T09:55:08.000Z
2019-03-06T03:47:14.000Z
vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go
erikvanbrakel/terraform-provider-cloudconformity
81ab817a6dc1ce7e3b414f4861df205b8764974a
[ "MIT" ]
2
2018-10-17T15:39:50.000Z
2019-03-06T04:12:03.000Z
vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go
erikvanbrakel/terraform-provider-cloudconformity
81ab817a6dc1ce7e3b414f4861df205b8764974a
[ "MIT" ]
null
null
null
package plugin import ( "net/rpc" "github.com/hashicorp/go-plugin" "github.com/hashicorp/terraform/terraform" ) // ResourceProvisionerPlugin is the plugin.Plugin implementation. type ResourceProvisionerPlugin struct { F func() terraform.ResourceProvisioner } func (p *ResourceProvisionerPlugin) Server(b *plugin.MuxBroker) (interface{}, error) { return &ResourceProvisionerServer{Broker: b, Provisioner: p.F()}, nil } func (p *ResourceProvisionerPlugin) Client( b *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { return &ResourceProvisioner{Broker: b, Client: c}, nil } // ResourceProvisioner is an implementation of terraform.ResourceProvisioner // that communicates over RPC. type ResourceProvisioner struct { Broker *plugin.MuxBroker Client *rpc.Client } func (p *ResourceProvisioner) Validate(c *terraform.ResourceConfig) ([]string, []error) { var resp ResourceProvisionerValidateResponse args := ResourceProvisionerValidateArgs{ Config: c, } err := p.Client.Call("Plugin.Validate", &args, &resp) if err != nil { return nil, []error{err} } var errs []error if len(resp.Errors) > 0 { errs = make([]error, len(resp.Errors)) for i, err := range resp.Errors { errs[i] = err } } return resp.Warnings, errs } func (p *ResourceProvisioner) Apply( output terraform.UIOutput, s *terraform.InstanceState, c *terraform.ResourceConfig) error { id := p.Broker.NextId() go p.Broker.AcceptAndServe(id, &UIOutputServer{ UIOutput: output, }) var resp ResourceProvisionerApplyResponse args := &ResourceProvisionerApplyArgs{ OutputId: id, State: s, Config: c, } err := p.Client.Call("Plugin.Apply", args, &resp) if err != nil { return err } if resp.Error != nil { err = resp.Error } return err } func (p *ResourceProvisioner) Stop() error { var resp ResourceProvisionerStopResponse err := p.Client.Call("Plugin.Stop", new(interface{}), &resp) if err != nil { return err } if resp.Error != nil { err = resp.Error } return err } func (p *ResourceProvisioner) Close() error { return p.Client.Close() } type ResourceProvisionerValidateArgs struct { Config *terraform.ResourceConfig } type ResourceProvisionerValidateResponse struct { Warnings []string Errors []*plugin.BasicError } type ResourceProvisionerApplyArgs struct { OutputId uint32 State *terraform.InstanceState Config *terraform.ResourceConfig } type ResourceProvisionerApplyResponse struct { Error *plugin.BasicError } type ResourceProvisionerStopResponse struct { Error *plugin.BasicError } // ResourceProvisionerServer is a net/rpc compatible structure for serving // a ResourceProvisioner. This should not be used directly. type ResourceProvisionerServer struct { Broker *plugin.MuxBroker Provisioner terraform.ResourceProvisioner } func (s *ResourceProvisionerServer) Apply( args *ResourceProvisionerApplyArgs, result *ResourceProvisionerApplyResponse) error { conn, err := s.Broker.Dial(args.OutputId) if err != nil { *result = ResourceProvisionerApplyResponse{ Error: plugin.NewBasicError(err), } return nil } client := rpc.NewClient(conn) defer client.Close() output := &UIOutput{Client: client} err = s.Provisioner.Apply(output, args.State, args.Config) *result = ResourceProvisionerApplyResponse{ Error: plugin.NewBasicError(err), } return nil } func (s *ResourceProvisionerServer) Validate( args *ResourceProvisionerValidateArgs, reply *ResourceProvisionerValidateResponse) error { warns, errs := s.Provisioner.Validate(args.Config) berrs := make([]*plugin.BasicError, len(errs)) for i, err := range errs { berrs[i] = plugin.NewBasicError(err) } *reply = ResourceProvisionerValidateResponse{ Warnings: warns, Errors: berrs, } return nil } func (s *ResourceProvisionerServer) Stop( _ interface{}, reply *ResourceProvisionerStopResponse) error { err := s.Provisioner.Stop() *reply = ResourceProvisionerStopResponse{ Error: plugin.NewBasicError(err), } return nil }
23.977011
90
0.710451
a378486dbf500859ef2484e96f69fdf50a919e72
2,725
java
Java
interpreter-backend/GuitarLanguage/src/com/zachl/objects/data/Chord.java
Ddg3/TabWriter
9447b5cb9a801163b4a35d2fb86ebdbcd2a71a82
[ "MIT" ]
null
null
null
interpreter-backend/GuitarLanguage/src/com/zachl/objects/data/Chord.java
Ddg3/TabWriter
9447b5cb9a801163b4a35d2fb86ebdbcd2a71a82
[ "MIT" ]
null
null
null
interpreter-backend/GuitarLanguage/src/com/zachl/objects/data/Chord.java
Ddg3/TabWriter
9447b5cb9a801163b4a35d2fb86ebdbcd2a71a82
[ "MIT" ]
null
null
null
package com.zachl.objects.data; import com.zachl.Constants; import java.util.*; import java.util.Map.Entry; public class Chord { protected Note root; protected Set<Integer> intervals; protected boolean hasOctave = false; protected int[] frets; protected Note[] notes = new Note[6]; private String name = ""; private Chord(Note root, Set<Integer> intervalSet, int[] frets){ this.root = root; this.intervals = intervalSet; this.frets = frets; for(int i = 0; i < notes.length; i++){ if(frets[i] == -1){ notes[i] = null; continue; } notes[i] = new Note(frets[i], i); } intervals.removeIf(o -> o == 0); if(intervals.size() != intervalSet.size()) hasOctave = true; int[] tempIntervals = new int[intervals.size()]; int i = 0; for(int interval : intervals){ tempIntervals[i] = interval; i++; } if(tempIntervals.length > 0) { outerLoop: for (Entry<String, int[]> entry : Constants.CHORDS.entrySet()) { for (i = 0; i < entry.getValue().length; i++) { if (tempIntervals[i] != entry.getValue()[i]) continue outerLoop; } name = entry.getKey(); } if (name.equalsIgnoreCase("")) { if (hasOctave) name = "Octave"; else name = Arrays.toString(tempIntervals); } } } public static Chord getChord(int[] notes){ Note root = null; Queue<Note> intervalNotes = new LinkedList<>(); for(int i = 0; i < notes.length; i++){ if(notes[i] != -1) { if (root == null) { root = new Note(notes[i], i); continue; } intervalNotes.add(new Note(notes[i], i)); } } Set<Integer> intervals = new TreeSet<>(); for(Note n : intervalNotes){ intervals.add(root.intervalTo(n)); } return new Chord(root, intervals, notes); } public int[] getFrets(){ return frets; } public int lastValidFret(){ int max = 0; for(int i = 0; i < frets.length; i++){ if(frets[i] != -1) max = i + 1; } return max; } public Note getRoot(){ return root; } public Note noteAtString(int stringIndex){ return notes[stringIndex]; } @Override public String toString(){ return root.notation + name; } }
29.301075
76
0.482569
a167d384a7480e2505e01c9f0bb2565335848628
349
ts
TypeScript
src/parser/utils/power.ts
ittedev/towait
ba488eeec3c464bd1dc001e2af8ddadf66435756
[ "MIT" ]
null
null
null
src/parser/utils/power.ts
ittedev/towait
ba488eeec3c464bd1dc001e2af8ddadf66435756
[ "MIT" ]
null
null
null
src/parser/utils/power.ts
ittedev/towait
ba488eeec3c464bd1dc001e2af8ddadf66435756
[ "MIT" ]
null
null
null
export const power = (operator: string): number => { switch (operator) { case '!': return 70 case '*': case '/': case '%': return 60 case '+': case '-': return 50 case '<': case '>': case '<=': case '>=': return 40 case '==': case '!=': case '===': case '!==': return 30 case '&&': return 20 case '||': return 10 } }
29.083333
59
0.487106
5ace1c1633d731e5b3b108c7c40e9bfa77815540
9,238
cs
C#
Reflector/XmlRenderer.cs
forki/Labs
403ee5e05fcd280bf8123b874a7e9bb2b6dc390c
[ "Apache-2.0" ]
1
2015-09-08T17:11:41.000Z
2015-09-08T17:11:41.000Z
Reflector/XmlRenderer.cs
forki/Labs
403ee5e05fcd280bf8123b874a7e9bb2b6dc390c
[ "Apache-2.0" ]
null
null
null
Reflector/XmlRenderer.cs
forki/Labs
403ee5e05fcd280bf8123b874a7e9bb2b6dc390c
[ "Apache-2.0" ]
1
2018-02-28T09:12:45.000Z
2018-02-28T09:12:45.000Z
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Xml.Linq; namespace Reflector { public class XmlRenderer : BaseRenderer, IRenderable { private Assembly _assemblySource; private List<Assembly> _assemblyTypes; public XmlRenderer(string sourcePath = "", bool includeSystemObjects = false) : base(sourcePath, includeSystemObjects) { _assemblyTypes = new List<Assembly>(); } public bool IncludeSystemObjects { get { return _includeSystemObjects; } } public string SourcePath { get { return _sourcePath; } } public Assembly AssemblySource { set { _assemblySource = value; } } public string Render(Type type, Type[] onlyTypes, string[] onlyMethods) { var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output"); if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath); var fileName = Path.Combine(basePath, type.FullName.Split('.').Last().Replace("Controller",string.Empty)) + ".xml"; if (File.Exists(fileName)) { File.Delete(fileName); } var methods = type.GetMethods().Where(x => x.CustomAttributes.Count() > 0); if (!_includeSystemObjects) { methods = methods.Where(m => !AppConfig.IncludeNetObjectMethods.Contains(m.Name)) .ToArray(); } if (null != onlyMethods && onlyMethods.Any()) { methods = methods.Where(m => onlyMethods.Contains(m.Name)).ToArray(); } Common.Extensions.TraceLog.Information("Rendering type {type} for file {fileName}", type, fileName); using (var writer = new StreamWriter(fileName)) { var root = new XElement("type", new XAttribute("name", type.FullName), new XElement("attributes", from ta in type.GetCustomAttributes(true) where ta != null select new XElement("attribute", new XAttribute("type", ta.GetType().FullName), GetAttributeValues(ta) ) ), new XElement("properties", from prop in type.GetProperties() .Where(x => !AppConfig.IncludeNetObjectProperties.Contains(x.Name)) select new XElement("property", new XAttribute("name", prop.Name), new XAttribute("type", prop.PropertyType.FullName) ) ), new XElement("methods", from m in methods select new XElement("method", new XAttribute("name", m.Name), new XAttribute("type", m.ReturnType.FullName), m.ReturnType.FullName.Contains("System.Collections") ? new XAttribute("itemType", m.ReturnType.GenericTypeArguments.First().FullName) : null, new XElement("attributes", from ma in m.GetCustomAttributes(true) where ma != null select new XElement("attribute", new XAttribute("type", ma.GetType().FullName), GetAttributeValues(ma) ) ), new XElement("parameters", from p in m.GetParameters() where p != null select new XElement("parameter", new XAttribute("name", p.Name), new XAttribute("type", p.ParameterType.FullName), new XAttribute("defaultValue", GetInstanceValue(p.ParameterType)), GetTypeProperties(p.ParameterType), new XElement("attributes", from pa in p.GetCustomAttributes(true) where pa != null select new XElement("attribute", new XAttribute("type", pa.GetType().FullName), GetAttributeValues(pa) ) ) ) ) ) ) ); if (!string.IsNullOrEmpty(_sourcePath)) { root.Add(new XAttribute("source", _sourcePath)); root.Add(new XElement("assemblies", from asm in _assemblyTypes .Where(x => x.FullName != type.Assembly.FullName) .Distinct() select new XElement("assembly", new XAttribute("name", asm.Location) ) )); } root.Save(writer); } return fileName; } public object GetAttributeValues(object attribute) { return new XElement("properties", from prop in attribute.GetType().GetProperties() .Where(x => !AppConfig.IncludeNetObjectProperties.Contains(x.Name)) let value = prop.GetValue(attribute) ?? string.Empty select new XElement("property", new XAttribute("name", prop.Name), new XAttribute("type", prop.PropertyType.FullName), new XAttribute("value", value.ToString()), GetAttributeValueProperties(prop.Name, value) ) ); } public object GetAttributeValueProperties(string properyName, object value) { if (properyName != "ResponseType" || null == value || string.IsNullOrEmpty(value.ToString()) || value.ToString().Split('.').Length <= 1) return null; return GetTypeProperties((Type)value, true); } public XElement GetTypeProperties(Type type, bool ignoreInnerProps = false) { if (type == null || type.IsPrimitive || type == typeof(string)) return null; if (!_assemblyTypes.Contains(type.Assembly)) { _assemblyTypes.Add(type.Assembly); } return new XElement("properties", from prop in type.GetProperties() let ptype = prop.PropertyType select new XElement("property", new XAttribute("name", prop.Name), new XAttribute("isArray", type.IsArray || prop.PropertyType.FullName.Contains("System.Collections") ), new XAttribute("type", prop.PropertyType.FullName), new XAttribute("defaultValue", GetInstanceValue(prop.PropertyType)), ignoreInnerProps ? null : prop.PropertyType.IsClass && prop.PropertyType.FullName != "System.String" && !prop.PropertyType.FullName.Contains("System.Collections") ? GetTypeProperties(prop.PropertyType) : GetTypeProperties(prop.PropertyType.GenericTypeArguments.FirstOrDefault()) ) ); } public string GetInstanceValue(Type type) { try { if (type == typeof(DateTime)) return DateTime.Now.Ticks.ToString(); return Activator.CreateInstance(type).ToString(); } catch(Exception) { return string.Empty; } } } }
39.478632
127
0.430071
2c4f42f57cba27e8e7f815d693fbc45340c3bb54
20,084
py
Python
ContainmentTrials/triangulate_topology.py
kasmith/cbmm-project-christmas
2543eaf9ab57f31d68fef8a9f5d629ce0116ca1a
[ "MIT" ]
null
null
null
ContainmentTrials/triangulate_topology.py
kasmith/cbmm-project-christmas
2543eaf9ab57f31d68fef8a9f5d629ce0116ca1a
[ "MIT" ]
null
null
null
ContainmentTrials/triangulate_topology.py
kasmith/cbmm-project-christmas
2543eaf9ab57f31d68fef8a9f5d629ce0116ca1a
[ "MIT" ]
null
null
null
from physicsTable import * from operator import itemgetter import sys import geometry import numpy as np # Constants for ease L = 101 R = -101 T = 103 B = -103 # Wall class for various operations class Wall(object): def __init__(self, p1, p2): self.l = p1[0] self.t = p1[1] self.r = p2[0] self.b = p2[1] self.grouped = False self.is_touching = [] # Returns boolean if two walls are touching # NOTE: Only works for auto-generated trials where pixels are aligned def touches(self, other): # Do they touch on the side? if self.r == other.l or self.l == other.r: # Make sure that there is some overlap (e.g., the bottom of other is not above the top, or top of other not below the bottom) return not (self.t > other.b or self.b < other.t) # Do they touch on the top or bottom? elif self.t == other.b or self.b == other.t: # Make sure there is some overlap return not (self.r < other.l or self.l > other.r) else: return False # Figures out all touching walls and adds them to internal state def get_touch_indices(self, others): tidxs = [i for i in range(len(others)) if self.touches(others[i])] self.is_touching = [others[i] for i in tidxs] return tidxs # Determines whether a point touches any side def touches_wall(self, point): return geometry.point_on_line(point, [self.l, self.t], [self.r, self.t]) or \ geometry.point_on_line(point, [self.r, self.t], [self.r, self.b]) or \ geometry.point_on_line(point, [self.r, self.b], [self.l, self.b]) or \ geometry.point_on_line(point, [self.l, self.b], [self.l, self.t]) def touches_top_wall(self, point): return geometry.point_on_line(point, [self.l, self.t], [self.r, self.t]) # From a given point, traverses clockwise on the inside to collect points def get_next_point_and_wall_and_dir(self, lastpt, dir): # Traveling along the bottom wall if dir == B: # Sort touching walls from left to right walls = sort_by_direction(self.is_touching, L) for w in walls: # Skip anything to the left of the last point if w.l > lastpt[0]: # The next wall is under the current one - this wall's top left is new, go down along the left wall if w.t == self.b: return (w.l, w.t), w, L # The next wall is adjacent to this one and continues along the bottom elif (self.r, self.b) == (w.l, w.b): # Check along the bottom of this wall return w.get_next_point_and_wall_and_dir((w.l, w.b), B) # The next wall is to the right of this one elif w.l == self.r: return (self.r, self.b), w, L return (self.r, self.b), self, R # Traveling along the left wall elif dir == L: # Sort touching walls from top to bottom walls = sort_by_direction(self.is_touching, T) for w in walls: # Skip anything above the last point if w.t > lastpt[1]: # The next wall is to the left of thecurrent one if w.r == self.l: return (w.r, w.t), w, T # The next wall is adjacent and continues along the left elif (self.l, self.b) == (w.l, w.t): return w.get_next_point_and_wall_and_dir((w.l, w.t), L) # The next wall is below the current one elif w.t == self.b: return (self.l, self.b), w, T return (self.l, self.b), self, B # Traveling along the top wall elif dir == T: # Sort touching walls from right to left walls = sort_by_direction(self.is_touching, R) for w in walls: # Skip anything to the right of the last point if w.r < lastpt[0]: # The next wall is above the current one if w.b == self.t: return (w.r, w.b), w, R # The next wall is adjancent and continues along the top elif (self.l, self.t) == (w.r, w.t): return w.get_next_point_and_wall_and_dir((w.r, w.t), T) # The next wall is to the left of this one elif w.r == self.l: return (self.l, self.t), w, R return (self.l, self.t), self, L # Traveling along the right wall elif dir == R: walls = sort_by_direction(self.is_touching, B) for w in walls: # Skip anything below if w.b < lastpt[1]: # The next wall is to the right of the current one if w.l == self.r: return (w.l, w.b), w, B # The next wall is adjancent and continues along the right elif (self.r, self.t) == (w.r, w.b): return w.get_next_point_and_wall_and_dir((w.r, w.b), R) # The next wall is above this one elif w.b == self.t: return (self.r, self.t), w, B return (self.r, self.t), self, T def get_next_outer_point_and_wall_and_dir(self, lastpt, dir): # Traveling along the bottom wall if dir == B: # Sort touching walls from right to left walls = sort_by_outside_direction(self.is_touching, R) for w in walls: # Skip anything to the right of the last point if w.r < lastpt[0]: # The next wall is under the current one - this wall's top left is new, go down along the right wall if w.t == self.b: return (w.r, w.t), w, R # The next wall is adjacent to this one and continues along the bottom elif (self.l, self.b) == (w.r, w.b): # Check along the bottom of this wall return w.get_next_outer_point_and_wall_and_dir((w.r, w.b), B) # The next wall is to the left of this one elif w.r == self.l: return (self.l, self.b), w, R return (self.l, self.b), self, L # Traveling along the left wall elif dir == L: # Sort touching walls from bottom to top walls = sort_by_outside_direction(self.is_touching, B) for w in walls: # Skip anything below the last point if w.b < lastpt[1]: # The next wall is to the left of thecurrent one if w.r == self.l: return (w.r, w.b), w, B # The next wall is adjacent and continues along the left elif (self.l, self.t) == (w.l, w.b): return w.get_next_outer_point_and_wall_and_dir((w.l, w.b), L) # The next wall is above the current one elif w.b == self.t: return (self.l, self.t), w, B return (self.l, self.t), self, T # Traveling along the top wall elif dir == T: # Sort touching walls from left to right walls = sort_by_outside_direction(self.is_touching, L) for w in walls: # Skip anything to the left of the last point if w.l > lastpt[0]: # The next wall is above the current one if w.b == self.t: return (w.l, w.b), w, L # The next wall is adjancent and continues along the top elif (self.r, self.t) == (w.l, w.t): return w.get_next_outer_point_and_wall_and_dir((w.l, w.t), T) # The next wall is to the right of this one elif w.l == self.r: return (self.r, self.t), w, L return (self.r, self.t), self, R # Traveling along the right wall elif dir == R: walls = sort_by_outside_direction(self.is_touching, T) for w in walls: # Skip anything above if w.t > lastpt[1]: # The next wall is to the right of the current one if w.l == self.r: return (w.l, w.t), w, T # The next wall is adjancent and continues along the right elif (self.r, self.b) == (w.r, w.t): return w.get_next_outer_point_and_wall_and_dir((w.r, w.t), R) # The next wall is below this one elif w.t == self.b: return (self.r, self.b), w, T return (self.r, self.b), self, B def to_pg_rect(self): w = self.r - self.l h = self.b - self.t return pg.Rect((self.l, self.t), (w,h)) # Converts trial into a set of wall rectangles [right, top, left, bottom] def convert_trial_2_wallrects(trial): return [Wall(w[0],w[1]) for w in trial.normwalls] def get_topleft_wall(walls): best_idx = 0 most_top = walls[0].t most_left = walls[0].l for i in range(1,len(walls)): w = walls[i] if w.t < most_top or \ (w.t == most_top and w.l < most_left): best_idx = i most_top = w.t most_left = w.l return best_idx, walls[best_idx] def get_topright_wall(walls): best_idx = 0 most_top = walls[0].t most_right = walls[0].r for i in range(1, len(walls)): w = walls[i] if w.t < most_top or \ (w.t == most_top and w.r > most_right): best_idx = i most_top = w.t most_right = w.r return best_idx, walls[best_idx] def sort_by_direction(walls, dir): if dir == L: pfnc = lambda x: (x.l, -x.b) elif dir == R: pfnc = lambda x: (-x.r, x.t) elif dir == T: pfnc = lambda x: (x.t, x.l) elif dir == B: pfnc = lambda x: (-x.b, -x.r) vals = zip(map(pfnc, walls), walls) vsort = sorted(vals, key=itemgetter(0)) return [w for _, w in vsort] def sort_by_outside_direction(walls, dir): if dir == L: pfnc = lambda x: (x.l, x.t) elif dir == R: pfnc = lambda x: (-x.r, -x.b) elif dir == T: pfnc = lambda x: (x.t, -x.r) elif dir == B: pfnc = lambda x: (-x.b, x.l) vals = zip(map(pfnc, walls), walls) vsort = sorted(vals, key=itemgetter(0)) return [w for _, w in vsort] # Takes in a list of Walls, returns a list including: # [ # A list of points that form the inner hull, # The walls used to form that hull # ] def get_inner_hull(walls): # Start with the upper-left wall tl_idx, tl_wall = get_topleft_wall(walls) tl_wall.grouped = True inc_walls = [tl_wall] def add_walls(w1, others): tidxs = w1.get_touch_indices(others) for i in tidxs: ow = others[i] if not ow.grouped: inc_walls.append(ow) ow.grouped = True add_walls(ow, others) return add_walls(tl_wall, walls) getting_first = True not_goods = [] while getting_first: getting_first = False chkwalls = [w for w in tl_wall.is_touching if w not in not_goods] if len(chkwalls) == 0: # Edge case where we're finding some internal walls cur_wall = tl_wall cur_pt = (cur_wall.r, cur_wall.b) cur_traverse = R else: _, cur_wall = get_topright_wall(chkwalls) cur_pt = (cur_wall.l, cur_wall.b) # Check that there is not a wall below this point for w in cur_wall.is_touching: if w != tl_wall and w.touches_top_wall(cur_pt) and not getting_first: #wait_4_kp(lambda: draw_everything(tb, [tl_wall, cur_wall], [cur_pt])) not_goods.append(tl_wall) not_goods.append(cur_wall) tl_wall = w getting_first = True cur_traverse = B inner_pts = [cur_pt] running = True while running: cur_pt, cur_wall, cur_traverse = cur_wall.get_next_point_and_wall_and_dir(cur_pt, cur_traverse) if cur_pt == inner_pts[0]: running = False else: inner_pts.append(cur_pt) #wait_4_kp(lambda: draw_everything(tb, walls, inner_pts)) return inner_pts, inc_walls def get_outer_hull(wall_list): _, cur_wall = get_topleft_wall(wall_list) cur_pt = (cur_wall.l, cur_wall.t) cur_traverse = T outer_pts = [cur_pt] while True: cur_pt, cur_wall, cur_traverse = cur_wall.get_next_outer_point_and_wall_and_dir(cur_pt, cur_traverse) if cur_pt == outer_pts[0]: return outer_pts else: outer_pts.append(cur_pt) def get_islands(rem_walls): islands = [] while len(rem_walls) > 0: tl_idx, tl_wall = get_topleft_wall(rem_walls) tl_wall.grouped = True this_island = [tl_wall] def add_walls(w1, others): tidxs = w1.get_touch_indices(others) for i in tidxs: ow = others[i] if not ow.grouped: this_island.append(ow) ow.grouped = True add_walls(ow, others) return add_walls(tl_wall, rem_walls) islands.append(this_island) rem_walls = [w for w in rem_walls if w not in this_island] island_pts = [get_outer_hull(wl) for wl in islands] return island_pts, islands # Takes in a trial and produces the list of triangles that make up its inner container. class Triangulation(object): def __init__(self, trial): self._trial = trial self._walls = convert_trial_2_wallrects(self._trial) inner_pts, inc_walls = get_inner_hull(self._walls) rem_walls = [w for w in self._walls if w not in inc_walls] islands, _ = get_islands(rem_walls) self._init_tris, self._wound_hull = geometry.ear_clip_with_holes(inner_pts, islands) self._has_all_tris = False self._all_tris = [self._init_tris] def make_all_triangulations(self): if not self._has_all_tris: for i in range(1, len(self._wound_hull)): #if i == 5: # print 'here' # newtri = ear_clip(self._wound_hull[i:] + self._wound_hull[:i]) newtri = geometry.ear_clip(self._wound_hull[i:] + self._wound_hull[:i]) self._all_tris.append(newtri) self._has_all_tris = True def make_graph(self): pass def triangulation(self, index = 0): if index >0 and not self._has_all_tris: print "Cannot get triangle by index without make_all_triangulations" index = 0 return self._all_tris[index] def get_n_tris(self): return len(self._all_tris) n_triangles = property(get_n_tris) class ACD(object): def __init__(self, trial, convexity_limit = 10): self._trial = trial self._walls = convert_trial_2_wallrects(self._trial) self._clim = convexity_limit inner_pts, inc_walls = get_inner_hull(self._walls) rem_walls = [w for w in self._walls if w not in inc_walls] islands, _ = get_islands(rem_walls) outer_shell = map(np.array, inner_pts) polys = [outer_shell] + [map(np.array, pts) for pts in islands] self._acd = geometry.approximate_convex_decomposition(polys, self._clim) #self._acd = _acd_outer(outer_shell, self._clim, geometry._sl_concavity) # TEMPORARY from geometry import _find_cut_heur, _find_witness def _acd_outer(vertices, tau, witness_fnc): d, witness, pocket = _find_witness(vertices, witness_fnc) if d < tau: return [vertices] # We're below threshold or it's already convex cut_v = _find_cut_heur(witness, vertices, pocket) poly_1 = [] poly_2 = [] vidx = 0 on_poly_2 = False for vidx in range(len(vertices)): this_v = vertices[vidx] # Are we at a cut point? If so, add to both polygons if all(this_v == witness) or all(this_v == cut_v): poly_1.append(this_v) poly_2.append(this_v) on_poly_2 = not on_poly_2 else: if on_poly_2: poly_2.append(this_v) else: poly_1.append(this_v) wait_4_kp(lambda: draw_polys(tb, [poly_1, poly_2])) return _acd_outer(poly_1, tau, witness_fnc) + _acd_outer(poly_2, tau, witness_fnc) def trianglulate_trial(trial, do_all_triangulations = False): walls = convert_trial_2_wallrects(trial) inner_pts, inc_walls = get_inner_hull(walls) rem_walls = [w for w in walls if w not in inc_walls] islands, _ = get_islands(rem_walls) init_tris, wound_hull = geometry.ear_clip_with_holes(inner_pts, islands) if do_all_triangulations: tris = [init_tris] for i in range(1, len(wound_hull)): tris.append(geometry.ear_clip(wound_hull[i:] + wound_hull[:i])) return tris else: return init_tris if __name__ == '__main__': # If running directly, use PyGame -- otherwise allow loading without requiring these libraries import pygame as pg from pygame.constants import * def draw_wall_outlines(surf, walls, color=(255, 0, 0)): for w in walls: r = w.to_pg_rect() pg.draw.rect(surf, color, r, 2) return surf def draw_everything(table, wall_list=[], ptlist=[], tris = [], ptcol=(0, 255, 0), tricol=(255,0,0)): s = table.draw() draw_wall_outlines(s, wall_list) for p in ptlist: pg.draw.circle(s, ptcol, p, 4) for t in tris: pg.draw.polygon(s, tricol, t, 2) def draw_polys(table, poly_list=[], ptlist=[], poly_col=(0,255,0), pt_col=(255,0,0)): s = table.draw() for p in poly_list: pg.draw.polygon(s, poly_col, p, 2) for p in ptlist: pg.draw.circle(s, pt_col, p, 4) def wait_4_kp(draw_fn, hz=20): clk = pg.time.Clock() while True: draw_fn() pg.display.flip() for e in pg.event.get(): if e.type == KEYDOWN: return clk.tick(hz) # Load in the trial if len(sys.argv) == 1: tr = loadTrial('automatic_generator/samp.ptr') else: tr = loadTrialFromJSON(sys.argv[1]) pg.init() s = pg.display.set_mode((1000, 620)) tb = tr.makeTable() #from numpy import array #p1 = [array([79, 78]), array([493, 78]), array([493, 114]), array([678, 114]), array([678, 163]), array([928, 163]), array([928, 269]), array([934, 269]), array([934, 491]), array([974, 491]), array([974, 596]), array([909, 596]), array([909, 560]), array([663, 560]), array([663, 491]), array([699, 491]), array([699, 401]), array([656, 469]), array([588, 469]), array([588, 401]), array([551, 401]), array([551, 365]), array([438, 365]), array([438, 431]), array([153, 431]), array([153, 258]), array([ 79, 258])] #p2 = [array([699,401]), array([656,401]), array([656,469])] #wait_4_kp(lambda: draw_polys(tb, [p2])) acd = ACD(tr, 20) for cd in acd._acd: print cd wait_4_kp(lambda: draw_polys(tb, acd._acd)) #triang = Triangulation(tr) #triang.make_all_triangulations() #for i in range(triang.n_triangles): # wait_4_kp(lambda: draw_everything(tb, [], [], triang.triangulation(i)))
38.772201
521
0.552878
5a7d126c2c5ec732a554a6f67d045f758340814c
613
dart
Dart
test/extensions/index_test.dart
ibrahimyetkin/darq
9e4a317aa4f734addc49aad1a16c127c50d3482b
[ "MIT" ]
53
2019-06-12T19:08:24.000Z
2021-04-03T15:24:38.000Z
test/extensions/index_test.dart
ibrahimyetkin/darq
9e4a317aa4f734addc49aad1a16c127c50d3482b
[ "MIT" ]
8
2021-04-03T18:35:23.000Z
2021-12-09T13:48:32.000Z
test/extensions/index_test.dart
ibrahimyetkin/darq
9e4a317aa4f734addc49aad1a16c127c50d3482b
[ "MIT" ]
8
2019-06-12T23:18:35.000Z
2021-03-10T13:51:06.000Z
import 'package:darq/darq.dart'; import 'package:test/test.dart'; void main() { group('index', () { test('Generate indices', () { final list = ['a', 'b', 'c', 'd']; final result = list.index(); expect(result.length, 4); expect(result.elementAt(0).key, 0); expect(result.elementAt(0).value, 'a'); expect(result.elementAt(1).key, 1); expect(result.elementAt(1).value, 'b'); expect(result.elementAt(2).key, 2); expect(result.elementAt(2).value, 'c'); expect(result.elementAt(3).key, 3); expect(result.elementAt(3).value, 'd'); }); }); }
29.190476
45
0.579119
dac53e506a462d98e0577245adcccffe6afd3116
43
rb
Ruby
test/fixtures/cookbooks/test/metadata.rb
sclark007/sudo
106b9781ccc4f86d9c6aa90053e63ef3e1c575db
[ "Apache-2.0" ]
43
2015-09-11T12:28:55.000Z
2021-08-24T01:04:41.000Z
test/fixtures/cookbooks/test/metadata.rb
sclark007/sudo
106b9781ccc4f86d9c6aa90053e63ef3e1c575db
[ "Apache-2.0" ]
70
2015-09-17T19:15:40.000Z
2021-06-18T23:47:03.000Z
test/fixtures/cookbooks/test/metadata.rb
sclark007/sudo
106b9781ccc4f86d9c6aa90053e63ef3e1c575db
[ "Apache-2.0" ]
85
2015-09-24T00:45:39.000Z
2021-08-12T21:36:38.000Z
name 'test' version '1.0.0' depends 'sudo'
10.75
15
0.674419
c9f7c61a68e238a1d3792b808d513a1b2d36ee4b
649
ts
TypeScript
build/generate-root-readme-badges.ts
jameswilddev/woobly
6b1721f3e9c0a5036d4beb330702180e4d21a719
[ "MIT" ]
null
null
null
build/generate-root-readme-badges.ts
jameswilddev/woobly
6b1721f3e9c0a5036d4beb330702180e4d21a719
[ "MIT" ]
1
2019-11-24T11:17:41.000Z
2019-11-24T11:17:41.000Z
build/generate-root-readme-badges.ts
jameswilddev/woobly
6b1721f3e9c0a5036d4beb330702180e4d21a719
[ "MIT" ]
1
2019-11-08T23:33:05.000Z
2019-11-08T23:33:05.000Z
export default function ( ): string { return [ `[![Travis](https://img.shields.io/travis/jameswilddev/woobly.svg)](https://travis-ci.org/jameswilddev/woobly)`, `[![License](https://img.shields.io/github/license/jameswilddev/woobly.svg)](https://github.com/jameswilddev/woobly/blob/master/license)`, `[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjameswilddev%2Fwoobly.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjameswilddev%2Fwoobly?ref=badge_shield)`, `[![Renovate enabled](https://img.shields.io/badge/renovate-enabled-brightgreen.svg)](https://renovatebot.com/)`, ].join(` `) }
64.9
205
0.728814
159776b01a57502649203d6ffd3743a480846398
13,442
lua
Lua
tests/test_cache.lua
JanSharp/phobos
8dc4957873c732cbb4bb1a8c2b98af3d47da6de8
[ "MIT" ]
3
2021-10-29T20:36:19.000Z
2021-11-19T05:02:08.000Z
tests/test_cache.lua
JanSharp/phobos
8dc4957873c732cbb4bb1a8c2b98af3d47da6de8
[ "MIT" ]
2
2021-11-21T00:20:54.000Z
2021-11-24T21:46:14.000Z
tests/test_cache.lua
JanSharp/phobos
8dc4957873c732cbb4bb1a8c2b98af3d47da6de8
[ "MIT" ]
null
null
null
local framework = require("test_framework") local assert = require("assert") local virtual_io_util = require("lib.virtual_io_util") local io_util = require("io_util") local cache = require("cache") local profile_util = require("profile_util") local phobos_version = require("phobos_version") local constants = require("constants") local util = require("util") local Path = require("lib.path") local binary = require("binary_serializer") local action_enum = constants.action_enum local function compare_profile(expected_profile, got_profile) expected_profile.include_exclude_copy_definitions = nil expected_profile.include_exclude_definitions = nil expected_profile.include_exclude_delete_definitions = nil expected_profile.inject_scripts = nil expected_profile.on_pre_profile_ran = nil expected_profile.on_post_profile_ran = nil local optimizations = expected_profile.optimizations optimizations.fold_const = optimizations.fold_const or false optimizations.fold_control_statements = optimizations.fold_control_statements or false optimizations.tail_calls = optimizations.tail_calls or false assert.contents_equals(expected_profile, got_profile, "save loaded profile") end local function compare_file_list(expected_file_list, got_file_list) assert.contents_equals(expected_file_list, got_file_list, "save loaded file_list") end do local scope = framework.scope:new_scope("cache") function scope.before_all() virtual_io_util.hook() end function scope.after_all() virtual_io_util.unhook() end local profile local all_inject_scripts local file_list local next_inject_scripts_id local next_inject_scripts_file_modification local make_profile local make_all_inject_scripts local make_file_list local function before_each() virtual_io_util.new_fs() io_util.mkdir_recursive("/test") io_util.set_working_dir("/test") make_profile{} make_all_inject_scripts() make_file_list() next_inject_scripts_id = 0 next_inject_scripts_file_modification = 0 end local function save_cache() cache.save(profile, all_inject_scripts, file_list) end local function load_cache() -- no tailcall, they make stack traces so much less readable local got_profile, got_file_list, err = cache.load(profile.root_dir, profile.cache_dir) return got_profile, got_file_list, err end local function normalize_filename(filename) return Path.combine(profile.root_dir, filename):normalize():str() end local function get_cache_filename(filename) return normalize_filename(Path.new(profile.cache_dir) / filename) end local function get_metadata_filename() return get_cache_filename("phobos_metadata.dat") end local function assert_save() save_cache() local got = io_util.exists(get_metadata_filename()) assert(got, "cache.save did not create the metadata file '"..get_metadata_filename().."'.") end local function assert_save_load() assert_save() local got_profile, got_file_list, err = load_cache() if not got_profile then assert(false, "Failed to load cache: "..err) end compare_profile(profile, got_profile) compare_file_list(file_list, got_file_list) end local function assert_load_warning(warning_pattern) local got_profile, got_file_list, err = load_cache() assert.contents_equals({}, { profile = got_profile, file_list = got_file_list, }, "Unexpected success, expected warning with the pattern "..warning_pattern) assert.errors(warning_pattern, function() error(err) end) end local function add_test(label, func) scope:add_test(label, function() before_each() func() end) end ---@param params NewProfileInternalParams function make_profile(params) params.name = params.name or "test_profile" params.output_dir = params.output_dir or "out" params.cache_dir = params.cache_dir or "cache" params.root_dir = params.root_dir or io_util.get_working_dir() profile = profile_util.new_profile(params) ---@diagnostic disable-next-line:undefined-field profile.phobos_version = params.phobos_version or phobos_version end function make_all_inject_scripts() all_inject_scripts = {} end ---adds to `all_inject_scripts` local function add_inject_scripts(usage_count) local inject_scripts = { id = next_inject_scripts_id, usage_count = util.debug_assert(usage_count), filenames = {}, required_files = {}, modification_lut = {}, } all_inject_scripts[#all_inject_scripts+1] = inject_scripts next_inject_scripts_id = next_inject_scripts_id + 1 return inject_scripts end ---adds to latest in `all_inject_scripts` local function add_inject_script(inject_scripts, filename) inject_scripts.filenames[#inject_scripts.filenames+1] = normalize_filename(filename) end ---adds to latest in `all_inject_scripts` local function add_inject_script_required_file(inject_scripts, filename) filename = normalize_filename(filename) local file = { filename = filename, modification = next_inject_scripts_file_modification, } next_inject_scripts_file_modification = next_inject_scripts_file_modification + 1 inject_scripts.required_files[#inject_scripts.required_files+1] = file inject_scripts.modification_lut[filename] = file.modification end function make_file_list() file_list = {} end local function get_source_filename(params) local source_filename = util.assert_params_field(params, "source_filename") return normalize_filename(source_filename) end local function get_output_filename(params) local output_filename = util.assert_params_field(params, "output_filename") return normalize_filename(Path.new(profile.output_dir) / output_filename) end local function add_compile_file(params) file_list[#file_list+1] = { action = action_enum.compile, source_filename = get_source_filename(params), relative_source_filename = util.assert_params_field(params, "relative_source_filename"), output_filename = get_output_filename(params), source_name = util.assert_params_field(params, "source_name"), use_load = util.assert_params_field(params, "use_load"), error_message_count = util.assert_params_field(params, "error_message_count"), inject_scripts = util.assert_params_field(params, "inject_scripts"), } end local function add_test_compile_file(inject_scripts) add_compile_file{ source_filename = "src/foo.pho", relative_source_filename = "foo.pho", output_filename = "foo.lua", source_name = "@?", use_load = true, error_message_count = 7, inject_scripts = inject_scripts, } end local function add_copy_file(params) file_list[#file_list+1] = { action = action_enum.copy, source_filename = get_source_filename(params), output_filename = get_output_filename(params), } end local function add_delete_file(params) file_list[#file_list+1] = { action = action_enum.delete, output_filename = get_output_filename(params), } end add_test("minimal profile, no files", function() assert_save_load() end) add_test("non default profile, no files", function() make_profile{ incremental = false, error_message_count = 1000, optimizations = profile_util.get_all_optimizations(), measure_memory = true, use_load = true, } assert_save_load() end) add_test("profile with inject scripts and functions which get ignored, no files", function() make_profile{ inject_scripts = {"path to some inject script"}, on_pre_profile_ran = function() error("some nonsense") end, on_post_profile_ran = function() error("even more nonsense") end, } assert_save_load() end) add_test("profile with inject_scripts with usage_count 0 (technically invalid)", function() add_inject_scripts(0) assert.errors("Attempt to save cache with inject_scripts with usage_count == 0%.", save_cache) end) add_test("compile file actions", function() local inject_scripts = add_inject_scripts(2) add_test_compile_file(inject_scripts) add_compile_file{ source_filename = "src/bar/baz.pho", relative_source_filename = "baz.pho", output_filename = "bar/baz.lua", source_name = "@bar/?", use_load = false, error_message_count = 10000, inject_scripts = inject_scripts, } assert_save_load() end) add_test("a copy file action", function() add_copy_file{ source_filename = "src/foo.pho", output_filename = "foo.lua", } assert_save_load() end) add_test("a delete file action", function() add_delete_file{ output_filename = "delete_me.txt", } assert_save_load() end) add_test("invalid file action", function() file_list[#file_list+1] = { action = 255, -- any larger and we get an out of bounds error for uint8 } assert.errors("Invalid file action '255'%.", save_cache) end) add_test("inject script filenames", function() local inject_scripts = add_inject_scripts(1) add_inject_script(inject_scripts, "scripts/inject.pho") add_inject_script(inject_scripts, "scripts/inject_move.pho") add_test_compile_file(inject_scripts) assert_save_load() end) add_test("different inject_scripts for 2 compile file actions", function() local inject_scripts_one = add_inject_scripts(1) add_inject_script(inject_scripts_one, "scripts/inject.pho") local inject_scripts_two = add_inject_scripts(1) add_inject_script(inject_scripts_two, "scripts/inject_move.pho") add_test_compile_file(inject_scripts_one) add_test_compile_file(inject_scripts_two) assert_save_load() end) add_test("inject scripts with required files", function() local inject_scripts = add_inject_scripts(1) add_inject_script(inject_scripts, "scripts/inject.pho") add_inject_script_required_file(inject_scripts, "scripts/inject_lib.pho") add_inject_script_required_file(inject_scripts, "scripts/inject_other_lib.pho") add_test_compile_file(inject_scripts) assert_save_load() end) add_test("load absent cache", function() local got = {load_cache()} -- nil, nil, nil assert.contents_equals({}, got, "load results") end) add_test("load invalid cache, too short to read signature and version", function() io_util.write_file(get_metadata_filename(), "????????") -- 8 `?` assert_load_warning("Invalid cache metadata, it is too short%.") end) add_test("load invalid cache signature", function() io_util.write_file(get_metadata_filename(), "??????????") -- 10 `?` assert_load_warning("Invalid cache metadata signature%.") end) add_test("load cache with a newer version", function() io_util.write_file(get_metadata_filename(), constants.phobos_signature.."\xfe\xff") -- little endian assert_load_warning( "Cannot load cache version "..(0xfffe).." from a newer version of Phobos%." ) end) do local function test_cache_too_short(filename) assert_save() local contents = io_util.read_file(get_cache_filename(filename)) io_util.write_file(get_cache_filename(filename), contents:sub(1, -2)) assert_load_warning("Corrupted cache:.*Attempt to read .*") end add_test("load corrupted cache (too short phobos_metadata.dat)", function() test_cache_too_short("phobos_metadata.dat") end) add_test("load corrupted cache (too short files.dat)", function() test_cache_too_short("files.dat") end) end do local function test_expected_end_of_binary_data(filename) assert_save() local contents = io_util.read_file(get_cache_filename(filename)) io_util.write_file(get_cache_filename(filename), contents.."\0") assert_load_warning("Corrupted cache:.*Expected end of binary data in cache file '"..filename.."'%.") end add_test("load corrupted cache (too long phobos_metadata.dat)", function() test_expected_end_of_binary_data("phobos_metadata.dat") end) add_test("load corrupted cache (too long files.dat)", function() test_expected_end_of_binary_data("files.dat") end) end add_test("load corrupted cache (invalid inject script ids)", function() local inject_scripts = add_inject_scripts(1) all_inject_scripts[#all_inject_scripts] = nil add_test_compile_file(inject_scripts) assert_save() assert_load_warning("Corrupted cache:.*Invalid inject script ids%.") end) add_test("load corrupted cache (invalid file action)", function() add_delete_file{output_filename = "foo"} assert_save() -- Replace the file action in the binary string with an invalid one. -- This relies on the binary layout of the output, so it -- might need to be changed in future versions. local filename = get_output_filename{output_filename = "foo"} local ser = binary.new_serializer() ser:write_uint8(255) ser:write_string(filename) local replacement_str = ser:tostring() local contents = io_util.read_file(get_cache_filename("files.dat")) contents = contents:sub(1, -#replacement_str - 1)..replacement_str io_util.write_file(get_cache_filename("files.dat"), contents) assert_load_warning("Corrupted cache:.*Invalid file action '255'%.") end) end
34.03038
107
0.73553
c39bb48fb83201ad7dabab13f0ee276bffd1041f
1,646
cs
C#
SharpSploit.Tests/SharpSploit.Tests/Persistence/AutorunTests.cs
awsmhacks/SharpSploit
2e567e25243f189a9034680572be0c279ad0ebd6
[ "BSD-3-Clause" ]
1,464
2018-09-20T15:39:43.000Z
2022-03-31T14:35:37.000Z
SharpSploit.Tests/SharpSploit.Tests/Persistence/AutorunTests.cs
awsmhacks/SharpSploit
2e567e25243f189a9034680572be0c279ad0ebd6
[ "BSD-3-Clause" ]
51
2018-10-08T22:06:30.000Z
2021-12-22T16:30:25.000Z
SharpSploit.Tests/SharpSploit.Tests/Persistence/AutorunTests.cs
awsmhacks/SharpSploit
2e567e25243f189a9034680572be0c279ad0ebd6
[ "BSD-3-Clause" ]
286
2018-09-20T16:32:30.000Z
2022-02-10T12:12:36.000Z
// Author: Ryan Cobb (@cobbr_io) // Project: SharpSploit (https://github.com/cobbr/SharpSploit) // License: BSD 3-Clause using System; using Win = Microsoft.Win32; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharpSploit.Enumeration; using SharpSploit.Persistence; namespace SharpSploit.Tests.Persistence { [TestClass] public class AutorunTests { [TestMethod] public void InstallHKCUAutorun() { string cmd = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(@"New-Item -Path C:\Temp\hkcu.txt -ItemType File")); string valueExpected = $@"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe -nop -w hidden -enc {cmd}"; Autorun.InstallAutorun(Win.RegistryHive.CurrentUser, valueExpected); string result = Registry.GetRegistryKey(Win.RegistryHive.CurrentUser, @"Software\Microsoft\Windows\CurrentVersion\Run", "Updater"); Assert.IsTrue(result.Contains(valueExpected)); } [TestMethod] public void InstallHKLMAutorun() { string cmd = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(@"New-Item -Path C:\Temp\hkcu.txt -ItemType File")); string valueExpected = $@"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe -nop -w hidden -enc {cmd}"; Autorun.InstallAutorun(Win.RegistryHive.LocalMachine, valueExpected); string result = Registry.GetRegistryKey(Win.RegistryHive.LocalMachine, @"Software\Microsoft\Windows\CurrentVersion\Run", "Updater"); Assert.IsTrue(result.Contains(valueExpected)); } } }
42.205128
144
0.695018
609acf2a80ad296912ca35329264b36f5c4f4690
5,264
h
C
build-Takingvariables-Desktop_Qt_6_1_0_MinGW_64_bit-Debug/ui_mainwindow.h
morkos11/files-reader-desktop-app
d0b9c5586c12b87a840352163e2c2063bb6d82da
[ "Apache-2.0" ]
null
null
null
build-Takingvariables-Desktop_Qt_6_1_0_MinGW_64_bit-Debug/ui_mainwindow.h
morkos11/files-reader-desktop-app
d0b9c5586c12b87a840352163e2c2063bb6d82da
[ "Apache-2.0" ]
null
null
null
build-Takingvariables-Desktop_Qt_6_1_0_MinGW_64_bit-Debug/ui_mainwindow.h
morkos11/files-reader-desktop-app
d0b9c5586c12b87a840352163e2c2063bb6d82da
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 6.1.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QStatusBar> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralwidget; QGridLayout *gridLayout; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *lineEdit; QSpacerItem *verticalSpacer_2; QHBoxLayout *horizontalLayout_2; QLabel *label_2; QLineEdit *lineEdit_2; QSpacerItem *verticalSpacer; QPushButton *pushButton; QMenuBar *menubar; QStatusBar *statusbar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QString::fromUtf8("MainWindow")); MainWindow->setWindowModality(Qt::WindowModal); MainWindow->resize(552, 226); MainWindow->setMinimumSize(QSize(552, 226)); MainWindow->setMaximumSize(QSize(552, 226)); centralwidget = new QWidget(MainWindow); centralwidget->setObjectName(QString::fromUtf8("centralwidget")); centralwidget->setMinimumSize(QSize(552, 175)); centralwidget->setMaximumSize(QSize(552, 175)); gridLayout = new QGridLayout(centralwidget); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); label = new QLabel(centralwidget); label->setObjectName(QString::fromUtf8("label")); QFont font; font.setPointSize(9); label->setFont(font); horizontalLayout->addWidget(label); lineEdit = new QLineEdit(centralwidget); lineEdit->setObjectName(QString::fromUtf8("lineEdit")); horizontalLayout->addWidget(lineEdit); verticalLayout->addLayout(horizontalLayout); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer_2); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); label_2 = new QLabel(centralwidget); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setFont(font); horizontalLayout_2->addWidget(label_2); lineEdit_2 = new QLineEdit(centralwidget); lineEdit_2->setObjectName(QString::fromUtf8("lineEdit_2")); horizontalLayout_2->addWidget(lineEdit_2); verticalLayout->addLayout(horizontalLayout_2); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); verticalLayout->addItem(verticalSpacer); pushButton = new QPushButton(centralwidget); pushButton->setObjectName(QString::fromUtf8("pushButton")); QFont font1; font1.setPointSize(11); font1.setBold(true); pushButton->setFont(font1); verticalLayout->addWidget(pushButton); gridLayout->addLayout(verticalLayout, 0, 0, 1, 1); MainWindow->setCentralWidget(centralwidget); menubar = new QMenuBar(MainWindow); menubar->setObjectName(QString::fromUtf8("menubar")); menubar->setGeometry(QRect(0, 0, 552, 26)); MainWindow->setMenuBar(menubar); statusbar = new QStatusBar(MainWindow); statusbar->setObjectName(QString::fromUtf8("statusbar")); MainWindow->setStatusBar(statusbar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QCoreApplication::translate("MainWindow", "Select Variables", nullptr)); label->setText(QCoreApplication::translate("MainWindow", "Select Indexs Locations :", nullptr)); lineEdit->setPlaceholderText(QCoreApplication::translate("MainWindow", "ex: 0,1,2,3,6,9", nullptr)); label_2->setText(QCoreApplication::translate("MainWindow", "Enter Indexs Names :", nullptr)); lineEdit_2->setPlaceholderText(QCoreApplication::translate("MainWindow", "ex: id,email,phone,location,work at,loction", nullptr)); pushButton->setText(QCoreApplication::translate("MainWindow", "Enter", nullptr)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
35.328859
138
0.679141
05a4e4bbe1f24d33952a396deb85f1e737213fd6
3,867
py
Python
batch3/outputs/ns_r_inflation.py
sjoudaki/CosmoJBD
3c1d029b74034b92cb2974de15e4c18637a5277e
[ "MIT" ]
null
null
null
batch3/outputs/ns_r_inflation.py
sjoudaki/CosmoJBD
3c1d029b74034b92cb2974de15e4c18637a5277e
[ "MIT" ]
null
null
null
batch3/outputs/ns_r_inflation.py
sjoudaki/CosmoJBD
3c1d029b74034b92cb2974de15e4c18637a5277e
[ "MIT" ]
null
null
null
# Uses first-order slow-roll results, with naive N definition, as in inflation paper import planckStyle as s from pylab import * import numpy as np BK = 'BK15' def N_r_ns(r, ns): return (r - 16) / (8. * ns - 8 + r) / 2. def r_ns(ns, p): return 8. * (1 - ns) * p / (2. + p) def r_ns_2(ns, p): return -4. / 3 * ( 32 * ns - 12 * ns * p - 28 - 6 * p - 3 * p ** 2 + 3 * p ** 2 * ns ** 2 + 18 * p * ns ** 2 - 4 * ns ** 2) * p / ( (2. + p) ** 3) def ns_N(N, p): # first order return (4 * N - p - 4) / (4. * N + p) def ns_N_2(N, p): # solved used above expresion for r_ns, but naive expression for N return 0.5 * (-12 * p ** 2 + 96 * N + 80 * N * p + 12 * N * p ** 3 + 32 * p + 96 * N * p ** 2 - 2 * sqrt( 384. * p - 1008 * p ** 2 - 2304 * p ** 3 + 384 * N * p + 4608 * N * p ** 2 + 6912 * N * p ** 3 + 3936 * p ** 4 * N + 936 * p ** 5 * N + 2304 * N ** 2 + 4608 * N ** 2 * p + 3456 * N ** 2 * p ** 2 + 1152 * N ** 2 * p ** 3 + 144 * N ** 2 * p ** 4 - 1464 * p ** 4 - 360 * p ** 5 + 72 * N * p ** 6 - 27 * p ** 6)) / ( 6. * N * p ** 3 + 36 * N * p ** 2 - 8 * N * p - 3 * p ** 3 - 18 * p ** 2 + 4 * p) # return (-12.*p ** 2 + 96 * N + 80 * N * p + 12 * N * p ** 3 + 32 * p + 96 * N * p ** 2 + 2 * sqrt(384. * p - 1008 * p ** 2 - 2304 * p ** 3 + 384 * N * p + 4608 * N * p ** 2 + 6912 * N * p ** 3 + 3936 * p ** 4 * N + 936 * p ** 5 * N + 2304 * N ** 2 + 4608 * N ** 2 * p + 3456 * N ** 2 * p ** 2 + 1152 * N ** 2 * p ** 3 + 144 * N ** 2 * p ** 4 - 1464 * p ** 4 - 360 * p ** 5 + 72 * N * p ** 6 - 27 * p ** 6)) / (6. * N * p ** 3 + 36 * N * p ** 2 - 8 * N * p - 3 * p ** 3 - 18 * p ** 2 + 4 * p) g = s.getSinglePlotter(ratio=1) roots = ['base_r_' + s.defdata_TTTEEE, 'base_r_' + s.defdata_TTTEEE + '_lensing', 'base_r_plikHM_TTTEEE_lowl_lowE_%s_lensing_post_BAO' % BK, ] colors = [g.settings.solid_colors[1], g.settings.solid_colors[3], g.settings.solid_colors[0]] g.plot_2d(roots, ['ns', 'r02'], filled=True, colors=colors) g.add_2d_contours('base_r_CamSpecHM_TTTEEE_lowl_lowE_%s_post_BAO_lensing' % BK, 'ns', 'r02', ls='--', color='gray') # g.add_2d_contours('base_r_plikHM_TT_lowl_lowE_BK15_post_BAO_lensing', 'ns', 'r02', ls='-.', color='darkcyan') ns = np.arange(0.91, 1.02, 0.0005) r = np.arange(0, 0.34, 0.002) ns, r = np.meshgrid(ns, r) # this is the first order result N = N_r_ns(r, ns) N[r > 8 * (1 - ns)] = 100 CS = contour(ns, r, N, origin='lower', levels=[50, 60], colors='k', linestyles=':', linewidths=0.3, extent=[0.95, 1.01, 0, 0.25]) for x, y, lab in zip([0.954, 0.9585], [0.2, 0.211], ['N=50', 'N=60']): plt.text(x, y, lab, size=7, rotation=-62, color='k', ha="center", va="center", bbox=dict(ec='1', fc='1', alpha=0)) ns = arange(0.9, 1.1, 0.001) # plot(ns, r_ns(ns, 1), ls='-', color='k', lw=1, alpha=0.8) plt.text(0.954, 0.13, 'Convex', size=7, rotation=-30, color='k', ha="center", va="center") plt.text(0.954, 0.116, 'Concave', size=7, rotation=-30, color='k', ha="center", va="center") modcol = 'red' text(0.962, 0.155, r'$\phi^2$', fontsize=9, color=modcol, bbox=dict(ec='1', fc='1', alpha=0.8), zorder=-2) text(0.971, 0.081, r'$\phi$', fontsize=9, color=modcol) for p in [1, 2]: ns = arange(0.93, 1.1, 0.002) # if p != 1: plot(ns, r_ns(ns, p), ls='-', color='black', lw=0.6, alpha=0.4) # print p, ns_N(50, p), ns_N(60, p) ns = arange(ns_N(50, p), ns_N(60, p), 0.0005) # plot(ns, r_ns(ns, p), ls='-', color=modcol, lw=1.2, alpha=1) labels = [s.planckall, s.planckall + '+lensing', '+%s+BAO' % BK] leg = g.add_legend(labels, colored_text=True, align_right=True) xlim([0.945, 1]) ylim([0, 0.26]) gca().set_xticks([0.95, 0.96, 0.97, 0.98, 0.99, 1.0]) gca().set_yticks([0, 0.05, 0.1, 0.15, 0.2, 0.25]) g.export('ns_r_inflation', tag=BK)
39.060606
493
0.504784
2cc40282401d286361ae77fca61b80f8276105d1
8,835
py
Python
inferpy/models/prob_model.py
PGM-Lab/InferPy
a9530ff7cde1894d54c393b69ea176d44dba7670
[ "Apache-2.0" ]
140
2018-04-04T10:35:36.000Z
2022-03-23T22:49:33.000Z
inferpy/models/prob_model.py
amidst/INFERPY
a9530ff7cde1894d54c393b69ea176d44dba7670
[ "Apache-2.0" ]
183
2018-03-13T16:06:41.000Z
2020-12-29T14:18:57.000Z
inferpy/models/prob_model.py
amidst/InferPy
a9530ff7cde1894d54c393b69ea176d44dba7670
[ "Apache-2.0" ]
17
2018-03-27T07:34:18.000Z
2021-12-13T14:48:24.000Z
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import functools from collections import OrderedDict from tensorflow_probability import edward2 as ed import tensorflow as tf import networkx as nx import warnings from inferpy import util from inferpy import contextmanager from inferpy.queries import Query from .random_variable import RandomVariable from inferpy.data.loaders import build_data_loader def probmodel(builder): """ Decorator to create probabilistic models. The function decorated must be a function which declares the Random Variables in the model. It is not required that the function returns such variables (they are captured using ed.tape). """ @functools.wraps(builder) def wrapper(*args, **kwargs): @util.tf_run_ignored def fn(): return builder(*args, **kwargs) return ProbModel( builder=fn ) return wrapper class ProbModel: """ Class that implements the probabilistic model functionality. It is composed of a graph, capturing the variable relationships, an OrderedDict containing the Random Variables/Parameters in order of creation, and the function which declare the Random Variables/Parameters. """ def __init__(self, builder): # Initialize object attributes self.builder = builder g_for_nxgraph = tf.Graph() # first buid the graph of dependencies with g_for_nxgraph.as_default(): with tf.Session() as sess: try: default_sess = util.session.swap_session(sess) self.graph = self._build_graph() finally: # sess is closed by context, no need to use set_session (which closes the actual running session) util.session.swap_session(default_sess) # Now initialize vars and params for the model (no sample_shape) self.vars, self.params = self._build_model() # This attribute contains the inference method used. If it is None, the `fit` function has not been used yet self.inference_method = None self.observed_vars = [] # list of variables that have been observed during the inference # losses tensor if model contains any inferpy layers Sequential object self.layer_losses = None # all the results of prior, posterior and posterior_predictive are evaluated always, because they depends on # tf.Variables, and therefore a tensor cannot be return because the results would depend on the value of that # tf.Variables def prior(self, target_names=None, data={}, size_datamodel=1): if size_datamodel > 1: variables, _ = self.expand_model(size_datamodel) elif size_datamodel == 1: variables = self.vars else: raise ValueError("size_datamodel must be greater than 0 but it is {}".format(size_datamodel)) util.init_uninit_vars() return Query(variables, target_names, data) def posterior(self, target_names=None, data={}): if self.inference_method is None: raise RuntimeError("posterior cannot be used before using the fit function.") # only non-observed variables can be in target_names if target_names is None: target_names = [name for name in self.vars.keys() if name not in self.observed_vars] else: if any(var in self.observed_vars for var in target_names): raise ValueError("target_names must correspond to not observed variables during the inference: \ {}".format([v for v in self.vars.keys() if v not in self.observed_vars])) return self.inference_method.posterior(target_names, data) def posterior_predictive(self, target_names=None, data={}): if self.inference_method is None: raise RuntimeError("posterior_preductive cannot be used before using the fit function.") # only non-observed variables can be in target_names if target_names is None: target_names = [name for name in self.vars.keys() if name in self.observed_vars] else: if any(var not in self.observed_vars for var in target_names): raise ValueError("target_names must correspond to observed variables during the inference: \ {}".format(self.observed_vars)) return self.inference_method.posterior_predictive(target_names, data) def _build_graph(self): with contextmanager.randvar_registry.init(): self.builder() # ed2 RVs created. Relations between them captured in randvar_registry builder as a networkx graph nx_graph = contextmanager.randvar_registry.get_graph() return nx_graph def _build_model(self): with contextmanager.randvar_registry.init(self.graph): with contextmanager.layer_registry.init(): # use edward2 model tape to capture RandomVariable declarations with ed.tape() as model_tape: self.builder() # store the losses from the build layers through layers.sequential.Sequential # NOTE: this must be done inside the layer_registry context, where the sequentials are stored self.layer_losses = contextmanager.layer_registry.get_losses() # get variables from parameters var_parameters = contextmanager.randvar_registry.get_var_parameters() # wrap captured edward2 RVs into inferpy RVs model_vars = OrderedDict() for k, v in model_tape.items(): registered_rv = contextmanager.randvar_registry.get_variable(k) if registered_rv is None: # a ed Random Variable. Create a inferpy Random Variable and assign the var directly. # do not know the args and kwars used to build the ed random variable. Use None. model_vars[k] = RandomVariable(v, name=k, is_datamodel=False, ed_cls=None, var_args=None, var_kwargs=None, sample_shape=()) else: model_vars[k] = registered_rv return model_vars, var_parameters def plot_graph(self): try: import matplotlib.pyplot as plt except ImportError: print("The function plot_graph requires to install inferpy[visualization]") raise nx.draw(self.graph, cmap=plt.get_cmap('jet'), with_labels=True) plt.show() @util.tf_run_ignored def fit(self, data, inference_method): # Parameter checkings # sample_dict must be a non empty python dict or dataloader data_loader = build_data_loader(data) plate_size = data_loader.size if len(data_loader.variables) == 0: raise ValueError('The number of mapped variables must be at least 1.') # if fit was called before, warn that it restarts everything if self.inference_method: warnings.warn("Fit was called before. This will restart the inference method and \ re-build the expanded model.") # set the inference method self.inference_method = inference_method # compile the inference method # if the inference method needs to intercept random variables, enable this context using a boolean # tf.Variable defined in this inference method object with util.interceptor.enable_interceptor(*self.inference_method.get_interceptable_condition_variables()): inference_method.compile(self, plate_size, self.layer_losses) # and run the update method with the data inference_method.update(data_loader) # If it works, set the observed variables self.observed_vars = data_loader.variables def expand_model(self, size=1): """ Create the expanded model vars using size as plate size and return the OrderedDict """ with contextmanager.data_model.fit(size=size): expanded_vars, expanded_params = self._build_model() return expanded_vars, expanded_params
42.071429
117
0.662932
2488786a2b37c908902f37dc31813763ea644058
14,625
php
PHP
resources/views/front/registration/include/career.blade.php
ashokkumar2342/nse
9dfecdc078a7bf0a6318e4b6c0b871f11b7664d2
[ "MIT" ]
null
null
null
resources/views/front/registration/include/career.blade.php
ashokkumar2342/nse
9dfecdc078a7bf0a6318e4b6c0b871f11b7664d2
[ "MIT" ]
null
null
null
resources/views/front/registration/include/career.blade.php
ashokkumar2342/nse
9dfecdc078a7bf0a6318e4b6c0b871f11b7664d2
[ "MIT" ]
null
null
null
<div class="row"> <form action="{{ route('career') }}" method="post" no-reset="true" class="add_form" accept-charset="utf-8" novalidate> {{ csrf_field() }} <div class="col-md-12"> <div class="col-md-6 col-lg-6 b-r"> <div class="form-horizontal"> <div class="box-body"> <div class="form-group"> <div class="col-md-12"> <label class="control-label col-lg-4" style="font-size: 14px; "> Sports</label> <div class="col-lg-8"> <input type="radio" {{ $pr->sport ==='Good'?'checked':'' }} value="Good" name="sport" id="Good" /> Good &nbsp;&nbsp;&nbsp; <input type="radio" value="Average" {{ $pr->sport ==='Average'?'checked':'' }} name="sport" id="Average" /> Average&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" value="Indifferent" {{ $pr->sport ==='Indifferent'?'checked':'' }} name="sport" id="Indifferent" /> Indifferent </div> </div> </div> <div class="form-group"> <div class="col-md-12"> <label class="control-label col-lg-4" style="font-size: 14px; "> Medical History</label> <div class="col-lg-8"> <input type="radio" {{ $pr->is_medical ==='Y'?'checked':'' }} value="Y" name="is_medical" id="MedicalHistoryYes" /> Yes <input type="radio" {{ $pr->is_medical ==='N'?'checked':'' }} value="N" name="is_medical" id="MedicalHistoryNo" /> No </div> </div> </div> <div class="form-group"> <div class="col-md-12" id="tdMedicalHistory"> <textarea rows="2" cols="53" name="medical_history" id="MedicalHistory" class="form-control input-sm" style="text-transform:uppercase;" autocomplete="off" maxlength="120" >{{ $pr->medical_history }}</textarea> <small class="floating-lable">If Yes, please Specify</small> </div> </div> <div class="form-group"> <div class="col-md-12"> <label class="control-label col-lg-4" style="font-size: 14px; ">Evidence of Any Learning Disability</label>&nbsp;&nbsp;&nbsp; <div class="col-lg-8"> <input type="radio" value="Y" {{ $pr->is_evidence_learning ==='Y'?'checked':'' }} name="is_evidence_learning" id="EvidenceLearningDisabilityYes" /> Yes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" value="N" {{ $pr->is_evidence_learning ==='N'?'checked':'' }} name="is_evidence_learning" id="EvidenceLearningDisabilityNo" checked="checked" /> No&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> </div> </div> <div class="form-group"> <div class="col-md-12" name="evidence_learning_disability"> <textarea rows="2" cols="53" id="idEvidenceLearningDisability" class="form-control input-sm" style="text-transform:uppercase;" autocomplete="off" maxlength="120" required>{{ $pr->evidence_learning_disability }}</textarea> <small class="floating-lable">If Yes, please Specify</small> </div> </div> <div class="form-group"> <div class="col-md-12"> <label class="control-label col-lg-4" style="font-size: 14px; "> Would You Like To Apply For Scholarship</label>&nbsp;&nbsp;&nbsp; <div class="col-lg-8"> <input type="radio" value="1" {{ $pr->is_scholarship ===1?'checked':'' }} name="is_scholarship" id="ApplyScholarshipYes" /> Yes &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" value="2" {{ $pr->is_scholarship ==2?'checked':'' }} name="is_scholarship" id="ApplyScholarshipNo" checked="checked" /> No&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </div> </div> </div> <div class="form-group"> <div class="col-md-12" id="tdApplyScholarship"> <label class="control-label" style="font-size: 12px; "> If Yes, Please Select The One</label>&nbsp;&nbsp;&nbsp; <input type="radio" value="Academic" {{ $pr->is_scholarship ==='Academic'?'checked':'' }} name="scholarship" id="idAcademic" /> Academic &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" value="Sports" {{ $pr->is_scholarship ==='Sports'?'checked':'' }} name="scholarship" id="idSports" /> Sports&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="radio" value="Activity" {{ $pr->is_scholarship ==='Activity'?'checked':'' }} name="scholarship" id="idActivity" /> Activity </div> </div> </div> <!-- /.box-body --> <!-- /.box-footer --> </div> </div> <div class="col-md-3 col-lg-3 b-r"> <div class="form-horizontal"> <div id="gvCoCurCular"> <label class="control-label col-lg-4" style="text-align:center;">Co-Curricular</label> <div class="col-lg-8"> <div id="divCoCulr" > <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" value="SPORTS" {{ $pr->co_curricular ==='SPORTS'?'checked':'' }} name="co_curricular[]" class="chkSCoCulr" id="1">SPORTS </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" value="DEBATE" {{ $pr->co_curricular ==='DEBATE'?'checked':'' }} name="co_curricular[]" class="chkSCoCulr" id="2">DEBATE </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->co_curricular ==='MUSIC'?'checked':'' }} value="MUSIC" name="co_curricular[]" class="chkSCoCulr" id="3">MUSIC </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->co_curricular ==='ELOCUTION'?'checked':'' }} value="ELOCUTION" name="co_curricular[]" class="chkSCoCulr" id="4">ELOCUTION </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->co_curricular ==='ACTING'?'checked':'' }} value="ACTING" name="co_curricular[]" class="chkSCoCulr" id="5">ACTING </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->co_curricular ==='FINE ART'?'checked':'' }} value="FINE ART" name="co_curricular[]" class="chkSCoCulr" id="6">FINE ART </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->co_curricular ==='OTHERS'?'checked':'' }} value="OTHERS" name="co_curricular[]" class="chkSCoCulr" id="7">OTHERS </label> </div> </div> </div> </div> </div> </div> </div> <div class="col-md-3 col-lg-3"> <div class="form-horizontal"> <div id="gvInstrument"> <label class="control-label col-lg-4" style="text-align:center;">Music</label> <div class="col-lg-8"> <div id="divInstrument"> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='GUITAR'?'checked':'' }} value="GUITAR" name="music[]" class="chkSInstrument" id="1">GUITAR </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='PIANO'?'checked':'' }} value="PIANO" name="music[]" class="chkSInstrument" id="2">PIANO </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='VIOLIN'?'checked':'' }} value="VIOLIN" name="music[]" class="chkSInstrument" id="3">VIOLIN </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='HARMONIUM'?'checked':'' }} value="HARMONIUM" name="music[]" class="chkSInstrument" id="4">HARMONIUM </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='DRUMS'?'checked':'' }} value="DRUMS" name="music[]" class="chkSInstrument" id="5">DRUMS </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='FLUTE'?'checked':'' }} value="FLUTE" name="music[]" class="chkSInstrument" id="6">FLUTE </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='KEYBOARD'?'checked':'' }} value="KEYBOARD" name="music[]" class="chkSInstrument" id="7">KEYBOARD </label> </div> </div> <div class="form-group"> <div class="col-lg-12"> <label class="checkbox-inline"> <input type="checkbox" {{ $pr->music ==='OTHERS'?'checked':'' }} value="OTHERS" name="music[]" class="chkSInstrument" id="8">OTHERS </label> </div> </div> <input type="hidden" id="hiddivInstrument"> </div> </div> </div> </div> </div> </div> <div class="clearfix"> </div> <div class="text-center"> @if ($pr->status!=11) <input type="submit" id="btnSave" value="Save" class="btn btn-primary btn-size-md" style="width:85px" tabindex="0" /> @endif <a data-toggle="tab" class="btn btn-primary btn-size-md menu8" onclick="menu('mm9')" style="width:85px" href="#menu9">Next</a> </div> </form> </div>
54.775281
251
0.388718
cdfa92a9f6faab1515102dada3050f42f71f9c80
116
cs
C#
src/quartz.reservoirs.test/NewReservoirTests.cs
alahearty/quartz
77a6868fe3aa2b57f81d9ec88d95c00350b81514
[ "MIT" ]
null
null
null
src/quartz.reservoirs.test/NewReservoirTests.cs
alahearty/quartz
77a6868fe3aa2b57f81d9ec88d95c00350b81514
[ "MIT" ]
null
null
null
src/quartz.reservoirs.test/NewReservoirTests.cs
alahearty/quartz
77a6868fe3aa2b57f81d9ec88d95c00350b81514
[ "MIT" ]
null
null
null
using NUnit.Framework; using System; namespace quartz.reservoirs.test { class NewReservoirTests { } }
11.6
32
0.698276
bd3dcf57d18d916778fdcc82f10360471684fb49
1,298
gemspec
Ruby
eol.gemspec
itroman/eol
7e4e09f7584d12ced137b0544009389b70dfc324
[ "MIT" ]
null
null
null
eol.gemspec
itroman/eol
7e4e09f7584d12ced137b0544009389b70dfc324
[ "MIT" ]
null
null
null
eol.gemspec
itroman/eol
7e4e09f7584d12ced137b0544009389b70dfc324
[ "MIT" ]
null
null
null
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'eol/version' Gem::Specification.new do |spec| spec.name = "eol" spec.version = Eol::VERSION spec.authors = ["Rob Roman"] spec.email = ["rob@romancoding.com"] spec.summary = "A comprehensive Encyclopedia of Life API wrapper" spec.description = "A wrapper for the Encyclopedia of Life API. It provides simple methods to call all of the available EOL API endpoints." spec.homepage = "http://github.com/itroman/eol" spec.license = "MIT" spec.required_ruby_version = '>= 2.0.0' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.14" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.6" spec.add_development_dependency "vcr", "~> 3.0" spec.add_development_dependency "webmock", "~> 3.0" spec.add_development_dependency "rubocop", "~> 0.49.1" spec.add_development_dependency "yard", "~> 0.9" spec.add_development_dependency "simplecov", "~> 0.10" spec.add_dependency "httparty", "~> 0.15" end
37.085714
144
0.665639
7c04e4d4ef99c13ab723e975362279ad5e0a78a7
18
asm
Assembly
test/jzas/symboltable/invalid/fail09.asm
scoffey/jz80sim
0de07a5ef51a1e7131b27056744459f29cd11d39
[ "MIT" ]
1
2015-03-27T15:58:50.000Z
2015-03-27T15:58:50.000Z
test/jzas/symboltable/invalid/fail09.asm
scoffey/jz80sim
0de07a5ef51a1e7131b27056744459f29cd11d39
[ "MIT" ]
null
null
null
test/jzas/symboltable/invalid/fail09.asm
scoffey/jz80sim
0de07a5ef51a1e7131b27056744459f29cd11d39
[ "MIT" ]
null
null
null
var1: defs "pepe"
9
17
0.666667
85124beab1d0e54fab649e58ff69662ce9f4ed15
4,212
cs
C#
Content/MainPatcher.cs
Stari0n/MagicTime
16decca0b0ab01f16a66555645e85f90897975c8
[ "MIT" ]
3
2021-12-07T10:12:35.000Z
2022-01-06T16:16:52.000Z
Content/MainPatcher.cs
Vek17/MagicTime
5eeb4c09aa473a09e63d346ef1d83c9fe78dcd27
[ "MIT" ]
6
2021-12-06T10:24:08.000Z
2022-03-04T16:09:05.000Z
Content/MainPatcher.cs
Vek17/MagicTime
5eeb4c09aa473a09e63d346ef1d83c9fe78dcd27
[ "MIT" ]
7
2021-12-05T05:57:19.000Z
2022-01-25T04:26:54.000Z
using HarmonyLib; using Kingmaker.Blueprints.JsonSystem; using Kingmaker.Blueprints.Classes; using Kingmaker.Blueprints; namespace MagicTime { static class MainPatcher { [HarmonyPatch(typeof(BlueprintsCache), "Init")] public static class BlueprintPatcher { static bool Initialized; [HarmonyPriority(Priority.LowerThanNormal)] static void Postfix() { if (Initialized) return; Initialized = true; var no_hb = Main.SettingsContainer.groups["disable_homebrew"].enabled; if (Main.SettingsContainer.groups["a_discoveries"].enabled) { ArcaneDiscoveries.Main.Create(); if (DiscoveryON("alch_affinity")) { ArcaneDiscoveries.AlchemicalAffinity.Create(); } if (DiscoveryON("forest_blessing")) { ArcaneDiscoveries.ForestBlessing.Create(); } if (DiscoveryON("suck_it_bft")) { ArcaneDiscoveries.Idealize.Create(); } if (DiscoveryON("muscle_wizard")) { ArcaneDiscoveries.KnowledgeIsPower.Create(); } if (DiscoveryON("opp_research")) { ArcaneDiscoveries.OppositionResearch.Create(); } if (DiscoveryON("staff_wand")) { ArcaneDiscoveries.StaffLikeWand.Create(); } if (DiscoveryON("metamagic_insight") && !no_hb) { ArcaneDiscoveries.MetamagicInsight.Create(); } } if (Main.SettingsContainer.groups["feats"].enabled) { if (FeatON("shrewd_tactician")) { Feats.ShrewdTactician.Create(); } if (FeatON("acadamae")) { Feats.AcadamaeGraduate.Create(); } if (FeatON("meta_intensified")) { Feats.MetamagicIntensfied.Create(); } if (FeatON("meta_dazing")) { Feats.MetamagicDazing.Create(); } } if (Main.SettingsContainer.groups["magus_arcana"].enabled) { if (ArcanaON("law_circle")) { MagusArcana.CircleOfOrder.Create(); } } if (Main.SettingsContainer.groups["mythic"].enabled) { if (MythicON("warrior_priest")) { Mythic.WarriorPriest.Create(); } if (MythicON("mythic_poison") && !no_hb && !WorldcrawlLoaded()) { Mythic.MythicPoisons.Create(); } if (MythicON("material_freedom") && !no_hb) { Mythic.MaterialFreedom.Create(); } } if (Main.SettingsContainer.groups["archetypes"].enabled) { if (ArchetypeON("flagellant") && !no_hb) { Archetypes.Flagellant.Create(); } if (ArchetypeON("warsighted")) { Archetypes.Warsighted.Create(); } if (ArchetypeON("blood_arcanist")) { Archetypes.BloodArcanist.Create(); } if (ArchetypeON("pact_wizard")) { Archetypes.PactWizard.Create(); } } Resources.Cleanup(); } } private static bool ArchetypeON(string id) { return Main.SettingsContainer.groups["archetypes"].settings[id].enabled; } private static bool DiscoveryON(string id) { return Main.SettingsContainer.groups["a_discoveries"].settings[id].enabled; } private static bool FeatON(string id) { return Main.SettingsContainer.groups["feats"].settings[id].enabled; } private static bool ArcanaON(string id) { return Main.SettingsContainer.groups["magus_arcana"].settings[id].enabled; } private static bool MythicON(string id) { return Main.SettingsContainer.groups["mythic"].settings[id].enabled; } private static bool WorldcrawlLoaded() { var ar = ResourcesLibrary.TryGetBlueprint<BlueprintCharacterClass>("3ae2ff4b51ad5bde3436ffac822611c1"); if (ar == null) { return false; } Main.Log("Mythic Poisons disabled because Worldcrawl is present."); return true; } } }
40.5
118
0.570038
e62a1564986fa570c23fc08ac214bb295a8396d2
200
ps1
PowerShell
build.ps1
upperdim/3d-software-renderer
3e81beaebd9d5ee7a1e02f8e543f950a386c348b
[ "MIT" ]
1
2021-08-03T08:12:19.000Z
2021-08-03T08:12:19.000Z
build.ps1
upperdim/3d-software-renderer
3e81beaebd9d5ee7a1e02f8e543f950a386c348b
[ "MIT" ]
null
null
null
build.ps1
upperdim/3d-software-renderer
3e81beaebd9d5ee7a1e02f8e543f950a386c348b
[ "MIT" ]
null
null
null
cd src gcc -c *.c -Wall -I"C:\libsdl\include" -L"C:\libsdl\lib" -lmingw32 -lSDL2main -lSDL2 gcc -s *.o -I"C:\libsdl\include" -L"C:\libsdl\lib" -lmingw32 -lSDL2main -lSDL2 -o .\..\swrender3d.exe cd ..
40
101
0.655
74f46ebffee93bbd4c2e8882e2140ea3fc7c82b7
7,990
css
CSS
public/stylesheets/home_styles.css
Madhuvandhana/stevenshealthcare
20a3ba185b5972d849678401b65d4e5c5c17fdcd
[ "MIT" ]
null
null
null
public/stylesheets/home_styles.css
Madhuvandhana/stevenshealthcare
20a3ba185b5972d849678401b65d4e5c5c17fdcd
[ "MIT" ]
null
null
null
public/stylesheets/home_styles.css
Madhuvandhana/stevenshealthcare
20a3ba185b5972d849678401b65d4e5c5c17fdcd
[ "MIT" ]
null
null
null
* {box-sizing: border-box;} /* header */ .header { overflow: hidden; background-color: #BFEFFF; padding: 20px 10px; } .header a { float: left; color: #296097; text-align: center; padding: 12px; text-decoration: none; font-size: 21px; font-family: graduate; line-height: 25px; border-radius: 4px; } .header a.logo { font-size: 25px; font-weight: bold; } .header a:hover { background-color: #B9D3EE; } .header-right { float: right; } /*============================================ * Hero Area *=============================================*/ .hero-area { padding: 140px 0 211px; background: url(../home_images/hero-bg.jpg) center/cover no-repeat; } .hero-content h2 { font-size: 60px; font-weight: 700; color: #222222; letter-spacing: 0; line-height: 66px; margin-bottom: 17px; } .hero-content p { font-size: 18px; color: #878787; font-weight: 400; letter-spacing: 0; } .hero-content a { margin-top: 35px; display: inline-block; height: 60px; background: #2c76e2; line-height: 60px; letter-spacing: 0; color: #fff; padding: 0 35px; border-radius: 60px; font-size: 16px; font-weight: 500; text-transform: uppercase; } /*============================================ * END Hero Area *=============================================*/ /*============================================ * help-center-area start *=============================================*/ /* .intermediate-region { background-color: white; padding: 100px; } */ .help-center-area { position: relative; z-index: 1; padding-bottom: 100px; padding-top: 50px; } .hlp-center-thumb { margin-right: 30px; border-radius: 9px; overflow: hidden; display: inline-block; } .hlp-center-content>h4 { font-size: 40px; font-weight: 700; color: #222222; line-height: 51px; margin-bottom: 20px; letter-spacing: 0; } .hlp-center-content p { font-size: 16px; color: #878787; letter-spacing: 0; } .help-feature-lists { margin-top: 32px; } .help-feature-lists li { overflow: hidden; display: block; margin-bottom: 20px; } .help-feature-lists li .icon { float: left; height: 70px; width: 70px; border-radius: 50%; background: #0bc1bb; margin-right: 30px; text-align: center; line-height: 68px; padding: 0 17px; } .help-feature-lists li:nth-child(2) .icon { background: #2c76e2; } .help-feature-lists li:nth-child(3) .icon { background: #fe94c4; } .help-feature-lists li .content { overflow: hidden; } .help-feature-lists li .content h4 { font-size: 22px; font-weight: 700; color: #222222; letter-spacing: 0; margin-bottom: 7px; } .help-feature-lists li .content p { font-size: 16px; color: #878787; font-weight: 400; line-height: 26px; } /*============================================ * END help-center-area *=============================================*/ /*============================================ * service-area *=============================================*/ .service-area { padding: 100px 0 55px; position: relative; z-index: 1; } .shape2 { position: absolute; right: 0; bottom: 0; z-index: -1; } .section-title { text-align: center; margin-bottom: 60px; } .section-title h2 { font-size: 40px; letter-spacing: 0; color: #222222; font-weight: 700; line-height: 43px; margin-bottom: 14px; } .single-service { margin-bottom: 45px; } .single-service .icon { height: 72px; margin-bottom: 20px; } .single-service .content h2 { font-size: 22px; color: #222222; letter-spacing: 0; font-weight: 700; margin-bottom: 19px; } .single-service .content p { font-size: 14px; line-height: 26px; } .single-service .content a:hover { color: #1160d4; } .single-service .content a:hover i { margin-left: 5px; } /*============================================ * END service-area *=============================================*/ /*============================================ * doctors-carousel *=============================================*/ .mt-doctor { position: relative; z-index: 1; } .mt-doctor .content { position: absolute; left: 0; bottom: -10px; padding: 25px; width: 100%; opacity: 0; } .mt-doctor:hover .content { opacity: 1; bottom: 0; } .doctors-carousel .owl-dots { text-align: center; margin-top: 50px; } .doctors-carousel .owl-dots { margin-top: 30px; } /* :horizontal */ /* #wrap { display: flex; justify-content: center; } */ /*============================================ * END doctors-carousel *=============================================*/ /*============================================ * book-appointment *=============================================*/ .appointment-inner { position: relative; z-index: 1; padding-top: 50px; margin-bottom: 50px; background: url(../home_images/appointment-bg.jpg) center/cover no-repeat; } .appointment-inner .vector-shape2 { position: absolute; right: 0; bottom: 0; z-index: -1; max-width: 100%; } .appnt-form { margin-right: 60px; margin-bottom: -50px; background: #fff; padding: 40px 50px; box-shadow: 0 5px 15px rgba(0, 0, 0, 0.04); } .appnt-form h4 { font-size: 37px; font-weight: 700; color: #222222; letter-spacing: 0; line-height: 47px; margin-bottom: 28px; } .form-group { margin-bottom: 20px; } .form-control, select.form-control:not([size]):not([multiple]) { height: 50px; border: 1px solid #ebebeb; padding-left: 15px; letter-spacing: 0; font-size: 14px; font-weight: 400; } .form-control:focus, select.form-control:not([size]):not([multiple]):focus { border-color: #2c76e2; box-shadow: none; } textarea.form-control { height: 95px; padding-top: 12px; } .btn { height: 50px; line-height: 48px; font-size: 14px; letter-spacing: 0; padding: 0 15px; } .btn-lg { height: 60px; line-height: 60px; } .btn-primary { background: #2c76e2; } .btn-secondary { background: #2ea6f7; border-color: #2ea6f7; } .btn-secondary:hover { background: #0987dc; border-color: #0987dc; } .btn-secondary.focus, .btn-secondary:focus { box-shadow: 0 0 0 0.2rem rgba(46, 166, 247, 0.26); } .btn-liedark { background: #23408e; color: #fff; } .btn-liedark:hover { background: #2f54b7; border-color: #2f54b7; color: #fff; } .btn-liedark.focus, .btn-liedark:focus { box-shadow: 0 0 0 0.2rem rgba(46, 166, 247, 0.26); } .btn-radius { border-radius: 50px; } /*============================================ * END book-appointment *=============================================*/ /*============================================ * footer-top *=============================================*/ .footer-top { background: #5fc8ee; } .fwidget { margin-bottom: 40px; } .fwidget-company { padding-right: 50px; } .flogo { margin-bottom: 40px; } .flogo a { display: inline-block; } .fwidget-company p { font-size: 16px; color: #878787; } .fwidget-title { font-size: 20px; color: #ffffff; font-weight: 600; letter-spacing: 0; margin-bottom: 23px; } .fwidget .links li { display: block; } .fwidget .links li a { display: block; font-size: 14px; color: #ffffff; letter-spacing: 0; font-weight: 500; margin-bottom: 18px; } .fwidget .links li a:hover { color: #2c76e2; } .footer-bottom-area { padding: 30px 0; background: #142949; } .copyright { color: #8e8d8e; font-size: 14px; } .ft-bottom-sc { text-align: right; } /*============================================ * END footer-top *=============================================*/
17.219828
78
0.520275
8b0089a455f9c069912f7b8b53a86090223a6b77
503
rb
Ruby
lib/kavenegar-ruby/requests/info.rb
jmimi/kavenegar-ruby
e60f13b802dca02b56225ba16543e760b0a8c7da
[ "MIT" ]
4
2017-03-31T18:29:48.000Z
2019-09-23T11:22:25.000Z
lib/kavenegar-ruby/requests/info.rb
KaveNegar/kavenegar-ruby
b7bc1e7917ab94bee2d3c4d2efeade0d2e6834a6
[ "MIT" ]
1
2018-10-20T09:53:17.000Z
2018-10-20T09:53:17.000Z
lib/kavenegar-ruby/requests/info.rb
KaveNegar/kavenegar-ruby
b7bc1e7917ab94bee2d3c4d2efeade0d2e6834a6
[ "MIT" ]
3
2017-06-17T06:59:26.000Z
2018-10-20T09:42:41.000Z
module KaveRestApi class Info < KaveRestApi::RequestBase def initialize(args = {}) @ACTION_NAME = [:info,@FORMAT].join('.').freeze @response = ResponseInfo.new end def call connection = Faraday.new(url: "#{API_URL}/account/") do |faraday| faraday.adapter Faraday.default_adapter faraday.response FORMAT.to_sym end response = connection.get(@ACTION_NAME) @response.validate(response.body) end end end
25.15
73
0.616302
88b8ca3f93c0746462a491d9f59c6746cbde7b67
685
rs
Rust
src/lib.rs
hixio-mh/exit-status-ext
467007352e1e1869b9888fc195a35f9b2ad1ba48
[ "MIT" ]
2
2019-04-14T13:55:25.000Z
2020-01-31T18:02:12.000Z
src/lib.rs
hixio-mh/exit-status-ext
467007352e1e1869b9888fc195a35f9b2ad1ba48
[ "MIT" ]
1
2020-07-01T09:56:21.000Z
2020-07-01T09:56:21.000Z
src/lib.rs
pop-os/exit-status-ext
467007352e1e1869b9888fc195a35f9b2ad1ba48
[ "MIT" ]
4
2020-05-05T00:27:14.000Z
2022-03-25T09:48:09.000Z
use std::io; use std::process::ExitStatus; /// Additional methods for `std::process::ExitStatus`-like types. pub trait ExitStatusExt { /// Converts the exit status into a `io::Result<()>`. fn as_result(self) -> io::Result<()>; } impl ExitStatusExt for ExitStatus { fn as_result(self) -> io::Result<()> { if self.success() { Ok(()) } else if let Some(127) = self.code() { Err(io::Error::new(io::ErrorKind::NotFound, "command was not found")) } else { Err(io::Error::new( io::ErrorKind::Other, format!("command failed with exit status: {}", self), )) } } }
28.541667
81
0.540146
664f2d91c6b8a25d0d209116cc1196d2264e5f1b
73
py
Python
homeassistant/components/senz/const.py
jlmaners/core
9d016dd4346ec776da40f816764a5be441e34a3b
[ "Apache-2.0" ]
30,023
2016-04-13T10:17:53.000Z
2020-03-02T12:56:31.000Z
homeassistant/components/senz/const.py
jlmaners/core
9d016dd4346ec776da40f816764a5be441e34a3b
[ "Apache-2.0" ]
24,710
2016-04-13T08:27:26.000Z
2020-03-02T12:59:13.000Z
homeassistant/components/senz/const.py
jlmaners/core
9d016dd4346ec776da40f816764a5be441e34a3b
[ "Apache-2.0" ]
11,956
2016-04-13T18:42:31.000Z
2020-03-02T09:32:12.000Z
"""Constants for the nVent RAYCHEM SENZ integration.""" DOMAIN = "senz"
18.25
55
0.712329
46c18910800c39a0af697dc04831e7203975e2f5
2,519
py
Python
core/enum.py
devalv/dj-turnirotron9000
b9ba4f0ac30b907e5d7191bef902c85b6b8cd2ad
[ "MIT" ]
1
2021-12-26T00:10:12.000Z
2021-12-26T00:10:12.000Z
core/enum.py
devalv/dj-turnirotron9000
b9ba4f0ac30b907e5d7191bef902c85b6b8cd2ad
[ "MIT" ]
null
null
null
core/enum.py
devalv/dj-turnirotron9000
b9ba4f0ac30b907e5d7191bef902c85b6b8cd2ad
[ "MIT" ]
null
null
null
from django.db import models from django.utils.translation import gettext_lazy as _ class UnitTypes(models.TextChoices): HQ = "HQ", _("Командир") TROOPS = "Troops", _("Пехота") ELITES = "Elites", _("Элита") FAST_ATTACK = "Fast Attack", _("Быстрая атака") HEAVY_SUPPORT = "Heavy Support", _("Артиллерия") FLYERS = "Flyers", _("Летательные аппараты") FORMATION = "Formation", _("Формация") FORTIFICATION = "Fortification", _("Фортификация") LOW = "Lord Of War", _("Лорд войны") OTHER = "Other", _("Прочее") class Fractions(models.TextChoices): SPACE_MARINES = "Space Marines", _("Космодесант") IMPERIUM = "Imperium", _("Империум") NECRONS = "Necrons", _("Некроны") ORKS = "Orks", _("Орки") TYRANIDS = "Tyranids", _("Тираниды") MECHANICUS = "Mechanicus", _("Механикус") SORORITAS = "Adepta Sororitas", _("Сёстры битвы") ASTRA_MILITARUM = "Astra Militarum", _("Имперская гвардия") CHAOS_SPACE_MARINES = "Chaos Space Marines", _("Космодесант хаоса") CHAOS_DAEMONS = "Chaos Daemons", _("Демоны хаоса") TAU = "Tau", _("Тау") ELDAR = "Eldar", _("Эльдар") class GameSystems(models.TextChoices): FORTY = "40K", _("40K") HERESY = "Horus Heresy", _("Ересь Хоруса") class Deployments(models.TextChoices): HAMMER_ANVIL = "Hammer and Anvil", _("Молот и наковальня") DAWN_WAR = "Dawn of War", _("Туман войны") VANGUARD_STRIKE = "Vanguard Strike", _("Авангардный удар") class Missions(models.TextChoices): ETERNAL_WAR_REAPING = "Eternal War: The Reaping", _("Вечная война: Жатва") ETERNAL_WAR_BIG_GUNS = "Eternal War: Big Guns Never Tire", _("Вечная война: Большие пушки") ETERNAL_WAR_SCOURING = "Eternal War: The Scouring", _("Вечная война: Чистка") ETERNAL_WAR_CRUSADE = "Eternal War: Crusade", _("Вечная война: Крестовый поход") ETERNAL_WAR_EMPEROR = "Eternal War: The Emperor`s Will and Relic", _( "Вечная война: Воля Императора" ) MAELSTROM_WAR_CLEANSE = "Maelstrom of War: Cleanse and Control", _( "Водоворот войны: очищение и контроль" ) MAELSTROM_WAR_CONTACT = "Maelstrom of War: Contact Lost", _("Водоворот войны: Контакт потерян") MAELSTROM_WAR_SPOILS = "Maelstrom of War: Spoils of War", _("Водоворот войны: Сполохи войны") MAELSTROM_WAR_TACTICAL = "Maelstrom of War: Tactical Escalation", _( "Водоворот войны: Тактическая эскалация" ) MAELSTROM_WAR_CLOAK = "Maelstrom of War: Cloak and Shadows", _("Водоворот войны: Плащ и тени")
41.295082
99
0.679238
a33142a031a3330df337c8abfd19179e4334bcee
369
ts
TypeScript
src/components/theme/theme-styles.ts
deetoouk/deetooui
a95253021963ca8cb4b96ec4e40e866e9cbe6fe4
[ "MIT" ]
null
null
null
src/components/theme/theme-styles.ts
deetoouk/deetooui
a95253021963ca8cb4b96ec4e40e866e9cbe6fe4
[ "MIT" ]
1
2021-05-10T02:21:36.000Z
2021-05-10T02:21:36.000Z
src/components/theme/theme-styles.ts
deetoouk/deetooui
a95253021963ca8cb4b96ec4e40e866e9cbe6fe4
[ "MIT" ]
null
null
null
import { Style } from 'jss'; import forEach from 'lodash/forEach'; export const GlobalStyles = (theme): Style => { let globalVars = {}; const { name, colors } = theme; forEach(colors, (color, type) => { forEach(color, (value, key) => { globalVars[`--d2-${name}-${type}-${key}-color`] = value; }); }); return { ':root': globalVars }; };
20.5
62
0.566396
d93afb51a5b8fc3de71f61fe04dee89e2ed91987
620
kt
Kotlin
librum/src/main/kotlin/com/librum/ui/reader/EpubReaderChapterCallback.kt
materka/Librum
b681edb4ef0847196c5402a1b7c4733b94deae48
[ "BSD-3-Clause" ]
8
2020-11-06T05:08:23.000Z
2022-02-21T13:54:19.000Z
librum/src/main/kotlin/com/librum/ui/reader/EpubReaderChapterCallback.kt
alphasldiallo/Librum
b681edb4ef0847196c5402a1b7c4733b94deae48
[ "BSD-3-Clause" ]
null
null
null
librum/src/main/kotlin/com/librum/ui/reader/EpubReaderChapterCallback.kt
alphasldiallo/Librum
b681edb4ef0847196c5402a1b7c4733b94deae48
[ "BSD-3-Clause" ]
3
2019-10-21T18:07:29.000Z
2021-08-05T07:20:09.000Z
package com.librum.ui.reader /** * @author lusinabrian on 07/09/17. * @Notes interface to handle chapter click events on drawer, if any */ interface EpubReaderChapterCallback { /** * on chapter clicked, we get the current position of the view and navigate to it * @param position the position of the given item in the adapter * */ fun onChapterClicked(position: Int) /** * on Chapter expanded callback used to expand the current chapter selection, if it has children * @param position the current position of the chapter item * */ fun onChapterExpanded(position: Int) }
32.631579
100
0.701613
7bd77c37429090f62d3db356b42a313c37f22fee
10,358
cpp
C++
third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
5
2015-04-30T09:08:30.000Z
2018-08-13T05:00:39.000Z
third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
third party/openRTMFP-Cumulus/CumulusLib/sources/RTMFPServer.cpp
Patrick-Bay/SocialCastr
888a57ca63037e566f6c0bf03a646ae91b484086
[ "MIT" ]
null
null
null
/* Copyright 2010 OpenRTMFP This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License received along this program for more details (or else see http://www.gnu.org/licenses/). This file is a part of Cumulus. */ #include "RTMFPServer.h" #include "RTMFP.h" #include "Handshake.h" #include "Middle.h" #include "PacketWriter.h" #include "Util.h" #include "Logs.h" #include "Poco/Format.h" #include "string.h" using namespace std; using namespace Poco; using namespace Poco::Net; namespace Cumulus { RTMFPServer::RTMFPServer() : Startable("RTMFPServer"),_pCirrus(NULL),_handshake(*this,_edgesSocket,*this,*this),_sessions(*this) { #ifndef POCO_OS_FAMILY_WINDOWS // static const char rnd_seed[] = "string to make the random number generator think it has entropy"; // RAND_seed(rnd_seed, sizeof(rnd_seed)); #endif DEBUG("Id of this RTMFP server : %s",Util::FormatHex(id,ID_SIZE).c_str()); } RTMFPServer::RTMFPServer(const string& name) : Startable(name),_pCirrus(NULL),_handshake(*this,_edgesSocket,*this,*this),_sessions(*this) { #ifndef POCO_OS_FAMILY_WINDOWS // static const char rnd_seed[] = "string to make the random number generator think it has entropy"; // RAND_seed(rnd_seed, sizeof(rnd_seed)); #endif DEBUG("Id of this RTMFP server : %s",Util::FormatHex(id,ID_SIZE).c_str()); } RTMFPServer::~RTMFPServer() { stop(); } Session* RTMFPServer::findSession(UInt32 id) { // Id session can't be egal to 0 (it's reserved to Handshake) if(id==0) { DEBUG("Handshaking"); return &_handshake; } Session* pSession = _sessions.find(id); if(pSession) return pSession; WARN("Unknown session %u",id); return NULL; } void RTMFPServer::start() { RTMFPServerParams params; start(params); } void RTMFPServer::start(RTMFPServerParams& params) { if(running()) { ERROR("RTMFPServer server is yet running, call stop method before"); return; } _port = params.port; if(_port==0) { ERROR("RTMFPServer port must have a positive value"); return; } _edgesPort = params.edgesPort; if(_port==_edgesPort) { ERROR("RTMFPServer port must different than RTMFPServer edges.port"); return; } _freqManage = 2000000; // 2 sec by default if(params.pCirrus) { _pCirrus = new Target(*params.pCirrus); _freqManage = 0; // no waiting, direct process in the middle case! NOTE("RTMFPServer started in man-in-the-middle mode with server %s (unstable debug mode)",_pCirrus->address.toString().c_str()); } _middle = params.middle; if(_middle) NOTE("RTMFPServer started in man-in-the-middle mode between peers (unstable debug mode)"); (UInt32&)udpBufferSize = params.udpBufferSize==0 ? _socket.getReceiveBufferSize() : params.udpBufferSize; _socket.setReceiveBufferSize(udpBufferSize);_socket.setSendBufferSize(udpBufferSize); _edgesSocket.setReceiveBufferSize(udpBufferSize);_edgesSocket.setSendBufferSize(udpBufferSize); DEBUG("Socket buffer receving/sending size = %u/%u",udpBufferSize,udpBufferSize); (UInt32&)keepAliveServer = params.keepAliveServer<5 ? 5000 : params.keepAliveServer*1000; (UInt32&)keepAlivePeer = params.keepAlivePeer<5 ? 5000 : params.keepAlivePeer*1000; (UInt8&)edgesAttemptsBeforeFallback = params.edgesAttemptsBeforeFallback; setPriority(params.threadPriority); Startable::start(); } bool RTMFPServer::prerun() { NOTE("RTMFP server starts on %u port",_port); if(_edgesPort>0) NOTE("RTMFP edges server starts on %u port",_edgesPort); bool result=true; try { onStart(); result=Startable::prerun(); } catch(Exception& ex) { FATAL("RTMFPServer : %s",ex.displayText().c_str()); } catch (exception& ex) { FATAL("RTMFPServer : %s",ex.what()); } catch (...) { FATAL("RTMFPServer unknown error"); } onStop(); NOTE("RTMFP server stops"); return result; } void RTMFPServer::run(const volatile bool& terminate) { SocketAddress address("0.0.0.0",_port); _socket.bind(address,true); SocketAddress edgesAddress("0.0.0.0",_edgesPort); if(_edgesPort>0) _edgesSocket.bind(edgesAddress,true); SocketAddress sender; UInt8 buff[PACKETRECV_SIZE]; int size = 0; while(!terminate) { bool stop=false; bool idle = realTime(stop); if(stop) break; _handshake.isEdges=false; if(_socket.available()>0) { try { size = _socket.receiveFrom(buff,sizeof(buff),sender); } catch(Exception& ex) { DEBUG("Main socket reception : %s",ex.displayText().c_str()); _socket.close(); _socket.bind(address,true); continue; } } else if(_edgesPort>0 && _edgesSocket.available()>0) { try { size = _edgesSocket.receiveFrom(buff,sizeof(buff),sender); _handshake.isEdges=true; } catch(Exception& ex) { DEBUG("Main socket reception : %s",ex.displayText().c_str()); _edgesSocket.close(); _edgesSocket.bind(edgesAddress,true); continue; } Edge* pEdge = edges(sender); if(pEdge) pEdge->update(); } else { if(idle) { Thread::sleep(1); if(!_timeLastManage.isElapsed(_freqManage)) { // Just middle session! if(_middle) { Sessions::Iterator it; for(it=_sessions.begin();it!=_sessions.end();++it) { Middle* pMiddle = dynamic_cast<Middle*>(it->second); if(pMiddle) pMiddle->manage(); } } } else { _timeLastManage.update(); manage(); } } continue; } if(isBanned(sender.host())) { INFO("Data rejected because client %s is banned",sender.host().toString().c_str()); continue; } if(size<RTMFP_MIN_PACKET_SIZE) { ERROR("Invalid packet"); continue; } PacketReader packet(buff,size); Session* pSession=findSession(RTMFP::Unpack(packet)); if(!pSession) continue; if(!pSession->checked) _handshake.commitCookie(*pSession); pSession->setEndPoint(_handshake.isEdges ? _edgesSocket : _socket,sender); pSession->receive(packet); } _handshake.clear(); _sessions.clear(); _socket.close(); if(_edgesPort>0) _edgesSocket.close(); if(_pCirrus) { delete _pCirrus; _pCirrus = NULL; } } UInt8 RTMFPServer::p2pHandshake(const string& tag,PacketWriter& response,const SocketAddress& address,const UInt8* peerIdWanted) { // find the flash client equivalence Session* pSession = NULL; Sessions::Iterator it; for(it=_sessions.begin();it!=_sessions.end();++it) { pSession = it->second; if(Util::SameAddress(pSession->peer.address,address)) break; } if(it==_sessions.end()) pSession=NULL; ServerSession* pSessionWanted = (ServerSession*)_sessions.find(peerIdWanted); if(_pCirrus) { // Just to make working the man in the middle mode ! if(!pSession) { ERROR("UDP Hole punching error : middle equivalence not found for session wanted"); return 0; } PacketWriter& request = ((Middle*)pSession)->handshaker(); request.write8(0x22);request.write8(0x21); request.write8(0x0F); request.writeRaw(pSessionWanted ? ((Middle*)pSessionWanted)->middlePeer().id : peerIdWanted,ID_SIZE); request.writeRaw(tag); ((Middle*)pSession)->sendHandshakeToTarget(0x30); // no response here! return 0; } if(!pSessionWanted) { DEBUG("UDP Hole punching : session wanted not found, must be dead"); return 0; } else if(pSessionWanted->failed()) { DEBUG("UDP Hole punching : session wanted is deleting"); return 0; } UInt8 result = 0x00; if(_middle) { if(pSessionWanted->pTarget) { HelloAttempt& attempt = _handshake.helloAttempt<HelloAttempt>(tag); attempt.pTarget = pSessionWanted->pTarget; _handshake.createCookie(response,attempt,tag,""); response.writeRaw("\x81\x02\x1D\x02"); response.writeRaw(pSessionWanted->pTarget->publicKey,KEY_SIZE); result = 0x70; } else ERROR("Peer/peer dumped exchange impossible : no corresponding 'Target' with the session wanted"); } if(result==0x00) { /// Udp hole punching normal process pSessionWanted->p2pHandshake(address,tag,pSession); bool first=true; list<Address>::const_iterator it2; for(it2=pSessionWanted->peer.addresses.begin();it2!=pSessionWanted->peer.addresses.end();++it2) { const Address& addr = *it2; if(addr == address) { CRITIC("Two peers with the same %s address?",address.toString().c_str()); continue; } response.writeAddress(addr,first); first=false; } result = 0x71; } return result; } Session& RTMFPServer::createSession(UInt32 farId,const Peer& peer,const UInt8* decryptKey,const UInt8* encryptKey,Cookie& cookie) { Target* pTarget=_pCirrus; if(_middle) { if(!cookie.pTarget) { cookie.pTarget = new Target(peer.address,&cookie); memcpy((UInt8*)cookie.pTarget->peerId,peer.id,ID_SIZE); memcpy((UInt8*)peer.id,cookie.pTarget->id,ID_SIZE); NOTE("Mode 'man in the middle' : to connect to peer '%s' use the id :\n%s",Util::FormatHex(cookie.pTarget->peerId,ID_SIZE).c_str(),Util::FormatHex(cookie.pTarget->id,ID_SIZE).c_str()); } else pTarget = cookie.pTarget; } ServerSession* pSession; if(pTarget) { pSession = new Middle(_sessions.nextId(),farId,peer,decryptKey,encryptKey,*this,_sessions,*pTarget); if(_pCirrus==pTarget) pSession->pTarget = cookie.pTarget; DEBUG("500ms sleeping to wait cirrus handshaking"); Thread::sleep(500); // to wait the cirrus handshake pSession->manage(); } else { pSession = new ServerSession(_sessions.nextId(),farId,peer,decryptKey,encryptKey,*this); pSession->pTarget = cookie.pTarget; } _sessions.add(pSession); return *pSession; } void RTMFPServer::destroySession(Session& session) { if(session.flags&SESSION_BY_EDGE) { Edge* pEdge = edges(session.peer.address); if(pEdge) pEdge->removeSession(session); } } void RTMFPServer::manage() { _handshake.manage(); if(_sessions.manage()) displayCount(_sessions.count()); if(!_middle && !_pCirrus && _timeLastManage.isElapsed(20000)) WARN("Process management has lasted more than 20ms : %ums",UInt32(_timeLastManage.elapsed()/1000)); } void RTMFPServer::displayCount(UInt32 sessions) { INFO("%u clients",clients.count()); } } // namespace Cumulus
28.070461
187
0.708728
24b9cd598c6479a9e312c041bb459497ad0d5f2e
2,277
php
PHP
resources/views/master/permissions/show.blade.php
burrodecarga/base-laravel-8-roles
3255ea1552f07e30866d03308c8896f7e019caed
[ "MIT" ]
null
null
null
resources/views/master/permissions/show.blade.php
burrodecarga/base-laravel-8-roles
3255ea1552f07e30866d03308c8896f7e019caed
[ "MIT" ]
null
null
null
resources/views/master/permissions/show.blade.php
burrodecarga/base-laravel-8-roles
3255ea1552f07e30866d03308c8896f7e019caed
[ "MIT" ]
null
null
null
@extends('adminlte::page') @section('content') <div class="container"> <div class="row"> <div class="col-12 col-md-12 mx-auto"> <h4><strong>{{__($title)}}</strong>{{' : '.__($permission->name)}}</h4> <form class="bg-white shadow rounded py-3 px-3" action="{{route('permissions.index')}}"> <div class="row"> <div class="form-group col-12 col-md-6"> <label for="name" class="form-label font-weight-bold text-capitalize">{{__("name of permission")}} </label> <input id="name" type="text" name="name" value="{{old('name', $permission->name)}}" class="form-control shadow-sm" readonly> </div> <div class="form-group col-12 col-md-6"> <label for="name" class="form-label font-weight-bold text-capitalize">{{__("work area")}} </label> <input id="name" type="text" name="name" value="{{old('area', $permission->permission)}}" class="form-control shadow-sm" readonly> </div> <div class="form-group col-md-12"> <h3 class="display-6 text-capitalize font-weight-bold">{{__('roles with permission')}}</h3> <hr> </div> <div class="form-group col-md-12"> <div class="form-group col-md-12"> <div class="row"> @foreach ($roles as $key => $p) <div class="form-check col-md-4"> <label class="form-check-label"> <p>{{$p}}</p> </label> </div> @endforeach </div> </div> <hr> <div class="form-group"> <a href="{{route('permissions.index')}}" class="btn btn-info mt-2 mb-2 text-capitalize">{{__('back')}} </a> </div> </div> </form> </div> </div> </div> @stop @section('css') {{-- <link rel="stylesheet" href="/css/admin_custom.css"> --}} @stop @section('js') <script> </script> @stop
35.578125
122
0.44664
df1eec69c2a0e9bcf58c375579e5c4ff7ccb1445
410
rb
Ruby
lib/jibby.rb
sidapa/jibby
87616da02d9c86331fae70347f5977456136aa97
[ "MIT" ]
null
null
null
lib/jibby.rb
sidapa/jibby
87616da02d9c86331fae70347f5977456136aa97
[ "MIT" ]
4
2015-07-25T01:13:18.000Z
2015-08-09T14:52:37.000Z
lib/jibby.rb
sidapa/jibby
87616da02d9c86331fae70347f5977456136aa97
[ "MIT" ]
null
null
null
Dir["#{File.dirname(__FILE__)}/jibby/**/*.rb"].each { |file| require file } # Jibby is a console client that connects to JIRA module Jibby class << self attr_reader :gateway end module_function def interface @interface ||= Console.new end def application @application ||= Application.new end def start(host) @gateway = JiraGateway.new(host) application.start end end
17.083333
75
0.678049
fd86ec53b56069b4680bce99ffc89ae67bb14415
3,149
css
CSS
css/cards.css
Bandwidth/design-system
773e498eab90f1e8b63f5f09676f4296ff28a86d
[ "MIT" ]
null
null
null
css/cards.css
Bandwidth/design-system
773e498eab90f1e8b63f5f09676f4296ff28a86d
[ "MIT" ]
19
2017-04-12T19:14:25.000Z
2017-08-30T14:30:35.000Z
css/cards.css
Bandwidth/design-system
773e498eab90f1e8b63f5f09676f4296ff28a86d
[ "MIT" ]
2
2018-10-01T18:04:56.000Z
2019-08-09T03:22:09.000Z
@import url('buttons.css'); body *, html *{ -webkit-transition: all 0.3s; -moz-transition: all 0.3s; transition: all 0.3s; } .card{ border-radius: var(--border-radius); height: auto; margin: var(--m); box-shadow: var(--shadow); vertical-align: top; } .card h2{ font-weight: 500; font-size: 1.2em; text-transform: uppercase; margin: 0; } .card-image, .card-details, .card-action{ padding: var(--m); } .normal .inner:last-child{ border-top: var(--bw-border); } .left-image{ cursor: pointer; } .left-image *{ float: left; width: 50%; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .clickable{ cursor: pointer; } .clickable:hover{ box-shadow: var(--shadow-hover); } .clickable:active{ box-shadow: var(--shadow); } .wButton .card-action button{ display: block; margin: 0 auto; } .card-image{ color: #fff; font-size: 1.2em; font-weight: 500; text-transform: uppercase; background-image: url("../images/blue.png"); background-size: cover; padding-top: var(--xl); border-radius: var(--border-radius) var(--border-radius) 0px 0px; } .cardsContainer{ box-shadow: var(--shadow); border-radius: var(--border-radius); display: flex; margin: var(--m) 0px; } .cardsContainer .card{ border-right: var(--bw-border); } .cardsContainer .card, .cardsContainer .card .card-image{ flex: 1; margin: 0; box-shadow: none; border-radius: 0px; } .cardsContainer .card:first-child{ border-radius: var(--border-radius) 0px 0px var(--border-radius); } .cardsContainer .card:first-child .card-image{ border-radius: var(--border-radius) 0px 0px 0px; } .cardsContainer .card:last-child{ border-radius: 0px var(--border-radius) var(--border-radius) 0px; } .cardsContainer .card:last-child .card-image{ border-radius: 0px var(--border-radius) 0px 0px; } .cardsContainerSpaced{ display: flex; justify-content: space-between; margin: var(--m) 0px; } .cardsContainerSpaced .card{ border-right: var(--bw-border); } .cardsContainerSpaced .card:first-child{ margin-left: 0px; } .cardsContainerSpaced .card:last-child { margin-right: 0px; } .cardsContainerSpaced .card{ flex: 1; } .fixed{ width: 900px; margin: var(--m) auto; } .smaller{ font-size: .85em; line-height: 1.5em; } @media (max-width: 900px){ .cardsContainerSpaced{ flex-direction: column; width: 90vw; margin: 0 auto; } .cardsContainerSpaced .card{ margin: var(--s) 0px; } .cardsContainer{ flex-direction: column; width: 90vw; margin: 0 auto; } .cardsContainer .card{ border: none; border-bottom: var(--bw-border); } .cardsContainer .card:first-child{ border-radius: var(--border-radius) var(--border-radius) 0px 0px; } .cardsContainer .card:first-child .card-image{ border-radius: var(--border-radius) var(--border-radius) 0px 0px; } .cardsContainer .card:last-child{ border-radius: 0px 0px var(--border-radius) var(--border-radius); border-bottom: none; } .cardsContainer .card:last-child .card-image{ border-radius: 0px 0px var(--border-radius) var(--border-radius); } }
21.568493
69
0.666243
2fb3c3428f697abdd7be188f6220ff2f03a32b0d
666
py
Python
scanner/dummy_GPIO.py
mcecchi/SuperScanTest
63aeed26ccb6a80f4edd58ab523037d45f67625b
[ "Apache-2.0" ]
81
2017-05-17T02:10:59.000Z
2022-02-03T08:22:44.000Z
scanner/dummy_GPIO.py
smilejx/sweep-3d-scanner
2d245517b04ca49ea3d1238d1625fa0c993274c0
[ "MIT" ]
43
2017-05-16T19:57:48.000Z
2020-01-13T01:16:37.000Z
scanner/dummy_GPIO.py
smilejx/sweep-3d-scanner
2d245517b04ca49ea3d1238d1625fa0c993274c0
[ "MIT" ]
53
2017-05-17T02:24:45.000Z
2022-02-06T08:46:04.000Z
""" Dummy version of GPIO """ from random import randint BCM = 1 IN = 2 PUD_DOWN = 3 FALLING = 4 RELEASE = 5 def setmode(mode=None): """ Docstring """ pass def setup(pin=None, IO=None, pull_up_down=None): """ Docstring """ pass def add_event_detect(pin=None, edge=None, callback=None, bouncetime=None): """ Docstring """ pass def input(pin=None): """ Docstring """ # simulates an input 10% of the time return randint(0, 10) < 1 def event_detected(pin=None): """ Docstring """ # simulates an input 10% of the time return randint(0, 10) < 1 def remove_event_detect(pin=None): """ Docstring """ pass
16.243902
74
0.621622
e69d1d8a2a4aa16a0fcec02eb5041375ecec512d
2,126
c
C
src/parse.c
alexmyczko/logswan
ad3efac05fb79937eaf57ee2c294a48a2629d971
[ "BSD-2-Clause" ]
null
null
null
src/parse.c
alexmyczko/logswan
ad3efac05fb79937eaf57ee2c294a48a2629d971
[ "BSD-2-Clause" ]
null
null
null
src/parse.c
alexmyczko/logswan
ad3efac05fb79937eaf57ee2c294a48a2629d971
[ "BSD-2-Clause" ]
null
null
null
/*****************************************************************************/ /* */ /* Logswan 2.0.3 */ /* Copyright (c) 2015-2018, Frederic Cambus */ /* https://www.logswan.org */ /* */ /* Created: 2015-05-31 */ /* Last Updated: 2018-10-15 */ /* */ /* Logswan is released under the BSD 2-Clause license. */ /* See LICENSE file for details. */ /* */ /*****************************************************************************/ #include <string.h> #include "parse.h" void parseDate(struct date *parsedDate, char *date) { parsedDate->day = strtok(date, "/"); parsedDate->month = strtok(NULL, "/"); parsedDate->year = strtok(NULL, ":"); parsedDate->hour = strtok(NULL, ":"); parsedDate->minute = strtok(NULL, ":"); parsedDate->second = strtok(NULL, " "); } void parseLine(struct logLine *parsedLine, char *lineBuffer) { if (*lineBuffer) { /* Remote host */ parsedLine->remoteHost = strtok(lineBuffer, " "); /* User-identifier */ strtok(NULL, " "); /* User ID */ strtok(NULL, "["); /* Date */ parsedLine->date = strtok(NULL, "]"); /* Requested resource */ strtok(NULL, "\""); parsedLine->request = strtok(NULL, "\""); /* HTTP status codes */ parsedLine->statusCode = strtok(NULL, " "); /* Returned object size */ parsedLine->objectSize = strtok(NULL, " \""); } } void parseRequest(struct request *parsedRequest, char *request) { char *pch = strrchr(request, ' '); if (pch) { parsedRequest->protocol = pch + 1; parsedRequest->method = strtok(request, " "); } }
32.707692
79
0.392756
a4980790a43b29afdd867daeef3da13eb48fbc0d
6,833
php
PHP
app/Http/Controllers/CategoriaController.php
engelcituk/POS
f76788080c52a1a002473bdc28be7eb45c13dea7
[ "MIT" ]
null
null
null
app/Http/Controllers/CategoriaController.php
engelcituk/POS
f76788080c52a1a002473bdc28be7eb45c13dea7
[ "MIT" ]
null
null
null
app/Http/Controllers/CategoriaController.php
engelcituk/POS
f76788080c52a1a002473bdc28be7eb45c13dea7
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use function GuzzleHttp\json_decode; use Yajra\DataTables\DataTables; use Illuminate\Support\Facades\Storage; use Image; class CategoriaController extends Controller { public $urlBase = ""; public function __construct(){ $this->middleware('accesoCategoriasFiltro'); $this->urlBase = $this->urlApiTPV()."Categoria/"; } public function index(){ $categorias = $this->obtenerTodasLasCategorias(); return view('categorias',compact('categorias')); } public function AllCategorias(){ $categorias = $this->obtenerTodasLasCategorias(); $acciones = 'categorias.datatables.botones'; /*creo los botones de acciones en una vista*/ return Datatables::of($categorias) ->addColumn('acciones', $acciones) ->rawColumns(['acciones'])->make(true); /*Retorno los datos en un datatables y pinto los botones que obtengo de la vista*/ } public function obtenerTodasLasCategorias(){ //es una funcion que esta en el controller principal $respuesta = $this->realizarPeticion('GET', $this->urlBase.'GetCategoria'); $datos = json_decode($respuesta); $categorias = $datos->objeto; return $categorias; } public function create() { // $users = \App::call('App\Http\Controllers\ApiUsuarioController@obtenerTodosLosUsuarios'); return view('categorias.partials.create'); } public function store(Request $request){ $nombreCategoria = $request->get('name'); $idUsuario = $request->get('idUsuarioAlta'); $orden = $request->get('orden'); $imagen = $request->file('imagen'); //Creamos una instancia de la libreria instalada // $imagen = Image::make(\Input::file('imagen')); // Cambiar de tamaño // $imagen->resize(400, 400); if ($imagen == null) { $nombreImg = "SIN IMAGEN"; } else { $imgUrl = $imagen->store('public/categorias');//guardo la img $nombreImg = basename($imgUrl); //obtengo su nombre el que se guarda en la db $image = Image::make(Storage::get($imgUrl)); //obtengo la img $image->resize(400, 300); // $image->resize(400, 300, function ($constraint) { //le modifco las medidas // $constraint->aspectRatio(); // $constraint->upsize(); // }); Storage::put($imgUrl, (string) $image->encode('jpg', 50)); //reemplazo la imagen anterior. } // dd( $icono); $this->guardarCategoria($nombreCategoria, $idUsuario, $orden, $nombreImg); return redirect('/categorias'); } public function guardarCategoria($nombreCategoria, $idUsuario, $orden, $nombreImg){ $respuesta = $this->realizarPeticion('POST', $this->urlBase.'AddCategoria', [ 'form_params' => [ 'name' => $nombreCategoria, "idUsuarioAlta" => $idUsuario, 'orden' => $orden, "imagen" =>$nombreImg ] ]); return $respuesta; } public function show($idCategoria){ $categoria = $this->obtenerUnaCategoria($idCategoria); $idUsuario = $categoria->idUsuarioAlta; $usuario = new ApiUsuarioController(); $usuario = $usuario->obtenerUnUsuario($idUsuario); return view('categorias.partials.show', compact('categoria', 'usuario')); } public function edit($idCategoria){ $categoria = $this->obtenerUnaCategoria($idCategoria); $idUsuario = $categoria->idUsuarioAlta; $usuario = new ApiUsuarioController(); $usuario = $usuario->obtenerUnUsuario($idUsuario); $users = \App::call('App\Http\Controllers\ApiUsuarioController@obtenerTodosLosUsuarios'); return view('categorias.partials.edit', compact('categoria', 'usuario', 'users')); } public function obtenerUnaCategoria($idCategoria){ $respuesta = $this->realizarPeticion('GET', $this->urlBase . "GetCategoria/{$idCategoria}"); $datos = json_decode($respuesta); $categoria = $datos->objeto; return $categoria; } public function actualizar(Request $request){ $idCategoria = $request->get('id'); $nombreCategoria = $request->get('name'); $idUsuario = $request->get('idUsuarioAlta'); $orden = $request->get('orden'); $imagen = $request->file('imagen'); $nombreImgApi = $request->get('imagenValor'); if ($imagen == null) { $nombreImg = $nombreImgApi; } else { $rutaImg = "/storage/categorias/" . $nombreImgApi; $imgUrlBorrar = str_replace('storage', 'public', $rutaImg); Storage::delete($imgUrlBorrar); $imgUrl = $imagen->store('public/categorias'); $nombreImg = basename($imgUrl); //modifico las dimensiones de la img agregada $image = Image::make(Storage::get($imgUrl)); //obtengo la img $image->resize(400, 300); // $image->resize(400, 300, function ($constraint) { //le modifco las medidas // $constraint->aspectRatio(); // $constraint->upsize(); // }); Storage::put($imgUrl, (string) $image->encode('jpg', 50)); //reemplazo la imagen anterior. } // dd( $icono); $this-> actualizarCategoria($idCategoria, $nombreCategoria, $idUsuario, $orden, $nombreImg); return redirect('/categorias'); } public function actualizarCategoria($idCategoria,$nombreCategoria,$idUsuario,$orden, $nombreImg){ $respuesta = $this->realizarPeticion('POST', $this->urlBase."UpdateCategoria/{$idCategoria}", [ 'form_params' => [ 'name' => $nombreCategoria, "idUsuarioAlta"=> $idUsuario, 'orden' => $orden, "imagen"=> $nombreImg ] ]); return $respuesta; } public function destroy(Request $request, $idCategoria){ $nombreImg = $request->get('nombreImagen'); $respuesta = $this->realizarPeticion('POST', $this->urlBase."DeleteCategoria/{$idCategoria}"); $datos = json_decode($respuesta); $ok = $datos->ok; //si respuesta de api es true borro en mi carpeta el archivo if ($ok) { $rutaImg = "/sandostpv/storage/categorias/" . $nombreImg; $imgUrlBorrar = str_replace('storage', 'public', $rutaImg); Storage::delete($imgUrlBorrar); } return redirect('/categorias'); } }
33.826733
134
0.578809
2c590980d0fd0e12ed4d1c1b315d21272a512ecb
6,339
py
Python
release_motif.py
SteadfastAsArt/simple_motif
f6b07f52b8cecd1317dbe8753e7f5e1766e74413
[ "Apache-2.0" ]
2
2019-07-04T05:37:47.000Z
2021-04-24T05:33:47.000Z
release_motif.py
SteadfastAsArt/simple_motif
f6b07f52b8cecd1317dbe8753e7f5e1766e74413
[ "Apache-2.0" ]
null
null
null
release_motif.py
SteadfastAsArt/simple_motif
f6b07f52b8cecd1317dbe8753e7f5e1766e74413
[ "Apache-2.0" ]
null
null
null
import warnings warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') import sys from sklearn.linear_model import LogisticRegression import detect_contract as sm import graph_utils as gu import numpy as np import time import pickle as pk import csv import os import observation as ob import itertools import random import math import performance_analysis as pa from collections import defaultdict def uniform_sphere_sampling(dim, N, r): vec = np.random.randn(dim, N) vec /= np.linalg.norm(vec, axis=0) vec *= r return vec def release_specific(_motif, trans_motif, emb, final_emb, radius2, dim, flag_triad=False, flag_conn=False): """ Release new node back to original :param _motif: :param trans_motif: :param g: :param emb: pre-trained emb. to be released, not the original emb0 :param final_emb: :param radius2: :param flag_triad: :param flag_conn: :return: """ _map = defaultdict(list) # _map: new node -> anchors:list for k in _motif.keys(): for kk in trans_motif.keys(): if _motif[k] == trans_motif[kk]: for _k in k: # tuple k -> _k _map[kk].append(_k) # anchors:list out = [] with open(final_emb, 'a+') as f: central_np = ob.get_central(emb) for k in emb.keys(): if k in trans_motif.keys(): # k -> new node # suitable for spanners with interactions if flag_triad: # different spanners' rules towards triads _r = ob.euclidean_dist(emb[_map[k][-1]], emb[k]) # _r = 0.0 elif flag_conn: # _r = np.mean([ob.euclidean_dist(emb[kk], emb[k]) for kk in _map[k]]) # _r = ob.euclidean_dist(emb[_map[k][-1]], emb[k]) # _r = radius2 * 0.8 _r = radius2 else: # for fans _r = radius2 if not flag_conn: # different center rules towards connectors center = _map[k][0] else: center = k for item in trans_motif[k]: cnt = 0 v1 = np.array(emb[center]) - central_np # central -> anchor # while True: # # todo: dimension 128 is hyper_parameter that could be toned; hyper-sphere surface sampling # # todo: THIS is slow !!!! # vec_list = uniform_sphere_sampling(dim, 1, _r).transpose() # # if not flag_conn and _r != 0.0 and ob.cosine(v1, vec_list[0]) < -1/2: # if not flag_conn and _r != 0.0: # cnt += 1 # continue # else: # break vec_list = uniform_sphere_sampling(dim, 1, _r).transpose() _vec = [] for idx, i in enumerate(vec_list[0]): # centered at anchor/(new_node) _vec.append(round(emb[center][idx] + i, 8)) f.write(str(item)) for x in _vec: f.write(" " + str(x)) f.write('\n') out.append(k) return out def get_r2(g, emb): # radius2: suitable for spanners with no interactions # control the sampling size if g.number_of_edges() < 1e4: # todo: from 3e4 -> 1e4 _rate = int(len(g)/3) else: _rate = int(len(g)/20) x1, l1 = pa.sample_positive(g, emb, _rate) x2, l2 = pa.sample_negative(g, emb, len(x1)) _X = (x1 + x2) X = np.array(_X).reshape(-1, 1) _label = (l1 + l2) LogR = LogisticRegression(C=1e5, ) print('Start fit:', time.ctime()) clf_logR = LogR.fit(X, _label) print('End fit:', time.ctime()) # radius2 = sum(x1+x2) / len(x1+x2) radius2 = LogR.intercept_ / LogR.coef_ print("radius2: {}".format(radius2)) return radius2 def release(_dir, _name, g_fil, method, dim): print('Release start: {}', time.ctime()) start = time.time() fan = ob.loadpy2mem(_dir + 'det_fans.' + _name) conn2 = ob.loadpy2mem(_dir + 'det_conn2.' + _name) triad = ob.loadpy2mem(_dir + 'det_triads.' + _name) trans_fan = ob.loadpy2mem(_dir + 'trans_fans.' + _name) trans_conn2 = ob.loadpy2mem(_dir + 'trans_conn2.' + _name) trans_triad = ob.loadpy2mem(_dir + 'trans_triads.' + _name) emb = gu.load_emb2(_dir + _name + '.' + method + '.emb') emb0 = gu.load_emb2(_dir + _name + '0.' + method + '.emb') print('original emb. size: {}'.format(len(emb0))) # manipulate on the new_graph g = gu.load_edgelist(_dir + g_fil, _name=_name) start_r2 = time.time() radius2 = get_r2(g, emb) end_r2 = time.time() print('R2 time:', end_r2 - start_r2) final_emb = _dir + _name + '1.' + method + '.emb' a = release_specific(fan, trans_fan, emb, final_emb, radius2, dim) b = release_specific(conn2, trans_conn2, emb, final_emb, radius2, dim, flag_conn=True) c = release_specific(triad, trans_triad, emb, final_emb, radius2, dim, flag_triad=True) rr = a+b+c todo = [] for k in emb.keys(): if k not in rr: todo.append(k) start = time.time() # take care of those nodes not in motifs with open(final_emb, 'a+') as f: for t in todo: f.write(str(t)) for item in emb[t]: f.write(" " + str(item)) f.write('\n') end = time.time() print(end - start) with open(final_emb, 'r+') as f: content = f.read() f.seek(0, 0) f.write(str(len(emb0)) + " 128\n"+content) end = time.time() print('Release End, total time cost: {}', end-start) test = gu.load_emb2(final_emb) print('post-trained emb. size: {}'.format(len(test))) print('post-trained emb. dimension: {}'.format(len(test[1]))) del test if __name__ == '__main__': root = './dataset/_social/' _name = 'arenas-pgp' g_file = 'out.new.arenas-pgp' # new graph method = 'dw' # enum: {gf, dw, n2v, line, sage} dim = 128 _dir = root + _name + '/' release(_dir, _name, g_file, method, dim, )
33.718085
117
0.548351
affbd1b322a7a7596f5d29c71d45a202026745ad
5,666
py
Python
ace_parser.py
Clearailhc/ACE2005-toolk
f41e6c499e04fdd6f3cca4e1384da0d678b6df3b
[ "MIT" ]
23
2020-12-14T07:53:53.000Z
2021-12-27T08:18:46.000Z
ace_parser.py
Clearailhc/ACE2005-toolk
f41e6c499e04fdd6f3cca4e1384da0d678b6df3b
[ "MIT" ]
3
2021-07-19T09:00:57.000Z
2022-03-08T20:31:44.000Z
ace_parser.py
Clearailhc/ACE2005-toolk
f41e6c499e04fdd6f3cca4e1384da0d678b6df3b
[ "MIT" ]
3
2021-12-01T17:41:11.000Z
2022-02-28T01:05:29.000Z
from xml.etree import ElementTree class Parser: def __init__(self, path): self.entity_mentions = [] self.event_mentions = [] self.relation_mentions = [] self.parse_xml(path + '.apf.xml') def parse_xml(self, xml_path): tree = ElementTree.parse(xml_path) root = tree.getroot() for child in root[0]: if child.tag == 'entity': self.entity_mentions.extend(self.parse_entity_tag(child)) elif child.tag in ['value', 'timex2']: self.entity_mentions.extend(self.parse_value_timex_tag(child)) elif child.tag == 'event': self.event_mentions.extend(self.parse_event_tag(child)) elif child.tag == 'relation': self.relation_mentions.extend(self.parse_relation_tag(child)) @staticmethod def parse_entity_tag(node): entity_mentions = [] for child in node: if child.tag != 'entity_mention': continue extent = child[0] head = child[1] charset = extent[0] head_charset = head[0] entity_mention = dict() entity_mention['entity-id'] = child.attrib['ID'] entity_mention['entity-type'] = '{}:{}'.format(node.attrib['TYPE'], node.attrib['SUBTYPE']) entity_mention['text'] = charset.text entity_mention['position'] = [int(charset.attrib['START']), int(charset.attrib['END'])] entity_mention["head"] = {"text": head_charset.text, "position": [int(head_charset.attrib['START']), int(head_charset.attrib['END'])]} entity_mentions.append(entity_mention) return entity_mentions @staticmethod def parse_relation_tag(node): relation_mentions = [] for child in node: if child.tag != 'relation_mention': continue extent = child[0] charset = extent[0] relation_mention = dict() relation_mention['relation-id'] = child.attrib['ID'] relation_mention['relation-type'] = '{}:{}'.format(node.attrib['TYPE'], node.attrib['SUBTYPE']) relation_mention['text'] = charset.text relation_mention['position'] = [int(charset.attrib['START']), int(charset.attrib['END'])] relation_mention['arguments'] = [] for child2 in child: if child2.tag == 'relation_mention_argument': extent = child2[0] charset = extent[0] relation_mention['arguments'].append({ 'text': charset.text, 'position': [int(charset.attrib['START']), int(charset.attrib['END'])], 'role': child2.attrib['ROLE'], 'entity-id': child2.attrib['REFID'], }) relation_mentions.append(relation_mention) return relation_mentions @staticmethod def parse_event_tag(node): event_mentions = [] for child in node: if child.tag == 'event_mention': event_mention = dict() event_mention['event-id'] = child.attrib['ID'] event_mention['event_type'] = '{}:{}'.format(node.attrib['TYPE'], node.attrib['SUBTYPE']) event_mention['arguments'] = [] for child2 in child: if child2.tag == 'ldc_scope': charset = child2[0] event_mention['text'] = charset.text event_mention['position'] = [int(charset.attrib['START']), int(charset.attrib['END'])] if child2.tag == 'anchor': charset = child2[0] event_mention['trigger'] = { 'text': charset.text, 'position': [int(charset.attrib['START']), int(charset.attrib['END'])], } if child2.tag == 'event_mention_argument': extent = child2[0] charset = extent[0] event_mention['arguments'].append({ 'text': charset.text, 'position': [int(charset.attrib['START']), int(charset.attrib['END'])], 'role': child2.attrib['ROLE'], 'entity-id': child2.attrib['REFID'], }) event_mentions.append(event_mention) return event_mentions @staticmethod def parse_value_timex_tag(node): entity_mentions = [] for child in node: extent = child[0] charset = extent[0] entity_mention = dict() entity_mention['entity-id'] = child.attrib['ID'] if 'TYPE' in node.attrib: entity_mention['entity-type'] = node.attrib['TYPE'] if 'SUBTYPE' in node.attrib: entity_mention['entity-type'] += ':{}'.format(node.attrib['SUBTYPE']) if child.tag == 'timex2_mention': entity_mention['entity-type'] = 'TIM:time' entity_mention['text'] = charset.text entity_mention['position'] = [int(charset.attrib['START']), int(charset.attrib['END'])] entity_mention["head"] = {"text": charset.text, "position": [int(charset.attrib['START']), int(charset.attrib['END'])]} entity_mentions.append(entity_mention) return entity_mentions
41.357664
119
0.518708
33b4a9c2e10bcb887f5f963ce40d2b3f059297b7
13,339
c
C
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/x86/oprofile/op_model_amd.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
4
2017-05-17T11:27:04.000Z
2020-05-24T07:23:26.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/x86/oprofile/op_model_amd.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
1
2018-08-21T03:42:06.000Z
2018-08-21T03:42:06.000Z
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/x86/oprofile/op_model_amd.c
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
5
2017-10-11T08:09:11.000Z
2020-10-14T04:10:13.000Z
/* * @file op_model_amd.c * athlon / K7 / K8 / Family 10h model-specific MSR operations * * @remark Copyright 2002-2009 OProfile authors * @remark Read the file COPYING * * @author John Levon * @author Philippe Elie * @author Graydon Hoare * @author Robert Richter <robert.richter@amd.com> * @author Barry Kasindorf <barry.kasindorf@amd.com> * @author Jason Yeh <jason.yeh@amd.com> * @author Suravee Suthikulpanit <suravee.suthikulpanit@amd.com> */ #include <linux/oprofile.h> #include <linux/device.h> #include <linux/pci.h> #include <linux/percpu.h> #include <asm/ptrace.h> #include <asm/msr.h> #include <asm/nmi.h> #include <asm/apic.h> #include <asm/processor.h> #include <asm/cpufeature.h> #include "op_x86_model.h" #include "op_counter.h" #define NUM_COUNTERS 4 #ifdef CONFIG_OPROFILE_EVENT_MULTIPLEX #define NUM_VIRT_COUNTERS 32 #else #define NUM_VIRT_COUNTERS NUM_COUNTERS #endif #define OP_EVENT_MASK 0x0FFF #define OP_CTR_OVERFLOW (1ULL<<31) #define MSR_AMD_EVENTSEL_RESERVED ((0xFFFFFCF0ULL<<32)|(1ULL<<21)) static unsigned long reset_value[NUM_VIRT_COUNTERS]; #define IBS_FETCH_SIZE 6 #define IBS_OP_SIZE 12 static u32 ibs_caps; struct op_ibs_config { unsigned long op_enabled; unsigned long fetch_enabled; unsigned long max_cnt_fetch; unsigned long max_cnt_op; unsigned long rand_en; unsigned long dispatched_ops; }; static struct op_ibs_config ibs_config; static u64 ibs_op_ctl; /* * IBS cpuid feature detection */ #define IBS_CPUID_FEATURES 0x8000001b /* * Same bit mask as for IBS cpuid feature flags (Fn8000_001B_EAX), but * bit 0 is used to indicate the existence of IBS. */ #define IBS_CAPS_AVAIL (1LL<<0) #define IBS_CAPS_RDWROPCNT (1LL<<3) #define IBS_CAPS_OPCNT (1LL<<4) /* * IBS randomization macros */ #define IBS_RANDOM_BITS 12 #define IBS_RANDOM_MASK ((1ULL << IBS_RANDOM_BITS) - 1) #define IBS_RANDOM_MAXCNT_OFFSET (1ULL << (IBS_RANDOM_BITS - 5)) static u32 get_ibs_caps(void) { u32 ibs_caps; unsigned int max_level; if (!boot_cpu_has(X86_FEATURE_IBS)) return 0; /* check IBS cpuid feature flags */ max_level = cpuid_eax(0x80000000); if (max_level < IBS_CPUID_FEATURES) return IBS_CAPS_AVAIL; ibs_caps = cpuid_eax(IBS_CPUID_FEATURES); if (!(ibs_caps & IBS_CAPS_AVAIL)) /* cpuid flags not valid */ return IBS_CAPS_AVAIL; return ibs_caps; } /* * 16-bit Linear Feedback Shift Register (LFSR) * * 16 14 13 11 * Feedback polynomial = X + X + X + X + 1 */ static unsigned int lfsr_random(void) { static unsigned int lfsr_value = 0xF00D; unsigned int bit; /* Compute next bit to shift in */ bit = ((lfsr_value >> 0) ^ (lfsr_value >> 2) ^ (lfsr_value >> 3) ^ (lfsr_value >> 5)) & 0x0001; /* Advance to next register value */ lfsr_value = (lfsr_value >> 1) | (bit << 15); return lfsr_value; } /* * IBS software randomization * * The IBS periodic op counter is randomized in software. The lower 12 * bits of the 20 bit counter are randomized. IbsOpCurCnt is * initialized with a 12 bit random value. */ static inline u64 op_amd_randomize_ibs_op(u64 val) { unsigned int random = lfsr_random(); if (!(ibs_caps & IBS_CAPS_RDWROPCNT)) val += (s8)(random >> 4); else val |= (u64)(random & IBS_RANDOM_MASK) << 32; return val; } static inline void op_amd_handle_ibs(struct pt_regs * const regs, struct op_msrs const * const msrs) { u64 val, ctl; struct op_entry entry; if (!ibs_caps) return; if (ibs_config.fetch_enabled) { rdmsrl(MSR_AMD64_IBSFETCHCTL, ctl); if (ctl & IBS_FETCH_VAL) { rdmsrl(MSR_AMD64_IBSFETCHLINAD, val); oprofile_write_reserve(&entry, regs, val, IBS_FETCH_CODE, IBS_FETCH_SIZE); oprofile_add_data64(&entry, val); oprofile_add_data64(&entry, ctl); rdmsrl(MSR_AMD64_IBSFETCHPHYSAD, val); oprofile_add_data64(&entry, val); oprofile_write_commit(&entry); /* reenable the IRQ */ ctl &= ~(IBS_FETCH_VAL | IBS_FETCH_CNT); ctl |= IBS_FETCH_ENABLE; wrmsrl(MSR_AMD64_IBSFETCHCTL, ctl); } } if (ibs_config.op_enabled) { rdmsrl(MSR_AMD64_IBSOPCTL, ctl); if (ctl & IBS_OP_VAL) { rdmsrl(MSR_AMD64_IBSOPRIP, val); oprofile_write_reserve(&entry, regs, val, IBS_OP_CODE, IBS_OP_SIZE); oprofile_add_data64(&entry, val); rdmsrl(MSR_AMD64_IBSOPDATA, val); oprofile_add_data64(&entry, val); rdmsrl(MSR_AMD64_IBSOPDATA2, val); oprofile_add_data64(&entry, val); rdmsrl(MSR_AMD64_IBSOPDATA3, val); oprofile_add_data64(&entry, val); rdmsrl(MSR_AMD64_IBSDCLINAD, val); oprofile_add_data64(&entry, val); rdmsrl(MSR_AMD64_IBSDCPHYSAD, val); oprofile_add_data64(&entry, val); oprofile_write_commit(&entry); /* reenable the IRQ */ ctl = op_amd_randomize_ibs_op(ibs_op_ctl); wrmsrl(MSR_AMD64_IBSOPCTL, ctl); } } } static inline void op_amd_start_ibs(void) { u64 val; if (!ibs_caps) return; if (ibs_config.fetch_enabled) { val = (ibs_config.max_cnt_fetch >> 4) & IBS_FETCH_MAX_CNT; val |= ibs_config.rand_en ? IBS_FETCH_RAND_EN : 0; val |= IBS_FETCH_ENABLE; wrmsrl(MSR_AMD64_IBSFETCHCTL, val); } if (ibs_config.op_enabled) { ibs_op_ctl = ibs_config.max_cnt_op >> 4; if (!(ibs_caps & IBS_CAPS_RDWROPCNT)) { /* * IbsOpCurCnt not supported. See * op_amd_randomize_ibs_op() for details. */ ibs_op_ctl = clamp(ibs_op_ctl, 0x0081ULL, 0xFF80ULL); } else { /* * The start value is randomized with a * positive offset, we need to compensate it * with the half of the randomized range. Also * avoid underflows. */ ibs_op_ctl = min(ibs_op_ctl + IBS_RANDOM_MAXCNT_OFFSET, IBS_OP_MAX_CNT); } if (ibs_caps & IBS_CAPS_OPCNT && ibs_config.dispatched_ops) ibs_op_ctl |= IBS_OP_CNT_CTL; ibs_op_ctl |= IBS_OP_ENABLE; val = op_amd_randomize_ibs_op(ibs_op_ctl); wrmsrl(MSR_AMD64_IBSOPCTL, val); } } static void op_amd_stop_ibs(void) { if (!ibs_caps) return; if (ibs_config.fetch_enabled) /* clear max count and enable */ wrmsrl(MSR_AMD64_IBSFETCHCTL, 0); if (ibs_config.op_enabled) /* clear max count and enable */ wrmsrl(MSR_AMD64_IBSOPCTL, 0); } #ifdef CONFIG_OPROFILE_EVENT_MULTIPLEX static void op_mux_switch_ctrl(struct op_x86_model_spec const *model, struct op_msrs const * const msrs) { u64 val; int i; /* enable active counters */ for (i = 0; i < NUM_COUNTERS; ++i) { int virt = op_x86_phys_to_virt(i); if (!reset_value[virt]) continue; rdmsrl(msrs->controls[i].addr, val); val &= model->reserved; val |= op_x86_get_ctrl(model, &counter_config[virt]); wrmsrl(msrs->controls[i].addr, val); } } #endif /* functions for op_amd_spec */ static void op_amd_shutdown(struct op_msrs const * const msrs) { int i; for (i = 0; i < NUM_COUNTERS; ++i) { if (!msrs->counters[i].addr) continue; release_perfctr_nmi(MSR_K7_PERFCTR0 + i); release_evntsel_nmi(MSR_K7_EVNTSEL0 + i); } } static int op_amd_fill_in_addresses(struct op_msrs * const msrs) { int i; for (i = 0; i < NUM_COUNTERS; i++) { if (!reserve_perfctr_nmi(MSR_K7_PERFCTR0 + i)) goto fail; if (!reserve_evntsel_nmi(MSR_K7_EVNTSEL0 + i)) { release_perfctr_nmi(MSR_K7_PERFCTR0 + i); goto fail; } /* both registers must be reserved */ msrs->counters[i].addr = MSR_K7_PERFCTR0 + i; msrs->controls[i].addr = MSR_K7_EVNTSEL0 + i; continue; fail: if (!counter_config[i].enabled) continue; op_x86_warn_reserved(i); op_amd_shutdown(msrs); return -EBUSY; } return 0; } static void op_amd_setup_ctrs(struct op_x86_model_spec const *model, struct op_msrs const * const msrs) { u64 val; int i; /* setup reset_value */ for (i = 0; i < NUM_VIRT_COUNTERS; ++i) { if (counter_config[i].enabled && msrs->counters[op_x86_virt_to_phys(i)].addr) reset_value[i] = counter_config[i].count; else reset_value[i] = 0; } /* clear all counters */ for (i = 0; i < NUM_COUNTERS; ++i) { if (!msrs->controls[i].addr) continue; rdmsrl(msrs->controls[i].addr, val); if (val & ARCH_PERFMON_EVENTSEL_ENABLE) op_x86_warn_in_use(i); val &= model->reserved; wrmsrl(msrs->controls[i].addr, val); /* * avoid a false detection of ctr overflows in NMI * handler */ wrmsrl(msrs->counters[i].addr, -1LL); } /* enable active counters */ for (i = 0; i < NUM_COUNTERS; ++i) { int virt = op_x86_phys_to_virt(i); if (!reset_value[virt]) continue; /* setup counter registers */ wrmsrl(msrs->counters[i].addr, -(u64)reset_value[virt]); /* setup control registers */ rdmsrl(msrs->controls[i].addr, val); val &= model->reserved; val |= op_x86_get_ctrl(model, &counter_config[virt]); wrmsrl(msrs->controls[i].addr, val); } if (ibs_caps) setup_APIC_eilvt_ibs(0, APIC_EILVT_MSG_NMI, 0); } static void op_amd_cpu_shutdown(void) { if (ibs_caps) setup_APIC_eilvt_ibs(0, APIC_EILVT_MSG_FIX, 1); } static int op_amd_check_ctrs(struct pt_regs * const regs, struct op_msrs const * const msrs) { u64 val; int i; for (i = 0; i < NUM_COUNTERS; ++i) { int virt = op_x86_phys_to_virt(i); if (!reset_value[virt]) continue; rdmsrl(msrs->counters[i].addr, val); /* bit is clear if overflowed: */ if (val & OP_CTR_OVERFLOW) continue; oprofile_add_sample(regs, virt); wrmsrl(msrs->counters[i].addr, -(u64)reset_value[virt]); } op_amd_handle_ibs(regs, msrs); /* See op_model_ppro.c */ return 1; } static void op_amd_start(struct op_msrs const * const msrs) { u64 val; int i; for (i = 0; i < NUM_COUNTERS; ++i) { if (!reset_value[op_x86_phys_to_virt(i)]) continue; rdmsrl(msrs->controls[i].addr, val); val |= ARCH_PERFMON_EVENTSEL_ENABLE; wrmsrl(msrs->controls[i].addr, val); } op_amd_start_ibs(); } static void op_amd_stop(struct op_msrs const * const msrs) { u64 val; int i; /* * Subtle: stop on all counters to avoid race with setting our * pm callback */ for (i = 0; i < NUM_COUNTERS; ++i) { if (!reset_value[op_x86_phys_to_virt(i)]) continue; rdmsrl(msrs->controls[i].addr, val); val &= ~ARCH_PERFMON_EVENTSEL_ENABLE; wrmsrl(msrs->controls[i].addr, val); } op_amd_stop_ibs(); } static int __init_ibs_nmi(void) { #define IBSCTL_LVTOFFSETVAL (1 << 8) #define IBSCTL 0x1cc struct pci_dev *cpu_cfg; int nodes; u32 value = 0; u8 ibs_eilvt_off; ibs_eilvt_off = setup_APIC_eilvt_ibs(0, APIC_EILVT_MSG_FIX, 1); nodes = 0; cpu_cfg = NULL; do { cpu_cfg = pci_get_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_10H_NB_MISC, cpu_cfg); if (!cpu_cfg) break; ++nodes; pci_write_config_dword(cpu_cfg, IBSCTL, ibs_eilvt_off | IBSCTL_LVTOFFSETVAL); pci_read_config_dword(cpu_cfg, IBSCTL, &value); if (value != (ibs_eilvt_off | IBSCTL_LVTOFFSETVAL)) { pci_dev_put(cpu_cfg); printk(KERN_DEBUG "Failed to setup IBS LVT offset, " "IBSCTL = 0x%08x", value); return 1; } } while (1); if (!nodes) { printk(KERN_DEBUG "No CPU node configured for IBS"); return 1; } return 0; } /* * check and reserve APIC extended interrupt LVT offset for IBS if * available * * init_ibs() preforms implicitly cpu-local operations, so pin this * thread to its current CPU */ static void init_ibs(void) { preempt_disable(); ibs_caps = get_ibs_caps(); if (!ibs_caps) goto out; if (__init_ibs_nmi() < 0) ibs_caps = 0; else printk(KERN_INFO "oprofile: AMD IBS detected (0x%08x)\n", ibs_caps); out: preempt_enable(); } static int (*create_arch_files)(struct super_block *sb, struct dentry *root); static int setup_ibs_files(struct super_block *sb, struct dentry *root) { struct dentry *dir; int ret = 0; /* architecture specific files */ if (create_arch_files) ret = create_arch_files(sb, root); if (ret) return ret; if (!ibs_caps) return ret; /* model specific files */ /* setup some reasonable defaults */ ibs_config.max_cnt_fetch = 250000; ibs_config.fetch_enabled = 0; ibs_config.max_cnt_op = 250000; ibs_config.op_enabled = 0; ibs_config.dispatched_ops = 0; dir = oprofilefs_mkdir(sb, root, "ibs_fetch"); oprofilefs_create_ulong(sb, dir, "enable", &ibs_config.fetch_enabled); oprofilefs_create_ulong(sb, dir, "max_count", &ibs_config.max_cnt_fetch); oprofilefs_create_ulong(sb, dir, "rand_enable", &ibs_config.rand_en); dir = oprofilefs_mkdir(sb, root, "ibs_op"); oprofilefs_create_ulong(sb, dir, "enable", &ibs_config.op_enabled); oprofilefs_create_ulong(sb, dir, "max_count", &ibs_config.max_cnt_op); if (ibs_caps & IBS_CAPS_OPCNT) oprofilefs_create_ulong(sb, dir, "dispatched_ops", &ibs_config.dispatched_ops); return 0; } static int op_amd_init(struct oprofile_operations *ops) { init_ibs(); create_arch_files = ops->create_files; ops->create_files = setup_ibs_files; return 0; } struct op_x86_model_spec op_amd_spec = { .num_counters = NUM_COUNTERS, .num_controls = NUM_COUNTERS, .num_virt_counters = NUM_VIRT_COUNTERS, .reserved = MSR_AMD_EVENTSEL_RESERVED, .event_mask = OP_EVENT_MASK, .init = op_amd_init, .fill_in_addresses = &op_amd_fill_in_addresses, .setup_ctrs = &op_amd_setup_ctrs, .cpu_down = &op_amd_cpu_shutdown, .check_ctrs = &op_amd_check_ctrs, .start = &op_amd_start, .stop = &op_amd_stop, .shutdown = &op_amd_shutdown, #ifdef CONFIG_OPROFILE_EVENT_MULTIPLEX .switch_ctrl = &op_mux_switch_ctrl, #endif };
23.360771
77
0.701927
1ab9291c12f3716b79a6ad46237708590a35d51e
12,813
py
Python
tests/test_matching_cost.py
qfardet/Pandora2D
9b36d29a199f2acc67499d22b796c7dd6867bc5f
[ "Apache-2.0" ]
4
2022-02-09T10:07:03.000Z
2022-03-08T05:16:30.000Z
tests/test_matching_cost.py
qfardet/Pandora2D
9b36d29a199f2acc67499d22b796c7dd6867bc5f
[ "Apache-2.0" ]
null
null
null
tests/test_matching_cost.py
qfardet/Pandora2D
9b36d29a199f2acc67499d22b796c7dd6867bc5f
[ "Apache-2.0" ]
4
2022-02-03T09:21:28.000Z
2022-03-25T07:32:13.000Z
#!/usr/bin/env python # coding: utf8 # # Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES). # # This file is part of PANDORA2D # # https://github.com/CNES/Pandora2D # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Test Matching cost class """ import unittest import numpy as np import xarray as xr import pytest import json_checker from rasterio import Affine from pandora2d import matching_cost class TestMatchingCost(unittest.TestCase): """ TestMatchingCost class allows to test all the methods in the class MatchingCost """ def setUp(self) -> None: """ Method called to prepare the test fixture """ # Create a stereo object data = np.array( ([-9999, -9999, -9999], [1, 1, 1], [3, 4, 5]), dtype=np.float64, ) mask = np.array(([1, 1, 1], [0, 0, 0], [0, 0, 0]), dtype=np.int16) self.left = xr.Dataset( {"im": (["row", "col"], data), "msk": (["row", "col"], mask)}, coords={"row": np.arange(data.shape[0]), "col": np.arange(data.shape[1])}, ) self.left.attrs = { "no_data_img": -9999, "valid_pixels": 0, "no_data_mask": 1, "crs": None, "transform": Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0), } data = np.array( ([1, 1, 1], [3, 4, 5], [1, 1, 1]), dtype=np.float64, ) mask = np.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=np.int16) self.right = xr.Dataset( {"im": (["row", "col"], data), "msk": (["row", "col"], mask)}, coords={"row": np.arange(data.shape[0]), "col": np.arange(data.shape[1])}, ) self.right.attrs = { "no_data_img": -9999, "valid_pixels": 0, "no_data_mask": 1, "crs": None, "transform": Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0), } @staticmethod def test_check_conf(): """ test check_conf of matching cost pipeline """ matching_cost.MatchingCost(**{"matching_cost_method": "zncc", "window_size": 5}) # type: ignore with pytest.raises(json_checker.core.exceptions.DictCheckerError): matching_cost.MatchingCost(**{"matching_cost_method": "census", "window_size": 5}) # type: ignore with pytest.raises(json_checker.core.exceptions.DictCheckerError): matching_cost.MatchingCost(**{"matching_cost_method": "zncc", "window_size": -1}) # type: ignore def test_compute_cv_ssd(self): """ Test the cost volume product by ssd """ # sum of squared difference images self.left, self.right, window_size=1 cfg = {"matching_cost_method": "ssd", "window_size": 1} # sum of squared difference ground truth for the images self.left, self.right, window_size=1 ad_ground_truth = np.zeros((3, 3, 2, 2)) # disp_x = -1, disp_y = -1 ad_ground_truth[:, :, 0, 0] = np.array( [[np.nan, np.nan, np.nan], [np.nan, 0, 0], [np.nan, (4 - 3) ** 2, (5 - 4) ** 2]] ) # disp_x = -1, disp_y = 0 ad_ground_truth[:, :, 0, 1] = np.array( [[np.nan, np.nan, np.nan], [np.nan, (1 - 3) ** 2, (1 - 4) ** 2], [np.nan, (4 - 1) ** 2, (5 - 1) ** 2]] ) # disp_x = 0, disp_y = 0 ad_ground_truth[:, :, 1, 1] = np.array( [ [np.nan, np.nan, np.nan], [(1 - 3) ** 2, (1 - 4) ** 2, (1 - 5) ** 2], [(3 - 1) ** 2, (4 - 1) ** 2, (5 - 1) ** 2], ] ) # disp_x = 0, disp_y = -1 ad_ground_truth[:, :, 1, 0] = np.array([[np.nan, np.nan, np.nan], [0, 0, 0], [0, 0, 0]]) # initialise matching cost matching_cost_matcher = matching_cost.MatchingCost(**cfg) # type: ignore # compute cost volumes ssd = matching_cost_matcher.compute_cost_volumes( img_left=self.left, img_right=self.right, min_col=-1, max_col=0, min_row=-1, max_row=0, **cfg ) # type: ignore # check that the generated cost_volumes is equal to ground truth np.testing.assert_allclose(ssd["cost_volumes"].data, ad_ground_truth, atol=1e-06) def test_compute_cv_sad(self): """ Test the cost volume product by sad """ # sum of squared difference images self.left, self.right, window_size=1 cfg = {"matching_cost_method": "sad", "window_size": 1} # sum of absolute difference ground truth for the images self.left, self.right, window_size=1 ad_ground_truth = np.zeros((3, 3, 2, 2)) # disp_x = -1, disp_y = -1 ad_ground_truth[:, :, 0, 0] = np.array( [[np.nan, np.nan, np.nan], [np.nan, 0, 0], [np.nan, np.abs(4 - 3), np.abs(5 - 4)]] ) # disp_x = -1, disp_y = 0 ad_ground_truth[:, :, 0, 1] = np.array( [[np.nan, np.nan, np.nan], [np.nan, np.abs(1 - 3), np.abs(1 - 4)], [np.nan, np.abs(4 - 1), np.abs(5 - 1)]] ) # disp_x = 0, disp_y = 0 ad_ground_truth[:, :, 1, 1] = np.array( [ [np.nan, np.nan, np.nan], [np.abs(1 - 3), np.abs(1 - 4), np.abs(1 - 5)], [np.abs(3 - 1), np.abs(4 - 1), np.abs(5 - 1)], ] ) # disp_x = 0, disp_y = -1 ad_ground_truth[:, :, 1, 0] = np.array([[np.nan, np.nan, np.nan], [0, 0, 0], [0, 0, 0]]) # initialise matching cost matching_cost_matcher = matching_cost.MatchingCost(**cfg) # type: ignore # compute cost volumes sad = matching_cost_matcher.compute_cost_volumes( img_left=self.left, img_right=self.right, min_col=-1, max_col=0, min_row=-1, max_row=0, **cfg ) # type: ignore # check that the generated cost_volumes is equal to ground truth np.testing.assert_allclose(sad["cost_volumes"].data, ad_ground_truth, atol=1e-06) @staticmethod def test_compute_cv_zncc(): """ Test the cost volume product by zncc """ data = np.array( ([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [3, 4, 5, 6, 7], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]), dtype=np.float64, ) mask = np.array( ([0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]), dtype=np.int16 ) left_zncc = xr.Dataset( {"im": (["row", "col"], data), "msk": (["row", "col"], mask)}, coords={"row": np.arange(data.shape[0]), "col": np.arange(data.shape[1])}, ) left_zncc.attrs = { "no_data_img": -9999, "valid_pixels": 0, "no_data_mask": 1, "crs": None, "transform": Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0), } data = np.array( ([[1, 1, 1, 1, 1], [3, 4, 5, 6, 7], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]), dtype=np.float64, ) mask = np.array( ([0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]), dtype=np.int16 ) right_zncc = xr.Dataset( {"im": (["row", "col"], data), "msk": (["row", "col"], mask)}, coords={"row": np.arange(data.shape[0]), "col": np.arange(data.shape[1])}, ) right_zncc.attrs = { "no_data_img": -9999, "valid_pixels": 0, "no_data_mask": 1, "crs": None, "transform": Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0), } # sum of squared difference images self.left, self.right, window_size=3 cfg = {"matching_cost_method": "zncc", "window_size": 3} # sum of absolute difference ground truth for the images self.left, self.right, window_size=1 left = left_zncc["im"].data right = right_zncc["im"].data right_shift = np.array( [ [np.nan, np.nan, np.nan, np.nan, np.nan], [1, 1, 1, 1, 1], [3, 4, 5, 6, 7], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], ] ) # row = 1, col = 1, disp_x = 0, disp_y = 0, ground truth equal -0,45 ad_ground_truth_1_1_0_0 = ( np.mean(left[0:3, 0:3] * right[0:3, 0:3]) - (np.mean(left[0:3, 0:3]) * np.mean(right[0:3, 0:3])) ) / (np.std(left[0:3, 0:3]) * np.std(right[0:3, 0:3])) # row = 1, col = 1, disp_x = 0, disp_y = -1, , ground truth equal NaN ad_ground_truth_1_1_0_1 = ( np.mean(left[0:3, 0:3] * right_shift[0:3, 0:3]) - (np.mean(left[0:3, 0:3]) * np.mean(right_shift[0:3, 0:3])) ) / (np.std(left[0:3, 0:3]) * np.std(right_shift[0:3, 0:3])) # row = 2, col = 2, disp_x = 0, disp_y = 0, , ground truth equal -0,47 ad_ground_truth_2_2_0_0 = ( np.mean(left[1:4, 1:4] * right[1:4, 1:4]) - (np.mean(left[1:4, 1:4]) * np.mean(right[1:4, 1:4])) ) / (np.std(left[1:4, 1:4]) * np.std(right[1:4, 1:4])) # row = 2, col = 2, disp_x = 0, disp_y = -1, ground truth equal 1 ad_ground_truth_2_2_0_1 = ( np.mean(left[1:4, 1:4] * right_shift[1:4, 1:4]) - (np.mean(left[1:4, 1:4]) * np.mean(right_shift[1:4, 1:4])) ) / (np.std(left[1:4, 1:4]) * np.std(right_shift[1:4, 1:4])) # initialise matching cost matching_cost_matcher = matching_cost.MatchingCost(**cfg) # type: ignore # compute cost volumes zncc = matching_cost_matcher.compute_cost_volumes( img_left=left_zncc, img_right=right_zncc, min_col=0, max_col=1, min_row=-1, max_row=0, **cfg ) # type: ignore # check that the generated cost_volumes is equal to ground truth np.testing.assert_allclose(zncc["cost_volumes"].data[1, 1, 0, 1], ad_ground_truth_1_1_0_0, rtol=1e-06) np.testing.assert_allclose(zncc["cost_volumes"].data[1, 1, 0, 0], ad_ground_truth_1_1_0_1, rtol=1e-06) np.testing.assert_allclose(zncc["cost_volumes"].data[2, 2, 0, 1], ad_ground_truth_2_2_0_0, rtol=1e-06) np.testing.assert_allclose(zncc["cost_volumes"].data[2, 2, 0, 0], ad_ground_truth_2_2_0_1, rtol=1e-06) def test_allocate_cost_volume(self): """ Test the allocate cost_volumes function """ # generated data for the test np_data = np.empty((3, 3, 3, 3)) np_data.fill(np.nan) c_row = [0, 1, 2] c_col = [0, 1, 2] # First pixel in the image that is fully computable (aggregation windows are complete) row = np.arange(c_row[0], c_row[-1] + 1) col = np.arange(c_col[0], c_col[-1] + 1) disparity_range_col = np.arange(-1, 1 + 1) disparity_range_row = np.arange(-1, 1 + 1) # Create the cost volume if np_data is None: np_data = np.zeros( (len(row), len(col), len(disparity_range_col), len(disparity_range_row)), dtype=np.float32 ) cost_volumes_test = xr.Dataset( {"cost_volumes": (["row", "col", "disp_col", "disp_row"], np_data)}, coords={"row": row, "col": col, "disp_col": disparity_range_col, "disp_row": disparity_range_row}, ) cost_volumes_test.attrs["measure"] = "zncc" cost_volumes_test.attrs["window_size"] = 3 cost_volumes_test.attrs["type_measure"] = "max" cost_volumes_test.attrs["subpixel"] = 1 cost_volumes_test.attrs["offset_row_col"] = 1 cost_volumes_test.attrs["cmax"] = 1 cost_volumes_test.attrs["crs"] = None cost_volumes_test.attrs["transform"] = Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0) # data by function compute_cost_volume cfg = {"matching_cost_method": "zncc", "window_size": 3} matching_cost_matcher = matching_cost.MatchingCost(**cfg) # type: ignore cost_volumes_fun = matching_cost_matcher.compute_cost_volumes( img_left=self.left, img_right=self.right, min_col=-1, max_col=1, min_row=-1, max_row=1, **cfg ) # type: ignore # check that the generated xarray dataset is equal to the ground truth np.testing.assert_array_equal(cost_volumes_fun["cost_volumes"].data, cost_volumes_test["cost_volumes"].data) assert cost_volumes_fun.attrs == cost_volumes_test.attrs
40.67619
120
0.543276
0d38e7652d8a54021a72746d91adb8d0e8aee9a7
178
cs
C#
advanced-programming-methods/labs/toy-interpreter-sharp/exceptions/HeapException.cs
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
6
2015-06-22T19:43:13.000Z
2019-07-15T18:08:41.000Z
advanced-programming-methods/labs/toy-interpreter-sharp/exceptions/HeapException.cs
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
null
null
null
advanced-programming-methods/labs/toy-interpreter-sharp/exceptions/HeapException.cs
vampy/university
9496cb63594dcf1cc2cec8650b8eee603f85fdab
[ "MIT" ]
1
2015-09-26T09:01:54.000Z
2015-09-26T09:01:54.000Z
using System; namespace Exceptions { public class HeapException : Exception { public HeapException(string message) : base(message) { } } }
13.692308
60
0.595506
a4a5d31f4ae1e54e683042286419825de74912ff
25,816
php
PHP
resources/views/people/editSchedule.blade.php
oammike/testRepo
b0b6ab483a904d673d0455c9688ca68ea4191395
[ "MIT" ]
null
null
null
resources/views/people/editSchedule.blade.php
oammike/testRepo
b0b6ab483a904d673d0455c9688ca68ea4191395
[ "MIT" ]
null
null
null
resources/views/people/editSchedule.blade.php
oammike/testRepo
b0b6ab483a904d673d0455c9688ca68ea4191395
[ "MIT" ]
null
null
null
@extends('layouts.main') @section('metatags') <title>Edit {{$user->firstname}}'s Schedule</title> <meta name="description" content="profile page"> @stop @section('content') <section class="content-header"> <h1> Employee Profile <small></small> </h1> <ol class="breadcrumb"> <li><a href="{{action('HomeController@index')}}"><i class="fa fa-dashboard"></i> Dashboard</a></li> <li class="active">Employee Profile</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-1"></div> <div class="col-xs-10"> <!-- Profile Image --> <div class="box box-primary"> <div class="box-body box-profile"> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-black" style="background: url('{{URL:: asset("public/img/bg.jpg")}}') top left;"> <h3 class="widget-user-username">{{$user->lastname}}, {{$user->firstname}} {{$user->middlename}}</h3> <h5 class="widget-user-desc">{{$user->position->name}} </h5> </div> <div class="widget-user-image"> @if ( file_exists('public/img/employees/'.$user->id.'.jpg') ) <img src="{{asset('public/img/employees/'.$user->id.'.jpg')}}" class="user-image" alt="User Image"> @else <img src="{{asset('public/img/useravatar.png')}}" class="user-image" alt="User Image"> @endif </div> <div class="box-footer"> <div class="row"> <div class="col-sm-6 border-right"> <div class="description-block"> <p class="description-header"><i class="fa fa-users margin-r-5"></i> Department / Program : </p> <span class="description-text text-primary"> @if(count($user->campaign) > 1) @foreach($user->campaign as $ucamp) {{$ucamp->name}} , @endforeach @else {{$user->campaign[0]->name}} @endif </span> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-6 "> <div class="description-block"> <p class="description-header"><i class="fa fa-envelope-o margin-r-5"></i> E-mail:</p> <span><a href="mailto:{{$user->email}}"> {{$user->email}}</a></span> </div> <!-- /.description-block --> </div> <!-- /.col --> <!-- START CUSTOM TABS --> <p>&nbsp;</p><p>&nbsp;</p> <div class="row"> <div class="col-lg-1 col-sm-12"></div> <div class="col-lg-10 col-sm-12"> <!-- Custom Tabs --> <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> <li class="active"><a href="#tab_2" data-toggle="tab">EDIT WORK SCHEDULE</a></li> <li class="dropdown pull-right"> <a class="dropdown-toggle" data-toggle="dropdown" href="#"> <i class="fa fa-gear"></i> Actions <span class="caret"></span> </a> <ul class="dropdown-menu"> @if ($canMoveEmployees) <li role="presentation"><a role="menuitem" tabindex="-1" href="{{action('MovementController@changePersonnel',$user->id)}}">Movements</a></li>@endif @if ($canEditEmployees) <li role="presentation"><a role="menuitem" tabindex="-1" href="{{action('UserController@editUser',$user->id)}}">Edit Employment Data</a></li>@endif <li role="presentation"><a role="menuitem" tabindex="-1" href="{{action('UserController@editSchedule',$user->id)}}">Edit Work Schedule</a></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="{{action('UserController@editContact',$user->id)}}">Edit Contact Info</a></li> <li role="presentation" class="divider"></li> <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Change Status</a></li> </ul> </li> </ul> <div class="tab-content"> {{ Form::open(['route' => ['user.updateSchedule', $user->id], 'method'=>'put','class'=>'col-lg-12', 'id'=> 'updateForm' ]) }} <input type="hidden" name="user_id" value="{{$user->id}} " /> <div class="tab-pane active" id="tab_2"> <div id="alert-submit" style="margin-top:10px"></div> <h4 style="margin-top:30px"> <input type="submit" id="submit" href="#" class="btn btn-sm btn-success pull-right" value="Save Changes"></input> <i class="fa fa-clock-o"></i> WORK SCHEDULE <br/><br/></h4> <div class="row"> <div class="col-lg-7"><strong> Shifts: </strong> <a href="#" id="addShift" class="btn btn-xs btn-primary "><i class="fa fa-plus"></i> Add Work Shift</a> <br/> <table class="table no-border"> <tr> <th>Day</th> <th class="text-center">In</th> <th class="text-center">Out</th> <th></th> </tr> @foreach($user->schedules as $sched) <tr> <td> <select data-id="{{$sched->id}}" name="workday[]" class="form-control"> <option data-id="{{$sched->id}}" value="Sundays" @if ( $sched->workday == "Sundays" ) selected="selected" @endif >Sundays</option> <option data-id="{{$sched->id}}" value="Mondays" @if ( $sched->workday == "Mondays" ) selected="selected" @endif >Mondays</option> <option data-id="{{$sched->id}}" value="Tuesdays" @if ( $sched->workday == "Tuesdays" ) selected="selected" @endif >Tuesdays</option> <option data-id="{{$sched->id}}" value="Wednesdays" @if ( $sched->workday == "Wednesdays" ) selected="selected" @endif >Wednesdays</option> <option data-id="{{$sched->id}}" value="Thursdays" @if ( $sched->workday == "Thursdays" ) selected="selected" @endif >Thursdays</option> <option data-id="{{$sched->id}}" value="Fridays" @if ( $sched->workday == "Fridays" ) selected="selected" @endif >Fridays</option> <option data-id="{{$sched->id}}" value="Saturdays" @if ( $sched->workday == "Saturdays" ) selected="selected" @endif >Saturdays</option> </select></td> <td> <select name="timeStart[]" class="form-control"> <?php for( $i = 1; $i <= 24; $i++){ $min=0; $time1 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); $min+=30; $time2 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); ?> <option @if( date('h:i A', strtotime('1999-01-01'. $sched->timeStart)) == $time1 ) selected="selected" @endif value="{{$time1}}">{{$time1}} </option> <option @if( date('h:i A', strtotime('1999-01-01'. $sched->timeStart)) == $time2 ) selected="selected" @endif value="{{$time2}}">{{$time2}} </option> <?php } ?> </select></td> <td> <select name="timeEnd[]" class="form-control"> <?php for( $i = 1; $i <= 24; $i++){ $min=0; $time1 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); $min+=30; $time2 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); ?> <option @if( date('h:i A', strtotime('1999-01-01'. $sched->timeEnd)) == $time1 ) selected="selected" @endif value="{{$time1}}">{{$time1}} </option> <option @if( date('h:i A', strtotime('1999-01-01'. $sched->timeEnd)) == $time2 ) selected="selected" @endif value="{{$time2}}">{{$time2}} </option> <?php } ?> </select> </td> <td> <a title="Delete" data-toggle="modal" data-target="#myModal{{$sched->id}}" class="btn btn-sm btn-default pull-left"><i class="fa fa-trash"></i></a></td> </tr> @endforeach </table> <div id="addShifts"></div> </div> <div class="col-lg-3"> <strong> Rest Days: </strong> <br/> <br/> <br/> <?php $ctr=0;?> @foreach($days as $d) <label><input data-id="{{$ctr}}" type="checkbox" name="restdays[]" value="{{$d}}" @if ($user->restdays->contains('RD',$d)) checked="checked" @endif> {{$d}} </label><br/> <?php $ctr++;?> @endforeach </div> <div class="col-lg-2"><strong>Flexible schedule</strong><br/><br/> <label> <input type="radio" name="isFlexi" value="1" @if(count($user->schedules) > 0) @if($user->schedules->first()->isFlexi) checked="checked" @endif @endif></input> Yes </label> <label style="margin-left:10px"> <input type="radio" name="isFlexi" value="0" @if ( (!count($user->schedules) > 0) || ($user->schedules->first()->isFlexi !=1) ) checked="checked" @endif></input> No</label> </div> </div> </div> <!-- /.tab-pane --> {{Form::close()}} </div> <!-- /.tab-content --> </div> <!-- nav-tabs-custom --> </div> <!-- /.col --> <div class="col-lg-1 col-sm-12"></div> </div> <!-- /.row --> <!-- END CUSTOM TABS --> <!-- /.col --> </div> </div> <!-- /.widget-user --> </div> <!-- /.box-body --> </div> </div> <div class="col-xs-1"></div> </div> @foreach($user->schedules as $sched) @include('layouts.modals', [ 'modelRoute'=>'schedule.destroy', 'modelID' => $sched->id, 'modelName'=>"Schedule", 'modalTitle'=>'Delete', 'modalMessage'=>'Are you sure you want to delete this schedule?', 'formID'=>'deleteSched', 'icon'=>'glyphicon-trash' ]) @endforeach </section> @stop @section('footer-scripts') <script> $(function () { 'use strict'; // -------- reset all default options, remove checked RDs var restdays = $('input[name="restdays[]"]:checkbox:checked').map(function() { return this.value; }).get(); $.each( restdays, function( key, value ) { $('select[name="workday[]"] option:contains("'+value+'")').remove(); }); //--------------------------------------------------------- var htmlcode ='<div class="row">'; htmlcode += '<div class="col-lg-4">'; htmlcode += ' <select name="addDay[]" class="form-control" style="margin-bottom:5px">'; htmlcode += ' <option value="0" selected="selected"> - Select a day - </option>'; @foreach ($days as $d) htmlcode += ' <option value="{{$d}}"> {{$d}} </option>'; @endforeach htmlcode += ' </select></div><div class="col-lg-3">'; htmlcode += ' <select name="addStart[]" class="form-control" style="margin-bottom:5px"><option value="0">-select time-</option>'; <?php for( $i = 1; $i <= 24; $i++){ $min=0; $time1 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); $min+=30; $time2 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); ?> htmlcode +=' <option value="{{$time1}}">{{$time1}} </option>'; htmlcode +=' <option value="{{$time2}}">{{$time2}} </option>'; <?php } ?> htmlcode +=' </select></div><div class="col-lg-3">'; htmlcode +=' <select name="addEnd[]" class="form-control" style="margin-bottom:5px"><option value="0">-select time-</option>'; <?php for( $i = 1; $i <= 24; $i++){ $min=0; $time1 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); $min+=30; $time2 = date('h:i A', strtotime('1999-01-01'.$i.":".$min.":00")); ?> htmlcode +=' <option value="{{$time1}}">{{$time1}} </option>'; htmlcode +=' <option value="{{$time2}}">{{$time2}} </option>'; <?php } ?> htmlcode +=' </select></div><div class="col-lg-2">'; //<a id="saveShift" class="btn btn-sm btn-success"><i class="fa fa-save"></i> Save Shift</a></div></div> $('#addShift').on('click', function(e) { e.preventDefault(); $('#addShifts').fadeIn(); $('#addShifts').append(htmlcode); var restdays = $('input:checkbox:checked').map(function() { return this.value; }).get(); $.each( restdays, function( key, value ) { $('select[name="addDay[]"] option:contains("'+value+'")').remove(); }); }); //update day options pag nag set ng RD $('input[name="restdays[]"]').on('click',function(){ var dayChecked = $(this).attr("value"); var idChecked = $(this).attr("data-id"); if ($(this).is(":checked")) { $('select[name="workday[]"] option:contains("'+dayChecked+'")').remove(); $('select[name="addDay[]"] option:contains("'+dayChecked+'")').remove(); } else { //$('select[name="workday[]"] option:contains("'+dayChecked+'")').remove(); var addcode = ""; @foreach ($days as $d) addcode += '<option value="{{$d}}"> {{$d}} </option>'; @endforeach $('select[name="workday[]"]') .find('option') .remove() .end() .append(addcode); $('select[name="addDay[]"]') .find('option') .remove() .end() .append(addcode); var restdays = $('input[name="restdays[]"]:checkbox:checked').map(function() { return this.value; }).get(); $.each( restdays, function( key, value ) { $('select[name="workday[]"] option:contains("'+value+'")').remove(); $('select[name="addDay[]"] option:contains("'+value+'")').remove(); }); } }); $('#updateForm').on('submit', function(e) { e.preventDefault(); e.stopPropagation(); console.log('Enter submit'); var _token = "{{ csrf_token() }}"; var workday = $('select[name="workday[]"]').map(function(){ return this.value }).get(); var schedIDs = $("select[name='workday[]']").map( function () { return $(this).attr("data-id"); }).get(); var timeStart = $('select[name="timeStart[]"]').map(function(){ return this.value }).get(); var timeEnd = $('select[name="timeEnd[]"]').map(function(){ return this.value }).get(); //var restdays = $('input[name="restdays[]" ]:checked').val(); var restdays = $('input[name="restdays[]"]:checkbox:checked').map(function() { return this.value; }).get(); var isFlexi = $('input[name="isFlexi"]:checked').val(); //$('input[name="isFlexi"]:checkbox:checked').val(); //.map(function() { // return this.value; // }).get(); var addDay = $('select[name="addDay[]"]').map(function(){ return this.value }).get(); var addStart = $('select[name="addStart[]"]').map(function(){ return this.value }).get(); var addEnd = $('select[name="addEnd[]"]').map(function(){ return this.value }).get(); var user_id = $('input[name="user_id').val(); console.log("flexi: " + isFlexi); $.ajax({ url:"{{action('UserController@updateSchedule', $user->id)}}", type:'POST', data:{ 'schedIDs': schedIDs, 'workday': workday, 'timeStart': timeStart, 'timeEnd': timeEnd, 'restdays': restdays, '_token':_token }, success: function(response2) { console.log(response2); $.ajax({ url:"{{action('ScheduleController@store')}}", type:'POST', data:{ 'user_id': user_id, 'addDay': addDay, 'addStart': addStart, 'addEnd': addEnd, 'isFlexi': isFlexi,// $('input[name="isFlexi"]:checkbox:checked').val(), '_token':_token }, success: function(response) { console.log(response); console.log("flexi2: " + isFlexi); $('#submit').fadeOut(); var htmcode = "<span class=\"success\"> <i class=\"fa fa-save\"></i> Employee Schedule updated. <br /><br/>"; $('#alert-submit').addClass('alert alert-success').fadeIn().html(htmcode).delay(2000).fadeOut(function() { window.location = "{{action('UserController@show', $user->id)}}"; }); } }); return false; } }); return false; }); //end updateForm }); </script> @stop
50.719057
268
0.326658
388c567bcf11c65cfd8d30fe354ea8dde8b69cfe
1,371
php
PHP
resources/views/evidance/index.blade.php
maudyannisa/tools_audit2
d1ef802f89745ef691ec10ffdda58c8b17507c16
[ "MIT" ]
null
null
null
resources/views/evidance/index.blade.php
maudyannisa/tools_audit2
d1ef802f89745ef691ec10ffdda58c8b17507c16
[ "MIT" ]
null
null
null
resources/views/evidance/index.blade.php
maudyannisa/tools_audit2
d1ef802f89745ef691ec10ffdda58c8b17507c16
[ "MIT" ]
null
null
null
@extends('layouts.app') @section('title', 'Dokumen Perusahaan') @section('content') <div class="content"> <div class="container"> <!-- Page-Title --> <div class="row"> <div class="col-sm-12"> <h4 class="pull-left page-title">Evidance Document</h4> <ol class="breadcrumb pull-right"> <li class="active"><a href="">Upload Evidance</a></li> </ol> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Upload Evidance</h3> </div> <div class="panel-body"> @include('evidance.notification.flash') <div class="row"> {!! Form::open(['action' => 'Proses_AuditController@submit', 'class'=>'form-horizontal', 'files' => true]) !!} @include('evidance.form.form', ['submit_text' => 'Upload Evidance']) {!! Form::close() !!} </div> <!-- End row --> <br> </div> </div> </div> </div> <!-- End Row --> </div> <!-- container --> </div> @endsection
39.171429
136
0.427425
717855699387102ede1ad5039faccea114dbf478
5,601
rs
Rust
libsplinter/src/circuit/routing/error.rs
isabeltomb/splinter
9a516e08cfaa7cbfb80fad9c512347a044757174
[ "Apache-2.0" ]
null
null
null
libsplinter/src/circuit/routing/error.rs
isabeltomb/splinter
9a516e08cfaa7cbfb80fad9c512347a044757174
[ "Apache-2.0" ]
null
null
null
libsplinter/src/circuit/routing/error.rs
isabeltomb/splinter
9a516e08cfaa7cbfb80fad9c512347a044757174
[ "Apache-2.0" ]
2
2020-12-26T06:24:55.000Z
2021-09-04T17:09:08.000Z
// Copyright 2018-2020 Cargill Incorporated // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Types for errors that can be raised by `RoutingTableReader` and `RoutingTableWriter` traits use std::error::Error; use std::fmt; /// Errors that could be raised when requesting a service #[derive(Debug, PartialEq)] pub struct FetchServiceError(pub String); impl Error for FetchServiceError {} impl fmt::Display for FetchServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when requesting all services in a circuit #[derive(Debug, PartialEq)] pub enum ListServiceError { /// Internal error InternalError(String), CircuitNotFound(String), } impl Error for ListServiceError {} impl fmt::Display for ListServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ListServiceError::InternalError(msg) => write!(f, "Received internal error: {}", msg), ListServiceError::CircuitNotFound(circuit_id) => { write!(f, "Circuit does not exist: {}", circuit_id) } } } } /// Errors that could be raised when requesting all nodes #[derive(Debug, PartialEq)] pub struct ListNodesError(pub String); impl Error for ListNodesError {} impl fmt::Display for ListNodesError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when requesting a node #[derive(Debug, PartialEq)] pub struct FetchNodeError(pub String); impl Error for FetchNodeError {} impl fmt::Display for FetchNodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when requesting all circuits #[derive(Debug, PartialEq)] pub struct ListCircuitsError(pub String); impl Error for ListCircuitsError {} impl fmt::Display for ListCircuitsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when requesting a circuit #[derive(Debug, PartialEq)] pub struct FetchCircuitError(pub String); impl Error for FetchCircuitError {} impl fmt::Display for FetchCircuitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when adding a service #[derive(Debug, PartialEq)] pub struct AddServiceError(pub String); impl Error for AddServiceError {} impl fmt::Display for AddServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when removing a service #[derive(Debug, PartialEq)] pub struct RemoveServiceError(pub String); impl Error for RemoveServiceError {} impl fmt::Display for RemoveServiceError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when adding a circuit #[derive(Debug, PartialEq)] pub struct AddCircuitError(pub String); impl Error for AddCircuitError {} impl fmt::Display for AddCircuitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when adding circuits #[derive(Debug, PartialEq)] pub struct AddCircuitsError(pub String); impl Error for AddCircuitsError {} impl fmt::Display for AddCircuitsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when removing a circuit #[derive(Debug, PartialEq)] pub struct RemoveCircuitError(pub String); impl Error for RemoveCircuitError {} impl fmt::Display for RemoveCircuitError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when adding a node #[derive(Debug, PartialEq)] pub struct AddNodeError(pub String); impl Error for AddNodeError {} impl fmt::Display for AddNodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when adding nodes #[derive(Debug, PartialEq)] pub struct AddNodesError(pub String); impl Error for AddNodesError {} impl fmt::Display for AddNodesError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } } /// Errors that could be raised when removing a node #[derive(Debug, PartialEq)] pub struct RemoveNodeError(pub String); impl Error for RemoveNodeError {} impl fmt::Display for RemoveNodeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Received internal error: {}", self.0) } }
28.576531
98
0.683985
2ffd24b4bce8ff58bd73d8edc7a22960a22087c4
565
py
Python
lib/Program.py
Youhana-Hana/interpolation
e091fef4ad258fe48a80169b5c448377246cd733
[ "MIT" ]
null
null
null
lib/Program.py
Youhana-Hana/interpolation
e091fef4ad258fe48a80169b5c448377246cd733
[ "MIT" ]
null
null
null
lib/Program.py
Youhana-Hana/interpolation
e091fef4ad258fe48a80169b5c448377246cd733
[ "MIT" ]
null
null
null
from lib import InputTransport from lib import Parser from lib import Interpolator class Program: def __init__(self): self.transport = InputTransport() self.parser = Parser() self.interpolator = Interpolator() def run(self): try: input = self.transport.read() parsed_input = self.parser.parse(input) result = self.interpolator.interpolate(parsed_input) except ValueError: self.transport.write('Invalid matrix!') else: self.transport.write(result)
28.25
64
0.630088
db83497e9c56049951cda52704b1dd1019302268
298
php
PHP
lvyecms/Application/Content/Fields/typeid/field_add_form.inc.php
xueyuwan/www
6ee4914baf88ca7c6a4c5fa966432e22d774bab4
[ "Apache-2.0" ]
null
null
null
lvyecms/Application/Content/Fields/typeid/field_add_form.inc.php
xueyuwan/www
6ee4914baf88ca7c6a4c5fa966432e22d774bab4
[ "Apache-2.0" ]
131
2017-04-10T06:10:03.000Z
2017-12-06T10:27:02.000Z
shuipf/Application/Content/Fields/typeid/field_add_form.inc.php
rentianhua/tsf
5aa420b063bf8bee20c2954963b7c8bf6f5b846b
[ "MIT" ]
1
2018-11-19T16:15:03.000Z
2018-11-19T16:15:03.000Z
<table cellpadding="2" cellspacing="1" width="96%"> <tr> <td>默认值</td> <td> <input type="hidden" name="setting[minnumber]" value="5"/> <input type="text" name="setting[defaultvalue]" value="0" size="40" class="input"/> 正整数 最大长度 5 </td> </tr> </table>
37.25
112
0.54698
23d98e73b22dd7072640ab33984d8f98e809716b
1,771
js
JavaScript
Documentation/search/all_4.js
CollegiumXR/Unity-SCORM-Integration-Kit
cc566fc11849611b195f3a35534714b83aca6db7
[ "Apache-2.0" ]
20
2016-03-09T15:02:58.000Z
2022-01-28T06:02:04.000Z
Documentation/search/all_4.js
CollegiumXR/Unity-SCORM-Integration-Kit
cc566fc11849611b195f3a35534714b83aca6db7
[ "Apache-2.0" ]
5
2016-11-10T03:52:07.000Z
2021-12-22T00:02:53.000Z
Documentation/search/all_4.js
CollegiumXR/Unity-SCORM-Integration-Kit
cc566fc11849611b195f3a35534714b83aca6db7
[ "Apache-2.0" ]
7
2020-03-05T18:57:20.000Z
2022-01-28T06:02:06.000Z
var searchData= [ ['debug',['debug',['../scorm_8js.html#a651046067579e48d7f0d03ce38dc7cf8',1,'scorm.js']]], ['debugprint',['DebugPrint',['../scorm_8js.html#a80a162fca7d5e07b8757a9f1b7f17fc1',1,'scorm.js']]], ['deliveryspeed',['deliverySpeed',['../class_student_record_1_1_learner_preference.html#a6718b9380069aa12657566d0736f7503',1,'StudentRecord::LearnerPreference']]], ['description',['description',['../class_student_record_1_1_learner_interaction_record.html#ac1a15b402380f6a5117cc46070178017',1,'StudentRecord.LearnerInteractionRecord.description()'],['../class_student_record_1_1_objectives.html#a606b6174e44e84d7c598309861addfbb',1,'StudentRecord.Objectives.description()']]], ['docommit',['doCommit',['../scorm_8js.html#a417015b33256e2b3c15105c079df9c1f',1,'scorm.js']]], ['dogetdiagnostic',['doGetDiagnostic',['../scorm_8js.html#ad1807788852d49eda6afe9b6bc2849a9',1,'scorm.js']]], ['dogeterrorstring',['doGetErrorString',['../scorm_8js.html#a1e7aece551668d7d4999893d51489d79',1,'scorm.js']]], ['dogetlasterror',['doGetLastError',['../scorm_8js.html#a6d4296a6ca774e74975ae2ddb29d7094',1,'scorm.js']]], ['dogetvalue',['doGetValue',['../scorm_8js.html#a0c0077a44c7fc074dfd5fb9d2115485a',1,'scorm.js']]], ['doinitialize',['doInitialize',['../scorm_8js.html#a1b823508e421d37a6ccbf1127d0e2c6f',1,'scorm.js']]], ['doisscorm2004',['doIsScorm2004',['../scorm_8js.html#a3bb1d4e6b589a592935df8265c346baf',1,'scorm.js']]], ['dologmessage',['DoLogMessage',['../class_scorm_manager.html#a3908c88bf18952b41114d9759bec46ea',1,'ScormManager']]], ['dosetvalue',['doSetValue',['../scorm_8js.html#a7477df26ca129051981962ef361db201',1,'scorm.js']]], ['doterminate',['doTerminate',['../scorm_8js.html#a6e5ba4ee5d3d09f540b1b678aa6d96af',1,'scorm.js']]] ];
98.388889
314
0.762846
91a3623b8b8789f2aa8b642f495cf31a52492108
14,365
dart
Dart
lib/slidable.dart
MXilian/simple_slidable
0d7ab478454a53a5f4290899754310acb6cd9914
[ "CC0-1.0" ]
1
2020-10-21T11:38:33.000Z
2020-10-21T11:38:33.000Z
lib/slidable.dart
MXilian/simple_slidable_flutter
0d7ab478454a53a5f4290899754310acb6cd9914
[ "CC0-1.0" ]
null
null
null
lib/slidable.dart
MXilian/simple_slidable_flutter
0d7ab478454a53a5f4290899754310acb6cd9914
[ "CC0-1.0" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:simple_slidable/slide_controller.dart'; import 'package:simple_slidable/utils.dart'; class Slidable extends StatefulWidget { final Widget child; /// Slide menu on the left final Widget slideMenuL; /// Slide menu on the right final Widget slideMenuR; /// If true, then "slideMenuL" will be equal to "slideMenuR" /// (and then you can transfer one of these parameters only) final bool isLeftEqualsRight; /// Minimum shift percentage (from 0 to 1) at which the slide will be completed /// (default - 0.3) final double minShiftPercent; /// Maximum possible slide percentage (from 0 to 1). /// Default value: 0.9 (i.e. 10% of the parent will remain visible at full shift) final double percentageBias; final SlideController controller; /// Duration of slide animation (in milliseconds) final int animationDuration; final Function onPressed; /// If true, the slide menu will automatically close when the parent scrolls final bool closeOnScroll; /// If the widget does not respond to the parent scrollable /// (this happens if the scrollable is not a direct parent), /// then you should additionally give access to scrollController final ScrollController scrollController; /// The factor at which the widget shift is ahead of the cursor/finger shift /// (relieves the user of having to shift the widget over a long distance /// to see the slide menu) final double cursorOvertaking; final Function onSlideCallback; /// The millisecond`s count after which the slide menu will automatically close /// (if 0, then the automatic closing will not occur) final int millisecondsToClose; Slidable({ @required this.child, this.slideMenuL, this.slideMenuR, this.isLeftEqualsRight = false, this.minShiftPercent = 0.2, this.percentageBias = 0.9, this.controller, this.animationDuration = 200, this.onPressed, this.closeOnScroll = true, this.scrollController, this.cursorOvertaking = 1.4, this.onSlideCallback, this.millisecondsToClose = 0, Key key, }) : super(key: key); @override _SlidableState createState() => _SlidableState(); } class _SlidableState extends State<Slidable> with TickerProviderStateMixin { SlideController slideController; ScrollPosition _scrollPosition; bool isAnimationOn = false; Animation animation; AnimationController animationController; /// Left slide-menu Widget leftMenu; /// Right slide-menu Widget rightMenu; /// Starting cursor/finger position when dragging double dragStart = 0; /// Cursor offset (not widget) relating of start position double dragDelta = 0; /// Widget`s start position double _offsetBase = 0; /// Saved widget offset double offsetXSaved = 0; /// Current widget offset double offsetXActual = 0; /// Maximum widget shift to the left double _maxDragFromRightToLeft = 0; /// Maximum widget shift to the right double _maxDragFromLeftToRight = 0; final GlobalKey _key = GlobalKey(); RenderBox _box; @override void initState() { slideController = widget.controller ?? SlideController(); animationController = AnimationController( vsync: this, duration: Duration(milliseconds: widget.animationDuration)); // Если активна опция isLeftEqualsRight, то делаем оба слайд-меню одинаковыми // (в противном случае активно будет только то, которое не равно null) if (widget.isLeftEqualsRight) { leftMenu = widget.slideMenuL ?? widget.slideMenuR; rightMenu = leftMenu; } else { leftMenu = widget.slideMenuL; rightMenu = widget.slideMenuR; } // Настраиваем контроллер slideController.setSlideToLeft = _slideToLeft; slideController.setSlideToRight = _slideToRight; slideController.setClose = _close; slideController.rightMenuIsDefault = rightMenu != null; super.initState(); } @override void didChangeDependencies() { removeScrollListener(); addScrollListener(); super.didChangeDependencies(); } /// Is slide-menu opened now bool get isOpened => slideController.isOpened; /// Open right slide menu void _slideToLeft() { animationController.reset(); setState(() { animation = Tween( begin: offsetXSaved, end: _maxDragFromRightToLeft, ).animate(animationController); // Включаем анимацию, чтобы она могла быть запущена // (т.к. при манипуляциях юзера с виджетом она отключается) isAnimationOn = true; }); animationController.forward(); // Сохраняем конечную точку анимации в качестве смещения виджета offsetXSaved = _maxDragFromRightToLeft; widget.onSlideCallback?.call(); if (widget.millisecondsToClose > 0) _autoClose(); } /// Open left slide menu void _slideToRight() { animationController.reset(); setState(() { animation = Tween( begin: offsetXSaved, end: _maxDragFromLeftToRight, ).animate(animationController); // Включаем анимацию, чтобы она могла быть запущена // (т.к. при манипуляциях юзера с виджетом она отключается) isAnimationOn = true; }); animationController.forward(); // Сохраняем конечную точку анимации в качестве смещения виджета offsetXSaved = _maxDragFromLeftToRight; widget.onSlideCallback?.call(); if (widget.millisecondsToClose > 0) _autoClose(); } DebounceAction _debounce; void _autoClose() { _debounce = DebounceAction(milliseconds: widget.millisecondsToClose); _debounce.run(() { slideController.close(); }); } /// Close slide menu void _close() { animationController.reset(); setState(() { animation = Tween( begin: offsetXSaved, end: 0.0, ).animate(animationController); isAnimationOn = true; }); animationController.forward(); // Обнуляем сохраненное смещение виджета, т.к. он был возвращен в исходное положение offsetXSaved = 0.0; } void addScrollListener() { if (widget.closeOnScroll) { // Находим скролл-контроллер if (widget.scrollController != null) _scrollPosition = widget.scrollController.position; else _scrollPosition = Scrollable.of(context)?.position; // Ставим листенер, чтобы при скролле закрывать все slidable if (_scrollPosition != null) _scrollPosition.isScrollingNotifier.addListener(scrollListener); } } /// Closing all slide menus at screen scrolling void scrollListener() { if (widget.closeOnScroll == false || _scrollPosition == null) return; if (_scrollPosition.isScrollingNotifier.value && slideController.isOpened) { slideController.close(); } } void removeScrollListener() { if (_scrollPosition != null) { _scrollPosition.isScrollingNotifier.removeListener(scrollListener); } } void afterBuild() { BuildContext context = _key.currentContext; if (context == null) return; setState(() { // Сохраняем _box, из которого будут браться размеры для виджета // при его перестроении _box = context.findRenderObject(); }); } @override Widget build(BuildContext context) { // При перестроении виджета будет вызван afterBuild() WidgetsBinding.instance.addPostFrameCallback((_) => afterBuild()); // При первом построении виджета сохраняем key. // После завешения билда будет вызван коллбэк afterBuild, // который извлечет из ключа RenderBox и сохранит его в _box. // Общая ширина виджета (видимая часть + слайд меню) double _maxWidth = _box?.size?.width ?? 0; // Если левое слайд-меню не пустое, тогда увеличиваем ширину виджета // на размер левого слайд-меню, а также устанавливаем новые значения для // максимального сдвига вправо и начального смещения виджета. if (leftMenu != null) { _maxWidth += (_box?.size?.width ?? 0) * widget.percentageBias; _maxDragFromLeftToRight = (_box?.size?.width ?? 0) * widget.percentageBias; _offsetBase = 0 - _maxDragFromLeftToRight; } // Если правое слайд-меню не пустое, тогда увеличиваем ширину виджета // на размер правого слайд-меню, а также устанавливаем новое значение для // максимального сдвига вправо. if (rightMenu != null) { _maxWidth += (_box?.size?.width ?? 0) * widget.percentageBias; _maxDragFromRightToLeft = 0 - (_box?.size?.width ?? 0) * widget.percentageBias; } return Stack( children: [ Opacity( opacity: 0, child: Container( key: _key, child: widget.child, ), ), _box == null ? SizedBox() : SizedBox( height: _box.size.height, width: _box.size.width, child: GestureDetector( behavior: HitTestBehavior.translucent, onTap: widget.onPressed ?? () {}, onHorizontalDragStart: (DragStartDetails details) { // Деактивируем анимацию, чтобы не мешала перетаскиванию isAnimationOn = false; animationController.reset(); // Сохраняем начальную позицию курсора dragStart = details.localPosition.dx; // Достаем сохраненное в памяти текущее смещение виджета, // чтобы относительно него вести дальнейшие вычисления offsetXActual = offsetXSaved; }, onHorizontalDragUpdate: (DragUpdateDetails details) { // Определяем текущую позицию курсора double dragCurrent = details.localPosition.dx; // Вычисляем, на сколько пикселей произошло отклонение относительно // начальной позиции курсора dragDelta = dragCurrent - dragStart; // Обновляем текущее смещение виджета в соответствии со смещением курсора setState(() { // Смещение виджета опережает смещение курсора (для удобства пользователя) offsetXActual = offsetXSaved + dragDelta * widget.cursorOvertaking; // Не даем виджету выйти за пределы минимального и максимального // смещений, установленных ранее if (offsetXActual > _maxDragFromLeftToRight) offsetXActual = _maxDragFromLeftToRight; if (offsetXActual < _maxDragFromRightToLeft) offsetXActual = _maxDragFromRightToLeft; }); }, onHorizontalDragEnd: (DragEndDetails details) { // Сохраняем текущее смещение виджета в памяти offsetXSaved = offsetXActual; // Минимальный порог сдвига в пикселях double minShift = _box.size.width * widget.minShiftPercent; // Если значение отрицательное, значит виджет сдвинут влево // (т.е. юзер видит правое слайд-меню) if (offsetXActual < 0) { // Если правое слайд меню закрыто, и юзер не дотянул виджет до минимального порога // либо правое слайд меню открыто, и юзер перетянул виджет дальше минимального порога, // тогда возвращаем виджет в исходное положение, а иначе - показываем правое меню if ((!isOpened && offsetXSaved.abs() < minShift) || (isOpened && _box.size.width + offsetXSaved >= minShift)) slideController.close(); else slideController.slideToLeft(); // Если значение положительное, значит виджет сдвинут вправо // (т.е. юзер видит левое слайд-меню) } else if (offsetXActual >= 0) { // Если левое слайд меню закрыто, и юзер не дотянул виджет до минимального порога // либо левое слайд меню открыто, и юзер перетянул виджет дальше минимального порога, // тогда возвращаем виджет в исходное положение, а иначе - показываем левое меню if ((!isOpened && offsetXSaved.abs() < minShift) || (isOpened && _box.size.width - offsetXSaved >= minShift)) slideController.close(); else slideController.slideToRight(); } }, // Обрезаем виджет, чтобы был виден только child (без слайд меню) child: ClipRect( clipBehavior: Clip.antiAliasWithSaveLayer, // Добавиаемся, чтобы обрезанные slide-меню были поверх основного контента // (т.е., чтобы не смещали его) child: OverflowBox( alignment: Alignment.centerLeft, maxHeight: _box.size.height, maxWidth: _maxWidth, child: AnimatedBuilder( animation: animationController, builder: (context, child) => Transform.translate( offset: Offset( isAnimationOn // При активной анимации смещаем виджет на значение анимации ? _offsetBase + animation.value // При неактивной анимации смещаем виджет относительно положения курсора : _offsetBase + offsetXActual, 0), child: Row( children: [ if (leftMenu != null) Expanded( flex: (widget.percentageBias * 100).toInt(), child: leftMenu, ), Expanded( flex: 100, child: widget.child, ), if (rightMenu != null) Expanded( flex: (widget.percentageBias * 100).toInt(), child: rightMenu, ), ], ), ), ), ), ), ), ), ], ); } @override void dispose() { _debounce?.destroyTimer(); animationController?.dispose(); slideController?.dispose(); // _boxController?.close(); removeScrollListener(); super.dispose(); } }
35.9125
102
0.624922
74f3bce4a0a037c0d3d6923f07bb19c72f4eef27
823
css
CSS
src/style.css
geicibarham/Team-Profile-Generator
677964636145aafcaa9115886495a51cf3750629
[ "MIT" ]
null
null
null
src/style.css
geicibarham/Team-Profile-Generator
677964636145aafcaa9115886495a51cf3750629
[ "MIT" ]
null
null
null
src/style.css
geicibarham/Team-Profile-Generator
677964636145aafcaa9115886495a51cf3750629
[ "MIT" ]
null
null
null
nav{ display: flex; flex-wrap: wrap; padding:25px; background-color:#9896f1; align-content: center; justify-content: center; } h1{ color:white; } .cards{ border-radius: 5px; margin-top: 25px; padding-top: 20px; display: flex; flex-wrap: wrap; justify-content: center; } .card-header { border-radius: 5px; border:solid 1px grey; width: auto; text-align: center; background-color: #8ef6e4!important; } .card { padding:30px; border-radius: 5px; margin: 20px; } .color-body{ border-radius: 5px; border:solid 1px grey; padding: 15px; background-color:#edb1f1; } .link{ border-bottom: solid 1px grey; text-decoration: none; } .email{ text-decoration: none; color:black; } a{ text-decoration: none; }
14.438596
36
0.616039
83267c86c3cb585f528ccc1b7201fb9974a3d0b0
144
ts
TypeScript
src/orden/dto/orden.dto.ts
andrucar25/BackendWebMovilConcursoProyectos
9ccafd1585f15132f48539c7edc87854ff600c25
[ "MIT" ]
null
null
null
src/orden/dto/orden.dto.ts
andrucar25/BackendWebMovilConcursoProyectos
9ccafd1585f15132f48539c7edc87854ff600c25
[ "MIT" ]
null
null
null
src/orden/dto/orden.dto.ts
andrucar25/BackendWebMovilConcursoProyectos
9ccafd1585f15132f48539c7edc87854ff600c25
[ "MIT" ]
null
null
null
export class CreateOrdenDto{ idConcurso:string; ordenProyectos:{}; categoria:string; tituloConcurso:string; estado:string; }
20.571429
28
0.708333
ada41818a3257b80a51ee154273e0fee8d8d39f4
3,321
swift
Swift
Tests/EvolvParticipantTest.swift
divbyzero/EvolvKit
2bb6da782a93a4eb30e268986ff33ca98714ac0e
[ "Apache-2.0" ]
2
2019-08-08T00:30:55.000Z
2019-11-04T11:20:43.000Z
Tests/EvolvParticipantTest.swift
divbyzero/EvolvKit
2bb6da782a93a4eb30e268986ff33ca98714ac0e
[ "Apache-2.0" ]
4
2019-07-30T17:34:23.000Z
2019-08-22T07:27:46.000Z
Tests/EvolvParticipantTest.swift
divbyzero/EvolvKit
2bb6da782a93a4eb30e268986ff33ca98714ac0e
[ "Apache-2.0" ]
1
2019-07-23T16:14:34.000Z
2019-07-23T16:14:34.000Z
// // EvolvParticipantTest.swift // // Copyright (c) 2019 Evolv Technology Solutions // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import PromiseKit @testable import EvolvKit class EvolvParticipantTest: XCTestCase { func testBuildDefaultParticipant() { let participant = EvolvParticipant.builder().build() XCTAssertNotNil(participant.userId) XCTAssertNotNil(participant.sessionId) XCTAssertNotNil(participant.userAttributes) } func testSetCustomParticipantAttributes() { let userId = "Testy" let sessionId = "McTestTest" let userAttributes = ["country": "us"] let participant = EvolvParticipant.builder() .set(userId: userId) .set(sessionId: sessionId) .set(userAttributes: userAttributes) .build() XCTAssertEqual(userId, participant.userId) XCTAssertEqual(sessionId, participant.sessionId) var expectedUserAttributes: [String: String] = [:] expectedUserAttributes["country"] = String("us") expectedUserAttributes[EvolvRawAllocation.CodingKey.userId.stringValue] = String(userId) expectedUserAttributes[EvolvRawAllocation.CodingKey.sessionId.stringValue] = String(sessionId) XCTAssertEqual(expectedUserAttributes, participant.userAttributes) } func testSetUserIdAfterParticipantCreated() { let newUserId = "Testy" let participant = EvolvParticipant.builder().build() let oldUserId = participant.userId participant.userId = newUserId XCTAssertNotEqual(oldUserId, newUserId) XCTAssertEqual(newUserId, participant.userId) } func testParticipantGetUserAttr() { let participant = EvolvParticipant.builder() .set(userId: "test_user") .set(sessionId: "test_session") .build() let userAttributes = participant.userAttributes let expectedUserAttributes = [EvolvRawAllocation.CodingKey.userId.stringValue: "test_user", EvolvRawAllocation.CodingKey.sessionId.stringValue: "test_session"] XCTAssertEqual(userAttributes[EvolvRawAllocation.CodingKey.userId.stringValue], expectedUserAttributes[EvolvRawAllocation.CodingKey.userId.stringValue]) XCTAssertEqual(userAttributes[EvolvRawAllocation.CodingKey.sessionId.stringValue], expectedUserAttributes[EvolvRawAllocation.CodingKey.sessionId.stringValue]) } func testEvolvParticipant() { let participant = EvolvParticipant.builder().build() participant.userId = "test_user" XCTAssertEqual(participant.userId, "test_user") } }
38.616279
105
0.682325
e8f1abe2f96a52918a6108883319d223dc607f9c
3,186
swift
Swift
07-Linking-Accounts/Auth0Sample/HomeViewController.swift
alexisluque/auth0-ios-swift-sample
bc752e61939f671aed5bdbc24cca8f6cc88261e9
[ "MIT" ]
1
2021-12-09T22:06:14.000Z
2021-12-09T22:06:14.000Z
07-Linking-Accounts/Auth0Sample/HomeViewController.swift
TillDev/auth0-ios
a271c34920054f35e486e201e8690a0c2ece7ced
[ "MIT" ]
null
null
null
07-Linking-Accounts/Auth0Sample/HomeViewController.swift
TillDev/auth0-ios
a271c34920054f35e486e201e8690a0c2ece7ced
[ "MIT" ]
null
null
null
// HomeViewController.swift // Auth0Sample // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Auth0 class HomeViewController: UIViewController { // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - IBAction @IBAction func showLoginController(_ sender: UIButton) { self.checkAccessToken() } // MARK: - Private private func showLogin() { guard let clientInfo = plistValues(bundle: Bundle.main) else { return } Auth0 .webAuth() .audience("https://" + clientInfo.domain + "/userinfo") .scope("openid profile email") .start { switch $0 { case .failure(let error): // Handle the error print("Error: \(error)") case .success(let credentials): guard let accessToken = credentials.accessToken, let idToken = credentials.idToken else { return } SessionManager.shared.storeTokens(accessToken, idToken: idToken) SessionManager.shared.retrieveProfile { error in DispatchQueue.main.async { guard error == nil else { return self.showLogin() } self.performSegue(withIdentifier: "ShowProfileNonAnimated", sender: nil) } } } } } private func checkAccessToken() { let loadingAlert = UIAlertController.loadingAlert() loadingAlert.presentInViewController(self) SessionManager.shared.retrieveProfile { error in DispatchQueue.main.async { loadingAlert.dismiss(animated: true) { guard error == nil else { return self.showLogin() } self.performSegue(withIdentifier: "ShowProfileNonAnimated", sender: nil) } } } } }
37.046512
118
0.603578
8ede24e05ed2ff7b85c655f051ff5f23ac188188
30,687
swift
Swift
ShowcaseApp/ShowcaseAppSwift/Controllers/VideoCamViewController.swift
samtstern/mlkit-material-ios
faadf28ee4478e69030483301d06da2c66ded957
[ "Apache-2.0" ]
57
2019-05-08T06:59:13.000Z
2020-07-12T22:52:58.000Z
ShowcaseApp/ShowcaseAppSwift/Controllers/VideoCamViewController.swift
samtstern/mlkit-material-ios
faadf28ee4478e69030483301d06da2c66ded957
[ "Apache-2.0" ]
7
2019-05-08T19:55:04.000Z
2020-08-03T12:52:05.000Z
ShowcaseApp/ShowcaseAppSwift/Controllers/VideoCamViewController.swift
samtstern/mlkit-material-ios
faadf28ee4478e69030483301d06da2c66ded957
[ "Apache-2.0" ]
16
2019-06-29T20:00:33.000Z
2020-06-19T18:48:34.000Z
/** * Copyright 2019 Google ML Kit team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import AVFoundation import Firebase import GTMSessionFetcher import MaterialComponents /** * The camera mode view controller that displays a rear facing live feed. */ private let videoDataOutputQueueLabel = "com.google.firebaseml.visiondetector.VideoDataOutputQueue" private let videoSessionQueueLabel = "com.google.firebaseml.visiondetector.VideoSessionQueue" //* Duration for presenting the bottom sheet. private let kBottomSheetAnimationDurationInSec: CGFloat = 0.25 //* Duration for confirming stage. private let kConfirmingDurationInSec: CGFloat = 1.5 // Constants for alpha values. private let kOpaqueAlpha: CGFloat = 1.0 private let kTransparentAlpha: CGFloat = 0.0 //* Radius of the searching indicator. private let kSearchingIndicatorRadius: CGFloat = 24.0 //* Target height of the thumbnail when it sits on top of the bottom sheet. private let kThumbnailbottomSheetTargetHeight: CGFloat = 200.0 //* Padding around the thumbnail when it sits on top of the bottom sheet. private let kThumbnailPaddingAround: CGFloat = 24.0 //* The thumbnail will fade out when it reaches this threshhold from screen edge. private let kThumbnailFadeOutEdgeThreshhold: CGFloat = 200.0 //* Number of faked product search results. private let kFakeProductSearchResultCount = 10 // Chip message related values. private let kChipBackgroundAlpha: CGFloat = 0.6 private let kChipCornerRadius: CGFloat = 8.0 private let kChipFadeInDuration: CGFloat = 0.075 private let kChipScaleDuration: CGFloat = 0.15 private let kChipScaleFromRatio: CGFloat = 0.8 private let kChipScaleToRatio: CGFloat = 1.25 private let kChipBottomPadding: CGFloat = 36.0 //* The message shown in detecting stage. private let kDetectingStageMessage = "Point your camera at an object" //* The Message shown in confirming stage. private let kConfirmingStageMessage = "Keep camera still for a moment" //* The message shown in searching stage. private let kSearchingMessage = "Searching" // Strings for fake search results. private let kFakeProductNameFormat = "Fake product name: %li" private let kFakeProductTypeName = "Fashion" private let kFakeProductPriceText = "$10" private let kFakeProductItemNumberText = "12345678" private let kKeyFileName = "key" private let kKeyFileType = "plist" class VideoCamViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, MDCBottomSheetControllerDelegate { // Views to be added as subviews of current view. private var previewView: UIView! private var overlayView: DetectionOverlayView! private var detectingReticle: CameraReticle! private var confirmingSpinner: ConfirmationSpinner! private var searchingIndicator: MDCActivityIndicator! // Video capture related properties. private var session = AVCaptureSession() private var videoDataOutput: AVCaptureVideoDataOutput! private var videoDataOutputQueue = DispatchQueue(label: videoDataOutputQueueLabel) private var sessionQueue = DispatchQueue(label: videoSessionQueueLabel) private var previewLayer: AVCaptureVideoPreviewLayer! // Vision server to generate `VisionObjectDetector`. private let vision = Vision.vision() // Current status in object detection. var status = ODTStatus.notStarted { didSet { switch status { case .notStarted: hideMessage() confirmingSpinner.isHidden = true detectingReticle.isHidden = true showSearchingIndicator(false) case .detecting: showMessage(kDetectingStageMessage) detectingReticle.isHidden = false confirmingSpinner.isHidden = true showSearchingIndicator(false) case .confirming: showMessage(kConfirmingStageMessage) detectingReticle.isHidden = true confirmingSpinner.isHidden = false showSearchingIndicator(false) case .searching: showMessage(kSearchingMessage) confirmingSpinner.isHidden = true detectingReticle.isHidden = true showSearchingIndicator(true) case .searched: hideMessage() confirmingSpinner.isHidden = true detectingReticle.isHidden = true showSearchingIndicator(false) } } } // View to show message during different stages. private var messageView: MDCChipView! // Properties to record latest detected results. private var lastDetectedObject: VisionObject! private var lastDetectedSampleBuffer: SampleBuffer! // Width to height ratio of the thumbnail. private var thumbnailWidthHeightRatio: CGFloat = 0.0 // Target height of the bottom sheet. private var bottomSheetTargetHeight: CGFloat = 0.0 // Array of timers scheduled before confirmation. private var timers = [AnyHashable]() // Used to fetch product search results. private var fetcherService = GTMSessionFetcherService() deinit { clearLastDetectedObject() fetcherService.stopAllFetchers() } // MARK: - UIViewController override func loadView() { super.loadView() view.clipsToBounds = true setUpPreviewView() setUpOverlayView() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setCameraSelection() // Set up video processing pipeline. setUpVideoProcessing() // Set up camera preview. #if !TARGET_IPHONE_SIMULATOR setUpCameraPreviewLayer() #endif setUpDetectingReticle() setUpConfirmingSpinner() setUpSearchingIndicator() setUpMessageView() startToDetect() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer.frame = view.frame previewLayer.position = CGPoint(x: previewLayer.frame.midX, y: previewLayer.frame.midY) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) weak var weakSelf = self #if !TARGET_IPHONE_SIMULATOR sessionQueue.async(execute: { weakSelf?.session.stopRunning() }) #endif } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { let buffer = SampleBuffer(sampleBuffer: sampleBuffer) detectObject(in: buffer) } // MARK: - MDCBottomSheetControllerDelegate func bottomSheetControllerDidDismissBottomSheet(_ controller: MDCBottomSheetController) { bottomSheetTargetHeight = 0 startToDetect() } func bottomSheetControllerDidChangeYOffset(_ controller: MDCBottomSheetController, yOffset: CGFloat) { let imageStartY = yOffset - kThumbnailbottomSheetTargetHeight - kThumbnailPaddingAround let rect = CGRect(x: kThumbnailPaddingAround, y: imageStartY, width: kThumbnailbottomSheetTargetHeight * thumbnailWidthHeightRatio, height: kThumbnailbottomSheetTargetHeight) // Height guard let currentWindow = UIApplication.shared.keyWindow else { return } let safeInsets = UIUtilities.safeAreaInsets() let screenHeight = currentWindow.bounds.size.height let topFadeOutOffsetY = safeInsets.top + kThumbnailFadeOutEdgeThreshhold let bottomFadeOutOffsetY = screenHeight - safeInsets.bottom - kThumbnailFadeOutEdgeThreshhold let imageAlpha = ratioOfCurrentValue(yOffset, from: (yOffset > bottomSheetTargetHeight) ? bottomFadeOutOffsetY : topFadeOutOffsetY, to: bottomSheetTargetHeight) overlayView.showImage(in: rect, alpha: imageAlpha) } // MARK: - Private //* Prepares camera session for video processing. func setUpVideoProcessing() { weak var weakSelf = self sessionQueue.async(execute: { guard let strongSelf = weakSelf else { return } strongSelf.videoDataOutput = AVCaptureVideoDataOutput() let rgbOutputSettings = [ kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA) ] strongSelf.videoDataOutput.videoSettings = rgbOutputSettings if let videoDataOutput = strongSelf.videoDataOutput { if !strongSelf.session.canAddOutput(videoDataOutput) { if strongSelf.videoDataOutput != nil { strongSelf.session.removeOutput(videoDataOutput) strongSelf.videoDataOutput = nil } print("Failed to set up video output") return } } strongSelf.videoDataOutput.alwaysDiscardsLateVideoFrames = true strongSelf.videoDataOutput.setSampleBufferDelegate(strongSelf, queue: strongSelf.videoDataOutputQueue) if let videoDataOutput = strongSelf.videoDataOutput { strongSelf.session.addOutput(videoDataOutput) } }) } //* Prepares preview view for camera session. func setUpPreviewView() { previewView = UIView(frame: view.frame) previewView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(previewView) } //* Initiates and prepares camera preview layer for later video capture. func setUpCameraPreviewLayer() { previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.backgroundColor = UIColor.black.cgColor previewLayer.videoGravity = .resizeAspectFill let rootLayer = previewView.layer rootLayer.masksToBounds = true previewLayer.frame = rootLayer.bounds rootLayer.addSublayer(previewLayer) } //* Prepares camera for later video capture. func setCameraSelection() { weak var weakSelf = self sessionQueue.async(execute: { guard let strongSelf = weakSelf else { return } strongSelf.session.beginConfiguration() strongSelf.session.sessionPreset = .hd1280x720 let oldInputs = strongSelf.session.inputs for oldInput in oldInputs { strongSelf.session.removeInput(oldInput) } let input = strongSelf.pickCamera(.back) if input == nil { // Failed, restore old inputs for oldInput in oldInputs { strongSelf.session.addInput(oldInput) } } else { // Succeeded, set input and update connection states if let input = input { strongSelf.session.addInput(input) } } strongSelf.session.commitConfiguration() }) } //* Determines camera for later video capture. Here only rear camera is picked. func pickCamera(_ desiredPosition: AVCaptureDevice.Position) -> AVCaptureDeviceInput? { var hadError = false for device in AVCaptureDevice.devices(for: .video) where device.position == desiredPosition { do { let input = try AVCaptureDeviceInput(device: device) if session.canAddInput(input) { return input } } catch { hadError = true print("Could not initialize for AVMediaTypeVideo for device \(device)") } } if !hadError { print("No camera found for requested orientation") } return nil } //* Initiates and prepares overlay view for later video capture. func setUpOverlayView() { overlayView = DetectionOverlayView(frame: view.frame) overlayView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(overlayView) } //* Clears up the overlay view. Caller must make sure this runs on the main thread. func cleanUpOverlayView() { assert(Thread.current.isEqual(Thread.main), "cleanUpOverlayView is not running on the main thread") overlayView.hideSubviews() overlayView.frame = view.frame } //* Initiates and prepares detecting reticle for later video capture. func setUpDetectingReticle() { detectingReticle = CameraReticle() detectingReticle.translatesAutoresizingMaskIntoConstraints = false let size = detectingReticle.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) detectingReticle.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) if let detectingReticle = detectingReticle { view.addSubview(detectingReticle) } NSLayoutConstraint.activate([ detectingReticle.centerXAnchor.constraint(equalTo: view.centerXAnchor), detectingReticle.centerYAnchor.constraint(equalTo: view.centerYAnchor) ].compactMap { $0 }) } //* Initiates and prepares confirming spinner for later video capture. func setUpConfirmingSpinner() { confirmingSpinner = ConfirmationSpinner(duration: CFTimeInterval(kConfirmingDurationInSec)) confirmingSpinner.translatesAutoresizingMaskIntoConstraints = false let size = confirmingSpinner.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) confirmingSpinner.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) if let confirmingSpinner = confirmingSpinner { view.addSubview(confirmingSpinner) } NSLayoutConstraint.activate([ confirmingSpinner.centerXAnchor.constraint(equalTo: view.centerXAnchor), confirmingSpinner.centerYAnchor.constraint(equalTo: view.centerYAnchor) ].compactMap { $0 }) } //* Initiates and prepares searching indicator for later video capture. func setUpSearchingIndicator() { searchingIndicator = MDCActivityIndicator() searchingIndicator.radius = kSearchingIndicatorRadius searchingIndicator.cycleColors = [UIColor.white] let size = confirmingSpinner.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) let centerX = view.frame.midX let centerY = view.frame.midY searchingIndicator.frame = CGRect(x: centerX, y: centerY, width: size.width, height: size.height) view.addSubview(searchingIndicator) NSLayoutConstraint.activate([ searchingIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), searchingIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor) ].compactMap { $0 }) } //* Initiates and prepares message view for later video capture. func setUpMessageView() { messageView = MDCChipView() messageView.backgroundColor = UIColor.black.withAlphaComponent(kChipBackgroundAlpha) messageView.isUserInteractionEnabled = false messageView.clipsToBounds = true messageView.titleLabel.textColor = UIColor.white messageView.layer.cornerRadius = kChipCornerRadius view.addSubview(messageView) messageView.alpha = kTransparentAlpha } /** * Clears last detected object. Caller must make sure that this method runs on the main thread. */ func clearLastDetectedObject() { assert(Thread.current.isEqual(Thread.main), "clearLastDetectedObject is not running on the main thread") lastDetectedObject = nil lastDetectedSampleBuffer = nil for timer in timers { guard let timer = timer as? Timer else { continue } timer.invalidate() } } // MARK: - Object detection and tracking. /** * Called to detect objects in the given sample buffer. * * @param sampleBuffer The `SampleBuffer` for object detection. */ func detectObject(in sampleBuffer: SampleBuffer) { let orientation = UIUtilities.imageOrientation(from: UIDevice.current.orientation, withCaptureDevicePosition: .back) let image = VisionImage(buffer: sampleBuffer.data) let metadata = VisionImageMetadata() metadata.orientation = orientation // metadata.orientation = FIRVisionDetectorImageOrientationRightTop; image.metadata = metadata let options = VisionObjectDetectorOptions() options.shouldEnableMultipleObjects = false options.shouldEnableClassification = false options.detectorMode = .stream let objectDetector = vision.objectDetector(options: options) do { let objects = try objectDetector.results(in: image) weak var weakSelf = self DispatchQueue.main.async(execute: { weakSelf?.onDetectedObjects(objects, in: sampleBuffer) }) } catch { } } /** * Call when objects are detected in the given sample buffer. Caller must make sure that this method * runs on the main thread. * * @param objects The list of objects that is detected in the given sample buffer. * @param sampleBuffer The given sampleBuffer. */ func onDetectedObjects(_ objects: [VisionObject]?, in sampleBuffer: SampleBuffer) { assert(Thread.current.isEqual(Thread.main), "onDetectedObjects:inSampleBuffer is not running on the main thread") guard let objects = objects, objects.count == 1, let object = objects.first, object.trackingID != nil else { startToDetect() return } let sampleBufferSize = self.sampleBufferSize(sampleBuffer.data) let isFocusInsideObjectFrame = object.frame.contains(CGPoint(x: sampleBufferSize.width / 2, y: sampleBufferSize.height / 2)) if !isFocusInsideObjectFrame { startToDetect() return } switch status { case .detecting: cleanUpOverlayView() let convertedRect = convertedRectOfObjectFrame(object.frame, inSampleBufferFrameSize: sampleBufferSize) overlayView.showBox(in: convertedRect) start(toConfirmObject: object, sampleBuffer: sampleBuffer) case .confirming: let convertedRect = convertedRectOfObjectFrame(object.frame, inSampleBufferFrameSize: sampleBufferSize) overlayView.showBox(in: convertedRect) lastDetectedObject = object lastDetectedSampleBuffer = sampleBuffer case .searching, .searched, .notStarted: break } } // MARK: - Status Handling /** * Called when it needs to start the detection. Caller must make sure that this method runs on the * main thread. */ func startToDetect() { assert(Thread.current.isEqual(Thread.main), "startToDetect is not running on the main thread") status = .detecting cleanUpOverlayView() clearLastDetectedObject() weak var weakSelf = self sessionQueue.async(execute: { guard let strongSelf = weakSelf else { return } #if !TARGET_IPHONE_SIMULATOR if !strongSelf.session.isRunning { strongSelf.session.startRunning() } #endif }) } /** * Starts a product search with last detected object. Caller must make sure that this method runs on * the main thread. */ func startToSearch() { assert(Thread.current.isEqual(Thread.main), "startToSearchWithImage:originalWidth:originalHeight is not running on the main thread") status = .searching let originalSampleBufferSize = sampleBufferSize(lastDetectedSampleBuffer.data) let croppedImage = self.croppedImage(from: lastDetectedSampleBuffer.data, in: lastDetectedObject.frame) let convertedRect = convertedRectOfObjectFrame(lastDetectedObject.frame, inSampleBufferFrameSize: originalSampleBufferSize) thumbnailWidthHeightRatio = lastDetectedObject.frame.size.height / lastDetectedObject.frame.size.width overlayView.image.image = croppedImage cleanUpOverlayView() overlayView.showImage(in: convertedRect, alpha: 1) guard let productSearchRequest = productSearchRequest(from: croppedImage) else { processSearchResponse(nil, for: croppedImage, originalWidth: size_t(originalSampleBufferSize.width), originalHeight: size_t(originalSampleBufferSize.height), useFakeResponse: true) clearLastDetectedObject() return } let fetcher = fetcherService.fetcher(with: productSearchRequest) weak var weakSelf = self DispatchQueue.global(qos: .default).async(execute: { fetcher.beginFetch { data, error in guard let strongSelf = weakSelf else { return } if error != nil { if let error = error { print("error in fetching: \(error)") } strongSelf.clearLastDetectedObject() return } DispatchQueue.main.async(execute: { guard let strongSelf = weakSelf else { return } strongSelf.processSearchResponse(data, for: croppedImage, originalWidth: size_t(originalSampleBufferSize.width), originalHeight: size_t(originalSampleBufferSize.height), useFakeResponse: false) strongSelf.clearLastDetectedObject() }) } }) } /** * Processes search response from server. Caller must make sure that this method runs on the main * thread. * * @param response The raw response from server on product search request. * @param image The image of the detected object that is to be searched. * @param width The width of the original sample buffer. * @param height The height of the original sample buffer. * @param useFakeResponse Whether to use fake response or send a product search request to the * server. */ func processSearchResponse(_ response: Data?, for image: UIImage, originalWidth width: size_t, originalHeight height: size_t, useFakeResponse: Bool) { assert(Thread.current.isEqual(Thread.main), """ processSearchRespose:forImage:originalWidth:originalHeight is not running on the main \ thread """) status = .searched var products: [Product] if useFakeResponse { products = fakeProductSearchResults() } else { products = Product.products(fromResponse: response) ?? [] } let productsViewController = ProductListViewController(products: products) let bottomSheet = MDCBottomSheetController(contentViewController: productsViewController) bottomSheet.trackingScrollView = productsViewController.collectionView bottomSheet.scrimColor = UIColor.clear bottomSheet.dismissOnBackgroundTap = true bottomSheet.delegate = self let contentHeight = productsViewController.collectionViewLayout.collectionViewContentSize.height let screenHeight = view.frame.size.height let safeInsets = UIUtilities.safeAreaInsets() let toOffsetY = contentHeight > screenHeight ? screenHeight / 2.0 - safeInsets.bottom : screenHeight - contentHeight - safeInsets.top - safeInsets.bottom bottomSheetTargetHeight = toOffsetY let toFrame = CGRect(x: kThumbnailPaddingAround, y: toOffsetY - kThumbnailbottomSheetTargetHeight - kThumbnailPaddingAround, width: thumbnailWidthHeightRatio * kThumbnailbottomSheetTargetHeight, height: kThumbnailbottomSheetTargetHeight) // Height UIView.animate(withDuration: TimeInterval(kBottomSheetAnimationDurationInSec), animations: { self.overlayView.showImage(in: toFrame, alpha: 1) }) present(bottomSheet, animated: true) } /** * Calculates the ratio of current value based on `from` and `to` value. * * @param currentValue The current value. * @param fromValue The start point of the range. * @param toValue The end point of the range. * @return Position of current value in the whole range. It falls into [0,1]. */ func ratioOfCurrentValue(_ currentValue: CGFloat, from fromValue: CGFloat, to toValue: CGFloat) -> CGFloat { var ratio = (currentValue - fromValue) / (toValue - fromValue) ratio = min(ratio, 1) return max(ratio, 0) } /** * Called to confirm on the given object.Caller must make sure that this method runs on the main * thread. * * @param object The object to confirm. It will be regarded as the same object if its objectID stays * the same during this stage. * @param sampleBuffer The original sample buffer that this object was detected in. */ func start(toConfirmObject object: VisionObject, sampleBuffer: SampleBuffer) { assert(Thread.current.isEqual(Thread.main), "startToConfirmObject:sampleBuffer is not running on the main thread") clearLastDetectedObject() let timer = Timer.scheduledTimer(timeInterval: TimeInterval(kConfirmingDurationInSec), target: self, selector: #selector(onTimerFired), userInfo: nil, repeats: false) timers.append(timer) status = .confirming lastDetectedObject = object lastDetectedSampleBuffer = sampleBuffer } //* Called when timer is up and the detected object is confirmed. @objc func onTimerFired() { weak var weakSelf = self DispatchQueue.main.async(execute: { guard let strongSelf = weakSelf else { return } switch strongSelf.status { case .confirming: #if !TARGET_IPHONE_SIMULATOR strongSelf.sessionQueue.async(execute: { weakSelf?.session.stopRunning() }) #endif strongSelf.startToSearch() case .detecting, .notStarted, .searched, .searching: break } }) } /** * Overrides setter for `status` property. It also shows corresponding indicator/message with the * status change. Caller must make sure that this method runs on the main thread. * * @param status The new status. */ // MARK: - Util methods /** * Returns size of given `CMSampleBufferRef`. * * @param sampleBuffer The `CMSampleBufferRef` to get size from. * @return The size of the given `CMSampleBufferRef`. It describes its width and height. */ func sampleBufferSize(_ sampleBuffer: CMSampleBuffer) -> CGSize { guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return CGSize.zero } let imageWidth = CVPixelBufferGetWidth(imageBuffer) let imageHeight = CVPixelBufferGetHeight(imageBuffer) return CGSize(width: CGFloat(imageWidth), height: CGFloat(imageHeight)) } /** * Converts given frame of a detected object to a `CGRect` in coordinate system of current view. * * @param frame The frame of detected object. * @param size The frame size of the sample buffer. * @return Converted rect. */ func convertedRectOfObjectFrame(_ frame: CGRect, inSampleBufferFrameSize size: CGSize) -> CGRect { let normalizedRect = CGRect(x: frame.origin.x / size.width, y: frame.origin.y / size.height, width: frame.size.width / size.width, height: frame.size.height / size.height) // Height let convertedRect = previewLayer.layerRectConverted(fromMetadataOutputRect: normalizedRect) return convertedRect.standardized } /** * Crops given `CMSampleBufferRef` with given rect. * * @param sampleBuffer The sample buffer to be cropped. * @param rect The rect of the area to be cropped. * @return Returns cropped image to the given rect. */ func croppedImage(from sampleBuffer: CMSampleBuffer, in rect: CGRect) -> UIImage { let croppedSampleBuffer = ImageUtilities.croppedSampleBuffer(sampleBuffer, with: rect) let croppedImage = ImageUtilities.image(from: croppedSampleBuffer) return UIUtilities.orientedUpImage(from: croppedImage!) } /** * Shows/Hides searching indicator. * * @param isVisible Whether to show/hide searching indicator. YES to show, NO to hide. */ func showSearchingIndicator(_ isVisible: Bool) { if isVisible { searchingIndicator.isHidden = false searchingIndicator.startAnimating() } else { searchingIndicator.isHidden = true searchingIndicator.stopAnimating() } } func showMessage(_ message: String) { if messageView.titleLabel.text == message { return } messageView.titleLabel.text = message messageView.sizeToFit() let size = messageView.sizeThatFits(view.frame.size) let startX = (view.frame.size.width - size.width) / 2.0 let startY = view.frame.size.height - kChipBottomPadding - size.height messageView.frame = CGRect(x: startX, y: startY, width: size.width, height: size.height) if messageView.alpha != kTransparentAlpha { return } messageView.alpha = kTransparentAlpha UIView.animate(withDuration: TimeInterval(kChipFadeInDuration), animations: { self.messageView?.alpha = kOpaqueAlpha }) let messageCenter = CGPoint(x: messageView.frame.midX, y: messageView.frame.midY) messageView.transform = messageView.transform.scaledBy(x: kChipScaleFromRatio, y: kChipScaleFromRatio) messageView.sizeToFit() UIView.animate(withDuration: TimeInterval(kChipScaleDuration), animations: { self.messageView.center = messageCenter self.messageView.transform = self.messageView.transform.scaledBy(x: kChipScaleToRatio, y: kChipScaleToRatio) }) } func hideMessage() { UIView.animate(withDuration: TimeInterval(kChipFadeInDuration), animations: { self.messageView.alpha = kTransparentAlpha }) } /** * Generates fake product search results for demo when there are no real backend server hooked up. */ func fakeProductSearchResults() -> [Product] { var fakeProductSearchResults: [Product] = [] for index in 0..<kFakeProductSearchResultCount { let product = Product.init(productName: String(format: kFakeProductNameFormat, index + 1), score: nil, itemNo: kFakeProductPriceText, imageURL: nil, priceFullText: kFakeProductPriceText, productTypeName: kFakeProductTypeName) fakeProductSearchResults.append(product) } return fakeProductSearchResults } } /** * A wrapper class that holds a reference to `CMSampleBufferRef` to let ARC take care of its * lifecyle for this `CMSampleBufferRef`. */ class SampleBuffer: NSObject { // The encapsulated `CMSampleBufferRed` data. var data: CMSampleBuffer! // MARK: - Public init(sampleBuffer: CMSampleBuffer) { super.init() self.data = sampleBuffer } }
38.120497
128
0.707824
cdb6ac58ad71a9ba3fd953bd3fadcb5c34ab300d
327
cs
C#
RMSDataManager.Library/Models/UserModel.cs
devsonukr/RetailManagementSystem
cc1da0cf1e8330bb6f9679eedf133bcb6759944c
[ "MIT" ]
null
null
null
RMSDataManager.Library/Models/UserModel.cs
devsonukr/RetailManagementSystem
cc1da0cf1e8330bb6f9679eedf133bcb6759944c
[ "MIT" ]
null
null
null
RMSDataManager.Library/Models/UserModel.cs
devsonukr/RetailManagementSystem
cc1da0cf1e8330bb6f9679eedf133bcb6759944c
[ "MIT" ]
null
null
null
using System; namespace RMSDataManager.Library.Models { public class UserModel { public string Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public DateTime CreateDate { get; set; } } }
23.357143
48
0.611621
259dc24b0e413dc974f3897f26c1529ac2457c39
8,356
cs
C#
Kooboo.Json.Test/Test/Deserialize/ObjectDeserializeTest.cs
Kooboo/Json
43ced8973ef20b029f735b371445e5cc272983f3
[ "MIT" ]
146
2019-03-26T10:03:12.000Z
2022-01-18T09:03:59.000Z
Kooboo.Json.Test/Test/Deserialize/ObjectDeserializeTest.cs
Kooboo/Json
43ced8973ef20b029f735b371445e5cc272983f3
[ "MIT" ]
7
2019-03-28T10:51:50.000Z
2022-01-20T08:11:32.000Z
Kooboo.Json.Test/Test/Deserialize/ObjectDeserializeTest.cs
Kooboo/Json
43ced8973ef20b029f735b371445e5cc272983f3
[ "MIT" ]
29
2019-03-27T05:18:20.000Z
2022-01-18T09:04:03.000Z
using Microsoft.VisualStudio.TestTools.UnitTesting; using Kooboo.Json; using System; using System.Dynamic; using System.Collections.Generic; namespace Kooboo.Json.Test { [TestClass] public class ObjectDeserializeTest { class _Objects { public int A; public string B { get; set; } } [TestMethod] public void NullString_deserialize_to_define_object_should_be_null() { var str = "null"; var obj = JsonSerializer.ToObject<_Objects>(str); Assert.IsNull(obj); } [TestMethod] public void NullString_deserialize_to_object_should_be_null() { var str = "null"; var obj = JsonSerializer.ToObject<object>(str); Assert.IsNull(obj); } [TestMethod] public void EmptyObjectString_deserialize_to_define_object_should_be_correct() { var str = "{}"; var val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual(default(int), val.A); Assert.IsNull(val.B); } [TestMethod] public void EmptyObjectString_deserialize_to_object_should_be_correct() { var str = "{}"; var val = JsonSerializer.ToObject<object>(str); Assert.IsNotNull(val); } [TestMethod] public void NormalObjectString_deserialize_to_object_should_be_correct() { var str = "{\"A\": 456, \"B\": \"hello\"}"; var val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual("hello", val.B); Assert.AreEqual(456, val.A); } [TestMethod] public void SkipMembersObjectString_deserialize_to_object_should_be_correct() { var str = "{\"A\": 123}"; var val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual(123, val.A); str = "{\"B\": \"hello\"}"; val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual("hello", val.B); } [TestMethod] public void ObjectString_with_space_deserialize_to_object_should_be_correct() { var str = " { \"B\" : \"hello\" , \"A\" : 456 } "; var val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual("hello", val.B); Assert.AreEqual(456, val.A); } [TestMethod] public void ObjectString_with_order_deserialize_to_object_should_be_correct() { var str = "{\"B\": \"hello\", \"A\": 456}"; var val = JsonSerializer.ToObject<_Objects>(str); Assert.IsNotNull(val); Assert.AreEqual("hello", val.B); Assert.AreEqual(456, val.A); } class _RecursiveObjects { public string A; public _RecursiveObjects B; } [TestMethod] public void RecursiveObjectsString_deserialize_to_RecursiveObject_should_be_correct() { var str = "{\"A\": \"hello world\", \"B\": { \"A\": \"foo bar\", \"B\": {\"A\": \"fizz buzz\"}}}"; var val = JsonSerializer.ToObject<_RecursiveObjects>(str); Assert.IsNotNull(val); Assert.AreEqual("hello world", val.A); Assert.AreEqual("foo bar", val.B.A); Assert.AreEqual("fizz buzz", val.B.B.A); Assert.IsNull(val.B.B.B); } class DataMemberName { public string Plain { get; set; } [Alias("FakeName")] public string RealName { get; set; } [Alias("NotSoSecretName")] public int SecretName { get; set; } } [TestMethod] public void AliasNameObjectString_deserialize_should_be_correct() { var str = "{\"Plain\":\"hello world\",\"FakeName\":\"Really RealName\",\"NotSoSecretName\":314159}"; var obj = JsonSerializer.ToObject<DataMemberName>(str); Assert.IsNotNull(obj); Assert.AreEqual("hello world", obj.Plain); Assert.AreEqual("Really RealName", obj.RealName); Assert.AreEqual(314159, obj.SecretName); } static T _EmptyAnonymousObject<T>(T example, string str) { return JsonSerializer.ToObject<T>(str); } [TestMethod] public void EmptyAnonymousObject_deserialize_should_be_correct() { var ex = new { }; var obj = _EmptyAnonymousObject(ex, "null"); Assert.IsNull(obj); obj = _EmptyAnonymousObject(ex, "{}"); Assert.IsNotNull(obj); } public interface IRange<T> { T First { get; set; } T Last { get; set; } } class Range<T> : IRange<T> { public T First { get; set; } public T Last { get; set; } } class NullInterfaceTestClass { public virtual Guid Id { get; set; } public virtual int? Year { get; set; } public virtual string Company { get; set; } public virtual IRange<decimal> DecimalRange { get; set; } public virtual IRange<int> IntRange { get; set; } public virtual IRange<decimal> NullDecimalRange { get; set; } } [TestMethod] public void NullValueObjectString_deserialize_should_be_correct() { NullInterfaceTestClass initial = new NullInterfaceTestClass { Company = "Company!", DecimalRange = new Range<decimal> { First = 0, Last = 1 }, Id = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), IntRange = new Range<int> { First = int.MinValue, Last = int.MaxValue }, Year = 2010, NullDecimalRange = null }; string json = JsonSerializer.ToJson(initial); Assert.AreEqual("{\"Id\":\"00000001-0002-0003-0405-060708090a0b\",\"Year\":2010,\"Company\":\"Company!\",\"DecimalRange\":{\"First\":0,\"Last\":1},\"IntRange\":{\"First\":-2147483648,\"Last\":2147483647},\"NullDecimalRange\":null}", json); NullInterfaceTestClass deserialized = JsonSerializer.ToObject<NullInterfaceTestClass>( json); Assert.AreEqual("Company!", deserialized.Company); Assert.AreEqual(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), deserialized.Id); Assert.AreEqual(0, deserialized.DecimalRange.First); Assert.AreEqual(1, deserialized.DecimalRange.Last); Assert.AreEqual(int.MinValue, deserialized.IntRange.First); Assert.AreEqual(int.MaxValue, deserialized.IntRange.Last); Assert.AreEqual(null, deserialized.NullDecimalRange); Assert.AreEqual(2010, deserialized.Year); } [TestMethod] public void ExpandoObject_deserialize_should_be_correct() { var json = "{\"Foo\":123,\"Bar\":\"hello\"}"; dynamic obj = JsonSerializer.ToObject<ExpandoObject>(json); Assert.AreEqual(123, obj.Foo); Assert.AreEqual("hello", obj.Bar); IDictionary<string, object> obj2 = JsonSerializer.ToObject<ExpandoObject>(json); Assert.AreEqual(123l, obj2["Foo"]); Assert.AreEqual("hello", obj2["Bar"]); } class Student { public Student() { Name = "DefaultName"; Age = 0; } public string Name { get; set; } public int Age { get; set; } } [TestMethod] public void LazyObject_deserialize_should_be_correct() { Lazy<Student> stu = new Lazy<Student>(); stu.Value.Name = "Tom"; stu.Value.Age = 21; var json = JsonSerializer.ToJson(stu); var lazystu = JsonSerializer.ToObject<Lazy<Student>>(json); Assert.AreEqual("Tom", lazystu.Value.Name); Assert.AreEqual(21, lazystu.Value.Age); } } }
34.386831
251
0.54787
798f1843ee47d9e709c3bad5df01f23cdf7bb53c
660
php
PHP
database/seeds/CompanyTableSeeder.php
emalisuranga/kpmg
c3feba8ad1df7e6f99e6b76bb9f9160b2e22debe
[ "MIT" ]
null
null
null
database/seeds/CompanyTableSeeder.php
emalisuranga/kpmg
c3feba8ad1df7e6f99e6b76bb9f9160b2e22debe
[ "MIT" ]
null
null
null
database/seeds/CompanyTableSeeder.php
emalisuranga/kpmg
c3feba8ad1df7e6f99e6b76bb9f9160b2e22debe
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Seeder; use App\Company; class CompanyTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $data = array( array('id' => 813181234, 'type_id'=> 17,'name' => 'ROC','postfix' => '(PVT) LTD','status' => 3,'created_by' => 1), array('id' => 813181235, 'type_id'=> 17,'name' => 'IMPERIUM','postfix' => '(PVT) LTD','status' => 3,'created_by' => 1), array('id' => 813181236, 'type_id'=> 17,'name' => 'C.A.T','postfix' => '(PVT) LTD','status' => 3,'created_by' => 1), ); $setting = Company::insert($data); } }
28.695652
125
0.533333
c67fc2c1e20ff89a755135f265bf316ac8234b20
2,998
rs
Rust
compiler/crates/graphql-transforms/src/validations/validate_global_variables.rs
HeroicHitesh/relay
b96329c9c90d28b4c2336cb4f1cdcae7f9c6f846
[ "MIT" ]
3
2020-09-11T17:04:49.000Z
2020-09-12T12:57:56.000Z
compiler/crates/graphql-transforms/src/validations/validate_global_variables.rs
HeroicHitesh/relay
b96329c9c90d28b4c2336cb4f1cdcae7f9c6f846
[ "MIT" ]
null
null
null
compiler/crates/graphql-transforms/src/validations/validate_global_variables.rs
HeroicHitesh/relay
b96329c9c90d28b4c2336cb4f1cdcae7f9c6f846
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{root_variables::InferVariablesVisitor, MATCH_CONSTANTS}; use common::{Diagnostic, NamedItem}; use graphql_ir::{ FragmentDefinition, OperationDefinition, Program, ValidationMessage, ValidationResult, Validator, }; pub fn validate_global_variables(program: &Program) -> ValidationResult<()> { ValidateGlobalVariables::new(program).validate_program(program) } pub struct ValidateGlobalVariables<'program> { visitor: InferVariablesVisitor<'program>, } impl<'program> ValidateGlobalVariables<'program> { fn new(program: &'program Program) -> Self { Self { visitor: InferVariablesVisitor::new(program), } } } /// Validates that all used arguments must be defined impl Validator for ValidateGlobalVariables<'_> { const NAME: &'static str = "ValidateGlobalVariables"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_operation(&mut self, operation: &OperationDefinition) -> ValidationResult<()> { // Skip 3D normalization fragments if operation .directives .named(MATCH_CONSTANTS.custom_module_directive_name) .is_some() { return Ok(()); } let variables = self.visitor.infer_operation_variables(operation); let undefined_variables: Vec<_> = variables .values() .filter(|var| { !(operation .variable_definitions .iter() .any(|def| def.name.item == var.name.item)) }) .collect(); if !undefined_variables.is_empty() { let is_plural = undefined_variables.len() > 1; let mut locations = undefined_variables .iter() .map(|arg_def| arg_def.name.location); let mut error = Diagnostic::error( ValidationMessage::GlobalVariables { operation_name: operation.name.item, variables_string: format!( "{}: '${}'", if is_plural { "s" } else { "" }, undefined_variables .iter() .map(|var| var.name.item.lookup()) .collect::<Vec<_>>() .join("', '$"), ), }, locations.next().unwrap(), ); for related_location in locations { error = error.annotate("related location", related_location); } return Err(vec![error]); } Ok(()) } fn validate_fragment(&mut self, _: &FragmentDefinition) -> ValidationResult<()> { Ok(()) } }
33.311111
95
0.556037
e3a75f1581cac701930afa3501a1670f14b8d5a9
2,268
psd1
PowerShell
ScsmMpcPx.psd1
KirkMunro/ScsmMpcPx
4e097e0eeac368e3b142ff89429e8ba87fb2745a
[ "Apache-2.0" ]
22
2015-12-08T23:49:08.000Z
2022-03-18T07:31:45.000Z
ScsmMpcPx.psd1
KirkMunro/ScsmMpcPx
4e097e0eeac368e3b142ff89429e8ba87fb2745a
[ "Apache-2.0" ]
null
null
null
ScsmMpcPx.psd1
KirkMunro/ScsmMpcPx
4e097e0eeac368e3b142ff89429e8ba87fb2745a
[ "Apache-2.0" ]
4
2015-05-29T07:20:48.000Z
2016-12-20T17:36:06.000Z
<############################################################################# DESCRIPTION Copyright 2015 Provance Technologies. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #############################################################################> @{ ModuleToProcess = 'ScsmMpcPx.psm1' ModuleVersion = '0.9.0.1' GUID = '351fa979-6dfe-41a7-8e47-3b181fd74dd6' Author = 'Kirk Munro' CompanyName = 'Poshoholic Studios' Copyright = 'Copyright 2015 Provance Technologies' Description = 'DESCRIPTION' PowerShellVersion = '4.0' NestedModules = @( 'SnippetPx' 'LanguagePx' ) RequiredModules = @( 'ScsmPx' ) AliasesToExport = @( 'ManagementPackConfiguration' ) FileList = @( 'ScsmMpcPx.psd1' 'ScsmMpcPx.psm1' 'LICENSE' 'NOTICE' 'en-us\about_ScsmMpcPx.xml' ) PrivateData = @{ PSData = @{ Tags = 'dsl domain specific modeling language system center service manager scsm management pack' LicenseUri = 'http://apache.org/licenses/LICENSE-2.0.txt' ProjectUri = 'https://github.com/KirkMunro/ScsmMpcPx' IconUri = '' ReleaseNotes = '' } } }
34.363636
130
0.455467
7dbf7cc510e2a23562c0513e4953cba59e0d07a8
40,079
css
CSS
public/dist/css/general.min.css
NullixAT/framelix-core
1d33c39ef09f72a26c1b8141ebaddfc86d56b451
[ "MIT" ]
null
null
null
public/dist/css/general.min.css
NullixAT/framelix-core
1d33c39ef09f72a26c1b8141ebaddfc86d56b451
[ "MIT" ]
null
null
null
public/dist/css/general.min.css
NullixAT/framelix-core
1d33c39ef09f72a26c1b8141ebaddfc86d56b451
[ "MIT" ]
null
null
null
@charset "UTF-8"; .framelix-alert { border-radius: var(--border-radius); margin-bottom: 5px; background: var(--color-alert-default-bg); color: var(--color-alert-default-text); --icon-color-hue: var(--color-primary-hue); font-size: 0.95rem; padding: 10px; position: relative; border: 2px solid rgba(0, 0, 0, 0.05); } .framelix-alert.framelix-alert-primary { background-color: var(--color-alert-primary-bg); color: var(--color-alert-primary-text); } .framelix-alert.framelix-alert-primary:any-link { color: var(--color-alert-primary-text); } .framelix-alert.framelix-alert-success { background-color: var(--color-alert-success-bg); color: var(--color-alert-success-text); } .framelix-alert.framelix-alert-success:any-link { color: var(--color-alert-success-text); } .framelix-alert.framelix-alert-warning { background-color: var(--color-alert-warning-bg); color: var(--color-alert-warning-text); } .framelix-alert.framelix-alert-warning:any-link { color: var(--color-alert-warning-text); } .framelix-alert.framelix-alert-error { background-color: var(--color-alert-error-bg); color: var(--color-alert-error-text); } .framelix-alert.framelix-alert-error:any-link { color: var(--color-alert-error-text); } .framelix-alert.framelix-alert-default { background-color: var(--color-alert-default-bg); color: var(--color-alert-default-text); } .framelix-alert.framelix-alert-default:any-link { color: var(--color-alert-default-text); } .framelix-alert.framelix-alert-trans { color: inherit; background-color: transparent; } .framelix-alert.framelix-alert-customcolor { background-color: var(--color-custom-bg); color: var(--color-custom-text); } .framelix-alert.framelix-alert-success { --icon-color-hue: var(--color-success-hue); } .framelix-alert.framelix-alert-warning { --icon-color-hue: var(--color-warning-hue); } .framelix-alert.framelix-alert-error { --icon-color-hue: var(--color-error-hue); } .framelix-alert[data-icon] { padding-left: 40px; } .framelix-alert[data-icon]::before { content: attr(data-icon string); position: absolute; color: hsl(var(--icon-color-hue), 50%, 50%); font-family: "Material Icons", sans-serif; font-size: 24px; flex: 0 0 auto; opacity: 0.4; margin-top: -7px; margin-left: -30px; } .framelix-alert[data-icon=""] { min-height: auto; } .framelix-alert[data-icon=""]::before { display: none; } .framelix-button { display: inline-flex; text-decoration: none; padding: 7px 10px; min-height: 30px; min-width: 30px; border-radius: var(--border-radius); margin-bottom: 3px; cursor: pointer; text-align: center; align-items: center; justify-content: center; font-weight: 700; font-size: 1rem; box-sizing: border-box; transition: box-shadow 0.2s; background: var(--color-button-default-bg); color: var(--color-button-default-text); border: none; } .framelix-button:any-link { color: var(--color-button-default-text); } .framelix-button:focus-visible { outline: 2px solid invert; } .framelix-button.framelix-button-primary { background-color: var(--color-button-primary-bg); color: var(--color-button-primary-text); } .framelix-button.framelix-button-primary:any-link { color: var(--color-button-primary-text); } .framelix-button.framelix-button-success { background-color: var(--color-button-success-bg); color: var(--color-button-success-text); } .framelix-button.framelix-button-success:any-link { color: var(--color-button-success-text); } .framelix-button.framelix-button-warning { background-color: var(--color-button-warning-bg); color: var(--color-button-warning-text); } .framelix-button.framelix-button-warning:any-link { color: var(--color-button-warning-text); } .framelix-button.framelix-button-error { background-color: var(--color-button-error-bg); color: var(--color-button-error-text); } .framelix-button.framelix-button-error:any-link { color: var(--color-button-error-text); } .framelix-button.framelix-button-default { background-color: var(--color-button-default-bg); color: var(--color-button-default-text); } .framelix-button.framelix-button-default:any-link { color: var(--color-button-default-text); } .framelix-button.framelix-button-trans { color: inherit; background-color: transparent; } .framelix-button.framelix-button-customcolor { background-color: var(--color-custom-bg); color: var(--color-custom-text); } .framelix-button.framelix-button-trans:hover { box-shadow: rgba(0, 0, 0, 0.2) 2px 4px 13px; } .framelix-button[data-icon-left]::before { font-family: "Material Icons"; font-size: 12px; line-height: 10px; display: block; content: attr(data-icon-left); margin-right: 10px; font-weight: normal; } .framelix-button[data-icon-right]::after { font-family: "Material Icons"; font-size: 12px; line-height: 10px; display: block; content: attr(data-icon-right); margin-left: 10px; font-weight: normal; } .framelix-button:empty::before, .framelix-button:empty::after { margin: 0; } .framelix-button:hover { box-shadow: rgba(255, 255, 255, 0.3) 0 0 999px inset; } .framelix-button:active { box-shadow: rgba(255, 255, 255, 0.4) 0 0 999px inset; } .framelix-button.framelix-button-small { font-size: 0.8rem; padding: 4px 7px; } .framelix-button.framelix-button-block { display: flex; width: 100%; margin-left: 0; margin-right: 0; } :root { --color-primary-hue: 204; --color-success-hue: 160; --color-warning-hue: 28; --color-error-hue: 353; --color-contrast-modifier: 0%; --color-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 50%); --color-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 50%); --color-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 50%); --color-error-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 50%); --color-border-strong: #222; --color-border-subtle: #aaa; --color-page-bg-hue: 0; --color-page-bg: #f5f7fb; --color-page-bg-stencil-weak: white; --color-page-bg-stencil: #eceef5; --color-page-bg-stencil-strong: #d5d5d5; --color-page-text: #111; --color-alert-default-bg: var(--color-page-bg-stencil); --color-alert-default-text: hsl(var(--color-primary-hue), 20%, 5%); --color-alert-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-alert-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-alert-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-alert-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-alert-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 5%); --color-toast-default-bg: hsl(var(--color-primary-hue), 20%, 25%); --color-toast-default-text: white; --color-toast-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-toast-success-text: white; --color-toast-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-toast-warning-text: white; --color-toast-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-toast-error-text: white; --color-toast-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-toast-primary-text: white; --color-button-default-bg: #444; --color-button-default-text: white; --color-button-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-button-success-text: white; --color-button-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-button-warning-text: white; --color-button-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-button-error-text: white; --color-button-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 40%); --color-button-primary-text: white; --color-modal-default-bg: var(--color-page-bg); --color-modal-default-text: var(--color-page-text); --color-modal-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-modal-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-modal-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-modal-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-modal-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 5%); --color-popup-default-bg: black; --color-popup-default-text: white; --color-popup-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-popup-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-popup-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-popup-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 90%); --color-popup-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 5%); --color-input-background: white; --color-input-border: 1px solid #ddd; --color-input-text: var(--color-page-text); --color-input-checkbox-background: var(--color-input-background); --color-input-checkbox-checked: var(--color-button-primary-bg); --color-table-zebra: hsl(var(--color-primary-hue), 20%, 95%); --color-progressbar-1: #f1c40f; --color-progressbar-2: #2c3e50; } :root ::-webkit-scrollbar { width: 15px; } :root ::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.3); border-radius: 100px; } :root ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.1); } [data-color-scheme=dark] { --color-primary-hue: 204; --color-success-hue: 160; --color-warning-hue: 28; --color-error-hue: 353; --color-page-bg-hue: 200; --color-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 70%); --color-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 70%); --color-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 70%); --color-error-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 70%); --color-border-strong: #777; --color-border-subtle: #444; --color-page-bg: #111; --color-page-bg-stencil-weak: #1c1c1c; --color-page-bg-stencil: #222; --color-page-bg-stencil-strong: #2c2c2c; --color-page-text: white; --color-alert-default-bg: var(--color-page-bg-stencil); --color-alert-default-text: white; --color-alert-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-alert-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-alert-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-alert-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-alert-primary-text: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-toast-default-bg: #333; --color-toast-default-text: white; --color-toast-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-toast-success-text: white; --color-toast-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-toast-warning-text: white; --color-toast-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-toast-error-text: white; --color-toast-primary-bg: #333; --color-toast-primary-text: white; --color-button-default-bg: #333; --color-button-default-text: white; --color-button-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 30%); --color-button-success-text: white; --color-button-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 30%); --color-button-warning-text: white; --color-button-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 30%); --color-button-error-text: white; --color-button-primary-bg: hsl(var(--color-primary-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-button-primary-text: white; --color-modal-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-modal-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-modal-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-modal-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-modal-primary-bg: var(--color-page-bg-stencil-weak); --color-modal-primary-text: white; --color-popup-success-bg: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-success-text: hsl(var(--color-success-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-popup-warning-bg: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-warning-text: hsl(var(--color-warning-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-popup-error-bg: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 20%); --color-popup-error-text: hsl(var(--color-error-hue), calc(var(--color-contrast-modifier) + 70%), 80%); --color-popup-primary-bg: var(--color-page-bg-stencil-weak); --color-popup-primary-text: white; --color-input-background: #333; --color-input-text: white; --color-input-border: none; --color-table-zebra: rgba(255, 255, 255, 0.05) ; } [data-color-contrast=less] { --color-contrast-modifier: -40%; } [data-color-contrast=more] { --color-contrast-modifier: 30%; } :root { --border-radius: 3px; } * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } body { background: var(--color-page-bg); color: var(--color-page-text); padding: 0; margin: 0; } body, button, input, select, textarea { font-family: var(--font); font-size: var(--font-size); line-height: var(--line-height); } input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:focus, input:-webkit-autofill:active, input:-webkit-autofill:first-line { -webkit-box-shadow: 0 0 0 30px var(--color-input-background) inset !important; -webkit-text-fill-color: var(--color-input-text) !important; font-family: var(--font) !important; font-size: var(--font-size) !important; line-height: var(--line-height) !important; } a:any-link { color: var(--color-primary-text); } .hidden, datalist { display: none !important; } .framelix-page { transition: 0.1s; } .framelix-blur { filter: blur(10px); pointer-events: none; } .framelix-page-backdrop { opacity: 0.1; pointer-events: none; } .framelix-word-separator { padding: 0 7px; opacity: 0.8; display: inline; } .framelix-word-separator::after { content: "•"; } .framelix-spacer { padding-bottom: 10px; } .framelix-spacer-x2 { padding-bottom: 20px; } .framelix-spacer-x4 { padding-bottom: 40px; } .framelix-modified-timestamp { display: inline-flex; align-items: center; white-space: nowrap; } .framelix-modified-timestamp .material-icons { opacity: 0.4; margin-left: 5px; } .framelix-code-block, .framelix-code-inline { background: var(--color-input-background); display: inline-block; font-family: "Consolas", "Source Code Pro", "Courier New", monospace; font-size: 80%; color: var(--color-input-text); padding: 2px 5px; border: hsl(0deg, 0%, 6%); margin-bottom: 1px; border-radius: var(--border-radius); } .framelix-code-block { display: block; white-space: pre-line; } .framelix-progress { width: 100%; height: 6px; background: rgba(0, 0, 0, 0.2); border-radius: var(--border-radius); overflow: hidden; box-sizing: border-box; opacity: 0; transition: 0.3s; } .framelix-progress[data-type=top] { position: fixed; top: 0; left: 0; width: 100vw; border-radius: 0; z-index: 999; } .framelix-progress:not([data-type=top]) { background: rgba(0, 0, 0, 0.7); padding: 5px; height: 16px; box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.25), 0 1px rgba(255, 255, 255, 0.08); } .framelix-progress.framelix-progress-show { opacity: 1; } .framelix-progress-bar { display: block; height: 100%; overflow: hidden; position: relative; transition: width 0.3s; border-radius: var(--border-radius); } .framelix-progress-bar-inner { display: block; height: 100%; width: calc(100% + 64px); position: absolute; border-radius: var(--border-radius); background-image: repeating-linear-gradient(45deg, var(--color-progressbar-1) 0, var(--color-progressbar-1) 16px, var(--color-progressbar-2) 16px, var(--color-progressbar-2) 32px); animation: framelix-progress-bar 1s linear infinite; } @keyframes framelix-progress-bar { from { left: -46px; } to { left: 0; } } .framelix-loading { display: inline-block; width: 30px; height: 16px; line-height: 0; user-select: none; overflow: hidden; position: relative; transition: width 0.3s; border-radius: var(--border-radius); margin-right: 10px; vertical-align: middle; } .framelix-loading::after { content: ""; display: block; height: 100%; width: calc(100% + 64px); position: absolute; border-radius: var(--border-radius); background-image: repeating-linear-gradient(45deg, var(--color-progressbar-1) 0, var(--color-progressbar-1) 16px, var(--color-progressbar-2) 16px, var(--color-progressbar-2) 32px); animation: framelix-progress-bar 1s linear infinite; } .framelix-pulse { animation: framelix-pulse 1s linear infinite; } @keyframes framelix-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } } .framelix-rotate { animation: framelix-rotate 1s linear infinite forwards; } @keyframes framelix-rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } html.dragging [title], html.dragging [data-tooltip] { pointer-events: none; } .framelix-responsive-grid-2 { display: flex; } .framelix-responsive-grid-2 > * { flex-basis: 50%; margin-right: 10px; } .framelix-responsive-grid-2 > *:last-child { margin-right: 0; } .framelix-responsive-grid-2 [data-grid-size="3"] > * { flex-basis: 30%; } .framelix-responsive-grid-3 { display: flex; } .framelix-responsive-grid-3 > * { flex-basis: 33%; margin-right: 10px; } .framelix-responsive-grid-3 > *:last-child { flex-basis: 34%; margin-right: 0; } .framelix-modal-backdrop { position: fixed; left: 0; top: 0; z-index: 50; background: black; width: 100vw; height: 100%; min-width: 100vw; min-height: 100%; opacity: 0; transition: 0.5s; } .framelix-modal-backdrop-visible { opacity: 0.5; } .framelix-modal { pointer-events: auto; z-index: 51; text-align: center; position: fixed; width: 100vw; height: 100%; top: 0; left: 0; display: grid; place-items: center; transition: 0.5s; transform: translateY(200%) perspective(700px) rotateX(-180deg); } .framelix-modal:focus-visible { outline: 0; } .framelix-modal.framelix-modal-visible { transform: translateY(0) perspective(700px) rotateX(0deg); } .framelix-modal .framelix-modal-inner { text-align: left; margin: 40px; background: var(--color-modal-default-bg); color: var(--color-modal-default-text); border-radius: var(--border-radius); box-shadow: rgba(0, 0, 0, 0.2) 2px 4px 13px; position: relative; display: flex; max-width: 85vw; max-height: 90vh; width: 85vw; } .framelix-modal .framelix-modal-inner.framelix-modal-inner-primary { background-color: var(--color-modal-primary-bg); color: var(--color-modal-primary-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-primary:any-link { color: var(--color-modal-primary-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-success { background-color: var(--color-modal-success-bg); color: var(--color-modal-success-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-success:any-link { color: var(--color-modal-success-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-warning { background-color: var(--color-modal-warning-bg); color: var(--color-modal-warning-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-warning:any-link { color: var(--color-modal-warning-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-error { background-color: var(--color-modal-error-bg); color: var(--color-modal-error-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-error:any-link { color: var(--color-modal-error-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-default { background-color: var(--color-modal-default-bg); color: var(--color-modal-default-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-default:any-link { color: var(--color-modal-default-text); } .framelix-modal .framelix-modal-inner.framelix-modal-inner-trans { color: inherit; background-color: transparent; } .framelix-modal .framelix-modal-inner.framelix-modal-inner-customcolor { background-color: var(--color-custom-bg); color: var(--color-custom-text); } .framelix-modal .framelix-modal-content { min-width: 20px; min-height: 20px; box-sizing: border-box; padding: 20px; display: flex; flex-direction: column; gap: 10px; width: 100%; } .framelix-modal .framelix-modal-content-maximized { width: 94vw; height: 90vh; } .framelix-modal .framelix-modal-header { font-weight: bold; text-align: center; } .framelix-modal .framelix-modal-body { flex: 1 1 auto; overflow: auto; padding: 5px; } .framelix-modal .framelix-modal-footer { text-align: center; display: flex; justify-content: center; gap: 5px; } .framelix-modal .framelix-modal-footer .framelix-button { flex: 1 1 auto; } .framelix-modal .framelix-modal-close { position: absolute; top: -20px; right: -20px; } .framelix-modal .framelix-modal-close button { padding: 15px 8px; } .framelix-modal .framelix-modal-close button::before { font-size: 24px; } .framelix-popup { border-radius: var(--border-radius); font-size: 0.9rem; z-index: 61; background: var(--color-popup-default-bg); color: var(--color-popup-default-text); box-shadow: rgba(0, 0, 0, 0.6) 0 0 10px; --arrow-color: var(--color-popup-default-bg); --arrow-size: 7px; } .framelix-popup.framelix-popup-primary { background-color: var(--color-popup-primary-bg); color: var(--color-popup-primary-text); } .framelix-popup.framelix-popup-primary:any-link { color: var(--color-popup-primary-text); } .framelix-popup.framelix-popup-success { background-color: var(--color-popup-success-bg); color: var(--color-popup-success-text); } .framelix-popup.framelix-popup-success:any-link { color: var(--color-popup-success-text); } .framelix-popup.framelix-popup-warning { background-color: var(--color-popup-warning-bg); color: var(--color-popup-warning-text); } .framelix-popup.framelix-popup-warning:any-link { color: var(--color-popup-warning-text); } .framelix-popup.framelix-popup-error { background-color: var(--color-popup-error-bg); color: var(--color-popup-error-text); } .framelix-popup.framelix-popup-error:any-link { color: var(--color-popup-error-text); } .framelix-popup.framelix-popup-default { background-color: var(--color-popup-default-bg); color: var(--color-popup-default-text); } .framelix-popup.framelix-popup-default:any-link { color: var(--color-popup-default-text); } .framelix-popup.framelix-popup-trans { color: inherit; background-color: transparent; } .framelix-popup.framelix-popup-customcolor { background-color: var(--color-custom-bg); color: var(--color-custom-text); } .framelix-popup .framelix-popup-inner { overflow: auto; max-width: calc(100vw - 50px); max-height: calc(100vh - 50px); } .framelix-popup > [data-popper-arrow] { opacity: 0; } .framelix-popup[data-show-arrow="1"] > [data-popper-arrow] { opacity: 1; transition: 0.2s; } .framelix-popup[data-popper-placement^=top] > [data-popper-arrow] { border-left: var(--arrow-size) solid transparent; border-right: var(--arrow-size) solid transparent; border-top: var(--arrow-size) solid var(--arrow-color); bottom: calc(var(--arrow-size) * -1); } .framelix-popup[data-popper-placement^=bottom] > [data-popper-arrow] { border-left: var(--arrow-size) solid transparent; border-right: var(--arrow-size) solid transparent; border-bottom: var(--arrow-size) solid var(--arrow-color); top: calc(var(--arrow-size) * -1); } .framelix-popup[data-popper-placement^=right] > [data-popper-arrow] { border-top: var(--arrow-size) solid transparent; border-bottom: var(--arrow-size) solid transparent; border-right: var(--arrow-size) solid var(--arrow-color); left: calc(var(--arrow-size) * -1); } .framelix-popup[data-popper-placement^=left] > [data-popper-arrow] { border-top: var(--arrow-size) solid transparent; border-bottom: var(--arrow-size) solid transparent; border-left: var(--arrow-size) solid var(--arrow-color); right: calc(var(--arrow-size) * -1); } .framelix-popup.framelix-popup-primary { --arrow-color: var(--color-popup-primary-bg); } .framelix-popup.framelix-popup-success { --arrow-color: var(--color-popup-succes-bg); } .framelix-popup.framelix-popup-warning { --arrow-color: var(--color-popup-warning-bg); } .framelix-popup.framelix-popup-error { --arrow-color: var(--color-popup-error-bg); } .framelix-popup.framelix-popup-trans { --arrow-color: transparent; } .framelix-quick-search .framelix-quick-search-options .framelix-form { padding: 0; box-shadow: none; } .framelix-quick-search .framelix-quick-search-options .framelix-form-submit-status { display: none; } .framelix-quick-search .framelix-quick-search-input { display: flex; padding: 5px; background: var(--color-button-primary-bg); color: var(--color-button-primary-text); border-top-left-radius: var(--border-radius); border-top-right-radius: var(--border-radius); } .framelix-quick-search .framelix-quick-search-input .material-icons { align-self: center; margin: 0 10px; } .framelix-quick-search .framelix-quick-search-input button { margin: 0; box-shadow: none; padding: 0 10px; } .framelix-quick-search .framelix-quick-search-input button:hover { background: rgba(0, 0, 0, 0.1); } .framelix-quick-search .framelix-quick-search-input button:before { font-size: 20px; } .framelix-quick-search .framelix-quick-search-input .framelix-quick-search-input-editable { font-size: 110%; font-weight: bold; flex: 1 1 auto; padding: 5px 5px 5px 10px; overflow: hidden; display: flex; } .framelix-quick-search .framelix-quick-search-input .framelix-quick-search-input-editable:before { content: "search"; font-family: "Material Icons"; padding-right: 10px; align-self: center; } .framelix-quick-search .framelix-quick-search-input .framelix-quick-search-input-editable[data-placeholder]:empty::before { content: attr(data-placeholder); font-family: var(--font); opacity: 0.6; } .framelix-quick-search .framelix-quick-search-input .framelix-quick-search-input-editable [data-placeholder]:empty:focus::before { content: ""; } .framelix-table > table { padding: 0; width: 100%; margin: 0 0 10px; border-spacing: 1px; height: 1px; border: 1px solid var(--color-border-subtle); border-radius: var(--border-radius); } .framelix-table > table > tbody > tr > *[data-flag-smallwidth="1"], .framelix-table > table > thead > tr > *[data-flag-smallwidth="1"], .framelix-table > table > tfoot > tr > *[data-flag-smallwidth="1"] { white-space: nowrap; width: 1%; } .framelix-table > table > tbody > tr > *[data-flag-smallfont="1"], .framelix-table > table > thead > tr > *[data-flag-smallfont="1"], .framelix-table > table > tfoot > tr > *[data-flag-smallfont="1"] { font-size: 80%; } .framelix-table > table > tbody > tr > *[data-flag-icon="1"], .framelix-table > table > thead > tr > *[data-flag-icon="1"], .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] { white-space: nowrap; width: 1%; min-width: 30px; vertical-align: middle; padding: 0; height: 100%; } html[data-touch="1"] .framelix-table > table > tbody > tr > *[data-flag-icon="1"], html[data-touch="1"] .framelix-table > table > thead > tr > *[data-flag-icon="1"], html[data-touch="1"] .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] { min-height: 30px; } .framelix-table > table > tbody > tr > *[data-flag-icon="1"] .framelix-button, .framelix-table > table > thead > tr > *[data-flag-icon="1"] .framelix-button, .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] .framelix-button { border-radius: 0; border: 0; margin: 0; box-sizing: border-box; height: 100%; width: 100%; padding: 2px 4px; display: flex; align-items: center; justify-content: center; user-select: none; text-align: center; opacity: 0.8; } .framelix-table > table > tbody > tr > *[data-flag-icon="1"] .framelix-button:hover, .framelix-table > table > thead > tr > *[data-flag-icon="1"] .framelix-button:hover, .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] .framelix-button:hover { opacity: 1; } .framelix-table > table > tbody > tr > *[data-flag-icon="1"] .framelix-button::before, .framelix-table > table > thead > tr > *[data-flag-icon="1"] .framelix-button::before, .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] .framelix-button::before { font-size: 16px; } html[data-touch="1"] .framelix-table > table > tbody > tr > *[data-flag-icon="1"] .framelix-button::before, html[data-touch="1"] .framelix-table > table > thead > tr > *[data-flag-icon="1"] .framelix-button::before, html[data-touch="1"] .framelix-table > table > tfoot > tr > *[data-flag-icon="1"] .framelix-button::before { font-size: 24px; } .framelix-table > table > tbody > tr > td, .framelix-table > table > thead > tr > td, .framelix-table > table > tfoot > tr > td { padding: 2px 8px; } .framelix-table > table > tbody > tr > [data-column-name=_checkbox], .framelix-table > table > thead > tr > [data-column-name=_checkbox], .framelix-table > table > tfoot > tr > [data-column-name=_checkbox] { text-align: center; padding: 0; } .framelix-table > table > tbody > tr > [data-column-name=_checkbox] label, .framelix-table > table > thead > tr > [data-column-name=_checkbox] label, .framelix-table > table > tfoot > tr > [data-column-name=_checkbox] label { padding: 0; width: 100%; display: block; cursor: pointer; } .framelix-table > table > tbody > tr.framelix-table-row-highlight td, .framelix-table > table > thead > tr.framelix-table-row-highlight td, .framelix-table > table > tfoot > tr.framelix-table-row-highlight td { border-top: 1px solid var(--color-primary-text); border-bottom: 1px solid var(--color-primary-text); } .framelix-table > table > tbody > tr:nth-child(even), .framelix-table > table > thead > tr:nth-child(even), .framelix-table > table > tfoot > tr:nth-child(even) { background-color: var(--color-table-zebra); } .framelix-table > table > tbody > tr[data-url] > td:not([data-flag-ignoreurl="1"]), .framelix-table > table > thead > tr[data-url] > td:not([data-flag-ignoreurl="1"]), .framelix-table > table > tfoot > tr[data-url] > td:not([data-flag-ignoreurl="1"]) { cursor: pointer; } .framelix-table > table > thead { position: sticky; top: 0; z-index: 1; } .framelix-table > table > thead th { text-align: left; margin: 0; padding: 8px; vertical-align: bottom; user-select: none; background: var(--color-page-bg-stencil); border-bottom: 3px solid var(--color-border-subtle); } .framelix-table > table > thead th:not([data-flag-ignoresort]) { cursor: pointer; } .framelix-table > table > tbody > tr:hover { outline: 1px solid var(--color-border-strong); } .framelix-table > table > tfoot td { font-weight: bold; border-top: 3px solid var(--color-border-subtle); background: var(--color-page-bg-stencil); } .framelix-table.framelix-table-sortable > table > thead th:not([data-flag-ignoresort]):hover { background-color: rgba(0, 0, 0, 0.1); } .framelix-table .framelix-table-row-deleted { text-decoration: line-through; pointer-events: none; user-select: none; } .framelix-table .framelix-table-row-deleted { text-decoration: line-through; opacity: 0.2; } .framelix-table .framelix-table-cell-header { display: flex; align-items: center; gap: 5px; } .framelix-table [data-flag-ignoresort] .framelix-table-header-sort-info { display: none; } .framelix-table .framelix-table-header-sort-info { height: 18px; display: flex; font-size: 0.6rem; line-height: 1; white-space: nowrap; border-radius: var(--border-radius); min-width: 50px; } .framelix-table .framelix-table-header-sort-info-number { background-color: hsla(var(--color-primary-hue), 50%, 50%, 0.5); border-radius: var(--border-radius); display: flex; padding: 0 5px; align-items: center; color: white; } .framelix-table .framelix-table-header-sort-info-number:empty { display: none; } .framelix-table .framelix-table-header-sort-info-text { display: flex; align-items: center; margin-left: 5px; } .framelix-table .framelix-table-header-sort-info-text:empty { display: none; } .framelix-tabs .framelix-tab-buttons { display: flex; flex-wrap: wrap; padding: 5px; border-radius: var(--border-radius); margin-bottom: 10px; background: var(--color-page-bg-stencil); column-gap: 10px; align-items: center; } .framelix-tabs .framelix-tab-buttons ::before { height: 10px; line-height: 10px; content: "arrow_right"; font-family: "Material Icons", sans-serif; font-size: 24px; opacity: 0.5; transition: transform 0.3s; } .framelix-tabs .framelix-tab-button { margin: 0; font-weight: bold; box-sizing: border-box; background: transparent; border: none; color: var(--color-page-text); padding: 5px 10px; padding-left: 5px; } .framelix-tabs .framelix-tab-button[data-active="1"] { color: var(--color-primary-text); } .framelix-tabs .framelix-tab-button[data-active="1"]::before { transform: rotate(90deg); } .framelix-tabs .framelix-tab-button:hover { box-shadow: rgba(0, 0, 0, 0.1) 0 0 1000px inset; } .framelix-tabs .framelix-tab-content { display: none; } .framelix-tabs .framelix-tab-content[data-active="1"] { display: block; } html[data-screen-size=s] .framelix-tab-button { width: calc(50% - 10px); } .framelix-toast { z-index: 71; position: fixed; bottom: 5px; right: 5px; text-align: center; transform: translateY(200%); transition: 0.3s; } .framelix-toast.framelix-toast-visible { transform: translateY(0); } .framelix-toast .framelix-toast-inner { min-width: 300px; max-width: 700px; margin: 0 auto; text-align: left; display: flex; transition: 0.3s; position: relative; padding: 10px; border-radius: var(--border-radius); align-items: center; background: var(--color-toast-default-bg); color: var(--color-toast-default-text); } .framelix-toast .framelix-toast-inner.framelix-toast-primary { background-color: var(--color-toast-primary-bg); color: var(--color-toast-primary-text); } .framelix-toast .framelix-toast-inner.framelix-toast-primary:any-link { color: var(--color-toast-primary-text); } .framelix-toast .framelix-toast-inner.framelix-toast-success { background-color: var(--color-toast-success-bg); color: var(--color-toast-success-text); } .framelix-toast .framelix-toast-inner.framelix-toast-success:any-link { color: var(--color-toast-success-text); } .framelix-toast .framelix-toast-inner.framelix-toast-warning { background-color: var(--color-toast-warning-bg); color: var(--color-toast-warning-text); } .framelix-toast .framelix-toast-inner.framelix-toast-warning:any-link { color: var(--color-toast-warning-text); } .framelix-toast .framelix-toast-inner.framelix-toast-error { background-color: var(--color-toast-error-bg); color: var(--color-toast-error-text); } .framelix-toast .framelix-toast-inner.framelix-toast-error:any-link { color: var(--color-toast-error-text); } .framelix-toast .framelix-toast-inner.framelix-toast-default { background-color: var(--color-toast-default-bg); color: var(--color-toast-default-text); } .framelix-toast .framelix-toast-inner.framelix-toast-default:any-link { color: var(--color-toast-default-text); } .framelix-toast .framelix-toast-inner.framelix-toast-trans { color: inherit; background-color: transparent; } .framelix-toast .framelix-toast-inner.framelix-toast-customcolor { background-color: var(--color-custom-bg); color: var(--color-custom-text); } .framelix-toast .framelix-toast-counter { display: flex; align-items: center; justify-content: center; opacity: 1; transition: 0.3s; } .framelix-toast[data-count="0"] .framelix-toast-counter { display: none; } .framelix-toast .framelix-toast-count { border-radius: var(--border-radius); background: rgba(0, 0, 0, 0.2); padding: 5px; font-size: 0.7rem; font-weight: bolder; width: 16px; height: 16px; display: block; text-align: center; color: white; } .framelix-toast .framelix-toast-message { max-height: 40vh; overflow: auto; padding-left: 10px; margin-right: 10px; flex: 1 1 auto; } .framelix-toast .framelix-toast-loader { position: absolute; left: 0; bottom: 0; width: 100%; height: 5px; background: rgba(0, 0, 0, 0.2); } @font-face { font-family: "Material Icons"; font-style: normal; font-weight: 400; src: url(../../fonts/MaterialIcons-Regular.woff2) format("woff2"); } .material-icons { font-family: "Material Icons"; font-weight: normal; font-style: normal; line-height: 1; letter-spacing: normal; text-transform: none; display: inline-block; white-space: nowrap; word-wrap: normal; direction: ltr; -webkit-font-feature-settings: "liga"; -webkit-font-smoothing: antialiased; user-select: none; }
32.088871
182
0.686369
6ff899e6e9bfbd771e797954f6bb5c6cab0d40e8
487
swift
Swift
RsyncUI/Model/Utils/Environment.swift
SpuzzSomchai/RsyncUI
7ebc0ef3e413f4afad2078464051923ed7d474b6
[ "MIT" ]
990
2017-03-19T18:28:51.000Z
2022-03-20T21:35:34.000Z
RsyncOSX/Environment.swift
FreddyZeng/RsyncOSX
f83124c60e8f779891584e28c0c6d1ab0ddff300
[ "MIT" ]
116
2017-05-06T05:33:50.000Z
2022-01-22T07:31:44.000Z
RsyncOSX/Environment.swift
FreddyZeng/RsyncOSX
f83124c60e8f779891584e28c0c6d1ab0ddff300
[ "MIT" ]
74
2017-05-16T15:07:00.000Z
2022-03-08T19:35:18.000Z
// // Environment.swift // RsyncOSX // // Created by Thomas Evensen on 02/06/2019. // Copyright © 2019 Thomas Evensen. All rights reserved. // import Foundation struct Environment { var environment: [String: String]? init?() { if let environment = SharedReference.shared.environment { if let environmentvalue = SharedReference.shared.environmentvalue { self.environment = [environment: environmentvalue] } } } }
22.136364
79
0.63655
38c756fa631c02a1b630b8f324233b8e37c728b4
1,431
php
PHP
tests/Toolbar/ViewFactoryTest.php
garfieldius/run-script
7c6457c1416d17ae406927210634f3f803fea973
[ "MIT" ]
1
2021-07-19T13:03:26.000Z
2021-07-19T13:03:26.000Z
tests/Toolbar/ViewFactoryTest.php
garfieldius/run-script
7c6457c1416d17ae406927210634f3f803fea973
[ "MIT" ]
null
null
null
tests/Toolbar/ViewFactoryTest.php
garfieldius/run-script
7c6457c1416d17ae406927210634f3f803fea973
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); /* * (c) 2021 Georg Großberger <contact@grossberger-ge.org> * * This file is free software; you can redistribute it and/or * modify it under the terms of the MIT license * * For the full copyright and license information see the file * LICENSE or <https://opensource.org/licenses/MIT> */ namespace GrossbergerGeorg\RunScript\Tests\Toolbar; use GrossbergerGeorg\RunScript\Toolbar\ViewFactory; use PHPUnit\Framework\TestCase; use TYPO3\CMS\Core\Utility\GeneralUtility; use TYPO3\CMS\Extbase\Mvc\Request; use TYPO3\CMS\Fluid\View\StandaloneView; class ViewFactoryTest extends TestCase { public function testCreateView() { $template = 'Tmpl'; $basedir = '/my/root/path/'; $request = $this->createMock(Request::class); $request->expects(static::once())->method('setControllerExtensionName')->with(self::equalTo('RunScript')); $view = $this->createMock(StandaloneView::class); $view->expects(static::once())->method('setTemplateRootPaths')->with(static::equalTo([$basedir . 'Templates/'])); $view->expects(static::once())->method('setTemplate')->with(static::equalTo($template)); $view->expects(static::once())->method('getRequest')->willReturn($request); GeneralUtility::addInstance(StandaloneView::class, $view); $subject = new ViewFactory($basedir); $subject->createView($template); } }
33.27907
121
0.694619
4ee73589f72d711360c5f26466ff188ef04625ea
6,495
asm
Assembly
Transynther/x86/_processed/NONE/_st_/i7-7700_9_0x48.log_21829_2890.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_st_/i7-7700_9_0x48.log_21829_2890.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_st_/i7-7700_9_0x48.log_21829_2890.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x9e36, %rsi lea addresses_WT_ht+0x1053c, %rdi clflush (%rsi) clflush (%rdi) and $3020, %rbx mov $21, %rcx rep movsq nop nop nop nop nop xor %r10, %r10 lea addresses_WT_ht+0x141de, %r9 nop nop nop cmp %r14, %r14 movl $0x61626364, (%r9) nop nop nop nop add $5151, %r10 lea addresses_D_ht+0x1b6fe, %rdi nop sub %r10, %r10 movl $0x61626364, (%rdi) nop nop nop nop nop inc %r14 lea addresses_WT_ht+0xa702, %rbx nop nop inc %r10 mov $0x6162636465666768, %rdi movq %rdi, %xmm1 vmovups %ymm1, (%rbx) nop nop xor $52154, %r10 lea addresses_WT_ht+0x11676, %rsi lea addresses_D_ht+0xc582, %rdi nop nop nop nop add $33072, %r11 mov $51, %rcx rep movsb nop nop nop nop nop dec %rdi lea addresses_A_ht+0x34db, %r10 nop nop dec %r9 mov (%r10), %cx cmp %rdi, %rdi lea addresses_A_ht+0x1b702, %rsi lea addresses_D_ht+0xed82, %rdi nop nop nop nop inc %r9 mov $25, %rcx rep movsq nop nop nop sub %r9, %r9 lea addresses_D_ht+0x1a742, %r14 nop nop nop nop add $55070, %rcx mov (%r14), %di nop nop nop nop inc %r11 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r8 push %rbp push %rcx push %rdi push %rsi // Store lea addresses_WC+0xb582, %rsi nop nop and $56533, %r11 mov $0x5152535455565758, %r10 movq %r10, %xmm0 vmovups %ymm0, (%rsi) nop nop nop and %r11, %r11 // Store mov $0x45fb76000000012a, %rdi sub %rcx, %rcx mov $0x5152535455565758, %r11 movq %r11, %xmm0 movups %xmm0, (%rdi) nop nop nop and %rcx, %rcx // Faulty Load lea addresses_A+0x5582, %rbp add $54420, %r10 mov (%rbp), %si lea oracles, %r11 and $0xff, %rsi shlq $12, %rsi mov (%r11,%rsi,1), %rsi pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 3, 'size': 16, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 1, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 5, 'size': 2, 'same': False, 'NT': False}} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
35.686813
2,999
0.658199
b33be3d81c428aa1780bf8e92dc9c2b133c3b923
3,681
py
Python
run_wallet.py
STR-Coding-Club/RobCoin
a47e232fdea193bea0c2c634f4c6fbf7d4806e0b
[ "MIT" ]
3
2021-05-27T23:00:58.000Z
2021-06-04T20:20:00.000Z
run_wallet.py
Ti1mmy/RobCoin
a47e232fdea193bea0c2c634f4c6fbf7d4806e0b
[ "MIT" ]
3
2021-05-20T19:31:35.000Z
2021-07-20T23:24:56.000Z
run_wallet.py
Ti1mmy/RobCoin
a47e232fdea193bea0c2c634f4c6fbf7d4806e0b
[ "MIT" ]
4
2021-05-27T23:01:13.000Z
2021-06-13T01:25:17.000Z
""" MIT License Copyright (c) 2021 STR-Coding-Club Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import wallet from os import path from print_welcome import print_welcome print_welcome() print('Looking for Private Key...') print() if path.exists("private_key.pem"): print("Private key detected!") print(f'Your Receiving Address: {wallet.get_address()}') # If private key is not detected else: print("No private key detected, creating private key now...") wallet.generate_key() print("Private key has been saved as \' private_key.pem \' DO NOT share this key with anyone") if path.exists("miner_address.txt"): print("Miner address detected!") else: print("No Miner address detected, generating one now...") wallet.save_address() def command_error(): print("Command error, listing available commands") print() print('\t> send <receiver> <amount>') print() print('\t> balance [optional: address]') print() print('\t> address') print() print() print('Wallet initialized!') print() while True: try: command = input('> ').split() except IndexError: command_error() try: if command[0].lower() == 'send': if len(command) == 3: receiver = command[1] amount = command[2] sent = wallet.send(receiver, amount, wallet.read_key()) if sent: print(f"Sent {amount} to {receiver}") print(f"Your current balance is: {wallet.get_balance()[0]} (Pending: {wallet.get_balance()[1]})") else: print("Command error, check if you have enough balance. Please refer to the documentation.") print("Link to docs") else: print("Command Error:") print("\tUsage: `send <receiver> <amount>`") elif command[0].lower() == 'balance': if len(command) == 1: print(f"Your current balance is: {wallet.get_balance()[0]} (Pending: {wallet.get_balance()[1]})") elif len(command) == 2: balance = wallet.get_balance(command[1])[0] if balance: print(f'Balance for input address: {balance}') else: print(f'Error: Invalid Address (Does not exist on blockchain)') elif command[0].lower() == 'address': print(f'Your Receiving Address is: {wallet.get_address()}') else: command_error() except IndexError: command_error() except Exception: print('Networking Error - Make sure you are connected to the internet/check your DNS')
36.445545
117
0.644933