text
stringlengths
27
775k
require 'date' require 'json' require 'time' require 'mixpanel-ruby/consumer' require 'mixpanel-ruby/error' module Mixpanel # Handles formatting Mixpanel group updates and # sending them to the consumer. You will rarely need # to instantiate this class directly- to send # group updates, use Mixpanel::Tracker#groups # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # tracker.groups.set(...) or .set_once(..), or .delete(...) etc. class Groups # You likely won't need to instantiate instances of Mixpanel::Groups # directly. The best way to get an instance of Mixpanel::Groups is # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # tracker.groups # An instance of Mixpanel::Groups # def initialize(token, error_handler=nil, &block) @token = token @error_handler = error_handler || ErrorHandler.new if block @sink = block else consumer = Consumer.new @sink = consumer.method(:send!) end end # Sets properties on a group record. Takes a Hash with string # keys, and values that are strings, numbers, booleans, or # DateTimes # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # # Sets properties on group with id "1234" # tracker.groups.set("GROUP KEY", "1234", { # 'company' => 'Acme', # 'plan' => 'Premium', # 'Sign-Up Date' => DateTime.now # }); # # If you provide an ip argument, \Mixpanel will use that # ip address for geolocation (rather than the ip of your server) def set(group_key, group_id, properties, ip=nil, optional_params={}) properties = fix_property_dates(properties) message = { '$group_key' => group_key, '$group_id' => group_id, '$set' => properties, }.merge(optional_params) message['$ip'] = ip if ip update(message) end # set_once works just like #set, but will only change the # value of properties if they are not already present # in the group. That means you can call set_once many times # without changing an original value. # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # tracker.groups.set_once("GROUP KEY", "1234", { # 'First Login Date': DateTime.now # }); # def set_once(group_key, group_id, properties, ip=nil, optional_params={}) properties = fix_property_dates(properties) message = { '$group_key' => group_key, '$group_id' => group_id, '$set_once' => properties, }.merge(optional_params) message['$ip'] = ip if ip update(message) end # Removes a specific value in a list property # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # # # removes "socks" from the "Items purchased" list property # # for the specified group # tracker.groups.remove("GROUP KEY", "1234", { 'Items purchased' => 'socks' }) # def remove(group_key, group_id, properties, ip=nil, optional_params={}) properties = fix_property_dates(properties) message = { '$group_key' => group_key, '$group_id' => group_id, '$remove' => properties, }.merge(optional_params) message['$ip'] = ip if ip update(message) end # Set union on list valued properties. # Associates a list containing all elements of a given list, # and all elements currently in a list associated with the given # property. After a union, every element in the list associated # with a property will be unique. # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # tracker.groups.union("GROUP KEY", "1234", { # 'Levels Completed' => ['Suffragette City'] # }); # def union(group_key, group_id, properties, ip=nil, optional_params={}) properties = fix_property_dates(properties) message = { '$group_key' => group_key, '$group_id' => group_id, '$union' => properties, }.merge(optional_params) message['$ip'] = ip if ip update(message) end # Removes properties and their values from a group. # # tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN) # # # removes a single property and its value from a group # tracker.groups.unset("GROUP KEY", "1234", "Overdue Since") # # # removes multiple properties and their values from a group # tracker.groups.unset("GROUP KEY", # "1234", # ["Overdue Since", "Paid Date"]) # def unset(group_key, group_id, properties, ip=nil, optional_params={}) properties = [properties] unless properties.is_a?(Array) message = { '$group_key' => group_key, '$group_id' => group_id, '$unset' => properties, }.merge(optional_params) message['$ip'] = ip if ip update(message) end # Permanently delete a group from \Mixpanel groups analytics (all group # properties on events stay) def delete_group(group_key, group_id, optional_params={}) update({ '$group_key' => group_key, '$group_id' => group_id, '$delete' => '', }.merge(optional_params)) end # Send a generic update to \Mixpanel groups analytics. # Caller is responsible for formatting the update message, as # documented in the \Mixpanel HTTP specification, and passing # the message as a dict to #update. This # method might be useful if you want to use very new # or experimental features of groups analytics from Ruby # The \Mixpanel HTTP tracking API is documented at # https://mixpanel.com/help/reference/http def update(message) data = { '$token' => @token, '$time' => ((Time.now.to_f) * 1000.0).to_i, }.merge(message) message = {'data' => data} ret = true begin @sink.call(:group_update, message.to_json) rescue MixpanelError => e @error_handler.handle(e) ret = false end ret end private def fix_property_dates(properties) properties.inject({}) do |ret, (key, value)| value = value.respond_to?(:new_offset) ? value.new_offset('0') : value value = value.respond_to?(:utc) ? value.utc : value # Handle ActiveSupport::TimeWithZone ret[key] = value.respond_to?(:strftime) ? value.strftime('%Y-%m-%dT%H:%M:%S') : value ret end end end end
package heap //HeapSort sorts a given integer array in ascending order func HeapSort(array []int) { /* * We will first build the heap * Then one by one we will swaps the root and last element */ //Building the heap buildHeap(array) //swaping the root and last element for length := len(array); length > 1; length-- { swapRoot(array, length) } } //buildHeap builds the heap structure of an integer array func buildHeap(array []int) { /* * We will run heapify for the entire array */ for i := len(array) / 2; i >= 0; i-- { heapify(array, i, len(array)) } } //swapRoot swaps the root and last element of the given array followed by a heapify from root element func swapRoot(array []int, length int) { /* * We will first swap the first and the last elements * Then runa heapify */ //Swapping the root and the last element var lastIndex = length - 1 array[0], array[lastIndex] = array[lastIndex], array[0] //Running a heapify after the element swaps heapify(array, 0, lastIndex) } //heapify heapifies an integer array func heapify(array []int, root, length int) { /* * First we will check whether the parent element is greater than the children * If not we will swap the parent and child node and run a heapify on the same */ //Checking if the root element is greater than its child nodes var max = root var l, r = (root * 2) + 1, (root * 2) + 2 if l < length && array[l] > array[max] { max = l } if r < length && array[r] > array[max] { max = r } if max != root { //If not swap between the root and the child nodes array[root], array[max] = array[max], array[root] heapify(array, max, length) } }
UNIT UGetFile; INTERFACE Uses Graph, Crt, MyMouse, Button, Rolls, Boxs, TextBoxs, RollBoxs, Objects, Labels, Config, SysUtils; TYPE PGetFile = ^OGetFile; OGetFile = Object (OBox) FileName : Str12; RollFile : ORollBox; btclick : TypeButtons; Title : String; btOk : OButton; btCancel : OButton; Constructor Init(ix, iy, h : Integer; tit, T : String; M : PMouse); Procedure Run; Virtual; Procedure Show; Virtual; Procedure Draw; Virtual; Destructor Done; End; IMPLEMENTATION Constructor OGetFile.Init(ix, iy, h : Integer; tit, T : String; M : PMouse); Var i : Integer; DirInfo : TSearchRec; Begin btclick := NONE; Title := tit; OBox.Init(ix, iy, 27+(20*8), 65+(h*15), True, Title, True, M); RollFile.Init(x+5, y+20, 19, h, T, M); if (FindFirst(T, faAnyFile, DirInfo) = 0) Then Begin Repeat RollFile.Add(DirInfo.Name); until FindNext(DirInfo) <> 0; FindClose(DirInfo); End; i := (Width-140) Div 3; btOk.Init (x+i, y+Height-20, 70, 15, 'Confirma', M); btCancel.Init(x+(i*2)+70, y+Height-20, 70, 15, 'Cancela', M); OBox.Draw; RollFile.Draw; btOk.Draw; btCancel.Draw; End; Procedure OGetFile.Run; Begin Repeat OBox.Run; RollFile.Run; btOk.Run; btCancel.Run; ScreenShow; If (RollFile.Selected) Then Begin FileName := RollFile.TextSelect; RollFile.Text := FileName; RollFile.Draw; End; If (btOk.Selected) Then btClick := OK; If (btCancel.Selected) Then btClick := CANCEL; Until (btClick <> NONE); End; Procedure OGetFile.Show; Begin OBox.Show; End; Procedure OGetFile.Draw; Begin OBox.Draw; End; Destructor OGetFile.Done; Begin btCancel.Done; btOk.Done; RollFile.Done; OBox.Done; End; End.
#!/bin/bash set -e cd src/Magick.Native ./create-nuget-config.sh $1 $2 ./install.sh macos
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect, ReactReduxContext } from 'react-redux'; import reduce from 'lodash/reduce'; import { Label } from 'semantic-ui-react'; import { filtersTransformer } from '../../../filters'; import { actions as filterActions, selectors as filterSelectors } from '../../../redux/modules/filters'; import { EMPTY_ARRAY } from '../../../helpers/consts'; import FilterTag from './FilterTag'; class FilterTags extends Component { static propTypes = { namespace: PropTypes.string.isRequired, tags: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string.isRequired, value: PropTypes.any })), removeFilterValue: PropTypes.func.isRequired, editExistingFilter: PropTypes.func.isRequired, changeFilterFromTag: PropTypes.func.isRequired, }; static defaultProps = { tags: EMPTY_ARRAY, }; static contextType = ReactReduxContext; renderTag = (tag) => { const { namespace } = this.props; const { name, value, index, isActive } = tag; const icon = filtersTransformer.getTagIcon(name); const label = filtersTransformer.valueToTagLabel(name, value, this.props, this.context.store); return ( <FilterTag key={`${name}_${index}`} icon={icon} isActive={isActive} label={label} onClick={() => { this.props.changeFilterFromTag(); this.props.editExistingFilter(namespace, name, index); }} onClose={() => { this.props.removeFilterValue(namespace, name, value); this.props.changeFilterFromTag(); }} /> ); }; render() { const { tags } = this.props; if (tags.length === 0) { return null; } return ( <div> <span>Active Filters:</span>&nbsp;&nbsp; <Label.Group style={{ display: 'inline-block' }}> { tags.map(this.renderTag) } </Label.Group> </div> ); } } export default connect( (state, ownProps) => { // TODO (yaniv): use reselect to cache selector const filters = filterSelectors.getFilters(state.filters, ownProps.namespace); const activeFilter = filterSelectors.getActiveFilter(state.filters, ownProps.namespace); const tags = reduce(filters, (acc, filter) => { const values = filter.values || []; return acc.concat(values.map((value, index) => { const activeValueIndex = filterSelectors.getActiveValueIndex(state.filters, ownProps.namespace, filter.name); return ({ name: filter.name, index, value, isActive: activeFilter === filter.name && activeValueIndex === index }); })); }, []); return { tags }; }, filterActions )(FilterTags);
// The MIT License (MIT) // Copyright (c) 2015 Ben Abelshausen // 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. using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using Reminiscence.Indexes; using Reminiscence.IO; namespace Reminiscence.Tests.Indexes { /// <summary> /// Contains tests for the index. /// </summary> public class IndexTests { /// <summary> /// Tests an index with just one element. /// </summary> [Test] public void TestOneElement() { using(var map = new MemoryMapStream()) { var index = new Index<string>(map); var id = index.Add("Ben"); Assert.AreEqual("Ben", index.Get(id)); } } /// <summary> /// Tests and index with tiny accessors. /// </summary> [Test] public void TestTinyAccessors() { using(var map = new MemoryMapStream()) { using(var tempStream = new MemoryStream(new byte[1024])) { var index = new Index<string>(map, 32); var element = "Ben"; var id1 = index.Add(element); Assert.AreEqual(0, id1); var id2Ref = MemoryMapDelegates.WriteToString(tempStream, id1, ref element); element = "Abelshausen"; var id2 = index.Add(element); Assert.AreEqual(id2Ref, id2); var id3Ref = MemoryMapDelegates.WriteToString(tempStream, id2, ref element) + id2; element = "is"; var id3 = index.Add(element); Assert.AreEqual(id3Ref, id3); var id4Ref = MemoryMapDelegates.WriteToString(tempStream, id3, ref element) + id3; element = "the"; var id4 = index.Add(element); Assert.AreEqual(id4Ref, id4); var id5Ref = MemoryMapDelegates.WriteToString(tempStream, id4, ref element) + id4; element = "author"; var id5 = index.Add(element); Assert.AreEqual(id5Ref, id5); var id6Ref = MemoryMapDelegates.WriteToString(tempStream, id5, ref element) + id5; element = "of"; var id6 = index.Add(element); Assert.AreEqual(id6Ref, id6); var id7Ref = MemoryMapDelegates.WriteToString(tempStream, id6, ref element) + id6; element = "this"; var id7 = index.Add(element); Assert.AreEqual(id7Ref, id7); var id8Ref = MemoryMapDelegates.WriteToString(tempStream, id7, ref element) + id7; element = "library"; var id8 = index.Add(element); Assert.AreEqual(id8Ref, id8); var id9Ref = MemoryMapDelegates.WriteToString(tempStream, id8, ref element) + id8; element = "and"; var id9 = index.Add(element); Assert.AreEqual(id9Ref, id9); var id10Ref = MemoryMapDelegates.WriteToString(tempStream, id9, ref element) + id9; element = "this"; var id10 = index.Add(element); Assert.AreEqual(id10Ref, id10); var id11Ref = MemoryMapDelegates.WriteToString(tempStream, id10, ref element) + id10; element = "test!"; var id11 = index.Add("test!"); Assert.AreEqual(id11Ref, id11); var id12Ref = MemoryMapDelegates.WriteToString(tempStream, id11, ref element) + id11; Assert.AreEqual(id12Ref, index.SizeInBytes); Assert.AreEqual("Ben", index.Get(id1)); Assert.AreEqual("Abelshausen", index.Get(id2)); Assert.AreEqual("is", index.Get(id3)); Assert.AreEqual("the", index.Get(id4)); Assert.AreEqual("author", index.Get(id5)); Assert.AreEqual("of", index.Get(id6)); Assert.AreEqual("this", index.Get(id7)); Assert.AreEqual("library", index.Get(id8)); Assert.AreEqual("and", index.Get(id9)); Assert.AreEqual("this", index.Get(id10)); Assert.AreEqual("test!", index.Get(id11)); } } } /// <summary> /// Tests copying the data to a stream. /// </summary> [Test] public void TestCopyTo() { using(var map = new MemoryMapStream()) { using(var refStream = new MemoryStream(new byte[1024])) { // write to index and to a stream. var index = new Index<string>(map, 32); var element = "Ben"; var id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "Abelshausen"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "is"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "the"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "author"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "of"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "this"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "library"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "and"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "this"; id = index.Add(element); MemoryMapDelegates.WriteToString(refStream, id, ref element); element = "test!"; id = index.Add("test!"); MemoryMapDelegates.WriteToString(refStream, id, ref element); refStream.SetLength(refStream.Position); using(var indexStream = new MemoryStream((int) index.SizeInBytes)) { var refBytes = refStream.ToArray(); Assert.AreEqual(refBytes.Length, index.CopyTo(indexStream)); var bytes = indexStream.ToArray(); Assert.AreEqual(index.SizeInBytes, bytes.Length); Assert.AreEqual(index.SizeInBytes, refBytes.Length); for (var i = 0; i < bytes.Length; i++) { Assert.AreEqual(refBytes[i], bytes[i]); } } using(var indexStream = new MemoryStream((int) index.SizeInBytes + 8)) { var refBytes = refStream.ToArray(); Assert.AreEqual(refBytes.Length + 8, index.CopyToWithSize(indexStream)); var bytes = indexStream.ToArray(); Assert.AreEqual(index.SizeInBytes, bytes.Length - 8); Assert.AreEqual(index.SizeInBytes, refBytes.Length); for (var i = 0; i < refBytes.Length; i++) { Assert.AreEqual(refBytes[i], bytes[i + 8]); } } } } } /// <summary> /// Tests create from. /// </summary> [Test] public void TestCreateFrom() { byte[] data = null; var indexDictionary = new System.Collections.Generic.Dictionary<long, string>(); using(var indexStream = new MemoryStream()) { using(var map = new MemoryMapStream()) { // write to index and to a stream. var index = new Index<string>(map, 32); var element = "Ben"; var id = index.Add(element); indexDictionary[id] = element; element = "Abelshausen"; id = index.Add(element); indexDictionary[id] = element; element = "is"; id = index.Add(element); indexDictionary[id] = element; element = "the"; id = index.Add(element); indexDictionary[id] = element; element = "author"; id = index.Add(element); indexDictionary[id] = element; element = "of"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "library"; id = index.Add(element); indexDictionary[id] = element; element = "and"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "test!"; id = index.Add("test!"); indexDictionary[id] = element; index.CopyToWithSize(indexStream); data = indexStream.ToArray(); } } using(var indexStream = new MemoryStream(data)) { var index = Index<string>.CreateFromWithSize(indexStream); foreach (var refIndexElement in indexDictionary) { var value = index.Get(refIndexElement.Key); Assert.AreEqual(refIndexElement.Value, value); } } using(var indexStream = new MemoryStream(data)) { var index = Index<string>.CreateFromWithSize(indexStream, true); foreach (var refIndexElement in indexDictionary) { var value = index.Get(refIndexElement.Key); Assert.AreEqual(refIndexElement.Value, value); } } } /// <summary> /// Tests create from and copy to in a row. /// </summary> [Test] public void TestCreateFromAndCopyTo() { byte[] data = null; var indexDictionary = new System.Collections.Generic.Dictionary<long, string>(); using(var indexStream = new MemoryStream()) { using(var map = new MemoryMapStream()) { // write to index and to a stream. var index = new Index<string>(map, 32); var element = "Ben"; var id = index.Add(element); indexDictionary[id] = element; element = "Abelshausen"; id = index.Add(element); indexDictionary[id] = element; element = "is"; id = index.Add(element); indexDictionary[id] = element; element = "the"; id = index.Add(element); indexDictionary[id] = element; element = "author"; id = index.Add(element); indexDictionary[id] = element; element = "of"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "library"; id = index.Add(element); indexDictionary[id] = element; element = "and"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "test!"; id = index.Add("test!"); indexDictionary[id] = element; index.CopyToWithSize(indexStream); data = indexStream.ToArray(); } } using(var indexStream = new MemoryStream(data)) { var index = Index<string>.CreateFromWithSize(indexStream); foreach (var refIndexElement in indexDictionary) { var value = index.Get(refIndexElement.Key); Assert.AreEqual(refIndexElement.Value, value); } using(var outputData = new MemoryStream()) { var size = index.CopyToWithSize(outputData); Assert.AreEqual(data.Length, size); } } } /// <summary> /// Tests make writable after deserialization. /// </summary> [Test] public void TestMakeWritable() { byte[] data = null; var indexDictionary = new System.Collections.Generic.Dictionary<long, string>(); // write to index and to a stream. var index = new Index<string>(); var element = "Ben"; var id = index.Add(element); indexDictionary[id] = element; element = "Abelshausen"; id = index.Add(element); indexDictionary[id] = element; element = "is"; id = index.Add(element); indexDictionary[id] = element; element = "the"; id = index.Add(element); indexDictionary[id] = element; element = "author"; id = index.Add(element); indexDictionary[id] = element; element = "of"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "library"; id = index.Add(element); indexDictionary[id] = element; element = "and"; id = index.Add(element); indexDictionary[id] = element; element = "this"; id = index.Add(element); indexDictionary[id] = element; element = "test!"; id = index.Add("test!"); indexDictionary[id] = element; using(var indexStream = new MemoryStream()) { index.CopyToWithSize(indexStream); data = indexStream.ToArray(); } using(var indexStream = new MemoryStream(data)) { index = Index<string>.CreateFromWithSize(indexStream); index.MakeWritable(new MemoryMapStream()); element = "These"; id = index.Add(element); indexDictionary[id] = element; element = "are"; id = index.Add(element); indexDictionary[id] = element; element = "updates"; id = index.Add(element); indexDictionary[id] = element; element = "that"; id = index.Add(element); indexDictionary[id] = element; element = "are"; id = index.Add(element); indexDictionary[id] = element; element = "now"; id = index.Add(element); indexDictionary[id] = element; element = "possible"; id = index.Add(element); indexDictionary[id] = element; foreach (var refIndexElement in indexDictionary) { var value = index.Get(refIndexElement.Key); Assert.AreEqual(refIndexElement.Value, value); } } } /// <summary> /// Tests enumeration. /// </summary> [Test] public void TestEnumerationString() { var index = new Index<string>(new MemoryMapStream(), 32); var id = index.Add("this"); id = index.Add("is"); id = index.Add("another"); id = index.Add("test"); id = index.Add("sentence"); var stringBuilder = new StringBuilder(); foreach (var pair in index) { stringBuilder.Append(pair.Value); } Assert.AreEqual("thisisanothertestsentence", stringBuilder.ToString()); } /// <summary> /// Tests <see cref="Index.Get(long)"/> in parallel /// </summary> [Test] public void TestGetParallel() { var index = new Index<string>(new MemoryMapStream(), 32); List<KeyValuePair<long, string>> ids = new List<KeyValuePair<long, string>>(); ids.Add(new KeyValuePair<long, string>(index.Add("this"), "this")); ids.Add(new KeyValuePair<long, string>(index.Add("is"), "is")); ids.Add(new KeyValuePair<long, string>(index.Add("another"), "another")); ids.Add(new KeyValuePair<long, string>(index.Add("test"), "test")); ids.Add(new KeyValuePair<long, string>(index.Add("sentence"), "sentence")); ParallelEnumerable.ForAll(ids.AsParallel(), kvp => { string found = index.Get(kvp.Key); Assert.AreEqual(found, kvp.Value); }); } /// <summary> /// Tests enumeration. /// </summary> [Test] public void TestEnumerationUInt32Array() { var index = new Index<uint[]>(new MemoryMapStream(), 32); var id = index.Add(new uint[] { 1, 2 }); id = index.Add(new uint[] { 3, 4 }); id = index.Add(new uint[] { 5, 6, 7 }); id = index.Add(new uint[] { 8, 9 }); id = index.Add(new uint[] { 10 }); var list = new List<uint>(); foreach (var pair in index) { foreach (var item in pair.Value) { list.Add(item); } } Assert.AreEqual(new uint[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, list); } /// <summary> /// Tests enumeration. /// </summary> [Test] public void TestEnumerationInt32Array() { var index = new Index<int[]>(new MemoryMapStream(), 32); var id = index.Add(new int[] { 1, 2 }); id = index.Add(new int[] { 3, 4 }); id = index.Add(new int[] { 5, 6, 7 }); id = index.Add(new int[] { 8, 9 }); id = index.Add(new int[] { 10 }); var list = new List<int>(); foreach (var pair in index) { foreach (var item in pair.Value) { list.Add(item); } } Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, list); } /// <summary> /// Tests enumeration. /// </summary> [Test] public void TestEnumerationAfterDeserializationInt32Array() { var index = new Index<int[]>(new MemoryMapStream(), 32); var id = index.Add(new int[] { 1, 2 }); id = index.Add(new int[] { 3, 4 }); id = index.Add(new int[] { 5, 6, 7 }); id = index.Add(new int[] { 8, 9 }); id = index.Add(new int[] { 10 }); using (var stream = new MemoryStream()) { index.CopyToWithSize(stream); stream.Seek(0, SeekOrigin.Begin); index = Index<int[]>.CreateFromWithSize(stream); } var list = new List<int>(); foreach (var pair in index) { foreach (var item in pair.Value) { list.Add(item); } } Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, list); } /// <summary> /// Tests enumeration. /// </summary> [Test] public void TestEnumerationAfterDeserializationEmpty() { var index = new Index<int[]>(new MemoryMapStream(), 32); using (var stream = new MemoryStream()) { index.CopyToWithSize(stream); stream.Seek(0, SeekOrigin.Begin); index = Index<int[]>.CreateFromWithSize(stream); } var enumerator = index.GetEnumerator(); Assert.False(enumerator.MoveNext()); } /// <summary> /// Tests making an empty serialized index writable. /// </summary> [Test] public void TestMakeWritableEmpty() { var index = new Index<int[]>(new MemoryMapStream(), 32); using (var stream = new MemoryStream()) { index.CopyToWithSize(stream); stream.Seek(0, SeekOrigin.Begin); index = Index<int[]>.CreateFromWithSize(stream); } var id = index.Add(new int[] { 10, 100 }); Assert.AreEqual(id, 0); Assert.AreEqual(new int[] { 10, 100 }, index.Get(id)); } } }
-------------------------------------------------------------------------------- -- Copyright © 2011 National Institute of Aerospace / Galois, Inc. -------------------------------------------------------------------------------- -- | Generates a C99 header from a copilot-specification. The functionality -- provided by the header must be implemented by back-ends targetting C99. {-# LANGUAGE Safe #-} {-# LANGUAGE GADTs #-} module Copilot.Compile.Header.C99 ( genC99Header , c99HeaderName ) where import Copilot.Core import Data.List (intersperse, nubBy) import Text.PrettyPrint.HughesPJ import Prelude hiding (unlines) -------------------------------------------------------------------------------- genC99Header :: Maybe String -> FilePath -> Spec -> IO () genC99Header mprefix path spec = let filePath = path ++ "/" ++ prefix ++ "copilot.h" prefix = case mprefix of Just cs -> cs ++ "_" _ -> "" in writeFile filePath (c99Header prefix spec) c99HeaderName :: Maybe String -> String c99HeaderName (Just cs) = cs ++ "_" ++ "copilot.h" c99HeaderName _ = "copilot.h" c99Header :: String -> Spec -> String c99Header prefix spec = render $ vcat $ [ text "/* Generated by Copilot Core." <+> text "*/" , text "" , ppHeaders , text "" , text "/* Observers (defined by Copilot): */" , text "" , ppObservers prefix (specObservers spec) , text "" , text "/* Triggers (must be defined by user): */" , text "" , ppTriggerPrototypes prefix (specTriggers spec) , text "" , text "/* External variables (must be defined by user): */" , text "" , ppExternalVariables (externVars spec) , text "" , text "/* External arrays (must be defined by user): */" , text "" , ppExternalArrays (externArrays spec) , text "" , text "/* External functions (must be defined by user): */" , text "" , ppExternalFunctions (externFuns spec) , text "" , text "/* Step function: */" , text "" , ppStep prefix ] -------------------------------------------------------------------------------- ppHeaders :: Doc ppHeaders = unlines [ "#include <stdint.h>" , "#include <stdbool.h>" ] -------------------------------------------------------------------------------- ppObservers :: String -> [Observer] -> Doc ppObservers prefix = vcat . map ppObserver where ppObserver :: Observer -> Doc ppObserver Observer { observerName = name , observerExprType = t } = text "extern" <+> text (typeSpec (UType t)) <+> text (prefix ++ name) <> text ";" -------------------------------------------------------------------------------- ppTriggerPrototypes :: String -> [Trigger] -> Doc ppTriggerPrototypes prefix = vcat . map ppTriggerPrototype where ppTriggerPrototype :: Trigger -> Doc ppTriggerPrototype Trigger { triggerName = name , triggerArgs = args } = text "void" <+> text (prefix ++ name) <> text "(" <> ppArgs args <> text ");" where ppArgs :: [UExpr] -> Doc ppArgs = hcat . intersperse (text ", ") . map ppArg ppArg :: UExpr -> Doc ppArg UExpr { uExprType = t } = text (typeSpec (UType t)) -------------------------------------------------------------------------------- ppExternalVariables :: [ExtVar] -> Doc ppExternalVariables = vcat . map ppExternalVariable ppExternalVariable :: ExtVar -> Doc ppExternalVariable ExtVar { externVarName = name , externVarType = t } = text "extern" <+> text (typeSpec t) <+> text name <> text ";" -------------------------------------------------------------------------------- ppExternalArrays :: [ExtArray] -> Doc ppExternalArrays = vcat . map ppExternalArray . nubBy eq where eq ExtArray { externArrayName = name1 } ExtArray { externArrayName = name2 } = name1 == name2 ppExternalArray :: ExtArray -> Doc ppExternalArray ExtArray { externArrayName = name , externArrayElemType = t , externArraySize = size } = text "extern" <+> text (typeSpec (UType t)) <+> text name <> lbrack <> int size <> rbrack <> text ";" -------------------------------------------------------------------------------- ppExternalFunctions :: [ExtFun] -> Doc ppExternalFunctions = vcat . map ppExternalFunction . nubBy eq where eq ExtFun { externFunName = name1 } ExtFun { externFunName = name2 } = name1 == name2 ppExternalFunction :: ExtFun -> Doc ppExternalFunction ExtFun { externFunName = name , externFunType = t , externFunArgs = args } = text (typeSpec (UType t)) <+> text name <> text "(" <> ppArgs args <> text ");" where ppArgs :: [UExpr] -> Doc ppArgs = hcat . intersperse (text ",") . map ppArg ppArg :: UExpr -> Doc ppArg UExpr { uExprType = t1 } = text (typeSpec (UType t1)) -------------------------------------------------------------------------------- typeSpec :: UType -> String typeSpec UType { uTypeType = t } = typeSpec' t where typeSpec' Bool = "bool" typeSpec' Int8 = "int8_t" typeSpec' Int16 = "int16_t" typeSpec' Int32 = "int32_t" typeSpec' Int64 = "int64_t" typeSpec' Word8 = "uint8_t" typeSpec' Word16 = "uint16_t" typeSpec' Word32 = "uint32_t" typeSpec' Word64 = "uint64_t" typeSpec' Float = "float" typeSpec' Double = "double" -------------------------------------------------------------------------------- ppStep :: String -> Doc ppStep prefix = text "void" <+> text (prefix ++ "step") <> text "();" -------------------------------------------------------------------------------- unlines :: [String] -> Doc unlines = vcat . map text --------------------------------------------------------------------------------
#!/bin/bash # C sudo apt install tcc sudo apt install gcc-10 sudo apt install clang-10 # C++ sudo apt install g++-10 sudo apt install clangxx-10 # Ada sudo apt install gnat-10 # D `dmd` ./install-dmd.sh # D `gdc` sudo apt install gdc-10 # Go: `gccgo` sudo apt install gccgo-10 # Go: `go` `gotype` sudo add-apt-repository ppa:longsleep/golang-backports sudo apt update sudo apt install golang-go golang-golang-x-tools # Julia sudo apt install julia # C# ./install-mono.sh sudo apt install mono-mcs # Java sudo apt install openjdk-14-jdk
<?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('/', function () use ($app) { return response()->json(['code' => 200,'message' => 'Welcome to osman api']); }); $app->post('/webhook', 'WebhookController@answerChat'); $app->get('/webhook', 'WebhookController@verifyToken'); $app->get('/teschat', 'ChatController@tesChat'); $app->get('/tes/user', 'TesController@tesUser'); $app->get('/tes/obj', 'TesController@obj');
<?php namespace Concrete\Core\Express\Event; use Concrete\Core\Entity\Express\Entry; use Symfony\Component\EventDispatcher\Event as AbstractEvent; class Event extends AbstractEvent { /** * @var Entry */ protected $entry; protected $entityManager; /** * @return mixed */ public function getEntityManager() { return $this->entityManager; } /** * @param mixed $entityManager */ public function setEntityManager($entityManager) { $this->entityManager = $entityManager; } /** * Event constructor. * @param $entry */ public function __construct($entry) { $this->entry = $entry; } /** * @return mixed */ public function getEntry() { return $this->entry; } /** * @param mixed $entry */ public function setEntry($entry) { $this->entry = $entry; } }
// PowerShellFar module for Far Manager // Copyright (c) Roman Kuzmin using FarNet; using System; using System.IO; using System.Management.Automation; namespace PowerShellFar.Commands { [OutputType(typeof(SetFile))] sealed class NewFarFileCommand : BaseCmdlet { #region [ Any parameter set ] [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] public string Description { get; set; } [Parameter] public string Owner { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Parameter] public System.Collections.ICollection Columns { get; set; } [Parameter] public object Data { get; set; } #endregion #region [ Name parameter set ] /// <summary> /// See <see cref="FarFile.Name"/>. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "Name")] [AllowEmptyString] public string Name { get; set; } [Parameter(ParameterSetName = "Name")] public long Length { get; set; } [Parameter(ParameterSetName = "Name")] public DateTime CreationTime { get; set; } [Parameter(ParameterSetName = "Name")] public DateTime LastAccessTime { get; set; } [Parameter(ParameterSetName = "Name")] public DateTime LastWriteTime { get; set; } [Parameter(ParameterSetName = "Name")] public FileAttributes Attributes { get; set; } #endregion #region [ File parameter set ] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "File")] public FileSystemInfo File { get; set; } [Parameter(ParameterSetName = "File")] public SwitchParameter FullName { get; set; } #endregion protected override void ProcessRecord() { // system file if (File != null) { var ff = new SetFile(File, FullName) { Description = Description, Owner = Owner, Columns = Columns }; if (Data == null) ff.Data = File; else ff.Data = Data; WriteObject(ff); return; } // user file WriteObject(new SetFile() { Name = Name, Description = Description, Owner = Owner, Length = Length, CreationTime = CreationTime, LastAccessTime = LastAccessTime, LastWriteTime = LastWriteTime, Attributes = Attributes, Columns = Columns, Data = Data, }); } } }
module QASM export @qasm_str using RBNF using ExprTools using OpenQASM using OpenQASM.Types using OpenQASM.Types: Gate using ..YaoCompiler mutable struct VirtualRegister type::Symbol address::UnitRange{Int} end mutable struct RegisterRecord map::Dict{String,VirtualRegister} nqubits::Int ncbits::Int end mutable struct GateRegisterRecord map::Dict total::Int end Base.getindex(x::RegisterRecord, key) = x.map[key] Base.getindex(x::VirtualRegister, xs...) = x.address[xs...] RegisterRecord() = RegisterRecord(Dict{String,UnitRange{Int}}(), 0, 0) GateRegisterRecord() = GateRegisterRecord(Dict(), 0) struct Ctx m::Module source::LineNumberNode record::Any end # tokens don't need context transpile(::Ctx, x::RBNF.Token) = transpile(x) transpile(x::RBNF.Token{:unnamed}) = Symbol(x.str) transpile(x::RBNF.Token{:reserved}) = Symbol(x.str) function transpile(x::RBNF.Token{:id}) x.str == "pi" && return Base.pi return Symbol(x.str) end function transpile(x::RBNF.Token{:float64}) return Base.parse(Float64, x.str) end function transpile(x::RBNF.Token{:int}) return Base.parse(Int, x.str) end transpile_list(::Ctx, ::Nothing) = Any[] transpile_list(ctx::Ctx, x) = Any[transpile(ctx, x)] function transpile_list(ctx::Ctx, xs::Vector) [transpile(ctx, each) for each in xs] end transpile(m::Module, ast::MainProgram) = transpile(m, LineNumberNode(0), ast) function transpile(m::Module, l::LineNumberNode, ast::MainProgram) # check sure minimum compatibility @assert v"2.0.0" <= ast.version < v"3.0.0" code = Expr(:block) body = Expr(:block) routines = [] record = scan_registers(ast) ctx = Ctx(m, l, record) for stmt in ast.prog if stmt isa RegDecl continue elseif stmt isa Types.Gate push!(routines, transpile(ctx, stmt)) elseif stmt isa Include file = stmt.file.str[2:end-1] # use relative path to current file if not in REPL # isinteractive can be true in IDEs if !isnothing(l.file) && !(isinteractive() && isempty(PROGRAM_FILE)) file = joinpath(dirname(string(l.file)), file) end source = read(file, String) ast = OpenQASM.parse(source) push!(code.args, transpile(m, l, ast)) else ex = transpile(ctx, stmt) if !isnothing(ex) push!(body.args, ex) end end end # if there are classical registers # return them in a NamedTuple ret = Expr(:tuple) for (k, r) in record.map if r.type === :classical name = Symbol(k) push!(ret.args, Expr(:(=), name, name)) end end if !isempty(body.args) if isempty(ret.args) push!(body.args, :(return)) else push!(body.args, :(return $ret)) end end # routines for each in routines push!(code.args, each) end # create an anoymous routine # if there are global statements if !isempty(body.args) def = Dict{Symbol,Any}(:name => gensym(:qasm), :body => body) push!(code.args, YaoCompiler.device_def(def)) end return code end function transpile(ctx::Ctx, stmt::Types.Gate) name = transpile(stmt.decl.name) args = transpile_list(ctx, stmt.decl.cargs) record = transpile_gate_registers(stmt.decl.qargs) body = Expr(:block) new_ctx = Ctx(ctx.m, ctx.source, record) for each in stmt.body push!(body.args, transpile(new_ctx, each)) end def = Dict(:name => name, :args => args, :body => body) return YaoCompiler.device_def(def) end function transpile_gate_registers(stmt::Vector) record = GateRegisterRecord() for each in stmt haskey(record.map, each.str) && throw(Meta.ParseError("duplicated register name $(each.str)")) record.total += 1 record.map[each.str] = record.total end return record end semantic_gate(gate, locs) = Expr(:call, GlobalRef(YaoCompiler.Semantic, :gate), gate, locs) semantic_ctrl(gate, locs, ctrl) = Expr(:call, GlobalRef(YaoCompiler.Semantic, :ctrl), gate, locs, ctrl) function transpile(ctx::Ctx, stmt::UGate) code = Expr(:block) locs = transpile(ctx, stmt.qarg) push!( code.args, semantic_gate(Expr(:call, GlobalRef(Intrinsics, :Rz), transpile(ctx, stmt.z1)), locs), ) push!( code.args, semantic_gate(Expr(:call, GlobalRef(Intrinsics, :Ry), transpile(ctx, stmt.y)), locs), ) push!( code.args, semantic_gate(Expr(:call, GlobalRef(Intrinsics, :Rz), transpile(ctx, stmt.z2)), locs), ) return code end function transpile(ctx::Ctx, stmt::CXGate) return semantic_ctrl( GlobalRef(Intrinsics, :X), transpile(ctx, stmt.qarg), CtrlLocations(transpile(ctx, stmt.ctrl)), ) end function transpile(ctx::Ctx, stmt::IfStmt) return :( if $(transpile(ctx, stmt.left)) == $(transpile(ctx, stmt.right)) $(transpile(ctx, stmt.body)) end ) end function transpile(ctx::Ctx, stmt::Measure) locs = transpile(ctx, stmt.qarg) name = transpile(ctx, stmt.carg) return Expr(:(=), name, Expr(:call, GlobalRef(YaoCompiler.Semantic, :measure), locs)) end function transpile(ctx::Ctx, stmt::Barrier) return Expr( :call, GlobalRef(YaoCompiler.Semantic, :barrier), transpile_locations(ctx, stmt.qargs), ) end function transpile(ctx::Ctx, stmt::Instruction) op = stmt.name # NOTE: these are not intrinsic function in QASM # users need qelib1.inc to get the definition # but for convenience we treat them as intrinsic # function here in YaoCompiler, since they are predefined # as stdlib in YaoCompiler. # isnothing(stmt.lst1) || throw(Meta.ParseError("$op gate should not have classical parameters")) locs = transpile_locations(ctx, stmt.qargs) if op == "x" semantic_gate(Intrinsics.X, locs) elseif op == "y" semantic_gate(Intrinsics.Y, locs) elseif op == "z" semantic_gate(Intrinsics.Z, locs) elseif op == "h" semantic_gate(Intrinsics.H, locs) elseif op == "s" semantic_gate(Intrinsics.S, locs) elseif op == "ccx" semantic_ctrl(Intrinsics.X, locs[3], CtrlLocations(locs[1:2])) else # some user defined routine gate = Expr(:call, GlobalRef(ctx.m, Symbol(op)), transpile_list(ctx, stmt.cargs)...) semantic_gate(gate, locs) end end function transpile(ctx::Ctx, stmt::FnExp) return Expr(:call, stmt.fn, transpile(ctx, stmt.arg)) end function transpile_locations(ctx, stmts::Vector) locs = map(stmts) do stmt transpile(ctx, stmt) end return merge_locations(locs...) end function transpile(ctx::Ctx, stmt::Bit) record = ctx.record if record isa RegisterRecord r = record[stmt.name.str] r.type === :classical && return Symbol(stmt.name.str) if isnothing(stmt.address) return Locations(r[:]) else address = transpile(stmt.address) return Locations(r[address+1]) end else return Locations(record.map[stmt.name.str]) end end transpile(ctx::Ctx, stmt::Negative) = Expr(:call, -, transpile(ctx, stmt.value)) function transpile(ctx::Ctx, stmt::Tuple) length(stmt) == 3 || throw(Meta.ParseError("unrecognized expression: $stmt")) stmt[2]::RBNF.Token if stmt[2].str in ("+", "-", "*", "/") return Expr(:call, Symbol(stmt[2].str), transpile(ctx, stmt[1]), transpile(ctx, stmt[3])) else throw(Meta.ParseError("unrecognized expression: $stmt")) end end function scan_registers(ast::MainProgram) return scan_registers!(RegisterRecord(), ast) end function scan_registers!(record::RegisterRecord, ast::MainProgram) for stmt in ast.prog scan_registers!(record, stmt) end return record end function scan_registers!(record::RegisterRecord, ast::RegDecl) nbits = transpile(ast.size) nqubits = record.nqubits ncbits = record.ncbits if ast.type.str == "qreg" record.map[ast.name.str] = VirtualRegister(:quantum, (nqubits+1):(nqubits+nbits)) record.nqubits += nbits else # classical record.map[ast.name.str] = VirtualRegister(:classical, (ncbits+1):(ncbits+nbits)) record.ncbits += nbits end return record end scan_registers!(record::RegisterRecord, ast) = record function qasm_str_m(m::Module, l::LineNumberNode, source::String) ast = OpenQASM.parse(source) return transpile(m, l, ast) end macro qasm_str(source::String) return esc(qasm_str_m(__module__, __source__, source)) end macro qasm_str(source::Expr) source.head === :string || error("expect a String") args = map(source.args) do x x isa String && return x return Base.eval(__module__, x) end return esc(qasm_str_m(__module__, __source__, join(args))) end macro include_str(path) if path isa Expr path.head === :string || error("expect a String") file = map(path.args) do x x isa String && return x return Base.eval(__module__, x) end |> join elseif path isa String file = path else error("expect a String") end return esc(qasm_str_m(__module__, __source__, read(file, String))) end end # end module
--- author: tim comments: true date: 2011-02-11 18:35:44+00:00 dsq_thread_id: '243134417' layout: post link: '' slug: a-note-on-magento-and-multiple-nodes-using-memcached title: A note on Magento and multiple nodes using Memcached wordpress_id: 831 category: Code tags: - magento - Memcached - php - xml --- If you have multiple nodes using a shared memcached server, make sure you define a shared prefix for the keys to use. In local.xml: ```XML <cache> ... <prefix>a1i</prefix> <id_prefix>a1i</id_prefix> <memcached> ... ```
/* Author - Aykut Asil(@aykuttasil) */ package com.aykuttasil.sweetloc.util import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.location.Location import android.os.Looper import androidx.core.content.ContextCompat import androidx.lifecycle.LiveData import com.google.android.gms.common.api.ApiException import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationCallback import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationResult import com.google.android.gms.location.LocationServices import com.google.android.gms.location.LocationSettingsRequest import com.google.android.gms.location.LocationSettingsStatusCodes /** * Created by Emre Eran on 31.08.2018. */ class LocationLiveData private constructor() : LiveData<Location>() { lateinit var context: Context lateinit var locationRequest: LocationRequest var onErrorCallback: OnErrorCallback? = null private lateinit var locationClient: FusedLocationProviderClient private val locationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult?) { super.onLocationResult(locationResult) locationResult ?: return for (location in locationResult.locations) { postValue(location) } } } @SuppressLint("MissingPermission") override fun onActive() { super.onActive() locationClient = FusedLocationProviderClient(context) // Check permissions if (ContextCompat.checkSelfPermission( context, Manifest.permission.ACCESS_COARSE_LOCATION ) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ) { // Check settings val locationSettingsRequest = LocationSettingsRequest.Builder() .addLocationRequest(locationRequest).build() val settingsClient = LocationServices.getSettingsClient(context) settingsClient.checkLocationSettings(locationSettingsRequest).addOnCompleteListener { try { val locationSettingsResponse = it.getResult(ApiException::class.java) locationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()) } catch (e: ApiException) { onErrorCallback?.onLocationSettingsException(e) } } } else { onErrorCallback?.onPermissionsMissing() } } override fun onInactive() { super.onInactive() locationClient.removeLocationUpdates(locationCallback) } interface OnErrorCallback { /** * Called when location setting check fails * Status codes include: * [LocationSettingsStatusCodes.RESOLUTION_REQUIRED] * [LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE] */ fun onLocationSettingsException(e: ApiException) fun onPermissionsMissing() } companion object { @JvmOverloads @JvmStatic fun create( context: Context, interval: Long? = null, fastestInterval: Long? = null, priority: Int? = null, smallestDisplacement: Float? = null, expirationTime: Long? = null, maxWaitTime: Long? = null, numUpdates: Int? = null, onErrorCallback: OnErrorCallback? = null ): LocationLiveData { val liveData = LocationLiveData() val locationRequest = LocationRequest.create() interval?.let { locationRequest.interval = it } fastestInterval?.let { locationRequest.fastestInterval = it } priority?.let { locationRequest.priority = it } smallestDisplacement?.let { locationRequest.smallestDisplacement = it } expirationTime?.let { locationRequest.expirationTime } maxWaitTime?.let { locationRequest.maxWaitTime = it } numUpdates?.let { locationRequest.numUpdates = it } liveData.context = context liveData.locationRequest = locationRequest liveData.onErrorCallback = onErrorCallback return liveData } } }
name := "bitcoin-s-cli-test" publish / skip := true
#include "stm32f4xx_hal.h" #ifndef NEOPIXEL_HANDLER_H #define NEOPIXEL_HANDLER_H #define NEOPIXEL_DATA_Pin GPIO_PIN_7 #define NEOPIXEL_DATA_Port GPIOB void neoPixel_initLeds(); void neoPixel_turnOffLeds(); void neoPixel_light(int strength); void neoPixel_reverse(); void neoPixel_Welcome(); void neoPixel_WelcomeOff(); void neoPixel_leftArrow(); void neoPixel_leftArrowOff(); void neoPixel_rightArrow(); void neoPixel_rightArrowOff(); void neoPixel_stop(); void neoPixel_turnOnLedsFullWhite(); void neoPixel_reverse() ; void neoPixel_Welcome() ; void neoPixel_WelcomeOff(); void neoPixel_leftArrowTemplate(const uint8_t *color); void neoPixel_rightArrowTemplate(const uint8_t *color) ; void neoPixel_setColor(int ledIdx, const uint8_t *color); void neoPixel_applyColors(); void neoPixel_fadeEffect( uint8_t maxLevel ); void neoPixel_warning(); void headlight_manager(uint8_t*headlight, uint8_t*reverse, uint16_t speed, uint8_t*warning, uint8_t*headlight_state); // >>>>> Color definitions #define OFF 0 #define FULL 255 #define MID 120 #define SOFT 15 static const uint8_t BLACK[] = { OFF, OFF, OFF }; static const uint8_t RED[] = { FULL, OFF, OFF }; static const uint8_t GREEN[] = { OFF, FULL, OFF }; static const uint8_t BLUE[] = { OFF, OFF, FULL }; static const uint8_t ORANGE[] = { FULL, 40, OFF }; static const uint8_t WHITE[] = { FULL, FULL, FULL }; static const uint8_t SOFT_WHITE[] = { SOFT, SOFT, SOFT }; static const uint8_t MID_WHITE[] = { MID, MID, MID }; static const uint8_t MID_RED[] = { MID, OFF, OFF }; static const uint8_t MID_GREEN[] = { OFF, MID, OFF }; static const uint8_t MID_BLUE[] = { OFF, OFF, MID }; static const uint8_t SOFT_RED[] = { SOFT, OFF, OFF }; static const uint8_t SOFT_GREEN[] = { OFF, SOFT, OFF }; static const uint8_t SOFT_BLUE[] = { OFF, OFF, SOFT }; // <<<<< Color definitions #endif
<?php class Signin_controller extends CI_Controller{ function __construct() { parent::__construct(); $this->load->helper('url'); $this->load->library('form_validation'); $this->load->library('session'); $this->load->model('user_model'); } public function index() { $this->load->view('login'); } public function validateAccount(){ $office_id = $this->input->post('office_id'); $password = $this->input->post('inputPassword'); $this->form_validation->set_rules('inputPassword', 'Password', 'trim|required'); if($this->form_validation->run() == FALSE){ $this->load->view('login'); } else{ $data['user_details'] = $this->user_model->validateUser($office_id, $password); if($data['user_details'] == NULL){ $this->load->view('login'); } else{ foreach ($data['user_details'] as $type) { $this->session->set_userdata('user_id', $type->user_id); $this->session->set_userdata('user_type_id', $type->user_type_id); $data['user_type_id'] = $this->session->userdata('user_type_id'); if(($type->user_type_id == 3) || ($type->user_type_id == 2) || ($type->user_type_id == 4)){ $this->load->view('NAV', $data); $this->load->view('USER_HOME', $data); } else{ $this->load->view('ADMIN_Nav', $data); $this->load->view('ADMIN_Home'); } } } } } public function getOfficeNames(){ $office_names = $this->user_model->getOffices(); echo json_encode($office_names); } }
#!/usr/bin/env ruby require "digest/md5" class Miner def initialize(prefix) @prefix = prefix end def find n = 0 begin n += 1 input = @prefix + n.to_s hex = Digest::MD5.hexdigest(input) end until hex =~ /^0{5}/ n end end p Miner.new(File.read("input").chomp).find
package org.jemiahlabs.skrls.view.main.context; import org.jemiahlabs.skrls.core.Channel; import org.jemiahlabs.skrls.core.Message; import org.jemiahlabs.skrls.core.Producer; import org.jemiahlabs.skrls.core.TypeMessage; public class ProducerImpl extends Producer { public ProducerImpl(Channel channel) { super(channel); } @Override public void emitInfoMessage(String text) { getChannel().sendMessage(new Message(text, TypeMessage.INFO)); } @Override public void emitWarningMessage(String text) { getChannel().sendMessage(new Message(text, TypeMessage.WARNNING)); } @Override public void emitErrorMessage(String text) { getChannel().sendMessage(new Message(text, TypeMessage.ERROR)); } }
/** * Created by 郑晓辉 on 2017/3/30. */ var templateUrl = '/questionnaireManage/templateMultiQuestionnaire'; var delTemporaryUrl = '/questionnaireManage/delTemporaryMultiQuestionnaire'; var shareUrl = '/questionnaireManage/shareMultiQuestionnaire'; $(function () { $('#multiShareBtn').click(function () { var questionnaireIds = getMultiQuestionnaireIds(); if (questionnaireIds.length > 0) { layer.confirm('确定批量共享问卷', { icon: 3, btn: ['确定', '取消'] }, function () { accessServerByQesIds(questionnaireIds, shareUrl); }, function () { cancelLayer(); }); } else { chooseNonLayer(); } }); $('#multiDelBtn').click(function () { var questionnaireIds = getMultiQuestionnaireIds(); if (questionnaireIds.length > 0) { layer.confirm('确定批量删除', { icon: 3, btn: ['确定', '取消'] //按钮 }, function () {//确定删除 accessServerByQesIds(questionnaireIds, delTemporaryUrl); }, function () { //取消删除 cancelLayer(); }); } else { chooseNonLayer(); } }); $('#multiTemplateBtn').click(function () { var questionnaireIds = getMultiQuestionnaireIds(); if (questionnaireIds.length > 0) { layer.confirm('确定批量模板化', { icon: 3, btn: ['确定', '取消'] //按钮 }, function () { accessServerByQesIds(questionnaireIds, templateUrl); }, function () { cancelLayer(); }); } else { chooseNonLayer(); } }); }); /** * 删除单张问卷 * @param questionnaireId */ function delQesPaper(questionnaireId) { var questionnaireIds = []; questionnaireIds.push(questionnaireId); accessServerByQesIds(questionnaireIds, delTemporaryUrl); } /** * 分享问卷到公共模板库 * @param questionnaireId */ function shareQesPaper(questionnaireId) { var questionnaireIds = []; questionnaireIds.push(questionnaireId); accessServerByQesIds(questionnaireIds, shareUrl); } /** * 添加到我的模板库 * @param questionnaireId */ function add2TemplateLib(questionnaireId) { var questionnaireIds = []; questionnaireIds.push(questionnaireId); accessServerByQesIds(questionnaireIds, templateUrl); } /** * 获取用户checked的checkbox值 * @returns {Array} */ function getMultiQuestionnaireIds() { var questionnaireIds = []; $('input[name="questionnaireId"]:checked').each(function () { questionnaireIds.push($(this).val()); }); return questionnaireIds; } /** * 取消layer方式提示 */ function cancelLayer() { layer.msg('取消成功', { icon: 7, btn: ['返回'] }); } /** * 未选择layer提示 */ function chooseNonLayer() { layer.alert('你还没有选择', {icon: 5}); } function accessServerById(questionnaire, url) { } /** * 异步加载服务器 * @param questionnaireIds * @param url */ function accessServerByQesIds(questionnaireIds, url) { $.ajax({ url: url, type: 'post', data: {questionnaireIds: questionnaireIds}, dataType: 'text', traditional: true, success: function (data) { analyzeResponse(data, url, questionnaireIds); }, error: function () { layer.alert('操作失败', {icon: 2}); } }); } /** * 解析回复数据包 * @param data * @param url * @param questionnaireIds */ function analyzeResponse(data, url, questionnaireIds) { var responsePkt = JSON.parse(data); if (responsePkt.code === 200) { var successMsg = ''; switch (url) { case delTemporaryUrl://暂时删除问卷 if (responsePkt.code === 200) { successMsg = "成功添加 【" + questionnaireIds.length + "】 张问卷到个人模板库"; successResultLayer(successMsg); location.reload(true); } dealGlobalError(responsePkt); break; case templateUrl: //模板化问卷 if (responsePkt.code === 200) { successMsg = "成功删除 【" + questionnaireIds.length + "】 张问卷,你可以在垃圾站中恢复这些问卷!"; successResultLayer(successMsg); location.reload(true); } dealGlobalError(responsePkt); break; case shareUrl: //分享问卷 if (responsePkt.code === 200) { successMsg = "成功共享 【" + questionnaireIds.length + "】 张问卷到公共模版库"; successResultLayer(successMsg); location.reload(true); } dealGlobalError(responsePkt); break; default: return; } } } function successResultLayer(successMsg) { layer.msg(successMsg, { icon: 1, time: 2000, shade: 0.5, closeBtn: 1 }); }
class PublicationModelGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) argument :model_name, type: :string, default: :article def generate create_model create_controller create_migration print_routing_instruction end private def create_model locals = { model_class_name: model_name.classify } template( 'publication_model.erb', "app/models/#{model_name.downcase}.rb", locals ) end def create_controller locals = { controller_class_name: model_name.classify.pluralize } template( 'publication_controller.erb', "app/controllers/#{model_name.downcase.pluralize}_controller.rb", locals ) end def create_migration ts = Time.now.strftime("%Y%m%d%H%M%S") locals = { migration_class_name: model_name.tableize.classify, migration_table_name: model_name.tableize } template( 'publication_migration.erb', "db/migrate/#{ts}_create_#{model_name.downcase}_publication_model.rb", locals ) end def print_routing_instruction puts " You have to add/remove the following routes".yellow puts """ ::ThePublication::Routes.mixin(self, '#{model_name.to_s.downcase}') """.red end end
use anyhow::{bail, Result}; use prost_types::compiler::{code_generator_response::File, CodeGeneratorResponse}; use protoc_gen_prost::{utils::*, Generator}; fn main() { let res = match gen_files() { Ok(file) => CodeGeneratorResponse { file, ..Default::default() }, Err(e) => CodeGeneratorResponse { error: Some(format!("{e:?}")), ..Default::default() }, }; response_to_env(res).unwrap(); } fn gen_files() -> Result<Vec<File>> { let req = request_from_env()?; let (gen, opts) = Generator::new_from_opts(split_escaped(req.parameter(), ',')); if !opts.is_empty() { bail!("Unknown opts:\n - {}", opts.join("\n - ")); } gen.generate(req.proto_file) }
use std::path::{Path, PathBuf}; use std::io; pub trait ImportResolver { fn resolve(&mut self, import_name: &str) -> Result<ResolvedImport, io::Error>; } pub struct ResolvedImport { pub reader: Box<dyn io::Read>, pub source: String, } impl ResolvedImport { pub fn text(&mut self) -> String { let mut result = String::new(); self.reader.read_to_string(&mut result).unwrap(); result } } pub struct FileImportResolver(PathBuf); impl FileImportResolver { pub fn new<P: AsRef<Path>>(path: P) -> Self { let path = path.as_ref().canonicalize().unwrap(); FileImportResolver(path) } } impl io::Read for ResolvedImport { fn read(&mut self, buf: &mut[u8]) -> io::Result<usize> { self.reader.read(buf) } } impl ImportResolver for FileImportResolver { fn resolve(&mut self, import_name: &str) -> Result<ResolvedImport, io::Error> { let FileImportResolver(base_dir) = self; let filename = format!("{}.ql", import_name); let filepath = base_dir.join(&filename).to_owned(); let module_text = std::fs::read_to_string(&filepath)?; Ok(ResolvedImport { reader: Box::new(io::Cursor::new(module_text)), source: filename, }) } } pub struct FilePathImportResolver; impl ImportResolver for FilePathImportResolver { fn resolve(&mut self, filepath: &str) -> Result<ResolvedImport, io::Error> { let module_text = std::fs::read_to_string(&filepath)?; Ok(ResolvedImport { reader: Box::new(io::Cursor::new(module_text)), source: filepath.to_owned(), }) } } pub struct ChainedImportResolver(Box<dyn ImportResolver>, Box<dyn ImportResolver>); impl ChainedImportResolver { pub fn new(a: Box<dyn ImportResolver>, b: Box<dyn ImportResolver>) -> Self { ChainedImportResolver(a, b) } } impl ImportResolver for ChainedImportResolver { fn resolve(&mut self, import_name: &str) -> Result<ResolvedImport, io::Error> { let ChainedImportResolver(ira, irb) = self; if let Ok(ri) = ira.resolve(import_name) { Ok(ri) } else { irb.resolve(import_name) } } }
Set-Location C:\ Clear-Host # Syntax for creating a hashtable is the at-sign (@) followed by curly brackets {}. # Keys and values are inside the curly brackets. # Use a semicolon to separate multiple key/value sets entered on the same line $Hashtable = @{FirstName = "Michael"; LastName = "Simmons"} $Hashtable #Using the object reference operator (.) to access the keys - just like a property. $Hashtable.FirstName #But using Select-Object on a hashtable doesn't work the way you expect. $Hashtable | Select-Object Firstname $Hashtable #Creating the PSCustomObject from the hashtable is easy. Place the object typename # into square brackets and PowerShell will attempt to convert an object to that type $Object = [PSCustomObject]$hashtable $AnotherWay = [PSCustomObject]@{FirstName = "Michael"; LastName = "Simmons"} $Object $AnotherWay $Hashtable $Object | Select-Object Firstname $Object | Add-Member -MemberType NoteProperty -Name Initial -Value "T" $Object
(require '[babashka.pods :as pods]) (pods/load-pod 'tzzh/mail "0.0.2") (require '[pod.tzzh.mail :as m]) (m/send-mail {:host "smtp.gmail.com" :port 587 :username "[email protected]" :password "kylian123" :subject "Subject of the email" :from "[email protected]" :to ["[email protected]"] :cc ["[email protected]"] :text "aaa" ;; for text body :html "<b> kajfhajkfhakjs </b>" ;; for html body :attachments ["./do-everything.clj"] ;; paths to the files to attch })
package com.tszj.chain.sdk.start; import com.tszj.chain.sdk.service.LockCoinsService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; @Component @Slf4j public class DataProcessStarter implements ApplicationRunner { @Value("${start.investment}") Boolean isInvestment; @Autowired ThreadPoolTaskExecutor taskExecutor; @Autowired LockCoinsService lockCoinsService; @Override public void run(ApplicationArguments args) { if (isInvestment) { taskExecutor.execute(() -> lockCoinsService.queryChainSaveLockCoins()); } } }
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) # only load pry for MRI > 1.8 require 'pry' if RUBY_ENGINE == 'ruby' rescue nil require 'popen4' require 'rspec' require 'rspec/mocks/standalone' require 'set' require 'librato/metrics' RSpec.configure do |config| # purge all metrics from test account def delete_all_metrics connection = Librato::Metrics.client.connection Librato::Metrics.metrics.each do |metric| #puts "deleting #{metric['name']}..." # expects 204 connection.delete("metrics/#{metric['name']}") end end # purge all annotations from test account def delete_all_annotations annotator = Librato::Metrics::Annotator.new streams = annotator.list if streams['annotations'] names = streams['annotations'].map{|s| s['name']} names.each { |name| annotator.delete name} end end # set up test account credentials for integration tests def prep_integration_tests raise 'no TEST_API_USER specified in environment' unless ENV['TEST_API_USER'] raise 'no TEST_API_KEY specified in environment' unless ENV['TEST_API_KEY'] if ENV['TEST_API_ENDPOINT'] Librato::Metrics.api_endpoint = ENV['TEST_API_ENDPOINT'] end Librato::Metrics.authenticate ENV['TEST_API_USER'], ENV['TEST_API_KEY'] end def rackup_path(*parts) File.expand_path(File.join(File.dirname(__FILE__), 'rackups', *parts)) end # fire up a given rackup file for the enclosed tests def with_rackup(name) if RUBY_PLATFORM == 'java' pid, w, r, e = IO.popen4("rackup", rackup_path(name), '-p 9296') else GC.disable pid, w, r, e = Open4.popen4("rackup", rackup_path(name), '-p 9296') end until e.gets =~ /HTTPServer#start:/; end yield ensure Process.kill(9, pid) if RUBY_PLATFORM != 'java' GC.enable Process.wait(pid) end end end # Ex: 'foobar'.should start_with('foo') #=> true # RSpec::Matchers.define :start_with do |start_string| match do |string| start_length = start_string.length string[0..start_length-1] == start_string end end # Compares hashes of arrays by converting the arrays to # sets before comparision # # @example # {:foo => [1,3,2]}.should equal_unordered({:foo => [1,2,3]}) RSpec::Matchers.define :equal_unordered do |result| result.each do |key, value| result[key] = value.to_set if value.respond_to?(:to_set) end match do |target| target.each do |key, value| target[key] = value.to_set if value.respond_to?(:to_set) end target == result end end
package ml.jannik.pmc.friendchat import org.bukkit.Bukkit import org.bukkit.plugin.java.JavaPlugin import ml.jannik.pmc.friendchat.commands.other.* import ml.jannik.pmc.friendchat.commands.friends.* import ml.jannik.pmc.friendchat.commands.guilds.* import ml.jannik.pmc.friendchat.commands.teams.* import ml.jannik.pmc.friendchat.db.DB import ml.jannik.pmc.friendchat.db.Users import ml.jannik.pmc.friendchat.events.player.* // import java.net.URLClassLoader // import java.util.logging.Level // import java.util.logging.Logger /** * The purpose of this plugin is to allow easy * communication between players as well as * create guilds. * * @author jannikwibker * @version 1.0-SNAPSHOT * @since 1.0-SNAPSHOT */ class PluginEntry : JavaPlugin() { override fun onEnable() { this.saveDefaultConfig() // friend commands this.getCommand("friends")?.setExecutor(FriendListCommand()) this.getCommand("friendrequest")?.setExecutor(FriendRequestCommand()) this.getCommand("friendaccept")?.setExecutor(FriendAcceptCommand()) this.getCommand("frienddecline")?.setExecutor(FriendDeclineCommand()) this.getCommand("friendrequests")?.setExecutor(FriendRequestListCommand()) this.getCommand("friendremove")?.setExecutor(FriendRemoveCommand()) this.getCommand("block")?.setExecutor(BlockCommand()) this.getCommand("unblock")?.setExecutor(UnblockCommand()) this.getCommand("blocklist")?.setExecutor(BlockListCommand()) this.getCommand("friendchat")?.setExecutor(FriendChatCommand()) this.getCommand("nofriendchat")?.setExecutor(NoFriendChatCommand()) // guild commands this.getCommand("guildcreate")?.setExecutor(GuildCreateCommand()) this.getCommand("guildinvite")?.setExecutor(GuildInviteCommand()) this.getCommand("guildaccept")?.setExecutor(GuildAcceptCommand()) this.getCommand("guilddecline")?.setExecutor(GuildDeclineCommand()) this.getCommand("guildleave")?.setExecutor(GuildLeaveCommand()) this.getCommand("guildremove")?.setExecutor(GuildRemoveCommand()) this.getCommand("guildmodify")?.setExecutor(GuildModifyCommand()) this.getCommand("guildtransfer")?.setExecutor(GuildTransferCommand()) this.getCommand("guilddelete")?.setExecutor(GuildDeleteCommand()) this.getCommand("guildmembers")?.setExecutor(GuildMembersCommand()) this.getCommand("guildprimary")?.setExecutor(GuildPrimaryCommand()) this.getCommand("guildmsg")?.setExecutor(GuildMessageCommand()) this.getCommand("guildchat")?.setExecutor(GuildChatCommand()) this.getCommand("noguildchat")?.setExecutor(NoGuildChatCommand()) // team commands this.getCommand("teamcreate")?.setExecutor(TeamCreateCommand()) this.getCommand("teamjoin")?.setExecutor(TeamJoinCommand()) this.getCommand("teamleave")?.setExecutor(TeamLeaveCommand()) // other commands this.getCommand("r")?.setExecutor(ReplyCommand()) this.getCommand("msg")?.setExecutor(MessageCommand()) this.getCommand("nick")?.setExecutor(NickCommand()) this.getCommand("unnick")?.setExecutor(UnNickCommand()) this.getCommand("inspect")?.setExecutor(InspectCommand()) // registering events val pm = Bukkit.getPluginManager() pm.registerEvents(JoinEvent(), this) pm.registerEvents(LeaveEvent(), this) // Logger.getLogger(PluginEntry::class.java.name).log(Level.WARNING, "testing") } override fun onDisable() { DB.disconnect() // TODO : Do something if your plugin needs it (saving custom configs, clearing cache, closing connections...) } }
SUBROUTINE GAZMML ( mproj, msppj, np, dlat, dlon, polat, + polon, rotat, azmsav, xl, yl, iret ) C************************************************************************ C* GAZMML * C* * C* This subroutine converts a point from latitude longitude * C* coordinates to linear intermediate coordinates for azimuthal map * C* projections. * C* * C* GAZMML ( MPROJ, MSPPJ, NP, DLAT, DLON, POLAT, POLON, ROTAT, * C* AZMSAV, XL, YL, IRET ) * C* * C* Input parameters: * C* MPROJ INTEGER Map class * C* MSPPJ INTEGER Map projection * C* NP INTEGER Number of points * C* DLAT (NP) REAL Latitudes * C* DLON (NP) REAL Longitudes * C* POLAT REAL Pole latitude * C* POLON REAL Central longitude * C* ROTAT REAL Rotation (not used) * C* AZMSAV REAL Special azimuthal angle (unused)* C* * C* Output parameters: * C* XL (NP) REAL X linear coordinates * C* YL (NP) REAL Y linear coordinates * C* IRET INTEGER Return code * C** * C* Log: * C* G. Chatters/RDS 7/87 GEMPLT Version 3.0 * C* M. desJardins/GSFC 6/85 GEMPLT Version 3.1 * C* B. Doty/RDS 7/87 Fixed Orthographic out-of-hemisphere * C* M. desJardins/GSFC 1/88 Fixed missing data * C* M. desJardins/GSFC 6/88 Cleaned up * C* A. Taylor/ARL 12/93 Enabled Oblique Azimuthal * C* K. Brill/NMC 1/94 Cleanup * C* D. Keiser/GSC 10/95 Fixed rounding error of "z" with EPS * C* K. Brill/EMC 3/96 Remove Taylor code; general rotated proj* C* K. Brill/EMC 5/96 Check for latitude out of range * C************************************************************************ INCLUDE 'GEMPRM.PRM' INCLUDE 'ERROR.PRM' C* REAL xl (*), yl (*), dlat (*), dlon (*) C* INCLUDE 'ERMISS.FNC' C------------------------------------------------------------------------- iret = NORMAL C C* Loop through all points. C DO i = 1, np C C* Check for missing data. C IF ( ERMISS (dlat (i)) .or. ERMISS (dlon (i)) .or. + dlat (i) .gt. 90.0 .or. dlat (i) .lt. -90.0 ) THEN xl (i) = RMISSD yl (i) = RMISSD ELSE rlat = dlat (i) * DTR rlon = dlon (i) * DTR xl (i) = RMISSD yl (i) = RMISSD gamp = RMISSD r = RMISSD C C* Ignore bad data. C IF ( ( ERMISS (rlat) ) .or. ( ERMISS (rlon) ) ) THEN C C* Compute projection angles. C C* North azimuthal projection C ELSE IF ( msppj .eq. MSANOR ) THEN gamp = rlon - polon a = HALFPI - rlat C C* South azimuthal projtection C ELSE IF ( msppj .eq. MSASOU ) THEN gamp = - ( rlon - polon ) a = rlat + HALFPI END IF C C* Select range computation based on projection type. C C* Stereographic projection C IF ( ( mproj .eq. MPASTR ) .and. ( a .lt. PI ) ) THEN r = TAN ( a / 2.0 ) C C* Azimuthal equidistant projection C ELSE IF ( mproj .eq. MPAEQU ) THEN r = a C C* Orthographic projection C ELSE IF ( mproj .eq. MPAORT ) THEN IF ( a .le. HALFPI ) THEN r = SIN ( a ) ELSE r = 1.0 END IF C C* Lambert equal area projection C ELSE IF ( mproj .eq. MPALAM ) THEN r = 2.0 * sin ( a ) / SQRT ( 2.0 * ( 1.0 + COS ( a ) ) ) C C* Gnomic projection C ELSE IF ( ( mproj .eq. MPAGNO ) .and. + ( a .lt. HALFPI ) ) THEN r = TAN ( a ) END IF C C* Convert polar coodinates to Cartesian. C IF ( ( ERMISS ( gamp ) ) .or. ( ERMISS ( r ) ) ) THEN xl (i) = RMISSD yl (i) = RMISSD ELSE xl (i) = r * COS ( gamp ) yl (i) = r * SIN ( gamp ) END IF END IF END DO C* RETURN END
import React, { useState } from 'react'; import { useHistory } from 'react-router-dom'; import { Divider } from 'antd'; import LandingCard from './LandingCard'; import TextInput from '../TextInput'; import Button from '../Button'; import '../../scss/landing.scss'; import API from '../../api/API'; import VerifyEmailModal from '../VerifyEmailModal'; import { CardProps } from './types'; function LoginCard({ switchCard }: CardProps): JSX.Element { const history = useHistory(); const [err, setError] = useState<string | null>(null); const [isEmailModalVisible, setEmailModalVisible] = useState(false); const [isLoading, setLoading] = useState(false); const openEmailModal = () => setEmailModalVisible(true); const closeEmailModal = () => setEmailModalVisible(false); async function onSubmit(event: React.SyntheticEvent) { event.preventDefault(); if (isLoading) { return; } const data = new FormData(event.target as HTMLFormElement); const username = data.get('Username') as string; const password = data.get('Password') as string; if (!username.trim() || !password.trim()) { return; } setLoading(true); try { const res = await API.login(username, password); const { token, id } = res; localStorage.setItem('token', token ?? ''); localStorage.setItem('id', id); } catch (e) { if (e.message.toLowerCase().includes('not verified')) { openEmailModal(); } else { setError(e.message); } setLoading(false); return; } // Move to next page history.push('/'); } return ( <LandingCard title="Log In" error={err ?? undefined}> <form onSubmit={onSubmit}> <div> <TextInput placeHolder="Username" name="Username" /> <TextInput placeHolder="Password" name="Password" type="password" /> </div> <Button type="submit" disabled={isLoading}> Login </Button> <Button className="btn-link" onClick={() => switchCard('forgotPassword')} > Forgot password? </Button> <Divider>OR</Divider> <Button className="btn-link" onClick={() => switchCard('register')}> Don&apos;t have an account? </Button> </form> <VerifyEmailModal visible={isEmailModalVisible} onClose={closeEmailModal} /> </LandingCard> ); } export default LoginCard;
/* See LICENSE for licensing and NOTICE for copyright. */ package org.ldaptive.extended; import org.ldaptive.LdapUtils; import org.ldaptive.asn1.DERBuffer; /** * LDAP unsolicited notification defined as: * * <pre> ExtendedResponse ::= [APPLICATION 24] SEQUENCE { COMPONENTS OF LDAPResult, responseName [10] LDAPOID OPTIONAL, responseValue [11] OCTET STRING OPTIONAL } * </pre> * * where the messageID is always zero. * * @author Middleware Services */ public class UnsolicitedNotification extends ExtendedResponse { /** hash code seed. */ private static final int HASH_CODE_SEED = 10331; /** * Default constructor. */ public UnsolicitedNotification() { setMessageID(0); } /** * Creates a new unsolicited notification. * * @param buffer to decode */ public UnsolicitedNotification(final DERBuffer buffer) { super(buffer); } @Override public void setMessageID(final int id) { if (id != 0) { throw new IllegalArgumentException("Message ID must be zero"); } super.setMessageID(id); } @Override public boolean equals(final Object o) { if (o == this) { return true; } return o instanceof UnsolicitedNotification && super.equals(o); } @Override public int hashCode() { return LdapUtils.computeHashCode( HASH_CODE_SEED, getMessageID(), getControls(), getResultCode(), getMatchedDN(), getDiagnosticMessage(), getReferralURLs(), getResponseName(), getResponseValue()); } /** * Creates a builder for this class. * * @return new builder */ public static Builder builder() { return new Builder(); } // CheckStyle:OFF public static class Builder extends ExtendedResponse.Builder { protected Builder() { super(new UnsolicitedNotification()); } protected Builder(final UnsolicitedNotification n) { super(n); } @Override protected Builder self() { return this; } } // CheckStyle:ON }
# frozen_string_literal: true require 'wordsapi/base' class WordsAPI < Base def service_url 'https://wordsapiv1.p.rapidapi.com/words' end def has_types?(word) response = connection.get has_types_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end def type_of?(word) response = connection.get type_of_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end def part_of?(word) response = connection.get part_of_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end def has_parts?(word) response = connection.get has_parts_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end def similar_to(word) response = connection.get similar_to_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end def usage_of(word) response = connection.get usage_of_endpoint(word) response = process_response(response) OpenStruct.new(success?: true, body: response) rescue Faraday::ClientError => exception OpenStruct.new(success?: false, message: 'Wrong data provided', details: exception.response[:body].to_s) rescue Faraday::Error::TimeoutError, Faraday::ConnectionFailed, Timeout::Error => e OpenStruct.new(success?: false, message: 'Words API is not available') end private def has_types_endpoint(word) "/#{word}/hasTypes" end def type_of_endpoint(word) "/#{word}/typeOf" end def part_of_endpoint(word) "/#{word}/partOf" end def has_parts_endpoint(word) "/#{word}/hasParts" end def similar_to_endpoint(word) "/#{word}/similarTo" end def usage_of_endpoint(word) "/#{word}/usageOf" end end
# Lightweight ASGI Web Framework This is a web framework for [ASGI](user-guide/asgi) servers in Python 3.8. The goal is to provide a minimal implementation, with other facilities (serving static files, CORS, sessions, etc.) being implemented by optional packages in an attempt to keep the implementation clear and lightweight.
import java.util.* fun foo() { val al = ArrayList<String>() al.size al.<!TYPE_INFERENCE_ONLY_INPUT_TYPES!>contains<!>(1) al.contains("") al.remove("") al.removeAt(1) val hs = HashSet<String>() hs.size hs.<!TYPE_INFERENCE_ONLY_INPUT_TYPES!>contains<!>(1) hs.contains("") hs.remove("") val hm = HashMap<String, Int>() hm.size hm.<!TYPE_INFERENCE_ONLY_INPUT_TYPES!>containsKey<!>(1) hm.containsKey("") <!TYPE_INFERENCE_ONLY_INPUT_TYPES!>hm[1]<!> hm[""] hm.remove("") }
wd=$(pwd) # Set up git configurations. ln -s $wd/gitconfig $HOME/.gitconfig ln -s $wd/gitignore $HOME/.gitignore ln -s $wd/git $HOME/.config/git # Set up ideavimrc. ln -s $wd/ideavimrc $HOME/.ideavimrc # Set up chemacs. git clone https://github.com/plexus/chemacs2.git ~/.emacs.d ln -s $wd/emacs-profiles.el $HOME/.emacs-profiles.el # Set up Doom Emacs. git clone --depth 1 https://github.com/hlissner/doom-emacs ~/.emacs.doom ~/.emacs.doom/bin/doom install # Set up spacemacs. git clone -b develop https://github.com/syl20bnr/spacemacs $HOME/.emacs.spacemacs ln -s $wd/spacemacs $HOME/.spacemacs ln -s $wd/layers/* $HOME/.emacs.spacemacs/private/ ln -s $wd/packages/* $HOME/.emacs.spacemacs/private/ # Set up atom. mkdir $HOME/.atom ln -s $wd/atom/* $HOME/.atom # Set up fish. mkdir -p $HOME/.config/fish/ ln -s $wd/fish/config.fish $HOME/.config/fish/config.fish ln -s $wd/fish/functions $HOME/.config/fish/functions fish fish/setup.fish chsh -s $(which fish) # Set up gpg-agent. ln -s $wd/gnupg/gpg-agent.conf $HOME/.gnupg/gpg-agent.conf gpgconf --reload gpg-agent
<?php namespace Troupe\File; class Php extends Common { function getType() { return 'php'; } }
cd /bin if test -e ./bash then echo "File exist" else echo "File not exist" fi
package com.aialias.hlibraries.utils import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * * @author HERB * @date Created on 2018/2/12 20:44 * @function: */ object AppDateMgr { val YYYYMMDD_FORMAT = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val HHMMSS_FORMAT = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) val YYYYMMDDHHMMSS_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) private val CHINESE_ZODIAC = arrayOf("猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊") private val ZODIAC = arrayOf("水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "魔羯座") private val ZODIAC_FLAGS = intArrayOf(20, 19, 21, 21, 21, 22, 23, 23, 23, 24, 23, 22) /** * 当天的年月日 * @return */ fun todayYyyyMmDd(): String { return YYYYMMDD_FORMAT.format(Date()) } /** * 当天的时分秒 * @return */ fun todayHhMmSs(): String { return HHMMSS_FORMAT.format(Date()) } /** * 当天的年月日时分秒 * @return */ fun todayYyyyMmDdHhMmSs(): String { return YYYYMMDDHHMMSS_FORMAT.format(Date()) } /** * 获取年月日 * @param dateTime * @return */ fun parseYyyyMmDd(dateTime: String): String { var result = "" try { val e = YYYYMMDDHHMMSS_FORMAT.parse(dateTime) result = YYYYMMDD_FORMAT.format(e) } catch (var3: ParseException) { var3.printStackTrace() } return result } /** * 获取年月日 * @param dateTime * @param simpleDateFormat * @return */ fun parseYyyyMmDd(dateTime: String, simpleDateFormat: SimpleDateFormat): String { var result = "" try { val e = simpleDateFormat.parse(dateTime) result = YYYYMMDD_FORMAT.format(e) } catch (var4: ParseException) { var4.printStackTrace() } return result } /** * 获取年月日 * @param date * @return */ fun parseYyyyMmDd(date: Date): String { return YYYYMMDD_FORMAT.format(date) } /** * 时分秒 * @param dateTime * @return */ fun parseHhMmSs(dateTime: String): String { try { val e = YYYYMMDDHHMMSS_FORMAT.parse(dateTime) return HHMMSS_FORMAT.format(e) } catch (var2: ParseException) { var2.printStackTrace() return "" } } /** * 时分秒 * @param dateTime * @param simpleDateFormat * @return */ fun parseHhMmSs(dateTime: String, simpleDateFormat: SimpleDateFormat): String { try { val e = simpleDateFormat.parse(dateTime) return HHMMSS_FORMAT.format(e) } catch (var3: ParseException) { var3.printStackTrace() return "" } } /** * 时分秒 * @param date * @return */ fun parseHhMmSs(date: Date): String { return HHMMSS_FORMAT.format(date) } /** * 将年月日时分秒转成Long类型 * @param dateTime * @return */ fun dateTimeToTimeStamp(dateTime: String): Long? { try { val e = YYYYMMDDHHMMSS_FORMAT.parse(dateTime) return java.lang.Long.valueOf(e.getTime() / 1000L) } catch (var2: ParseException) { var2.printStackTrace() return java.lang.Long.valueOf(0L) } } /** * 将Long类型转成年月日时分秒 * @param timeStamp * @return */ fun timeStampToDateTime(timeStamp: Long?): String { return YYYYMMDDHHMMSS_FORMAT.format(Date(timeStamp!!.toLong() * 1000L)) } /** * 将年月日时分秒转成Date类型 * @param time * @return */ fun string2Date(time: String): Date? { return string2Date(time, YYYYMMDDHHMMSS_FORMAT) } /** * 将年月日时分秒转成Date类型 * @param time * @param simpleDateFormat * @return */ fun string2Date(time: String, simpleDateFormat: SimpleDateFormat): Date? { try { return simpleDateFormat.parse(time) } catch (var3: ParseException) { var3.printStackTrace() return null } } /** * 将Date类型转成年月日时分秒 * @param date * @return */ fun date2String(date: Date?): String { try { return date2String(date!!, YYYYMMDDHHMMSS_FORMAT) }catch (e:Exception){ return "时间格式错误" } } /** * 将Date类型转成年月日时分秒 * @param date * @param simpleDateFormat * @return */ fun date2String(date: Date?, simpleDateFormat: SimpleDateFormat): String { return simpleDateFormat.format(date) } /** * 比较日期 * @param standDate * @param desDate * @return */ fun dateIsBefore(standDate: String, desDate: String): Boolean { try { return YYYYMMDDHHMMSS_FORMAT.parse(desDate).before(YYYYMMDDHHMMSS_FORMAT.parse(standDate)) } catch (var3: ParseException) { var3.printStackTrace() return false } } /** * 相差多少分钟 * @param beginDate * @param endDate * @return */ fun minutesBetweenTwoDate(beginDate: String, endDate: String): Long { val millisBegin = dateTimeToTimeStamp(beginDate)!!.toLong() val millisEnd = dateTimeToTimeStamp(endDate)!!.toLong() return (millisEnd - millisBegin) / 60L } /** * 获取日期中的生肖 * @param year * @return */ fun getChineseZodiac(year: Int): String { return CHINESE_ZODIAC[year % 12] } /** * 获取日期中的星座 * @param month * @param day * @return */ fun getZodiac(month: Int, day: Int): String { return ZODIAC[if (day >= ZODIAC_FLAGS[month - 1]) month - 1 else (month + 10) % 12] } /** * 获取日期 * * @param offset 表示偏移天数 * @return */ fun getNowDayOffset(offset: Int): String { val m_Calendar = Calendar.getInstance() var time = m_Calendar.getTimeInMillis() as Long time = time + offset * 24 * 3600 * 1000 val myDate = Date(time) val df = SimpleDateFormat("yyyy-MM-dd") return df.format(myDate) } /** * 获取日期 * * @param * @return */ fun getTime(time: Long): String { val myDate = Date(time) val df = SimpleDateFormat("yyyy-MM-dd hh:mm:ss") return df.format(myDate) } /** * 使指定日期向前走一天,变成“明天”的日期 * * @param cal 等处理日期 */ fun forward(cal: Calendar) { val year = cal.get(Calendar.YEAR) val month = cal.get(Calendar.MONTH)//0到11 val day = cal.get(Calendar.DAY_OF_MONTH) val days = getDaysOfMonth(year, month + 1) if (day == days) {//如果是本月最后一天,还要判断年份是不是要向前滚 if (month == 11) {//如果是12月份,年份要向前滚 cal.roll(Calendar.YEAR, true) cal.set(Calendar.MONTH, 0)//月份,第一月是0 cal.set(Calendar.DAY_OF_MONTH, 1) } else {//如果不是12月份 cal.roll(Calendar.MONTH, true) cal.set(Calendar.DAY_OF_MONTH, 1) } } else { cal.roll(Calendar.DAY_OF_MONTH, 1)//如果是月内,直接天数加1 } } /** * 使日期倒一天 * * @param cal */ fun backward(cal: Calendar) { //计算上一月有多少天 val month = cal.get(Calendar.MONTH)//0到11 val year = cal.get(Calendar.YEAR) val days = getDaysOfMonth(year, month)//上个月的天数 val day = cal.get(Calendar.DAY_OF_MONTH) if (day == 1) {//如果是本月第一天,倒回上一月 if (month == 0) {//如果是本年第一个月,年份倒一天 cal.roll(Calendar.YEAR, false) cal.set(Calendar.MONTH, 11)//去年最后一个月是12月 cal.set(Calendar.DAY_OF_MONTH, 31)//12月最后一天总是31号 } else {//月份向前 cal.roll(Calendar.MONTH, false) cal.set(Calendar.DAY_OF_MONTH, days)//上个月最后一天 } } else { cal.roll(Calendar.DAY_OF_MONTH, false)//如果是月内,日期倒一天 } } /** * 判断平年闰年 * * @param year * @return true表示闰年,false表示平年 */ fun isLeapYear(year: Int): Boolean { if (year % 400 == 0) { return true } else if (year % 100 != 0 && year % 4 == 0) { return true } return false } /** * 计算某月的天数 * * @param year * @param month 现实生活中的月份,不是系统存储的月份,从1到12 * @return */ fun getDaysOfMonth(year: Int, month: Int): Int { if (month < 1 || month > 12) { return 0 } val isLeapYear = isLeapYear(year) var daysOfMonth = 0 when (month) { 1, 3, 5, 7, 8, 10, 12 -> daysOfMonth = 31 4, 6, 9, 11 -> daysOfMonth = 30 2 -> if (isLeapYear) { daysOfMonth = 29 } else { daysOfMonth = 28 } } return daysOfMonth } /** * 获取当天凌晨的秒数 * * @return */ fun secondsMorning(c: Calendar): Long { val tempCalendar = Calendar.getInstance() tempCalendar.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0) return tempCalendar.getTimeInMillis() } /** * 获取第二天凌晨的秒数 * * @return */ fun secondsNight(c: Calendar): Long { val tempCalendar = Calendar.getInstance() tempCalendar.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0) forward(tempCalendar) return tempCalendar.getTimeInMillis() } /** * 判断某两天是不是同一天 * * @param c1 * @param c2 * @return */ fun isSameDay(c1: Calendar, c2: Calendar): Boolean { if (c1.get(Calendar.YEAR) !== c2.get(Calendar.YEAR)) return false if (c1.get(Calendar.MONTH) !== c2.get(Calendar.MONTH)) return false return if (c1.get(Calendar.DAY_OF_MONTH) !== c2.get(Calendar.DAY_OF_MONTH)) false else true } /** 日期格式:yyyy-MM-dd HH:mm:ss */ val DF_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss" /** 日期格式:yyyy-MM-dd HH:mm */ val DF_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm" /** 日期格式:yyyy-MM-dd */ val DF_YYYY_MM_DD = "yyyy-MM-dd" /** 日期格式:HH:mm:ss */ val DF_HH_MM_SS = "HH:mm:ss" /** 日期格式:HH:mm */ val DF_HH_MM = "HH:mm" private val MINUTE = (60 * 1000).toLong()// 1分钟 private val HOUR = 60 * MINUTE// 1小时 private val DAY = 24 * HOUR// 1天 private val MONTH = 31 * DAY// 月 private val YEAR = 12 * MONTH// 年 /** Log输出标识 */ private val TAG = AppDateMgr::class.java.simpleName /** * 将日期格式化成友好的字符串:几分钟前、几小时前、几天前、几月前、几年前、刚刚 * * @param date * @return */ fun formatFriendly(date: Date?): String? { if (date == null) { return null } val diff = Date().getTime() - date!!.getTime() var r: Long = 0 if (diff > YEAR) { r = diff / YEAR return r.toString() + "年前" } if (diff > MONTH) { r = diff / MONTH return r.toString() + "个月前" } if (diff > DAY) { r = diff / DAY return r.toString() + "天前" } if (diff > HOUR) { r = diff / HOUR return r.toString() + "个小时前" } if (diff > MINUTE) { r = diff / MINUTE return r.toString() + "分钟前" } return "刚刚" } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL * 日期 * @return */ fun formatDateTime(dateL: Long): String { val sdf = SimpleDateFormat(DF_YYYY_MM_DD_HH_MM_SS) val date = Date(dateL) return sdf.format(date) } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param dateL * 日期 * @return */ fun formatDateTime(dateL: Long, formater: String): String { val sdf = SimpleDateFormat(formater) return sdf.format(Date(dateL)) } /** * 将日期以yyyy-MM-dd HH:mm:ss格式化 * * @param formater * 日期 * @return */ fun formatDateTime(date: Date, formater: String): String { val sdf = SimpleDateFormat(formater) return sdf.format(date) } /** * 获取系统当前日期 * * @return */ fun gainCurrentDate(): Date { return Date() } /** * 对日期进行增加操作 * * @param target * 需要进行运算的日期 * @param hour * 小时 * @return */ fun addDateTime(target: Date?, hour: Double): Date? { return if (null == target || hour < 0) { target } else Date(target!!.getTime() + (hour * 60.0 * 60.0 * 1000.0).toLong()) } /** * 对日期进行相减操作 * * @param target * 需要进行运算的日期 * @param hour * 小时 * @return */ fun subDateTime(target: Date?, hour: Double): Date? { return if (null == target || hour < 0) { target } else Date(target!!.getTime() - (hour * 60.0 * 60.0 * 1000.0).toLong()) } private val second = SimpleDateFormat( "yy-MM-dd hh:mm:ss") private val day = SimpleDateFormat("yyyy-MM-dd") private val detailDay = SimpleDateFormat("yyyy年MM月dd日") private val fileName = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss") private val tempTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") private val excelDate = SimpleDateFormat("yyyy/MM/dd") /** * 格式化excel中的时间 * @param date * @return */ fun formatDateForExcelDate(date: Date): String { return excelDate.format(date) } /** * 将日期格式化作为文件名 * @param date * @return */ fun formatDateForFileName(date: Date): String { return fileName.format(date) } /** * 格式化日期(精确到秒) * * @param date * @return */ fun formatDateSecond(date: Date): String { return second.format(date) } /** * 格式化日期(精确到秒) * * @param date * @return */ fun tempDateSecond(date: Date): String { return tempTime.format(date) } /** * 格式化日期(精确到秒) * * @param str * @return */ fun tempDateSecond(str: String): Date { try { return tempTime.parse(str) } catch (e: ParseException) { e.printStackTrace() } return Date() } /** * 格式化日期(精确到天) * * @param date * @return */ fun formatDateDay(date: Date): String { return day.format(date) } /** * 将字符串转换成日期 * * @param date * @return * @throws Exception */ @Throws(Exception::class) fun formateDate(date: String): Date { return day.parse(date) } /** * 将字符日期转换成Date * @param date * @return * @throws Exception */ @Throws(Exception::class) fun parseStringToDate(date: String): Date { return day.parse(date) } /** * 获得指定Date类型的毫秒数 * @param date 指定的Date * @return 指定Date类型的毫秒数 */ fun getTimeMillis(date: Date): Long { return date.getTime() } /** * 获得当前时间的毫秒数 * @return 当前时间的毫秒数 */ fun getCurrentDayTimeMillis(): Long { return System.currentTimeMillis() } /** * 将格式化过的时间串转换成毫秒 * @param day 将格式化过的时间 * @param format 格式化字符串 * @return 毫秒 */ fun convertMillisecond(day: String?, format: String?): Long { if (day == null || format == null) return 0 val formatter = SimpleDateFormat(format) try { val dt = formatter.parse(day) return dt.getTime() } catch (e: ParseException) { e.printStackTrace() } return 0 } /** * 得到两个日期的天数 * @param sdate1 日期一 * @param sdate2 日期二 * @return 天数 */ fun getDateInterval(sdate1: String, sdate2: String): Int { var date1: Date? = null var date2: Date? = null var betweenDays: Long = 0 try { date1 = SimpleDateFormat("yyyy-MM-dd").parse(sdate1) date2 = SimpleDateFormat("yyyy-MM-dd").parse(sdate2) val beginTime = date1!!.getTime() val endTime = date2!!.getTime() betweenDays = ((endTime - beginTime) / (1000 * 60 * 60 * 24)).toLong() } catch (e: ParseException) { e.printStackTrace() } return betweenDays.toInt() } /** * 时间比较 * @param format 格式化字符串 * @param time1 时间1 * @param time2 时间2 * @return time1比time2早返回-1,time1与time2相同返回0,time1比time2晚返回1 */ fun compareTime(format: String?, time1: String?, time2: String?): Int { if (format == null || time1 == null || time2 == null) return 0 val formatter = SimpleDateFormat(format) val c1 = Calendar.getInstance() val c2 = Calendar.getInstance() try { c1.setTime(formatter.parse(time1)) c2.setTime(formatter.parse(time2)) } catch (e: ParseException) { e.printStackTrace() } return c1.compareTo(c2) } fun getunixforDate():Long{ val instance = Calendar.getInstance() val cal = Calendar.getInstance() cal.timeInMillis = System.currentTimeMillis() cal.set(Calendar.HOUR_OF_DAY, 0) cal.set(Calendar.MINUTE, 0) cal.set(Calendar.SECOND, 0) val today = cal.timeInMillis instance.set(2018,12,22) val all = instance.timeInMillis val swap = all -today return swap/(1000*60*60*24) } fun formatTime(millisecond:Long):String{ val hour : Long = (millisecond / 1000 / 60 / 60) var milliseconds = millisecond - hour*60*60*1000 val minute: Long = (milliseconds /1000/ 60)//分钟 val second: Long = (milliseconds /1000% 60)//秒数 return if (hour < 10){ if (minute < 10) { if (second < 10) { "0$hour:0$minute:0$second" } else { "0$hour:0$minute:$second" } } else { if (second < 10) { "0$hour:"+minute.toString() + ":" + "0" + second } else { "0$hour:"+minute.toString() + ":" + second } } }else{ if (minute < 10) { if (second < 10) { hour.toString()+":"+"0$minute:0$second" } else { hour.toString()+":"+"0$minute:$second" } } else { if (second < 10) { hour.toString()+":"+minute.toString() + ":" + "0" + second } else { hour.toString()+":"+minute.toString() + ":" + second } } } } }
using System; using UniRx; using UniRx.Triggers; using UnityEngine; using Zenject; namespace Characters.Enemies { public class EnemyAI : MonoBehaviour { [SerializeField] double dueTimeSeconds; [SerializeField] double updateLogicSpanMillis; [SerializeField] Range targetDistance; [SerializeField] float targetRotationDotThreshold; [SerializeField] float rotateSpeed; readonly ReactiveProperty<Vector2> moveDirection = new ReactiveProperty<Vector2>(); readonly ReactiveProperty<Vector2> targetDirection = new ReactiveProperty<Vector2>(); readonly ReactiveProperty<bool> fire = new ReactiveProperty<bool>(); public IReadOnlyReactiveProperty<Vector2> MoveDirection => moveDirection; public IReadOnlyReactiveProperty<Vector2> TargetDirection => targetDirection; public IReadOnlyReactiveProperty<bool> Fire => fire; [Inject] IReadOnlyPlayerCore player; void Start() { Observable.Timer(TimeSpan.FromSeconds(dueTimeSeconds), TimeSpan.FromMilliseconds(updateLogicSpanMillis)) .Select(_ => UpdateLogic()) .Switch() .Finally(Stop) .TakeUntil(player.Dead) .Subscribe() .AddTo(this); } IObservable<Unit> UpdateLogic() { return Observable.Defer(() => { if (targetDistance.IsCover(Distance())) { if (IsRotationCover()) { return ShootState(); } return LockState(); } return MoveState(); }); } float Distance() { return Vector3.Distance(transform.position, player.Position); } bool IsRotationCover() { return targetRotationDotThreshold < Vector3.Dot(transform.forward, player.Position - transform.position); } IObservable<Unit> ShootState() { return Observable.Defer(() => { fire.Value = true; moveDirection.Value = Vector2.zero; return Rotate(); }); } IObservable<Unit> LockState() { return Observable.Defer(() => { fire.Value = false; moveDirection.Value = Vector2.zero; return Rotate(); }); } IObservable<Unit> Rotate() { return this.UpdateAsObservable() .Do(_ => { var rot = Vector3.RotateTowards(transform.forward, player.Position - transform.position, rotateSpeed * Time.deltaTime, 0F); targetDirection.Value = new Vector2(rot.x, rot.z); }); } IObservable<Unit> MoveState() { return Observable.Defer(() => { fire.Value = false; return this.UpdateAsObservable() .Do(_ => { var distance = Distance(); if (targetDistance.IsCover(distance)) { return; } var diff = player.Position - transform.position; if (distance < targetDistance.Start) { diff *= -1; } var direction = new Vector2(diff.x, diff.z); moveDirection.Value = direction; targetDirection.Value = direction; }); }); } void Stop() { moveDirection.Value = Vector2.zero; fire.Value = false; } [Serializable] struct Range { [SerializeField] float start; [SerializeField] float length; public float Start => start; public float End => start + length; public bool IsCover(float value) { return start < value && value < End; } } } }
# Pregel A single-node [pregel](https://dl.acm.org/citation.cfm?id=1584010) implementation. ## Implemented * Combiner support * Aggregators support * Multi-thread computing * Functional API ## Usage See [examples](https://github.com/nickyc975/Pregel/tree/master/src/main/java/examples). ## License [MIT](./LICENSE)
/* * Copyright 2020-2021 Photos.network developers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package network.photos.android.data.user.network import network.photos.android.data.user.network.model.TokenResponse import network.photos.android.data.user.network.model.UserResponse import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.POST import retrofit2.http.Query interface UserApi { /** * OAuth token request based on [RFC6749](https://tools.ietf.org/html/rfc6749#section-4.1.3) * * @param code The authorization code received from the authorization server. * @param clientId The client identifier issued by the authorization server. * @param redirectUri The redirect_uri included in the authorization request. */ @FormUrlEncoded @POST("/api/oauth/token?grant_type=authorization_code") suspend fun accessTokenRequest( @Field("code") code: String, @Field("client_id") clientId: String, @Field("redirect_uri") redirectUri: String, @Field("grant_type") grantType: String = "authorization_code" ): TokenResponse /** * OAuth refresh token request based on [RFC6749](https://tools.ietf.org/html/rfc6749#section-6) * * @param refreshToken The refresh token issued to the client. * @param clientId The client identifier issued by the authorization server. * @param clientSecret The client secret issued during registration process. * @param scope list of case-sensitive strings to grant access based on. */ @POST("/api/oauth/token?grant_type=refresh_token") suspend fun refreshTokenRequest( @Query("refresh_token") refreshToken: String, @Query("client_id") clientId: String, @Query("client_secret") clientSecret: String, @Query("scope") scope: List<String> ): TokenResponse /** * OAuth token revocation based on [RFC7000](https://tools.ietf.org/html/rfc7009#section-2.1) * * @param token The token to revoke on the oauth server. * @param tokenTypeHint This optional param should either be 'access_token' or 'refresh_token'. */ @POST("/api/revoke") suspend fun revokeTokenRequest( @Query("token") token: String, @Query("token_type_hint") tokenTypeHint: String? ): TokenResponse @GET("/api/user/") suspend fun me(@Header("Authorization") token: String): UserResponse }
/* * MIT License * * Copyright (c) 2021 Hell Hole Studios * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.hhs.koto.util import com.badlogic.gdx.audio.Sound import com.badlogic.gdx.utils.Logger import com.hhs.koto.app.Config import ktx.collections.GdxMap import ktx.collections.set object SE { private val sounds = GdxMap<String, Sound>() private val fired = GdxMap<String, Boolean>() private val logger = Logger("SE", Config.logLevel) fun update() { if (Config.noDuplicateSE) { for (i in fired.safeKeys()) { fired[i] = false } } } fun play(name: String, volume: Float = 1f) { val sound = sounds[name] if (sound == null) { logger.error("SE with this name doesn't exist!") } else { if (Config.noDuplicateSE) { if (fired[name]) { return } fired[name] = true } val id = sound.play(volume) sound.setVolume(id, options.SEVolume) } } fun pause() { sounds.safeValues().forEach { it.pause() } } fun resume() { sounds.safeValues().forEach { it.resume() } } fun stop() { sounds.safeValues().forEach { it.stop() } } fun register(name: String, path: String): Sound { logger.debug("Registering sound with alias: $name path: $path") val snd: Sound = A[path] sounds.put(name, snd) fired.put(name, false) return snd } }
<?php namespace Database\Seeders; use App\Models\Course; use App\Models\Schoolclass; use Illuminate\Support\Str; use App\Models\Subjectmatter; use Illuminate\Database\Seeder; class SchoolclassCourseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Schoolclass::create([ 'teacher_id' => 1, 'name' => 'X RPL 1', 'information' => 'Kelas 10 jurusan rpl batch 1' ]); Schoolclass::create([ 'teacher_id' => null, 'name' => 'X RPL 2', 'information' => 'Kelas 10 jurusan rpl batch 2' ]); Schoolclass::create([ 'teacher_id' => null, 'name' => 'X TEI 1', 'information' => 'Kelas 10 jurusan tei batch 1' ]); $classes = [1,2]; $course1 = new Course; $course1->name = 'Desain Grafis X RPL'; $course1->information = 'Pelajaran dg kelas x rpl'; $course1->save(); $course1->schoolclasses()->attach($classes); $course2 = new Course; $course2->name = 'Pemrograman Dasar X RPL'; $course2->information = 'Pelajaran pd kelas x rpl'; $course2->save(); $course2->schoolclasses()->attach($classes); $course3 = new Course; $course3->name = 'Elektronika X TEI'; $course3->information = 'Pelajaran elektronika kelas x rpl'; $course3->save(); $course3->schoolclasses()->attach([3]); Subjectmatter::create([ 'course_id' => $course1->id, 'teacher_id' => 1, 'title' => 'Corel Draw', 'details' => 'Ini adalah pelajaran tentang corel draw untuk kelas xi', 'path' => 'public/', 'link' => 'https://www.youtube.com/embed/b8oQqADRbTE', ]); Subjectmatter::create([ 'course_id' => $course1->id, 'admin_id' => 1, 'title' => 'Adobe Photoshop', 'details' => 'Ini adalah pelajaran tentang adobe photoshop untuk kelas xi', 'path' => 'public/', 'link' => 'https://www.youtube.com/embed/A9pWXs_2QD4E', ]); Subjectmatter::create([ 'course_id' => $course2->id, 'teacher_id' => 2, 'title' => 'Algoritma dasar', 'details' => 'Ini adalah pelajaran tentang algoritma dasar untuk kelas xi', 'path' => 'public/', 'link' => 'https://www.youtube.com/embed/5JuNp0o4YEE' ]); Subjectmatter::create([ 'course_id' => $course3->id, 'teacher_id' => 2, 'title' => 'Analisa dan perhitungan listrik', 'details' => 'Ini adalah pelajaran tentang kelistrikan untuk kelas xi', 'path' => 'public/', 'link' => 'https://www.youtube.com/embed/s9A2EfcoBQg' ]); } }
import { Component , Element , Prop} from '@stencil/core'; import { MDCTextField } from "@material/textfield"; @Component({ tag: 'o-mdc-text-field', styleUrl: 'o-mdc-text-field.scss', shadow: true }) export class MdcTextFieldComponent { private mdcTextFields: any; @Element() el: HTMLElement; @Prop() label : string = ''; componentDidLoad() { const rootEl = this.el.shadowRoot.querySelector('.mdc-text-field'); this.mdcTextFields = new MDCTextField(rootEl); } componentDidUnload() { this.mdcTextFields.destroy(); } render() { return ( <div class="mdc-text-field"> <input type="text" id="my-text-field" class="mdc-text-field__input"/> <label class="mdc-text-field__label" htmlFor="my-text-field">{this.label}</label> <div class="mdc-text-field__bottom-line"/> </div> ); } }
#!/usr/bin/env python # Licensed to Pioneers in Engineering under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Pioneers in Engineering licenses # this file to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License from __future__ import print_function import os import subprocess as subp import shutil import argparse import re import traceback import sys def is_subpath_of_set(path, pathset): part_path = '' for part in path.split(os.path.sep): part_path = os.path.join(part_path, part) if part_path in pathset: return True return False def setup(): os.chdir('tests') try: os.mkdir('tmp') except IOError as e: # One reason we would get here is that the tmp directory was not # cleaned up. Delete the directory and try again. shutil.rmtree('tmp') os.mkdir('tmp') os.chdir('tmp') def cleanup(): os.chdir(os.pardir) shutil.rmtree('tmp') os.chdir(os.pardir) def get_test(path): return os.path.join(os.pardir, os.pardir, path) def get_test_base(root, path): return os.path.join(root, os.path.dirname(path)) EXT_TO_CMD = {'py': ['python'], 'js': ['node', '--harmony'], 'sh': ['bash']} def get_tests(): ''' Get all files under the tests directory, skipping directories that have tests files with the same name. ''' tests = set() dirs_to_skip = set(['tests/tmp']) for dirpath, dirnames, filenames in os.walk('tests', topdown=True): if not is_subpath_of_set(dirpath, dirs_to_skip): for filename in filenames: if filename[0] == '.': continue fullname = os.path.join(dirpath, filename) tests.add(fullname) base, ext = os.path.splitext(fullname) dirs_to_skip.add(base) return tests def run_test(name, root, failed_tests, stdout_logs): _, ext = os.path.splitext(name) cmd = EXT_TO_CMD[ext[1:]] args = cmd + [get_test(name), root, get_test_base(root, name)] p = subp.Popen(args, stdout=subp.PIPE, stderr=subp.STDOUT) stdout_logs[name] = p.communicate() ret = p.returncode if ret == 0: print('.', end='') else: failed_tests.append(name) print('x', end='') # Flush out the . or x we just printed, instead of waiting for a # newline to flush them. sys.stdout.flush() def main(): parser = argparse.ArgumentParser(description='Run angelic tests.') parser.add_argument('--no-cleanup', action='store_true') parser.add_argument('--verbose', action='store_true') parser.add_argument('--matching', action='store', default='') args = parser.parse_args() pattern = None if args.matching: pattern = re.compile(args.matching) tests = get_tests() failed_tests = [] stdout_logs = dict() root = os.getcwd() tests_run = 0 setup() try: for test in sorted(tests): if not pattern or pattern.search(test): tests_run += 1 try: run_test(test, root, failed_tests, stdout_logs) except KeyboardInterrupt as e: print('Encountered exception while running test{}:' .format(test)) traceback.print_exc() if args.verbose: print(stdout_logs[test][0].decode()) except Exception as e: print('Encountered exception while running tests:') traceback.print_exc() finally: if not args.no_cleanup: cleanup() if not failed_tests: print() print('OK (Ran {0} test)'.format(tests_run)) else: print() for failure in failed_tests: print('FAILED:', failure) print(' BEGIN TEST OUTPUT '.center(80, '*')) print(stdout_logs[failure][0].decode(), end='') print(' END TEST OUTPUT '.center(80, '*')) print() print('TEST FAILED ({0}/{1} tests failed)' .format(len(failed_tests), tests_run)) if __name__ == '__main__': main()
package io.github.dreamylost.websocket import akka.actor.ActorRef import io.github.dreamylost.model.entities.Message import io.github.dreamylost.util.Jackson import io.github.dreamylost.model.Mine /** @author 梦境迷离 * @version 1.0,2021/11/25 */ object Protocols { sealed trait ImProtocol { self => @inline final def stringify: String = self match { case ImProtocol.readOfflineMessage => "readOfflineMessage" case ImProtocol.message => "message" case ImProtocol.checkOnline => "checkOnline" case ImProtocol.addGroup => "addGroup" case ImProtocol.changOnline => "changOnline" case ImProtocol.addFriend => "addFriend" case ImProtocol.agreeAddFriend => "agreeAddFriend" case ImProtocol.agreeAddGroup => "agreeAddGroup" case ImProtocol.refuseAddGroup => "refuseAddGroup" case ImProtocol.unHandMessage => "unHandMessage" case ImProtocol.delFriend => "delFriend" } } object ImProtocol { @inline final def unStringify(`type`: String): ImProtocol = { val mapping = Map( ImProtocol.readOfflineMessage.stringify -> readOfflineMessage, ImProtocol.message.stringify -> message, ImProtocol.checkOnline.stringify -> checkOnline, ImProtocol.addGroup.stringify -> addGroup, ImProtocol.changOnline.stringify -> changOnline, ImProtocol.addFriend.stringify -> addFriend, ImProtocol.agreeAddFriend.stringify -> agreeAddFriend, ImProtocol.agreeAddGroup.stringify -> agreeAddGroup, ImProtocol.refuseAddGroup.stringify -> refuseAddGroup, ImProtocol.unHandMessage.stringify -> unHandMessage, ImProtocol.delFriend.stringify -> delFriend ) mapping(`type`) } case object readOfflineMessage extends ImProtocol case object message extends ImProtocol case object checkOnline extends ImProtocol case object addGroup extends ImProtocol case object changOnline extends ImProtocol case object addFriend extends ImProtocol case object agreeAddFriend extends ImProtocol case object agreeAddGroup extends ImProtocol case object refuseAddGroup extends ImProtocol case object unHandMessage extends ImProtocol case object delFriend extends ImProtocol } /** 添加群信息 */ case class Group(groupId: Int, remark: String) /** 同意添加群 */ case class AddRefuseMessage(toUid: Int, groupId: Int, messageBoxId: Int, mine: Mine) case class TransmitMessage(uId: Int, msg: String, originActorRef: ActorRef) { def getMessage: Message = Jackson.mapper.readValue[Message](msg) } case object OnlineUserMessage case class UserStatusChange(uId: Int, typ: String) }
package org.ggp.base.util.gdl.model.assignments; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ggp.base.util.gdl.GdlUtils; import org.ggp.base.util.gdl.grammar.GdlSentence; import org.ggp.base.util.gdl.grammar.GdlTerm; import org.ggp.base.util.gdl.grammar.GdlVariable; public class FunctionInfos { public static Set<GdlVariable> getProducibleVars(FunctionInfo functionInfo, GdlSentence sentence) { if (!functionInfo.getSentenceForm().matches(sentence)) { throw new RuntimeException("Sentence "+sentence+" does not match constant form"); } List<GdlTerm> tuple = GdlUtils.getTupleFromSentence(sentence); List<Boolean> dependentSlots = functionInfo.getDependentSlots(); Set<GdlVariable> candidateVars = new HashSet<GdlVariable>(); //Variables that appear multiple times go into multipleVars Set<GdlVariable> multipleVars = new HashSet<GdlVariable>(); //...which, of course, means we have to spot non-candidate vars Set<GdlVariable> nonCandidateVars = new HashSet<GdlVariable>(); for(int i = 0; i < tuple.size(); i++) { GdlTerm term = tuple.get(i); if(term instanceof GdlVariable && !multipleVars.contains(term)) { GdlVariable var = (GdlVariable) term; if(candidateVars.contains(var) || nonCandidateVars.contains(var)) { multipleVars.add(var); candidateVars.remove(var); } else if(dependentSlots.get(i)) { candidateVars.add(var); } else { nonCandidateVars.add(var); } } } return candidateVars; } }
class Api::V1::ApplicationController < ApplicationController respond_to :json layout "api_v1.json" # Handle errors rescue_from BSON::InvalidObjectId, with: :api_error_400 rescue_from Mongoid::Errors::DocumentNotFound, with: :api_error_400 # Authorization with CanCan load_and_authorize_resource # Skip authenticity token is more easy for an API skip_before_filter :verify_authenticity_token # Skip touch version skip_before_filter :set_touch_format private def api_error_400 exception @api_errors = { errorType: "param_error", errorDetail: exception.to_s } render layout: "api_v1", status: 400 end end
export const getTypeById = (id) => new Promise((resolve) => { fetch(`https://pokeapi.co/api/v2/type/${id}`).then((data) => resolve(data.json()) ); }); export const getTypeByName = (name) => new Promise((resolve) => { fetch(`https://pokeapi.co/api/v2/type/${name}`).then((data) => resolve(data.json()) ); });
import React, { Component, ReactElement } from 'react'; import { Container, Nav, Navbar } from 'react-bootstrap'; import { GoMarkGithub } from 'react-icons/go'; type Props = Readonly<{ onAbout: () => void }>; /** * Header component with application's name. * @inheritdoc */ export class AppHeader extends Component<Props> { public shouldComponentUpdate(nextProps: Props): boolean { return this.props.onAbout !== nextProps.onAbout; } public render(): ReactElement { return ( <Navbar bg='primary' sticky='top'> <Container className='header'> <Navbar.Brand>Git Cheatsheet</Navbar.Brand> <Navbar.Collapse> <Nav className='mr-auto'> <Nav.Link id='about-link' onClick={ this.props.onAbout }> About </Nav.Link> </Nav> <Nav> <Nav.Link href='https://github.com/kmingulov/git-cheatsheet' target='_blank'> <GoMarkGithub size={ 24 }/> </Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ); } }
package es.odavi.mandyville import common.entity.Player import common.Comparison import scala.math.BigDecimal.RoundingMode /** The base predictor providing shared predictor functionality * and an interface for all predictors. * * @constructor create a new predictor for a player in a context * @param player the player for whom we want to predict * @param context the context in which we are predicting * @param playerManager an instance of PlayerManager */ abstract class Predictor( context: Context, playerManager: PlayerManager ) { /** Compare a prediction with the real life result * * @return an instance of Comparison representing our comparison */ def comparePrediction(player: Player): Comparison = { val prediction = pointsForGameweek(player) val perf = playerManager.getFPLPerformance(player, context) val actual = perf.totalPoints Comparison(player, context, this, prediction, BigDecimal(actual)) } /** The unique ID of this predictor, used primarily when saving * results. */ def id: Int /** Find the predicted points for the gameweek provided in the * given context. * * Fetch the expected values and probabilities of various in-game * events, and combine them with the FPL ruleset to generate a * points total. * * @return the total predicted points */ def pointsForGameweek(player: Player): BigDecimal = { val mins = expectedMinutes(player) if (mins == 0) 0 else { val position = playerManager.getPositionForPlayer(player, context) val goalPoints = expectedGoals(player) * GoalPoints(position) val assistPoints = expectedAssists(player) * AssistPoints val conceded = expectedConceded(player) // TODO: do we need to think about whether the player is actually on the // pitch for the conceded goals here? val cleanSheetPoints = if (conceded < 0.5 && mins > 60) BigDecimal(CleanSheetPoints(position)) else if (conceded >= 1.5 && mins > 60) { val lastEven = (conceded / 2).setScale(0, RoundingMode.FLOOR) lastEven * TwoGoalsConcededPoints } else BigDecimal(0) val redPenalty = chanceOfRedCard(player) * RedCardPoints val yellowPenalty = chanceOfYellowCard(player) * YellowCardPoints val appearancePoints = if (mins >= 60) FullPlayPoints else SubPlayPoints // TODO: // * Penalty Saves // * Penalty Misses // * Own Goals // * Bonus Points goalPoints + assistPoints + cleanSheetPoints + redPenalty + yellowPenalty + appearancePoints } } /** Find the probability of the player getting a red card in the * gameweek given by the context. */ def chanceOfRedCard(player: Player): BigDecimal /** Find the probability of the player getting a yellow card in the * gameweek given by the context. */ def chanceOfYellowCard(player: Player): BigDecimal /** Find the expected number of assists for the player */ def expectedAssists(player: Player): BigDecimal /** Find the expected number of goals conceded by the player's team * in the gameweek given by the context. */ def expectedConceded(player: Player): BigDecimal /** Find the expected number of goals scored by the player */ def expectedGoals(player: Player): BigDecimal /** Find the expected number of minutes played by the player in the * gameweek given by the context */ def expectedMinutes(player: Player): BigDecimal }
-- -- Copyright 2017, 2018 Warlock <[email protected]> -- -- 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. -- module Data.Conduit.Parsers.Text.Parser.Spec ( tests ) where import Control.Monad.Error.Class import Data.Conduit hiding (ConduitM) import qualified Data.Conduit.Combinators as N import Data.Functor.Identity import Data.Maybe import qualified Data.Text as S (Text) import Test.HUnit.Base hiding (Label) import Data.Conduit.Parsers.Binary.Get hiding (runGet) import Data.Conduit.Parsers.Text.Parser tests :: Test tests = TestList [ TestCase testLinesRead , TestCase testSignedNumber ] testLinesRead :: Assertion testLinesRead = do let !r = runIdentity $ N.yieldMany testInput1 `connect` runParser parser1 assertEqual "" (Right ('t', 'x')) r parser1 :: Parser () (Char, Char) parser1 = do 0 <- linesRead 0 <- columnsRead c1 <- pChar 0 <- linesRead 1 <- columnsRead skipEndOfLine 1 <- linesRead 0 <- columnsRead skipCharIs 'a' 1 <- linesRead 1 <- columnsRead skipCharIs 'u' 1 <- linesRead 2 <- columnsRead skipEndOfLine 2 <- linesRead 0 <- columnsRead c2 <- pCharIsNot 'b' 2 <- linesRead 1 <- columnsRead endOfInput return (c1, c2) testInput1 :: [S.Text] testInput1 = [ "t\n" , "au\nx" , "" ] pSign :: Parser (Maybe Char) Bool pSign = do c <- pChar ?>> return Nothing case c of '+' -> return False '-' -> return True x -> throwError (Just x) pSignedNumber :: Parser String Int pSignedNumber = do is_negative <- fromMaybe False <$> option'' pSign value <- foldl1 (\ !a !b -> a * 10 + b) <$> many1'' pDigit ?>> return "digit or sign expected" return $ if is_negative then -value else value testSignedNumber :: Assertion testSignedNumber = do assertEqual "" (Right 145) $ runIdentity $ yield "145" `connect` runParser pSignedNumber assertEqual "" (Right 32) $ runIdentity $ yield "+32" `connect` runParser pSignedNumber assertEqual "" (Right (-7)) $ runIdentity $ yield "-7" `connect` runParser pSignedNumber assertEqual "" (Left "digit or sign expected") $ runIdentity $ yield "abc" `connect` runParser pSignedNumber assertEqual "" (Left "digit or sign expected") $ runIdentity $ yield "-abc" `connect` runParser pSignedNumber
const { Types } = require('mongoose'); module.exports = (Joi) => { /** * @static * @type {string} * @memberof JoiSchema */ const messageObjectId = 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'; return Joi.extend({ type: 'objectId', messages: { 'objectId.base': messageObjectId, }, validate(value, helpers) { if (!Types.ObjectId.isValid(value)) { return { value, errors: helpers.error('objectId.base'), }; } return { value, }; }, }); };
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Model\Admin\Newsletter; use App\Model\Order; use App\Model\Admin\Site_Setting; use App\Model\Contact; use App\Model\Admin\Product; use App\User; use Auth; // use Image; use Intervention\Image\Facades\Image; class FrontController extends Controller { // public function storenewsletter(Request $request) { $validateData=$request->validate([ 'email'=>'required|unique:newsletters|max:55', ]); // dd($request->all()); $nl=new Newsletter(); $nl->email=$request->email; $nl->save(); $notification=array( 'messege'=>'Thanks For Subscribing ', 'alert-type'=>'success' ); return Redirect()->back()->with($notification); } public function tracking(Request $request){ $code=$request->status_code; $track=Order::where('status_code',$code)->first(); // dd($order); if($track){ return view('pages.tracking',compact('track')); } else{ $notification=array( 'messege'=>'Status Code Invalid ', 'alert-type'=>'error' ); return Redirect()->back()->with($notification); } } public function contact(){ $contact=Site_Setting::all()->first(); return view('pages.contact',compact('contact')); } public function sendContact(Request $request){ $contact=new Contact(); $contact->name=$request->name; $contact->email=$request->email; $contact->phone=$request->phone; $contact->message=$request->message; $contact->save(); $notification=array( 'messege'=>'Thanx For Contacting Us ', 'alert-type'=>'success' ); return Redirect()->back()->with($notification); } public function search(Request $request){ $item=$request->search; // dd($item); $search=Product::where('product_name','LIKE',"%$item%")->paginate(10); // dd($search); return view('pages.search_result',compact('search')); } public function editProfile(){ $id=auth()->user()->id; $user=User::find($id); // dd($user); return view('pages.edit_profile',compact('user')); } public function updateProfile(Request $request){ $id=auth()->user()->id; $user=User::find($id); $user->name=$request->name; $user->phone=$request->phone; $user->email=$request->email; $user->update(); $notification=array( 'messege'=>'Profile Details Updated Successfully', 'alert-type'=>'success' ); return Redirect()->back()->with($notification); } public function updateProfileImage(Request $request){ $id=auth()->user()->id; $user=User::find($id); $image_one=$request->file('image_one'); if($image_one){ $image_one_name=hexdec(uniqid()).'.'.$image_one->getClientOriginalExtension(); Image::make($image_one)->resize(300,300)->save('public/media/profile_Images/'.$image_one_name); $user->avatar='public/media/Profile_images/'.$image_one_name; } $user->update(); $notification=array( 'messege'=>'Profile Image Changed Successfully', 'alert-type'=>'success' ); return Redirect()->back()->with($notification); } public function productAll(){ $product=Product::Paginate(20); // dd($product); return view('pages.product_all',compact('product')); } public function productFilterPrice(){ $product=Product::orderBy('selling_price','ASC')->paginate(20); // dd($product); return view('pages.product_price',compact('product')); } }
package gistova import ( "fmt" "io" "net/http" ) func bodyWrap(d io.Reader) (rc io.ReadCloser, l int64) { if d == nil { // nil means no body, so return nil rc and zero length return } // if the underlying type has Close, use it rc, ok := d.(io.ReadCloser) if !ok { // otherwise wrap with NopCloser rc = io.NopCloser(d) } // does the underlying type know how much data it has? type hasLen interface{ Len() int } if dl, ok := d.(hasLen); ok { // if so, return that l = int64(dl.Len()) } else { // if not, return -1; http.Request.Write treats -1 as an unknown length l = -1 } return } func httpStatusErr(r *http.Response) error { switch { case r.StatusCode >= 500: return fmt.Errorf("runtime API returned server error: %q", r.Status) case r.StatusCode >= 400: return fmt.Errorf("runtime API returned client error: %q", r.Status) case r.StatusCode >= 300, r.StatusCode < 200: return fmt.Errorf("runtime API returned unexpected HTTP %q", r.Status) } return nil }
import { IHelperSchema } from '../../utils'; export interface Schema extends IHelperSchema { /** * Target platforms to generate helpers for. */ platforms?: string; }
import { Box, Checkbox } from "@chakra-ui/core"; import React from "react"; const Retake = ({ retake, setRetake }) => { return ( <Box> <Checkbox variantColor="green" value={retake} onChange={e => setRetake(!retake)} name="assessment" > Retake </Checkbox> </Box> ); }; export default Retake;
package com.example.mymoviememoir.network.interfaces; /** * A data model belong to a Get request should implement this interface * @author sunkai */ public interface RestfulGetModel extends RestfulParameterModel { }
CREATE OR REPLACE TRIGGER TRIG_VDSMS_METAINFO AFTER INSERT ON VerDatasetMetaString FOR EACH ROW BEGIN INSERT INTO DatasetMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'S' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM DatasetMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'S'); END; CREATE OR REPLACE TRIGGER TRIG_VDSMN_METAINFO AFTER INSERT ON VerDatasetMetaNumber FOR EACH ROW BEGIN INSERT INTO DatasetMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'N' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM DatasetMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'N'); END; CREATE OR REPLACE TRIGGER TRIG_VDSMT_METAINFO AFTER INSERT ON VerDatasetMetaTimestamp FOR EACH ROW BEGIN INSERT INTO DatasetMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'T' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM DatasetMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'T'); END; CREATE OR REPLACE TRIGGER TRIG_DSCMS_METAINFO AFTER INSERT ON LogicalFolderMetaString FOR EACH ROW BEGIN INSERT INTO ContainerMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'S' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ContainerMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'S'); END; CREATE OR REPLACE TRIGGER TRIG_DSCMN_METAINFO AFTER INSERT ON LogicalFolderMetaNumber FOR EACH ROW BEGIN INSERT INTO ContainerMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'N' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ContainerMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'N'); END; CREATE OR REPLACE TRIGGER TRIG_DSCMT_METAINFO AFTER INSERT ON LogicalFolderMetaTimestamp FOR EACH ROW BEGIN INSERT INTO ContainerMetaInfo (MetaName, ValueType) SELECT :new.MetaName, 'T' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ContainerMetaInfo d WHERE d.MetaName = :new.MetaName and d.ValueType = 'T'); END;
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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. """ A threadpool to process incomming messages over MPI with a fixed number of (already running) threads. Based on threadpool implementation found at http://stackoverflow.com/ questions/3033952/python-thread-pool-similar-to-the-multiprocessing-pool """ try: import Queue as queue except ImportError: import queue from threading import Thread class Worker(Thread): """Thread executing tasks from a given tasks queue""" def __init__(self, tasks): """ Constructor :param tasks: queue containing tasks to execute """ Thread.__init__(self) self.tasks = tasks self.daemon = True self.start() def run(self): """ Run the worker thread """ while 1: func, args, kargs = self.tasks.get() try: func(*args, **kargs) except Exception as e: print(e) finally: self.tasks.task_done() class ThreadPool(object): """Pool of threads consuming tasks from a queue""" def __init__(self, num_threads): """ Constructor :param num_threads: number of threads to start """ self.tasks = queue.Queue() self.num_threads = num_threads for _ in range(num_threads): Worker(self.tasks) def __setstate__(self, state): """ For pickling """ # Obj will be empty, accept it though self.__init__(state) def __getstate__(self): """ For pickling """ # A queue is unpicklable... return self.num_threads def addTask(self, func, *args, **kwargs): """ Add a task to the queue :param func: function to execute """ self.tasks.put((func, args, kwargs))
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.github.fbdo.geomodel; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonProperty; /** * @author <a href="mailto:[email protected]">Fabio Oliveira</a> */ @JsonAutoDetect public class Geometry { public enum Type { ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE } @JsonProperty("location") private GeoCoordinate location; @JsonProperty("location_type") private Type locationType; @JsonProperty("viewport") private BoundingBox viewport; @JsonProperty("bounds") private BoundingBox bounds; public GeoCoordinate getLocation() { return location; } public void setLocation(GeoCoordinate location) { this.location = location; } public Type getLocationType() { return locationType; } public void setLocationType(Type locationType) { this.locationType = locationType; } public BoundingBox getViewport() { return viewport; } public void setViewport(BoundingBox viewport) { this.viewport = viewport; } public BoundingBox getBounds() { return bounds; } public void setBounds(BoundingBox bounds) { this.bounds = bounds; } }
# How do I ... ## ... setup custom Domains w/ SSL? See: [":rocket: __Domains, SSL, & YOU!__"](domains-ssl-you.md) ## ... start up the Healthify Rails app? * Follow the [Readme](github.com/healthify/healthify) in that repo. * Ask for help if you get stuck.
<?php /** * Default theme options. * * @package CoverNews */ if (!function_exists('covernews_get_default_theme_options')): /** * Get default theme options * * @since 1.0.0 * * @return array Default theme options. */ function covernews_get_default_theme_options() { $defaults = array(); // Preloader options section $defaults['enable_site_preloader'] = 1; // Header options section $defaults['header_layout'] = 'header-layout-1'; $defaults['show_top_header_section'] = 0; $defaults['top_header_background_color'] = "#353535"; $defaults['top_header_text_color'] = "#ffffff"; $defaults['show_top_menu'] = 0; $defaults['show_social_menu_section'] = 0; $defaults['disable_sticky_header_option'] = 0; $defaults['show_date_section'] = 0; $defaults['show_minicart_section'] = 1; $defaults['disable_header_image_tint_overlay'] = 0; $defaults['select_header_image_mode'] = 'default'; $defaults['show_offpanel_menu_section'] = 1; $defaults['banner_advertisement_section'] = ''; $defaults['banner_advertisement_section_url'] = ''; $defaults['banner_advertisement_open_on_new_tab'] = 1; $defaults['banner_advertisement_scope'] = 'front-page-only'; // breadcrumb options section $defaults['enable_breadcrumb'] = 0; $defaults['select_breadcrumb_mode'] = 'default'; // Frontpage Section $defaults['show_flash_news_section'] = 1; $defaults['flash_news_title'] = __('Flash Story', 'covernews'); $defaults['select_flash_news_category'] = 0; $defaults['number_of_flash_news'] = 5; $defaults['show_main_news_section'] = 1; $defaults['main_news_slider_title'] = __('Main Story', 'covernews'); $defaults['select_slider_news_category'] = 0; $defaults['select_main_banner_section_mode'] = 'slider-editors-picks-trending'; $defaults['select_main_banner_section_order_1'] = 'order-1'; $defaults['select_main_banner_section_order_2'] = 'order-1'; $defaults['number_of_slides'] = 5; $defaults['editors_picks_title'] = __("Editor's Picks", 'covernews'); $defaults['select_editors_picks_category'] = 0; $defaults['trending_slider_title'] = __("Trending Story", 'covernews'); $defaults['select_trending_news_category'] = 0; $defaults['number_of_trending_slides'] = 5; $defaults['show_featured_news_section'] = 1; $defaults['featured_news_section_title'] = __('Featured Story', 'covernews'); $defaults['select_featured_news_category'] = 0; $defaults['number_of_featured_news'] = 5; $defaults['frontpage_content_alignment'] = 'align-content-left'; $defaults['frontpage_sticky_sidebar'] = 1; $defaults['frontpage_sticky_sidebar_position'] = 'sidebar-sticky-top'; //layout options $defaults['global_content_layout'] = 'default-content-layout'; $defaults['global_content_alignment'] = 'align-content-left'; $defaults['global_single_content_mode'] = 'single-content-mode-default'; $defaults['global_image_alignment'] = 'full-width-image'; $defaults['global_post_date_author_setting'] = 'show-date-author'; $defaults['global_excerpt_length'] = 20; $defaults['global_read_more_texts'] = __('Read more', 'covernews'); $defaults['global_widget_excerpt_setting'] = 'trimmed-content'; $defaults['global_date_display_setting'] = 'theme-date'; $defaults['single_show_featured_image'] = 1; $defaults['archive_layout'] = 'archive-layout-grid'; $defaults['archive_image_alignment'] = 'archive-image-left'; $defaults['archive_content_view'] = 'archive-content-excerpt'; $defaults['disable_main_banner_on_blog_archive'] = 0; //Related posts $defaults['single_show_related_posts'] = 1; $defaults['single_related_posts_title'] = __( 'More Stories', 'covernews' ); //Pagination. $defaults['site_pagination_type'] = 'default'; // Footer. // Latest posts $defaults['frontpage_show_latest_posts'] = 1; $defaults['frontpage_latest_posts_section_title'] = __('You may have missed', 'covernews'); $defaults['site_title_font_size'] = 48; $defaults['footer_copyright_text'] = esc_html__('Copyright &copy; All rights reserved.', 'covernews'); $defaults['hide_footer_menu_section'] = 0; // Pass through filter. $defaults = apply_filters('covernews_filter_default_theme_options', $defaults); return $defaults; } endif;
using FlexOleoTerminais.DAO; using FlexOleoTerminais.Modelos; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace FlexOleoTerminais.Repositorios { public class ComandoRepositorio : IRepositorio<Comando> { private readonly IConfiguration _configuration; public ComandoRepositorio(IConfiguration configuration) { _configuration = configuration; } public async Task<Comando> CreateAsync(Comando entity) { try { var conexao = _configuration.GetConnectionString("Postgres"); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(conexao); using var contexto = new Contexto(optionsBuilder); await contexto.Comandos.AddAsync(entity); await contexto.SaveChangesAsync(); return entity; } catch (Exception e) { throw new Exception($"Impossível criar registro Comando => {e.Message}"); } } public async Task<bool> DeleteAsync(int id) { try { var conexao = _configuration.GetConnectionString("Postgres"); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(conexao); using var contexto = new Contexto(optionsBuilder); var comando = await contexto.Comandos.FindAsync(id); if (comando == null) throw new Exception($"Registro Comando não encontrado"); contexto.Comandos.Remove(comando); await contexto.SaveChangesAsync(); return true; } catch (Exception e) { throw new Exception($"Impossível excluir registro Comando => {e.Message}"); } } public async Task<IEnumerable<Comando>> GetAllAsync() { try { var conexao = _configuration.GetConnectionString("Postgres"); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(conexao); using var contexto = new Contexto(optionsBuilder); return await contexto .Comandos .ToListAsync(); } catch (Exception e) { throw new Exception($"Impossível encontrar registros Comando => {e.Message}"); } } public async Task<Comando> GetAsync(int id) { try { var conexao = _configuration.GetConnectionString("Postgres"); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(conexao); using var contexto = new Contexto(optionsBuilder); return await contexto.Comandos.FindAsync(id); } catch (Exception e) { throw new Exception($"Impossível encontrar registro Comando => {e.Message}"); } } public async Task<Comando> UpdateAsync(Comando entity) { try { var conexao = _configuration.GetConnectionString("Postgres"); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(conexao); using var contexto = new Contexto(optionsBuilder); var comando = await contexto.Comandos.FindAsync(entity.Id); if (comando == null) throw new Exception($"Registro Comando não encontrado"); comando.StringComando = entity.StringComando; await contexto.SaveChangesAsync(); return comando; } catch (Exception e) { throw new Exception($"Impossível editar registro Comando => {e.Message}"); } } } }
""" read_walz(file) Import a Walz GFS-3000 output file. # Examples ```julia file = joinpath(dirname(dirname(pathof(PlantBiophysics))),"test","inputs","data","P1F20129.csv") read_walz(file) ``` """ function read_walz(file) df = CSV.read(file, DataFrame, header = 1, datarow = 3) if hasproperty(df, :Ttop) rename!(df, :Ttop => :Tmin) end df[!,:Comment] = locf(df[!,:Comment]) dropmissing!(df, :VPD) # Renaming variables to fit the standard in the package: rename!( df, :GH2O => :gs, :ca => :Cₐ, :Tcuv => :T, :Pamb => :P, :rh => :Rh, :PARtop => :PPFD, :ci => :Cᵢ, :Comment => :curve ) # Recomputing the variables to fit the units used in the package: df[!,:VPD] = round.(df[:,:VPD] .* df[:,:P] ./ 1000.0, digits = 3) df[!,:gs] = round.(gsw_to_gsc.(df[:,:gs]) ./ 1000.0, digits = 5) df[!,:AVPD] = df[:,:A] ./ (df[:,:Cₐ] .* sqrt.(df[:,:VPD])) df[!,:Rh] = df[!,:Rh] ./ 100.0 return df end
# Stenography # Stenography is a small node application that is useful for testing a series of client requests that expect a 200 response body back. Stenography records all requests coming in (except those to: `/fetch_recording`), simply responding with 200 OK, and an empty body. From there you can call: `/fetch_recording`, and receive all the requests that have been "built up", this then flushes the recorded messages. This was originally created to test a LOG sink. Ensuring the LOG SINK got any messages. ## Build ## ### Requirements ### * Docker ### Building ### Simply run: `docker build -t <my-tag> .` to build an image tagged whatever value you passed in as my-tag. ## Running ## Once you have built an image locally (or just pulled: `securityinsanity/stenography`) you can simply run: `docker run --rm -p 8080:8080 -d <my-tag>` This will spin up stenography, and start it running on port 8080.
(load "../day10/day10.lisp") (defun set-bits (val offset array) (dotimes (bit 8) (setf (elt array (+ (* offset 8) (- 7 bit))) (logand (ash val (- bit)) 1)))) (defun to-bit-array (seq) (let ((arr (make-array (* (length seq) 8) :element-type 'bit :initial-element 0))) (dotimes (i (length seq)) (set-bits (elt seq i) i arr)) arr)) (defun render-row (bits) (dotimes (i (length bits)) (case (elt bits i) (1 (format t "#")) (0 (format t "."))))) (defun get-row-key (key row) (concatenate 'string key (format nil "-~a" row))) (defun generate-memory (key rows) (let ((arr (make-array (* rows 16 8) :element-type 'bit :initial-element 0))) (dotimes (row rows) (let ((val (knot-hash (get-row-key key row)))) (dotimes (i 16) (set-bits (elt val i) (+ (* row 16) i) arr)))) arr)) (defun run-day14a (input) (count 1 (generate-memory input 128))) (defun next-offset (idx len stride direction) (case direction (:n (when (> idx stride) (- idx stride))) (:s (when (< (+ idx stride) len) (+ idx stride))) (:e (unless (= (mod idx stride) (1- stride)) (1+ idx))) (:w (unless (= (mod idx stride) 0) (1- idx))))) (defun flood-clear (idx array stride) (when (and (>= idx 0) (< idx (length array)) (= (elt array idx) 1)) ;;(format t "clearing ~a,~a~%" (mod idx stride) (floor (/ idx stride))) (setf (elt array idx) 0) (let ((n (next-offset idx (length array) stride :n)) (e (next-offset idx (length array) stride :e)) (s (next-offset idx (length array) stride :s)) (w (next-offset idx (length array) stride :w))) (when n (flood-clear n array stride)) (when e (flood-clear e array stride)) (when s (flood-clear s array stride)) (when w (flood-clear w array stride))))) (defun render-grid (grid stride) (dotimes (row (/ (length grid) stride)) (dotimes (col stride) (if (= (elt grid (+ (* row stride) col)) 1) (format t "#") (format t "."))) (format t "~%"))) (defun count-regions (array stride) (do ((candidate (position 1 array) (position 1 array)) (count 0 (1+ count))) ((not candidate) count) ;;(format t "flood-clearing ~a,~a~%" (mod candidate stride) (floor (/ candidate stride))) (flood-clear candidate array stride))) (defun run-day14b (input) (let ((mem (generate-memory input 128))) (count-regions mem 128)))
require File.expand_path(File.dirname(__FILE__) + '/test_helper.rb') class TestFakerMarkdown < Test::Unit::TestCase def setup @tester = Faker::Markdown end def test_headers test_trigger = @tester.headers.split(' ') assert(test_trigger.length == 2) assert(test_trigger.first.include?('#')) end def test_emphasis test_trigger = @tester.emphasis.split('') assert(test_trigger.to_set.intersect?(["_", "~", "*", "**"].to_set)) end def test_ordered_list test_trigger = @tester.ordered_list.split("\n") test_trigger.each do |line| assert_instance_of(Fixnum, line[0].to_i) end end def test_unordered_list test_trigger = @tester.unordered_list.split("\n") test_trigger.each do |line| assert_equal("*", line[0]) end end def test_inline_code test_trigger = @tester.inline_code.split('') assert_equal(test_trigger.first, "`") assert_equal(test_trigger.last, "`") end def test_block_code test_trigger = @tester.block_code.split('') assert_equal(test_trigger[0], "`") assert_equal(test_trigger[1], "`") assert_equal(test_trigger[2], "`") assert_equal(test_trigger[-1], "`") assert_equal(test_trigger[-2], "`") assert_equal(test_trigger[-3], "`") end def test_table test_trigger = @tester.table.split("\n") test_trigger.each do |table_data| assert_instance_of(String, table_data) end assert_equal(test_trigger.length, 3) end def test_random test_trigger = @tester.random assert_instance_of(String, test_trigger) end end
namespace ProtobufMapper { internal class PropertyConfiguration { public ulong Order { get; internal set; } } }
<?php declare(strict_types=1); /* * The MIT License (MIT) * * Copyright (c) 2013 John Judy * * 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. */ namespace Trianglman\Sqrl; /** * Class to hold configurable data for all other SQRL classes */ class SqrlConfiguration { /** * The versions this SQRL server supports * * Defaults to only accepting version 1 * * @var array[]mixed */ protected $acceptedVersions = []; /** * Whether responses to the server should be secure * * Defaults to false * * @var boolean */ protected $secure = false; /** * The domain clients should generate a key for * This can include subdirectories of a web domain in order to allow sites managed * by subdirectories to use different SQRL keying material for the same user * * Required if generating the SQRL URLs and validating responses * * @var string */ protected $domain = ''; /** * Path to the authentication script * This is appended to the $domain value when generating SQRL URLs * * Required if generating SQRL URLs and validating responses * * @var string */ protected $authenticationPath = ''; /** * Whether users are allowed to generate anonymous accounts * * If a user with an unrecognized identification key attempts to authenticate, * should the site accept just the key as a user identification * * Defaults to false * * @var boolean */ protected $anonAllowed = false; /** * Time in minutes that a nonce is considered valid * * Default 5 * * @var int */ protected $nonceMaxAge = 5; /** * Height, in pixels, of a generated QR code * * Default 300 * * @var int */ protected $qrHeight = 300; /** * Padding, in pixels, around a generated QR code * * Default 10 * * @var int */ protected $qrPadding = 10; /** * Random string used to salt generated nonces * * @var string */ protected $nonceSalt = 'random data'; /** * Loads the configuration from the supplied file path * * @param string $filePath The file to load * * @throws \InvalidArgumentException If the file can not be parsed */ public function load(string $filePath): void { try { $this->loadConfigFromJSON($filePath); } catch (\Exception $ex) { throw new \InvalidArgumentException('Configuration data could not be parsed.', 1, $ex); } } protected function loadConfigFromJSON(string $filePath): void { if (!file_exists($filePath)) { throw new \InvalidArgumentException('Configuration file not found'); } $data = file_get_contents($filePath); $decoded = json_decode($data); if (is_null($decoded)) { throw new \InvalidArgumentException('Configuration data could not be parsed. Is it JSON formatted?'); } if (is_array($decoded->accepted_versions)) { $this->setAcceptedVersions($decoded->accepted_versions); } $this->setSecure(!empty($decoded->secure) && (int)$decoded->secure > 0); $this->setDomain($decoded->key_domain ?? ''); $this->setAuthenticationPath($decoded->authentication_path ?? ''); $this->setAnonAllowed( !empty($decoded->allow_anonymous_accounts) && (int)$decoded->allow_anonymous_accounts > 0 ); if (!empty($decoded->nonce_max_age)) { $this->setNonceMaxAge($decoded->nonce_max_age); } if (!empty($decoded->height)) { $this->setQrHeight($decoded->height); } if (!empty($decoded->padding)) { $this->setQrPadding($decoded->padding); } $this->setNonceSalt(!empty($decoded->nonce_salt)?$decoded->nonce_salt:''); } /** * Gets the versions this SQRL server supports * * @return array */ public function getAcceptedVersions(): array { return $this->acceptedVersions; } /** * Gets whether responses to the server should be secure * * @return boolean */ public function getSecure(): bool { return $this->secure; } /** * Gets the domain clients should generate a key for * * @return string */ public function getDomain(): string { return $this->domain; } /** * Gets the path to the authentication script * * @return string */ public function getAuthenticationPath(): string { return $this->authenticationPath; } /** * Gets whether users are allowed to generate anonymous accounts * * @return boolean */ public function getAnonAllowed(): bool { return $this->anonAllowed; } /** * Gets the time in minutes that a nonce is considered valid * * @return int */ public function getNonceMaxAge(): int { return $this->nonceMaxAge; } /** * Gets the height, in pixels, of a generated QR code * * @return int */ public function getQrHeight(): int { return $this->qrHeight; } /** * Gets the padding, in pixels, around a generated QR code * * @return int */ public function getQrPadding(): int { return $this->qrPadding; } /** * Gets the random string used to salt generated nonces * * @return string */ public function getNonceSalt(): string { return $this->nonceSalt; } /** * Sets the versions this SQRL server supports * * @param mixed $acceptedVersions * * @return SqrlConfiguration */ public function setAcceptedVersions($acceptedVersions): SqrlConfiguration { if (is_array($acceptedVersions)) { $this->acceptedVersions = $acceptedVersions; } else { $this->acceptedVersions = [$acceptedVersions]; } return $this; } /** * Sets whether responses to the server should be secure * * @param boolean $secure * * @return SqrlConfiguration */ public function setSecure(bool $secure): SqrlConfiguration { $this->secure = $secure; return $this; } /** * Sets the domain clients should generate a key for * * @param string $domain * * @return SqrlConfiguration */ public function setDomain(string $domain): SqrlConfiguration { $this->domain = $domain; return $this; } /** * Sets the path to the authentication script * * @param string $authenticationPath * * @return SqrlConfiguration */ public function setAuthenticationPath(string $authenticationPath): SqrlConfiguration { $this->authenticationPath = $authenticationPath; return $this; } /** * Sets whether users are allowed to generate anonymous accounts * * @param boolean $anonAllowed * * @return SqrlConfiguration */ public function setAnonAllowed(bool $anonAllowed): SqrlConfiguration { $this->anonAllowed = (bool)$anonAllowed; return $this; } /** * Sets the time in minutes that a nonce is considered valid * * @param int $nonceMaxAge * * @return SqrlConfiguration */ public function setNonceMaxAge(int $nonceMaxAge): SqrlConfiguration { $this->nonceMaxAge = $nonceMaxAge; return $this; } /** * Sets the height, in pixels, of a generated QR code * * @param int $qrHeight * * @return SqrlConfiguration */ public function setQrHeight(int $qrHeight): SqrlConfiguration { $this->qrHeight = $qrHeight; return $this; } /** * Sets the padding, in pixels, around a generated QR code * * @param int $qrPadding * * @return SqrlConfiguration */ public function setQrPadding(int $qrPadding): SqrlConfiguration { $this->qrPadding = $qrPadding; return $this; } /** * Sets the random string used to salt generated nonces * * @param string $nonceSalt * * @return SqrlConfiguration */ public function setNonceSalt(string $nonceSalt): SqrlConfiguration { $this->nonceSalt = $nonceSalt; return $this; } }
// // Copyright 2016 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // // This is similar to the sockaddr resolver, except that it supports a // bunch of query args that are useful for dependency injection in tests. #include <grpc/support/port_platform.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" #include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/parse_address.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/unix_sockets_posix.h" #include "src/core/lib/iomgr/work_serializer.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h" namespace grpc_core { // This cannot be in an anonymous namespace, because it is a friend of // FakeResolverResponseGenerator. class FakeResolver : public Resolver { public: explicit FakeResolver(ResolverArgs args); void StartLocked() override; void RequestReresolutionLocked() override; private: friend class FakeResolverResponseGenerator; friend class FakeResolverResponseSetter; ~FakeResolver() override; void ShutdownLocked() override; void MaybeSendResultLocked(); void ReturnReresolutionResult(); // passed-in parameters grpc_channel_args* channel_args_ = nullptr; RefCountedPtr<FakeResolverResponseGenerator> response_generator_; // If has_next_result_ is true, next_result_ is the next resolution result // to be returned. bool has_next_result_ = false; Result next_result_; // Result to use for the pretended re-resolution in // RequestReresolutionLocked(). bool has_reresolution_result_ = false; Result reresolution_result_; // True after the call to StartLocked(). bool started_ = false; // True after the call to ShutdownLocked(). bool shutdown_ = false; // if true, return failure bool return_failure_ = false; // pending re-resolution bool reresolution_closure_pending_ = false; }; FakeResolver::FakeResolver(ResolverArgs args) : Resolver(std::move(args.work_serializer), std::move(args.result_handler)), response_generator_( FakeResolverResponseGenerator::GetFromArgs(args.args)) { // Channels sharing the same subchannels may have different resolver response // generators. If we don't remove this arg, subchannel pool will create new // subchannels for the same address instead of reusing existing ones because // of different values of this channel arg. const char* args_to_remove[] = {GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR}; channel_args_ = grpc_channel_args_copy_and_remove( args.args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove)); if (response_generator_ != nullptr) { response_generator_->SetFakeResolver(Ref()); } } FakeResolver::~FakeResolver() { grpc_channel_args_destroy(channel_args_); } void FakeResolver::StartLocked() { started_ = true; MaybeSendResultLocked(); } void FakeResolver::RequestReresolutionLocked() { if (has_reresolution_result_ || return_failure_) { next_result_ = reresolution_result_; has_next_result_ = true; // Return the result in a different closure, so that we don't call // back into the LB policy while it's still processing the previous // update. if (!reresolution_closure_pending_) { reresolution_closure_pending_ = true; Ref().release(); // ref held by closure work_serializer()->Run([this]() { ReturnReresolutionResult(); }, DEBUG_LOCATION); } } } void FakeResolver::ShutdownLocked() { shutdown_ = true; if (response_generator_ != nullptr) { response_generator_->SetFakeResolver(nullptr); response_generator_.reset(); } } void FakeResolver::MaybeSendResultLocked() { if (!started_ || shutdown_) return; if (return_failure_) { // TODO(roth): Change resolver result generator to be able to inject // the error to be returned. result_handler()->ReturnError(grpc_error_set_int( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resolver transient failure"), GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNAVAILABLE)); return_failure_ = false; } else if (has_next_result_) { Result result; result.addresses = std::move(next_result_.addresses); result.service_config = std::move(next_result_.service_config); // TODO(roth): Use std::move() once grpc_error is converted to C++. result.service_config_error = next_result_.service_config_error; next_result_.service_config_error = GRPC_ERROR_NONE; // When both next_results_ and channel_args_ contain an arg with the same // name, only the one in next_results_ will be kept since next_results_ is // before channel_args_. result.args = grpc_channel_args_union(next_result_.args, channel_args_); result_handler()->ReturnResult(std::move(result)); has_next_result_ = false; } } void FakeResolver::ReturnReresolutionResult() { reresolution_closure_pending_ = false; MaybeSendResultLocked(); Unref(); } class FakeResolverResponseSetter { public: explicit FakeResolverResponseSetter(RefCountedPtr<FakeResolver> resolver, Resolver::Result result, bool has_result = false, bool immediate = true) : resolver_(std::move(resolver)), result_(std::move(result)), has_result_(has_result), immediate_(immediate) {} void SetResponseLocked(); void SetReresolutionResponseLocked(); void SetFailureLocked(); private: RefCountedPtr<FakeResolver> resolver_; Resolver::Result result_; bool has_result_; bool immediate_; }; // Deletes object when done void FakeResolverResponseSetter::SetReresolutionResponseLocked() { if (!resolver_->shutdown_) { resolver_->reresolution_result_ = std::move(result_); resolver_->has_reresolution_result_ = has_result_; } delete this; } // Deletes object when done void FakeResolverResponseSetter::SetResponseLocked() { if (!resolver_->shutdown_) { resolver_->next_result_ = std::move(result_); resolver_->has_next_result_ = true; resolver_->MaybeSendResultLocked(); } delete this; } // Deletes object when done void FakeResolverResponseSetter::SetFailureLocked() { if (!resolver_->shutdown_) { resolver_->return_failure_ = true; if (immediate_) resolver_->MaybeSendResultLocked(); } delete this; } // // FakeResolverResponseGenerator // FakeResolverResponseGenerator::FakeResolverResponseGenerator() {} FakeResolverResponseGenerator::~FakeResolverResponseGenerator() {} void FakeResolverResponseGenerator::SetResponse(Resolver::Result result) { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); if (resolver_ == nullptr) { has_result_ = true; result_ = std::move(result); return; } resolver = resolver_->Ref(); } FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(resolver, std::move(result)); resolver->work_serializer()->Run([arg]() { arg->SetResponseLocked(); }, DEBUG_LOCATION); } void FakeResolverResponseGenerator::SetReresolutionResponse( Resolver::Result result) { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); GPR_ASSERT(resolver_ != nullptr); resolver = resolver_->Ref(); } FakeResolverResponseSetter* arg = new FakeResolverResponseSetter( resolver, std::move(result), true /* has_result */); resolver->work_serializer()->Run( [arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION); } void FakeResolverResponseGenerator::UnsetReresolutionResponse() { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); GPR_ASSERT(resolver_ != nullptr); resolver = resolver_->Ref(); } FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(resolver, Resolver::Result()); resolver->work_serializer()->Run( [arg]() { arg->SetReresolutionResponseLocked(); }, DEBUG_LOCATION); } void FakeResolverResponseGenerator::SetFailure() { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); GPR_ASSERT(resolver_ != nullptr); resolver = resolver_->Ref(); } FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(resolver, Resolver::Result()); resolver->work_serializer()->Run([arg]() { arg->SetFailureLocked(); }, DEBUG_LOCATION); } void FakeResolverResponseGenerator::SetFailureOnReresolution() { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); GPR_ASSERT(resolver_ != nullptr); resolver = resolver_->Ref(); } FakeResolverResponseSetter* arg = new FakeResolverResponseSetter( resolver, Resolver::Result(), false /* has_result */, false /* immediate */); resolver->work_serializer()->Run([arg]() { arg->SetFailureLocked(); }, DEBUG_LOCATION); } void FakeResolverResponseGenerator::SetFakeResolver( RefCountedPtr<FakeResolver> resolver) { MutexLock lock(&mu_); resolver_ = std::move(resolver); if (resolver_ == nullptr) return; if (has_result_) { FakeResolverResponseSetter* arg = new FakeResolverResponseSetter(resolver_, std::move(result_)); resolver_->work_serializer()->Run([arg]() { arg->SetResponseLocked(); }, DEBUG_LOCATION); has_result_ = false; } } namespace { static void* response_generator_arg_copy(void* p) { FakeResolverResponseGenerator* generator = static_cast<FakeResolverResponseGenerator*>(p); // TODO(roth): We currently deal with this ref manually. Once the // new channel args code is converted to C++, find a way to track this ref // in a cleaner way. RefCountedPtr<FakeResolverResponseGenerator> copy = generator->Ref(); copy.release(); return p; } static void response_generator_arg_destroy(void* p) { FakeResolverResponseGenerator* generator = static_cast<FakeResolverResponseGenerator*>(p); generator->Unref(); } static int response_generator_cmp(void* a, void* b) { return GPR_ICMP(a, b); } static const grpc_arg_pointer_vtable response_generator_arg_vtable = { response_generator_arg_copy, response_generator_arg_destroy, response_generator_cmp}; } // namespace grpc_arg FakeResolverResponseGenerator::MakeChannelArg( FakeResolverResponseGenerator* generator) { grpc_arg arg; arg.type = GRPC_ARG_POINTER; arg.key = const_cast<char*>(GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR); arg.value.pointer.p = generator; arg.value.pointer.vtable = &response_generator_arg_vtable; return arg; } RefCountedPtr<FakeResolverResponseGenerator> FakeResolverResponseGenerator::GetFromArgs(const grpc_channel_args* args) { const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR); if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr; return static_cast<FakeResolverResponseGenerator*>(arg->value.pointer.p) ->Ref(); } // // Factory // namespace { class FakeResolverFactory : public ResolverFactory { public: bool IsValidUri(const grpc_uri* /*uri*/) const override { return true; } OrphanablePtr<Resolver> CreateResolver(ResolverArgs args) const override { return MakeOrphanable<FakeResolver>(std::move(args)); } const char* scheme() const override { return "fake"; } }; } // namespace } // namespace grpc_core void grpc_resolver_fake_init() { grpc_core::ResolverRegistry::Builder::RegisterResolverFactory( absl::make_unique<grpc_core::FakeResolverFactory>()); } void grpc_resolver_fake_shutdown() {}
/** * @license Use of this source code is governed by an MIT-style license that * can be found in the LICENSE file at https://github.com/cartant/eslint-plugin-rxjs */ import { stripIndent } from "common-tags"; import { fromFixture } from "eslint-etc"; import rule = require("../../source/rules/no-unsafe-subject-next"); import { ruleTester } from "../utils"; ruleTester({ types: true }).run("no-unsafe-subject-next", rule, { valid: [ { code: stripIndent` // number next import { Subject } from "rxjs"; const s = new Subject<number>(); s.next(42); `, }, { code: stripIndent` // replay number next import { ReplaySubject } from "rxjs"; const s = new ReplaySubject<number>(); s.next(42); `, }, { code: stripIndent` // any next import { Subject } from "rxjs"; const s = new Subject<any>(); s.next(42); s.next(); `, }, { code: stripIndent` // unknown next import { Subject } from "rxjs"; const s = new Subject<unknown>(); s.next(42); s.next(); `, }, { code: stripIndent` // void next import { Subject } from "rxjs"; const s = new Subject<void>(); s.next(); `, }, { code: stripIndent` // void union next import { Subject } from "rxjs"; const s = new Subject<number | void>(); s.next(42); s.next(); `, }, { code: stripIndent` // https://github.com/cartant/eslint-plugin-rxjs/issues/76 import { Subject } from "rxjs"; const s = new Subject(); s.next(); `, }, ], invalid: [ fromFixture( stripIndent` // optional number next import { Subject } from "rxjs"; const s = new Subject<number>(); s.next(); ~~~~ [forbidden] ` ), fromFixture( stripIndent` // optional replay number next import { ReplaySubject } from "rxjs"; const s = new ReplaySubject<number>(); s.next(); ~~~~ [forbidden] ` ), ], });
#!/usr/bin/env bash # This is process id, parameter passed by user ppid=$1 ps -o pid,ppid -ax | awk "{ if (\$2 == $ppid) { print \$1 }}" | xargs kill -2 >/dev/null
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Models\Client; use Illuminate\Http\Request; class ClientAuthController extends Controller { public function showlog(){ return view('client.login'); } public function clientLogin(Request $request){ $request->validate([ 'phone' => 'required', 'password' => 'required' ]); if(auth('client')->attempt($request->only('phone','password'))) { return redirect()->route('client-index'); } else { return 'data is not correct'; } } public function clientRegister(Request $request){ $request->validate([ 'name' => 'required', 'phone' => 'required', 'email' => 'required', 'password' => 'required|confirmed', 'd_o_b' => 'required', 'blood_type' => 'required', 'city_id' =>'required' ]); $newClient= new Client; //or newClient= new Client; $newClient->name = $request->name; $newClient->phone=$request->phone; $newClient->email=$request->email; $newClient->d_o_b=$request->d_o_b; $newClient->blood_type=$request->blood_type; $newClient->password = bcrypt($request->password); $newClient->city_id=$request->city_id; $newClient->save(); return redirect()->route('signin-account'); } // auth('client')->check($request->only('phone','password')) // true - false //auth('client')->loginUsingId($client->id); //auth()->login($client); public function logout() { auth('client')->logout(); return redirect(route('signin-account')); } }
<?php namespace App\Uploaders; class VideoUploader extends Uploader { public function baseDir() { return config('app.video_upload_path'); } }
module Stripe class CheckoutsController < ApplicationController def show current_user.processor = :stripe current_user.customer @payment = current_user.payment_processor.checkout(mode: "payment", line_items: "price_1ILVZaKXBGcbgpbZQ26kgXWG") @subscription = current_user.payment_processor.checkout(mode: "subscription", line_items: "default") @setup = current_user.payment_processor.checkout(mode: "setup") @portal = current_user.payment_processor.billing_portal(return_url: "http://localhost:3000/stripe/checkout") end end end
from transformers import modeling_bert as mb import torch from torch import nn import math # 15/06/2020 class BertModelNeuron(mb.BertModel): def __init__(self, config): config.output_attentions = True super().__init__(config) self.encoder = mb.BertEncoder(self.config) self.encoder.layer = nn.ModuleList([self.__build_bert_layer() for _ in range(self.config.num_hidden_layers)]) def __build_bert_layer(self): layer = mb.BertLayer(self.config) layer.attention = self.__build_bert_attention() if layer.is_decoder: layer.crossattention = self.__build_bert_attention() return layer def __build_bert_attention(self): attention = mb.BertAttention(self.config) attention.self = BertSelfAttentionNeuron(self.config) return attention class BertSelfAttentionNeuron(mb.BertSelfAttention): def __init__(self, config): super().__init__(config) def forward( self, hidden_states, attention_mask=None, head_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=False): outputs = super().forward(hidden_states, attention_mask=attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_attentions=output_attentions) context_layer, attention_probs = outputs mixed_query_layer = self.query(hidden_states) query_layer = self.transpose_for_scores(mixed_query_layer) mixed_key_layer = self.key(encoder_hidden_states if encoder_hidden_states is not None else hidden_states) key_layer = self.transpose_for_scores(mixed_key_layer) attn_data = { "attn": attention_probs, "queries": query_layer, "keys": key_layer } return context_layer, attn_data
package lt.petuska.kvdom.core.module.hooks import lt.petuska.kvdom.core.domain.* import kotlin.reflect.* private val store = Hooks.store("useState") typealias GetState<T> = () -> T typealias SetState<T> = (value: T) -> Unit class UseStateDelegate<T> internal constructor(val getState: GetState<T>, val setState: SetState<T>) { operator fun getValue(thisRef: Any?, property: KProperty<*>): T { return getState() } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { setState(value) } } @HooksDSL fun <T> VBuilder.useState(initValue: T): UseStateDelegate<T> { val currentIndex = +store.index store[currentIndex] = store[currentIndex] ?: initValue return UseStateDelegate({ @Suppress("UNCHECKED_CAST") store[currentIndex] as T }, { store[currentIndex] = it }) }
/** * @todo Enlarge part of the image to display * @param {String} url * @param {HTMLElement} [children] * @param {String} [className] * @param {Object} [normalStyle={width:600}] Normal display image width and height * Equal scale scaling,You must fill in either width or height * @param {CSSStyleRule} [maskLayerStyle={width:200}] The image shows the mask layer of the area * @param {Number} [multiple=2] The picture in the magnifying glass is several times larger than the original one * @function mouseEvent Mouse trigger event within the picture */ /** * @function mouseEvent * @type {String} [type] * @event event */ import "./index.css"; import React, { useState, useRef, useEffect, useLayoutEffect } from "react"; type Props = { url: string; children?: React.ReactNode; className?: string; normalStyle?: { width?: number; height?: number; }; maskLayerStyle?: { width?: number; height?: number; }; multiple?: number; mouseEvent?: (type?: string, event?: React.MouseEvent<HTMLElement>) => void; }; const MagnifyingGlass: React.FC<Props> = (props) => { const magnifyingGlass = useRef<any>(null); const { url, children, className = "", multiple = 2, normalStyle = { width: 600, }, maskLayerStyle = { width: 200, }, } = props; const __maskLayerStyle = { width: (maskLayerStyle.width || maskLayerStyle.height) as number, height: (maskLayerStyle.height || maskLayerStyle.width) as number, }; const __magnifyingStyle = { width: __maskLayerStyle.width * multiple, height: __maskLayerStyle.height * multiple, }; const [showMagnifying, setShowMagnifying] = useState<boolean>(false); const [magnifyingImg, setMagnifyingImg] = useState<React.CSSProperties>(); const [maskLayer, setMaskLayer] = useState<React.CSSProperties>(__maskLayerStyle); useLayoutEffect(() => { if (normalStyle && !normalStyle.width && !normalStyle.height) { throw new Error("normalStyle must contain either width or height"); } if (maskLayerStyle && !maskLayerStyle.width && !maskLayerStyle.height) { throw new Error("maskLayerStyle must contain either width or height"); } }, []); // Initialize the CSS parameters for the enlarged image useEffect(() => { const img: any = new Image(); img.src = url; img.onload = img.onerror = () => { const { width, height } = normalStyle; const imgHeight = (height || ((width as number) / img.width) * img.height) * multiple; const imgWidth = (width || ((height as number) / img.height) * img.width) * multiple; setMagnifyingImg({ width: imgWidth, height: imgHeight, }); }; }, []); const onMouseEnter = (event: React.MouseEvent<HTMLElement>) => { event.stopPropagation(); event.nativeEvent.stopImmediatePropagation(); if (event.type === "mouseenter" || event.type === "mousemove") { setShowMagnifying(true); const location: any = ( magnifyingGlass.current as HTMLElement ).getBoundingClientRect(); const { width, height, top, left } = location; const { clientX, clientY } = event; const maskLayerWidth = __maskLayerStyle.width; const maskLayerHeight = __maskLayerStyle.height; let offsetY = Math.abs(Math.ceil(clientY - top)); // The position of the mouse in the element let offsetX = Math.abs(Math.ceil(clientX - left)); // The position of the mouse in the element if (offsetY < maskLayerHeight / 2) { offsetY = 0; } else if (offsetY > height - maskLayerHeight / 2) { offsetY = height - maskLayerHeight; } else { offsetY -= maskLayerHeight / 2; } if (offsetX < maskLayerWidth / 2) { offsetX = 0; } else if (offsetX > width - maskLayerWidth / 2) { offsetX = width - maskLayerWidth; } else { offsetX -= maskLayerWidth / 2; } setMagnifyingImg({ ...magnifyingImg, ...{ transform: `translate(-${offsetX * multiple}px,-${ offsetY * multiple }px)`, }, }); setMaskLayer({ ...maskLayer, ...{ top: offsetY, left: offsetX, }, }); } if (event.type === "mouseleave") { setShowMagnifying(false); } if (props.mouseEvent) { props.mouseEvent(event.type, event); } }; return ( <div className={`magnifying-glass ${className}`} style={normalStyle}> <div className="magnifying-glass-normal" onMouseMove={onMouseEnter} onMouseEnter={onMouseEnter} onMouseOver={onMouseEnter} onMouseOut={onMouseEnter} onMouseLeave={onMouseEnter} ref={magnifyingGlass} > <img src={url} alt="" /> </div> {children} <div className={`mask-layer`} style={maskLayer} onMouseMove={onMouseEnter} onMouseLeave={onMouseEnter} /> {showMagnifying ? ( <div className="magnifying-glass-magnifying" style={__magnifyingStyle}> <img src={url} alt="" style={magnifyingImg} /> </div> ) : null} </div> ); }; export default MagnifyingGlass;
#!/bin/bash set -u -e USER=$(whoami) # i3WALLPATH="$HOME/.config/i3/walli3" i3WALLPATH="/media/$USER/projectid/programming/walli3/" if [ -d "$i3WALLPATH" ]; then wallpaperI3="$(find "$i3WALLPATH"/* -type f -name '*.jpg' | sort -R | head -1)" # feh --bg-center "$wallpaperI3" "$HOME"/.local/bin/wal -i "$wallpaperI3" fi
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitForByteSupport { public class PressureModifier { public string pressureCmd; public Double oldPressureValue; public Double newPressureValue; } }
require 'active_resource' class ActiveResource::Connection attr_writer :basic_auth_user, :basic_auth_password def authorization_header if (@basic_auth_user || @basic_auth_pass) build_auth_header(@basic_auth_user, @basic_auth_password) elsif (@site.user || @site.password) # remain backwards compatible build_auth_header(@site.user, @site.password) else {} end end def build_auth_header(user, password) { 'Authorization' => 'Basic ' + ["#{user}:#{password}"].pack('m').delete("\r\n") } end end class ActiveResource::Base def self.auth_as(user, password) connection.basic_auth_user = user connection.basic_auth_password = password end def self.clear_auth connection.basic_auth_user = nil connection.basic_auth_password = nil end end
using Cvl.ApplicationServer.Core.Database.Contexts; using Cvl.ApplicationServer.Core.Model; using Cvl.ApplicationServer.Core.Repositories; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cvl.ApplicationServer.Core.Services { public class BaseService<T, TRepository> where T : BaseEntity where TRepository : IRepository<T> { protected readonly TRepository Repository; public BaseService(TRepository repository) { Repository = repository; } public IQueryable<T> GetAllObjects() { return Repository.GetAll(); } public async Task<T> GetSingleAsync(long processId, bool loadNestedObject = false) { return await Repository.GetSingleAsync(processId); } public async Task UpdateAsync(T entity) { Repository.Update(entity); await Repository.SaveChangesAsync(); } public async Task InsertAsync(T entity) { Repository.Insert(entity); await Repository.SaveChangesAsync(); } } }
Module stateVar_Mod ! Module for loading and validating internal state variables ! Maximum possible state variables defined Integer, parameter :: nstatev_max = 33 ! Stores the state variables Type stateVars Integer :: nstatev ! Number of state variables ! Always stored Double Precision :: d2 ! Cohesive surface damage variable Double Precision :: Fb1 ! Fb = deformation gradient of the bulk material; 1,2,3 are the columns of Fb Double Precision :: Fb2 Double Precision :: Fb3 Double Precision :: Fm1 Double Precision :: Fm2 Double Precision :: Fm3 Double Precision :: B ! Mode mixity Double Precision :: Lc(3) ! Characteristic element lengths Double Precision :: rfT ! Fiber tension damage threshold Double Precision :: FIm ! Failure index for matrix Integer :: alpha ! The cohesive surface normal [degrees, integer]. Only modified in this subroutine if matrix failure criteria is satisfied. Integer :: STATUS ! Element deletion flag (0 := delete element) Double Precision :: Plas12 ! Plastic shear strain Double Precision :: Inel12 ! Inelastic shear strain Double Precision :: Plas13 ! Plastic shear strain Double Precision :: Inel13 ! Inelastic shear strain Double Precision :: slide(2) ! Slip on a cohesive crack, in the fiber and transverse directions Double Precision :: rfC ! Fiber compression damage threshold Double Precision :: d1T ! Fiber tension damage Double Precision :: d1C ! Fiber compression damage Double Precision :: phi0_12 Double Precision :: gamma_12 Double Precision :: phi0_13 Double Precision :: gamma_13 Double Precision :: Sr ! Schapery micro-damage state variable, reduced Double Precision :: direct(9) Double Precision :: Ep_schaefer(6) ! Total plastic strain for schaefer theory Double Precision :: fp ! yield function value Double Precision :: enerPlasOld ! Increment of dissipated plastic energy Double Precision :: enerPlasNew ! Increment of dissipated plastic energy Double Precision :: enerFracOld ! Increment of dissipated fracture energy Double Precision :: enerFracNew ! Increment of dissipated fracture energy ! Calculated once at the start of the analysis, not passed to abaqus ! Since this value depends on phi0, it needs to be a state variable and not global calculated parameter Double Precision :: Inel12c ! Critical plastic strain for fiber failure Double Precision :: Inel13c ! Critical plastic strain for fiber failure ! Stored for debugging only Integer :: debugpy_count Double Precision :: old(nstatev_max) ! Temporary values Double Precision :: Plas12_temp Double Precision :: Inel12_temp Double Precision :: Plas13_temp Double Precision :: Inel13_temp Double Precision :: enerPlas_temp Double Precision :: Sr_temp End Type stateVars Contains Pure Function loadStateVars(nstatev, stateOld, m) result(sv) ! Loads state variables into named fields Use matProp_Mod ! Arguments Integer, intent(IN) :: nstatev Double Precision, intent(IN) :: stateOld(nstatev) Type(matProps), intent(IN) :: m ! Output Type(stateVars) :: sv ! Parameters Double Precision, parameter :: zero=0.d0, one=1.d0 ! -------------------------------------------------------------------- ! sv%nstatev = nstatev sv%old(1:nstatev) = stateOld ! Global variable (not returned to abaqus) sv%Inel12c = Huge(zero) ! Initialize to a large positive number so it is not reached (turns off fiber failure) sv%Inel13c = Huge(zero) ! Initialize to a large positive number so it is not reached (turns off fiber failure) sv%d2 = MAX(zero, stateOld(1)) sv%Fb1 = stateOld(2) sv%Fb2 = stateOld(3) sv%Fb3 = stateOld(4) sv%B = stateOld(5) sv%Lc(1) = stateOld(6) sv%Lc(2) = stateOld(7) sv%Lc(3) = stateOld(8) sv%FIm = zero ! State variable 9 sv%alpha = stateOld(10) sv%STATUS = stateOld(11) If (m%shearNonlinearity12) Then sv%Plas12 = stateOld(12) sv%Inel12 = stateOld(13) sv%Sr = one Else If (m%schapery) Then sv%Plas12 = zero sv%Inel12 = zero sv%Sr = stateOld(12) Else sv%Plas12 = zero sv%Inel12 = zero sv%Sr = one End If IF (m%schaefer) THEN sv%Ep_schaefer(1) = stateOld(27) sv%Ep_schaefer(2) = stateOld(28) sv%Ep_schaefer(3) = stateOld(29) sv%Ep_schaefer(4) = stateOld(30) sv%Ep_schaefer(5) = stateOld(31) sv%Ep_schaefer(6) = stateOld(32) sv%fp = stateOld(33) ELSE sv%Ep_schaefer(1) = zero sv%Ep_schaefer(2) = zero sv%Ep_schaefer(3) = zero sv%Ep_schaefer(4) = zero sv%Ep_schaefer(5) = zero sv%Ep_schaefer(6) = zero sv%fp = zero END IF sv%rfT = stateOld(14) ! MAX(one, stateOld(14)) sv%slide(1) = stateOld(15) sv%slide(2) = stateOld(16) sv%rfC =stateOld(17) ! IF (m%fiberCompDamBL) Then ! sv%rfC = MAX(one, sv%rfC) ! End If sv%d1T = MAX(zero, stateOld(18)) sv%d1C = zero If (m%fiberCompDamBL) Then sv%d1C = MAX(zero, stateOld(19)) End If If (m%shearNonlinearity13) Then sv%Plas13 = stateOld(20) sv%Inel13 = stateOld(21) Else sv%Plas13 = zero sv%Inel13 = zero End If If (m%fiberCompDamFKT12) Then sv%d1C = MAX(zero, stateOld(19)) sv%phi0_12 = stateOld(22) sv%gamma_12 = stateOld(23) Else sv%phi0_12 = zero sv%gamma_12 = zero End If If (m%fiberCompDamFKT13) Then sv%d1C = MAX(zero, stateOld(19)) sv%phi0_13 = stateOld(24) sv%gamma_13 = stateOld(25) Else sv%phi0_13 = zero sv%gamma_13 = zero End If Return End Function loadStateVars Pure Function storeStateVars(sv, nstatev, m) result(stateNew) ! Returns an array of state variables (calling code should be stateNew = store(nstatev)) Use matProp_Mod ! Arguments Type(stateVars), intent(IN) :: sv Integer, intent(IN) :: nstatev Type(matProps), intent(IN) :: m ! Output Double Precision :: stateNew(nstatev) ! Parameters Double Precision, parameter :: zero=0.d0 ! -------------------------------------------------------------------- ! stateNew(1) = sv%d2 stateNew(2) = sv%Fb1 stateNew(3) = sv%Fb2 stateNew(4) = sv%Fb3 stateNew(5) = sv%B stateNew(6) = sv%Lc(1) stateNew(7) = sv%Lc(2) stateNew(8) = sv%Lc(3) stateNew(9) = sv%FIm stateNew(10) = sv%alpha stateNew(11) = sv%STATUS If (m%shearNonlinearity12) Then stateNew(12) = sv%Plas12 stateNew(13) = sv%Inel12 Else If (m%schapery) Then stateNew(12) = sv%Sr stateNew(13) = zero Else stateNew(12) = zero stateNew(13) = zero End If stateNew(14) = sv%rfT stateNew(15) = sv%slide(1) stateNew(16) = sv%slide(2) stateNew(17) = sv%rfC stateNew(18) = sv%d1T If (m%fiberCompDamBL .OR. m%fiberCompDamFKT12 .OR. m%fiberCompDamFKT13) Then stateNew(19) = sv%d1C Else If (nstatev >= 19) Then stateNew(19) = zero End If If (m%schaefer) Then stateNew(27) = sv%Ep_schaefer(1) stateNew(28) = sv%Ep_schaefer(2) stateNew(29) = sv%Ep_schaefer(3) stateNew(30) = sv%Ep_schaefer(4) stateNew(31) = sv%Ep_schaefer(5) stateNew(32) = sv%Ep_schaefer(6) stateNew(33) = sv%fp ELSE IF (nstatev == 33) THEN stateNew(27) = zero stateNew(28) = zero stateNew(29) = zero stateNew(30) = zero stateNew(31) = zero stateNew(32) = zero stateNew(33) = zero END IF If (m%shearNonlinearity13) Then stateNew(20) = sv%Plas13 stateNew(21) = sv%Inel13 Else If (nstatev > 21) Then stateNew(20) = zero stateNew(21) = zero End If If (m%fiberCompDamFKT12) Then stateNew(22) = sv%phi0_12 stateNew(23) = sv%gamma_12 Else If (nstatev >= 23) Then stateNew(22) = zero stateNew(23) = zero End If If (m%fiberCompDamFKT13) Then stateNew(24) = sv%phi0_13 stateNew(25) = sv%gamma_13 Else If (nstatev >= 25) Then stateNew(24) = zero stateNew(25) = zero End If Return End Function storeStateVars Subroutine initializeTemp(sv, m) ! This function sets all temporary state variables equal to the actual state variable value Use matProp_Mod ! Arguments Type(stateVars), intent(INOUT) :: sv Type(matProps), intent(IN) :: m ! -------------------------------------------------------------------- ! If (m%shearNonlinearity12) Then sv%Plas12_temp = sv%Plas12 sv%Inel12_temp = sv%Inel12 End If If (m%shearNonlinearity13) Then sv%Plas13_temp = sv%Plas13 sv%Inel13_temp = sv%Inel13 End If If (m%schapery) Then sv%Sr_temp = sv%Sr End If Return End Subroutine initializeTemp Subroutine finalizeTemp(sv, m) ! This function updates actual state variables to the value of corresponding temporary state variables ! This function is intended to be called once iterations for which temporary state variables were needed ! are complete Use matProp_Mod ! Arguments Type(stateVars), intent(INOUT) :: sv Type(matProps), intent(IN) :: m ! -------------------------------------------------------------------- ! If (m%shearNonlinearity12) Then sv%Plas12 = sv%Plas12_temp sv%Inel12 = sv%Inel12_temp End If If (m%shearNonlinearity13) Then sv%Plas13 = sv%Plas13_temp sv%Inel13 = sv%Inel13_temp End If If (m%schapery) Then sv%Sr = sv%Sr_temp End If Return End Subroutine finalizeTemp Subroutine writeStateVariablesToFile(fileUnit, sv, m) ! Writes provided state variables to a file as a python dictionary ! Assumes that file opening and closing is handled elsewhere Use matProp_Mod ! Arguments Integer, intent(IN) :: fileUnit Type(stateVars), intent(IN) :: sv Type(matProps), intent(IN) :: m ! Locals Character(len=32) :: nameValueFmt Double Precision, parameter :: zero=0.d0 ! -------------------------------------------------------------------- ! ! Defines the format for writing the floating point numbers nameValueFmt = "(A,E21.15E2,A)" ! Write the current state variables write(fileUnit, "(A)") 'sv = [' write(fileUnit, nameValueFmt) ' ', sv%d2, ', # d2' write(fileUnit, nameValueFmt) ' ', sv%Fb1, ', # Fb1' write(fileUnit, nameValueFmt) ' ', sv%Fb2, ', # Fb2' write(fileUnit, nameValueFmt) ' ', sv%Fb3, ', # Fb3' write(fileUnit, nameValueFmt) ' ', sv%B, ', # B' write(fileUnit, nameValueFmt) ' ', sv%Lc(1), ', # Lc1' write(fileUnit, nameValueFmt) ' ', sv%Lc(2), ', # Lc2' write(fileUnit, nameValueFmt) ' ', sv%Lc(3), ', # Lc3' write(fileUnit, nameValueFmt) ' ', sv%FIm, ', # FIm' write(fileUnit, "(A,I5,A)") ' ', sv%alpha, ', # alpha' write(fileUnit, "(A,I1,A)") ' ', sv%STATUS, ', # STATUS' If (m%shearNonlinearity12) Then write(fileUnit, nameValueFmt) ' ', sv%Plas12, ', # Plas12' write(fileUnit, nameValueFmt) ' ', sv%Inel12, ', # Inel12' Else If (m%schapery) Then write(fileUnit, nameValueFmt) ' ', sv%Sr, ', # Sr' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV13' Else write(fileUnit, nameValueFmt) ' ', zero, ', # SDV12' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV13' End If write(fileUnit, nameValueFmt) ' ', sv%rfT, ', # rfT' write(fileUnit, nameValueFmt) ' ', sv%slide(1), ', # slide1' write(fileUnit, nameValueFmt) ' ', sv%slide(2), ', # slide2' write(fileUnit, nameValueFmt) ' ', sv%rfC, ', # rfC' write(fileUnit, nameValueFmt) ' ', sv%d1T, ', # d1T' If (m%fiberCompDamBL .OR. m%fiberCompDamFKT12 .OR. m%fiberCompDamFKT13) Then write(fileUnit, nameValueFmt) ' ', sv%d1C, ', # d1C' Else If (sv%nstatev >= 19) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV19' End If If (m%shearNonlinearity13) Then write(fileUnit, nameValueFmt) ' ', sv%Plas13, ', # Plas13' write(fileUnit, nameValueFmt) ' ', sv%Inel13, ', # Inel13' Else If (sv%nstatev >= 21) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV20' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV21' End If If (m%fiberCompDamFKT12) Then write(fileUnit, nameValueFmt) ' ', sv%phi0_12, ', # phi0_12' write(fileUnit, nameValueFmt) ' ', sv%gamma_12, ', # gamma_12' Else If (sv%nstatev >= 23) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV22' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV23' End If If (m%fiberCompDamFKT13) Then write(fileUnit, nameValueFmt) ' ', sv%phi0_12, ', # phi0_13' write(fileUnit, nameValueFmt) ' ', sv%gamma_12, ', # gamma_13' Else If (sv%nstatev >= 25) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV24' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV25' End If If (sv%nstatev >= 26) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV26' End If If (m%schaefer) Then write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(1), ', # Ep1' write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(2), ', # Ep2' write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(3), ', # Ep3' write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(4), ', # Ep4' write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(5), ', # Ep5' write(fileUnit, nameValueFmt) ' ', sv%Ep_schaefer(6), ', # Ep6' write(fileUnit, nameValueFmt) ' ', sv%fp, ' # fp1' Else If (sv%nstatev >= 33) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV27' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV28' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV29' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV30' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV31' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV32' write(fileUnit, nameValueFmt) ' ', zero, ' #SDV33' End If write(fileUnit, "(A)") ']' ! Write old state variables too #ifndef PYEXT write(fileUnit, "(A)") 'sv_old = [' write(fileUnit, nameValueFmt) ' ', sv%old(1), ', # d2' write(fileUnit, nameValueFmt) ' ', sv%old(2), ', # Fb1' write(fileUnit, nameValueFmt) ' ', sv%old(3), ', # Fb2' write(fileUnit, nameValueFmt) ' ', sv%old(4), ', # Fb3' write(fileUnit, nameValueFmt) ' ', sv%old(5), ', # B' write(fileUnit, nameValueFmt) ' ', sv%old(6), ', # Lc1' write(fileUnit, nameValueFmt) ' ', sv%old(7), ', # Lc2' write(fileUnit, nameValueFmt) ' ', sv%old(8), ', # Lc3' write(fileUnit, nameValueFmt) ' ', sv%old(9), ', # FIm' write(fileUnit, "(A,I5,A)") ' ', INT(sv%old(10)), ', # alpha' write(fileUnit, "(A,I2,A)") ' ', INT(sv%old(11)), ', # STATUS' If (m%shearNonlinearity12) Then write(fileUnit, nameValueFmt) ' ', sv%old(12), ', # Plas12' write(fileUnit, nameValueFmt) ' ', sv%old(13), ', # Inel12' Else If (m%schapery) Then write(fileUnit, nameValueFmt) ' ', sv%old(12), ', # Sr' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV13' Else write(fileUnit, nameValueFmt) ' ', zero, ', # SDV12' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV13' End If write(fileUnit, nameValueFmt) ' ', sv%old(14), ', # rfT' write(fileUnit, nameValueFmt) ' ', sv%old(15), ', # slide1' write(fileUnit, nameValueFmt) ' ', sv%old(16), ', # slide2' write(fileUnit, nameValueFmt) ' ', sv%old(17), ', # rfC' write(fileUnit, nameValueFmt) ' ', sv%old(18), ', # d1T' If (m%fiberCompDamBL .OR. m%fiberCompDamFKT12 .OR. m%fiberCompDamFKT13) Then write(fileUnit, nameValueFmt) ' ', sv%old(19), ', # d1C' Else If (sv%nstatev >= 19) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV19' End If If (m%shearNonlinearity13) Then write(fileUnit, nameValueFmt) ' ', sv%old(20), ', # Plas13' write(fileUnit, nameValueFmt) ' ', sv%old(21), ', # Inel13' Else If (sv%nstatev >= 21) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV20' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV21' End If If (m%fiberCompDamFKT12) Then write(fileUnit, nameValueFmt) ' ', sv%old(22), ', # phi0_12' write(fileUnit, nameValueFmt) ' ', sv%old(23), ', # gamma_12' Else If (sv%nstatev >= 23) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV22' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV23' End If If (m%fiberCompDamFKT13) Then write(fileUnit, nameValueFmt) ' ', sv%old(22), ', # phi0_13' write(fileUnit, nameValueFmt) ' ', sv%old(23), ', # gamma_13' Else If (sv%nstatev >= 25) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV24' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV25' End If If (sv%nstatev >= 26) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV26' End If If (m%schaefer) Then write(fileUnit, nameValueFmt) ' ', sv%old(27), ', # Ep1' write(fileUnit, nameValueFmt) ' ', sv%old(28), ', # Ep2' write(fileUnit, nameValueFmt) ' ', sv%old(29), ', # Ep3' write(fileUnit, nameValueFmt) ' ', sv%old(30), ', # Ep4' write(fileUnit, nameValueFmt) ' ', sv%old(31), ', # Ep5' write(fileUnit, nameValueFmt) ' ', sv%old(32), ', # Ep6' write(fileUnit, nameValueFmt) ' ', sv%old(33), ' # fp1' Else If (sv%nstatev >= 33) Then write(fileUnit, nameValueFmt) ' ', zero, ', # SDV27' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV28' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV29' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV30' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV31' write(fileUnit, nameValueFmt) ' ', zero, ', # SDV32' write(fileUnit, nameValueFmt) ' ', zero, ' # SDV33' End If write(fileUnit, "(A)") ']' #endif Return End Subroutine writeStateVariablesToFile End Module stateVar_Mod
# -------------------------------------------------------------------------- # # Copyright 2002-2021, OpenNebula Project, OpenNebula Systems # # # # Licensed under the Apache License, Version 2.0 (the "License"); you may # # not use this file except in compliance with the License. You may obtain # # a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # #--------------------------------------------------------------------------- # module OneCfg # Transactional operations with configuration files class Transaction attr_accessor :prefix attr_accessor :read_from attr_accessor :unprivileged attr_accessor :no_operation attr_accessor :hook_post_copy def initialize # TODO: move common defaults on a single place @prefix = '/' @read_from = nil @unprivileged = false @no_operation = false @hook_post_copy = nil end # Runs a passed code block on a copy of configuration files in # a transaction-like way. If block finishes successfully, # the changed configuration files are copied back to their # right place. Code gets transactino prefix directory and # file FileOperation object. # # @yield [tr_prefix, fops] Execute custom code with # # @return [Boolean,Nil] True on successful migration. def execute OneCfg::LOG.ddebug("Preparing transaction for prefix '#{@prefix}'") check_symlinks(@prefix) check_symlinks(@read_from) if @read_from ### emergency backup ### <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< backup = backup_dirs ### emergency backup ### <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< tr_prefix = Dir.mktmpdir # copy data from @read_from/@prefix into transaction_prefix # rubocop:disable Style/RedundantCondition OneCfg::Common::Backup.restore_dirs( @read_from ? @read_from : @prefix, OneCfg::CONFIG_BACKUP_DIRS, tr_prefix ) # rubocop:enable Style/RedundantCondition # file operations will be locked to transaction prefix fops = OneCfg::Config::FileOperation.new(tr_prefix, @unprivileged) # run custom code OneCfg::LOG.ddebug("Running transaction in '#{tr_prefix}'") ret = yield(tr_prefix, fops) # in no-operation mode, we finish before copying # changed configuration back if @no_operation OneCfg::LOG.ddebug('Transaction code successful, but ' \ 'executed in no-op mode. Changes will ' \ 'NOT BE SAVED!') OneCfg::LOG.info('Changes ARE NOT saved in no-op mode!') return(ret) end OneCfg::LOG.ddebug('Transaction code successful') # Copy updated configuration back from transaction_prefix # to original @prefix location. Restore on any failure. begin # We copy back from transaction_prefix only CONFIG_UPDATE_DIRS, # which should be a subset of directories we have # backuped. This enables to work with whole remotes/, # but copy back only remotes/etc. OneCfg::Common::Backup.restore_dirs( tr_prefix, OneCfg::CONFIG_UPDATE_DIRS, # <-- !!! @prefix ) if @hook_post_copy OneCfg::LOG.ddebug('Running transaction post-copy hook') @hook_post_copy.call(ret) end rescue StandardError restore_dirs(backup) raise end OneCfg::LOG.ddebug('Transaction done') ret ensure # cleanup temporary transaction directory if defined?(tr_prefix) && !tr_prefix.nil? && File.exist?(tr_prefix) FileUtils.rm_r(tr_prefix) end end private # Checks there are no symlinks in backup directories. # Raise exception in case of error. # # @param custom_prefix [String] Custom prefix to check def check_symlinks(custom_prefix = @prefix) OneCfg::CONFIG_BACKUP_DIRS.each do |dir| pre_dir = OneCfg::Config::Utils.prefixed(dir, custom_prefix) OneCfg::LOG.dddebug("Checking symbolic links in '#{pre_dir}'") Dir["#{pre_dir}/**/**"].each do |f| if File.symlink?(f) raise OneCfg::Config::Exception::FatalError, "Found symbolic links in '#{f}'" end end end end # Backup all dirs inside prefix. This is intended as # backup for emergency cases, when upgrade fails and # we need to revert changes back. # # @return [String] Backup path def backup_dirs backup = OneCfg::Common::Backup.backup_dirs( OneCfg::CONFIG_BACKUP_DIRS, nil, # backup name autogenerated @prefix ) OneCfg::LOG.unknown("Backup stored in '#{backup}'") backup rescue StandardError => e raise OneCfg::Config::Exception::FatalError, "Error making backup due to #{e.message}" end # Restore all dirs inside prefix. This is intended as # restore after upgrade failure of production directories. # # @param backup [String] Backup path def restore_dirs(backup) OneCfg::LOG.unknown('Restoring from backups') OneCfg::Common::Backup.restore_dirs( backup, OneCfg::CONFIG_BACKUP_DIRS, @prefix ) OneCfg::LOG.debug('Restore successful') rescue StandardError msg = 'Fatal error on restore, we are very sorry! ' \ 'You have to restore following directories ' \ 'manually:' OneCfg::CONFIG_BACKUP_DIRS.each do |dir| src = File.join(backup, dir) dst = prefixed(dir) msg << "\n\t- copy #{src} into #{dst}" end OneCfg::LOG.fatal(msg) raise end end end
using System.Threading.Tasks; using Confuser.Core; using Confuser.Core.Project; using Confuser.UnitTest; using Xunit; using Xunit.Abstractions; namespace VisualBasicRenamingResx.Test{ public sealed class RenamingTest : TestBase { public RenamingTest(ITestOutputHelper outputHelper) : base(outputHelper) { } [Fact] [Trait("Category", "Protection")] [Trait("Protection", "rename")] [Trait("Issue", "https://github.com/mkaring/ConfuserEx/issues/25")] public async Task ProtectAndExecuteTest() => await Run("VisualBasicRenamingResx.exe", new[] {"Test (neutral)"}, new SettingItem<Protection>("rename")); } }
using System; using System.Collections.Generic; using System.Text; namespace FlatFileParser.Core.Enums { /// <summary> /// The type of processing to conduct on a line in the file. /// </summary> public enum LineProcessingType { /// <summary> /// Process the entire line. /// </summary> Full, /// <summary> /// Process pieces of the line at a time. /// </summary> Partial } }
<div class="form-group row"> <label class="col-lg-3 col-form-label">Questionnaire:<span class="text-danger">*</span></label> <div class="col-lg-9"> <input type="text" name="question_name" value="{{ old('question_name') }}" class="form-control"> @error('question_name') <span class="text-danger" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label class="col-lg-3 col-form-label">Questionnaire Image:</label> <div class="col-lg-9"> <input type="file" accept="image/gif, image/jpeg, image/png" name="question_image" class="form-control"> </div> </div>
package org.rsultan.bandit.algorithms import kotlin.math.exp import kotlin.math.ln class AnnealedSoftmax(nbArms: Int) : AbstractSoftmaxAlgorithm(nbArms) { override fun selectArm(): Int { val time = counts.sum().toFloat() + 1.0f val temperature = 1.0f / ln(time + 0.0000001f) val sum = values.map { exp(it / temperature) }.sum() val probabilities = values.map { exp(it / temperature) / sum } return categoricalDraw(probabilities) } } class AnnealedSoftmaxAlgorithmBuilder : AlgorithmBuilder<AnnealedSoftmax> { private var nbArms: Int = 2 fun setArms(nbArms: Int): AnnealedSoftmaxAlgorithmBuilder { this.nbArms = nbArms return this } override fun build(): AnnealedSoftmax = AnnealedSoftmax(nbArms) }
package FigureControls; import Utils.XCommand; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class PaintPanel extends JPanel implements MouseListener, MouseMotionListener, KeyListener { private XCommand cmd; private Point point; public String title; FigurePaintPanel current = null; public PaintPanel(XCommand cmd) { this.cmd = cmd; addMouseListener(this); addMouseMotionListener(this); this.addMouseMotionListener(this.cmd.eventListenerStatus); this.setLayout(null); cmd.eventListenerStatus.getListenerDataChange(cmd.data); } protected void setMemento(FigurePaintPanel figure){ if(current != null){ current.deselect(); } current = figure; if(figure != null) current.requestFocus(); } @Override public void mousePressed(MouseEvent e) { point = e.getPoint(); } @Override public void mouseReleased(MouseEvent e) { Rectangle r = new Rectangle(point.x, point.y, e.getX() - point.x, e.getY() - point.y); FigurePaintPanel f = new FigurePaintPanel(r, cmd); f.setBounds(point.x, point.y, e.getX() - point.x, e.getY() - point.y); this.add(f); f.requestFocus(); this.repaint(); } @Override public void mouseClicked(MouseEvent e) { setMemento(null); } @Override public void mouseDragged(MouseEvent e) {} @Override public void mouseMoved(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} }
--- layout: post title: Bintray... The Github of Binaries categories: Tools tags: Java Programming --- Debriefing These are some things I saw in me... and some things I saw in others. This is simply a bunch of cliches, but you don't realize them until you see or do them. I enjoyed beeing involved in the team creation, selection, and so on. Tech (microservices) * Commit to a platform (JVM, CLR). Don't aim to support everything as you would end up supporting nothing. * Do not use the best tools, use the tools that best fit you. For me it is more important for example that you can integrate a tool in your tests, than a few milliseconds in runtime. * Doing it simple is only for the brave... If you do it, well... it was easy, if you fail you are a damn fucking idiot... Be brave to do things easy. Everytime you see something you understand at first sight, think that someone though hard for it to be that way. * Start small, grow fast. start with something that works and build upon it... Better done than perfect. * Share code among components as libraries... but only for platform related things (transversal stuff) * If you try to reuse too much you get coupling. Sometimes less is more. * Something that is great for Google can harm you... know where you stand and who you are, you do not go to war with the army you want, but with the army you got. Plan for your army, do not pretend it to be other. * You NEVER do enough automated tests * Design so what you do is easy to understand for others. * Tools are never valued enough... people see a waste of time in them, a lack of proper tools will slow down people outside IT and inside development, as there will be task that needs to be done by other people that have to be done by developers due to a lack of tools. Managers always see the time it will take to have proper tools, they never see the time saved to other departments and develpment itself. * Documentation. I've got a mix of feelings about this... Do not document something that can be automated, do not think. Ie: the bootstraping of a project can be in the readme, or in a script The minimum? for me is the public API, the contract with the outside world (RPC, events, config parameters) and a readme How you do that is another question. Business * Investor's money is like items in Stephen King's "The shop" * Legacy software should be splitted and rewritten (clean your house before moving out), not repackaged. Workflow * Conway law. It doesn't mean that you build micro services if your team is a complete chaos. * Teams with boundaries develop software with boundaries. It has its drawbacks, but at the end of the day I prefer to be able to change components. * Let people decide their fates, if you impose something on others... Do not force something thinking it will be best... Demochracy is based in the assumption that everyone is represented in the same scale they exist in society, not the majority rule the minorities. * Hero mode development is for weaks, * Good software takes time at the beggining, bad software takes time at the end... Where you want to spend your time depends of the deadlines. * Prefer Scrum over Kanban * Tools matters... get good ones (JIRA, Slack, Google Docs, Gmail) * The easiest the process the less mistakes you'll have, reduce manual operations and documentation, simplify states (usually plan, ready, working, review, test, rejected, done is enough) Personal * Trust what people do, but check if everything is alright * Let people decide * Listen more than talk * Even if you think something is not important, just let everyone know * I should have payed more attention to code reviews * Believe in what you see, not what you ear * Prefer people that code over people that read * Do not give up if you believe in something * Do not trust people that never make mistakes * Do not trust people that laugh about other's work * Read less, think/do more * Check people motivations / goals... Some people want to learn things, others want to make money no matter what * There are good teachers and bad teachers... A good teacher will explain complex things quietly and in an easy way and will assure you actually understood what he explained, a bad teacher will explain things fast, focusing on the details and probably will think you are dumb if you didn't undertood. Good teachers are extreamly hard to find. You do not know how it would be until you try
package com.marknkamau.unipool.domain.authentication import com.google.android.gms.auth.api.signin.GoogleSignInResult interface AuthenticationService { fun signIn(result: GoogleSignInResult, listener: SignInListener) fun signOut(listener: SignOutListener) fun isSignedIn(): Boolean fun currentUserId(): String fun currentUserEmail(): String interface SignOutListener { fun onSuccess() fun onError(reason: String) } interface SignInListener { fun onSuccess(email: String) fun onError(reason: String) } }
# exportlivescript - janklab.mlxshake Export a Matlab Live Script (.mlx) file to Markdown or other formats. mdFile = janklab.mlxshake.exportlivescript(mlxFile, opts) Exports a Matlab Live Script `.mlx` file to Markdown or other presentation file formats. Defaults to Markdown format. Depending on the output format, this may produce multiple output files. InFile (string) is the path to the input Live Script `.mlx` file you want to export. You may omit the `'.mlx'` extension. Opts controls various aspects of exportlivescript's behavior. It is a `janklab.mlxshake.MlxExportOptions` or a cell vector of name/value pairs (which gets turned in to an `MlxExportOptions`). See `MlxExportOptions`' documentation for the available options and their effects. Useful options: * format - The output file format. May be "auto", "markdown", "html", "pdf", "latex", "msword", or maybe more. * outFile - Path to the output file to produce. Defaults to a file of the appropriate extension for the output format in the input directory next to the original input file. Returns the path to the main exported file. There may be other auxiliary files produced; they will be in the folder next to the main output file. What exactly they are and what they are named varies based on the output format. Examples: import janklab.mlxshake.exportlivescript exportlivescript('foo.mlx'); % Write to an alternate location exportlivescript('foo.mlx', {'outFile','/path/to/bar.md'}); % Export a different format, like PDF exportlivescript('foo.mlx', {'format', 'pdf'}); % Output format is automatically selected based on file extension exportlivescript('foo.mlx', {'outFile', 'blah.docx'}); % You can also work with the export options as an object opts = janklab.mlxshake.MlxExportOptions; opts.outFile = '/path/to/bar.md'; opts.keepIntermediateFiles = true; exportlivescript('foo.mlx', opts); See also: MLXEXPORTOPTIONS MLX2LATEX LSLATEX2MARKDOWN
/* * ov23850.c - ov23850 sensor driver * * Copyright (c) 2013-2017, NVIDIA CORPORATION. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/slab.h> #include <linux/uaccess.h> #include <linux/gpio.h> #include <linux/module.h> #include <linux/seq_file.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <media/tegra_v4l2_camera.h> #include <media/tegra-v4l2-camera.h> #include <media/camera_common.h> #include <media/ov23850.h> #include "ov23850_mode_tbls.h" #define CREATE_TRACE_POINTS #include <trace/events/ov23850.h> #define OV23850_MAX_COARSE_DIFF 0x20 #define OV23850_GAIN_SHIFT 8 #define OV23850_MIN_GAIN (1 << OV23850_GAIN_SHIFT) #define OV23850_MAX_GAIN (16 << OV23850_GAIN_SHIFT) #define OV23850_MIN_FRAME_LENGTH (0x0) #define OV23850_MAX_FRAME_LENGTH (0x7fff) #define OV23850_MIN_EXPOSURE_COARSE (0x0002) #define OV23850_MAX_EXPOSURE_COARSE \ (OV23850_MAX_FRAME_LENGTH-OV23850_MAX_COARSE_DIFF) #define OV23850_DEFAULT_GAIN OV23850_MIN_GAIN #define OV23850_DEFAULT_FRAME_LENGTH (0x12C6) #define OV23850_DEFAULT_EXPOSURE_COARSE \ (OV23850_DEFAULT_FRAME_LENGTH-OV23850_MAX_COARSE_DIFF) #define OV23850_DEFAULT_MODE OV23850_MODE_5632X3168 #define OV23850_DEFAULT_WIDTH 5632 #define OV23850_DEFAULT_HEIGHT 3168 #define OV23850_DEFAULT_DATAFMT MEDIA_BUS_FMT_SBGGR10_1X10 #define OV23850_DEFAULT_CLK_FREQ 24000000 struct ov23850 { struct mutex ov23850_camera_lock; struct camera_common_power_rail power; int numctrls; struct v4l2_ctrl_handler ctrl_handler; #if 0 struct camera_common_eeprom_data eeprom[OV23850_EEPROM_NUM_BLOCKS]; u8 eeprom_buf[OV23850_EEPROM_SIZE]; #endif struct i2c_client *i2c_client; struct v4l2_subdev *subdev; struct media_pad pad; u32 frame_length; s32 group_hold_prev; bool group_hold_en; struct regmap *regmap; struct camera_common_data *s_data; struct camera_common_pdata *pdata; struct v4l2_ctrl *ctrls[]; }; static const struct regmap_config sensor_regmap_config = { .reg_bits = 16, .val_bits = 8, .cache_type = REGCACHE_RBTREE, }; static u16 ov23850_to_gain(u32 rep, int shift) { u16 gain; int gain_int; int gain_dec; int min_int = (1 << shift); int step = 1; int num_step; int i; if (rep < 0x0100) rep = 0x0100; else if (rep > 0x0F80) rep = 0x0F80; /* last 4 bit of rep is * decimal representation of gain */ gain_int = (int)(rep >> shift); gain_dec = (int)(rep & ~(0xffff << shift)); for (i = 1; gain_int >> i != 0; i++) ; step = step << (5 - i); num_step = gain_dec * step / min_int; gain = 16 * gain_int + 16 * num_step / step; return gain; } static int ov23850_s_ctrl(struct v4l2_ctrl *ctrl); static const struct v4l2_ctrl_ops ov23850_ctrl_ops = { .s_ctrl = ov23850_s_ctrl, }; static struct v4l2_ctrl_config ctrl_config_list[] = { /* Do not change the name field for the controls! */ { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_GAIN, .name = "Gain", .type = V4L2_CTRL_TYPE_INTEGER, .flags = V4L2_CTRL_FLAG_SLIDER, .min = OV23850_MIN_GAIN, .max = OV23850_MAX_GAIN, .def = OV23850_DEFAULT_GAIN, .step = 1, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_FRAME_LENGTH, .name = "Frame Length", .type = V4L2_CTRL_TYPE_INTEGER, .flags = V4L2_CTRL_FLAG_SLIDER, .min = OV23850_MIN_FRAME_LENGTH, .max = OV23850_MAX_FRAME_LENGTH, .def = OV23850_DEFAULT_FRAME_LENGTH, .step = 1, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_COARSE_TIME, .name = "Coarse Time", .type = V4L2_CTRL_TYPE_INTEGER, .flags = V4L2_CTRL_FLAG_SLIDER, .min = OV23850_MIN_EXPOSURE_COARSE, .max = OV23850_MAX_EXPOSURE_COARSE, .def = OV23850_DEFAULT_EXPOSURE_COARSE, .step = 1, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_COARSE_TIME_SHORT, .name = "Coarse Time Short", .type = V4L2_CTRL_TYPE_INTEGER, .flags = V4L2_CTRL_FLAG_SLIDER, .min = OV23850_MIN_EXPOSURE_COARSE, .max = OV23850_MAX_EXPOSURE_COARSE, .def = OV23850_DEFAULT_EXPOSURE_COARSE, .step = 1, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_GROUP_HOLD, .name = "Group Hold", .type = V4L2_CTRL_TYPE_INTEGER_MENU, .min = 0, .max = ARRAY_SIZE(switch_ctrl_qmenu) - 1, .menu_skip_mask = 0, .def = 0, .qmenu_int = switch_ctrl_qmenu, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_HDR_EN, .name = "HDR enable", .type = V4L2_CTRL_TYPE_INTEGER_MENU, .min = 0, .max = 0, .menu_skip_mask = 0, .def = 0, .qmenu_int = switch_ctrl_qmenu, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_EEPROM_DATA, .name = "EEPROM Data", .type = V4L2_CTRL_TYPE_STRING, .flags = V4L2_CTRL_FLAG_VOLATILE, .min = 0, .max = OV23850_EEPROM_STR_SIZE, .step = 2, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_OTP_DATA, .name = "OTP Data", .type = V4L2_CTRL_TYPE_STRING, .flags = V4L2_CTRL_FLAG_READ_ONLY, .min = 0, .max = OV23850_OTP_STR_SIZE, .step = 2, }, { .ops = &ov23850_ctrl_ops, .id = TEGRA_CAMERA_CID_FUSE_ID, .name = "Fuse ID", .type = V4L2_CTRL_TYPE_STRING, .flags = V4L2_CTRL_FLAG_READ_ONLY, .min = 0, .max = OV23850_FUSE_ID_STR_SIZE, .step = 2, }, }; static inline void ov23850_get_frame_length_regs(ov23850_reg *regs, u32 frame_length) { regs->addr = OV23850_FRAME_LENGTH_ADDR_MSB; regs->val = (frame_length >> 8) & 0x7f; (regs + 1)->addr = OV23850_FRAME_LENGTH_ADDR_LSB; (regs + 1)->val = (frame_length) & 0xff; } static inline void ov23850_get_coarse_time_regs(ov23850_reg *regs, u32 coarse_time) { regs->addr = OV23850_COARSE_TIME_ADDR_MSB; regs->val = (coarse_time >> 8) & 0x7f; (regs + 1)->addr = OV23850_COARSE_TIME_ADDR_LSB; (regs + 1)->val = (coarse_time) & 0xff; } static inline void ov23850_get_coarse_time_short_regs(ov23850_reg *regs, u32 coarse_time) { regs->addr = OV23850_COARSE_TIME_SHORT_ADDR_MSB; regs->val = (coarse_time >> 8) & 0xff; (regs + 1)->addr = OV23850_COARSE_TIME_SHORT_ADDR_LSB; (regs + 1)->val = (coarse_time) & 0xff; } static inline void ov23850_get_gain_reg(ov23850_reg *regs, u16 gain) { regs->addr = OV23850_GAIN_ADDR_MSB; regs->val = (gain >> 8) & 0x07; (regs + 1)->addr = OV23850_GAIN_ADDR_LSB; (regs + 1)->val = (gain) & 0xff; } static inline void ov23850_get_gain_short_reg(ov23850_reg *regs, u16 gain) { regs->addr = OV23850_GAIN_SHORT_ADDR_MSB; regs->val = (gain >> 8) & 0x07; (regs + 1)->addr = OV23850_GAIN_SHORT_ADDR_LSB; (regs + 1)->val = (gain) & 0xff; } static int test_mode; module_param(test_mode, int, 0644); static inline int ov23850_read_reg(struct camera_common_data *s_data, u16 addr, u8 *val) { struct ov23850 *priv = (struct ov23850 *)s_data->priv; int err = 0; u32 reg_val = 0; err = regmap_read(priv->regmap, addr, &reg_val); *val = reg_val & 0xFF; return err; } static int ov23850_write_reg(struct camera_common_data *s_data, u16 addr, u8 val) { int err; struct ov23850 *priv = (struct ov23850 *)s_data->priv; struct device *dev = &priv->i2c_client->dev; err = regmap_write(priv->regmap, addr, val); if (err) dev_err(dev, "%s: i2c write failed, %x = %x\n", __func__, addr, val); return err; } static int ov23850_write_table(struct ov23850 *priv, const ov23850_reg table[]) { return regmap_util_write_table_8(priv->regmap, table, NULL, 0, OV23850_TABLE_WAIT_MS, OV23850_TABLE_END); } static int ov23850_power_on(struct camera_common_data *s_data) { int err = 0; struct ov23850 *priv = (struct ov23850 *)s_data->priv; struct camera_common_power_rail *pw = &priv->power; struct device *dev = &priv->i2c_client->dev; dev_dbg(dev, "%s: power on\n", __func__); if (priv->pdata->power_on) { err = priv->pdata->power_on(pw); if (err) dev_err(dev, "%s failed.\n", __func__); else pw->state = SWITCH_ON; return err; } if (pw->reset_gpio) gpio_set_value(pw->reset_gpio, 0); if (pw->pwdn_gpio) gpio_set_value(pw->pwdn_gpio, 0); usleep_range(10, 20); if (pw->avdd) err = regulator_enable(pw->avdd); if (err) goto ov23850_avdd_fail; if (pw->dvdd) err = regulator_enable(pw->dvdd); if (err) goto ov23850_dvdd_fail; if (pw->iovdd) err = regulator_enable(pw->iovdd); if (err) goto ov23850_iovdd_fail; if (pw->vcmvdd) err = regulator_enable(pw->vcmvdd); if (err) goto ov23850_vcmvdd_fail; if (pw->pwdn_gpio) gpio_set_value(pw->pwdn_gpio, 1); if (pw->reset_gpio) gpio_set_value(pw->reset_gpio, 1); usleep_range(5350, 5360); /* 5ms + 8192 EXTCLK cycles */ pw->state = SWITCH_ON; return 0; ov23850_vcmvdd_fail: regulator_disable(pw->iovdd); ov23850_iovdd_fail: regulator_disable(pw->dvdd); ov23850_dvdd_fail: regulator_disable(pw->avdd); ov23850_avdd_fail: dev_err(dev, "%s failed.\n", __func__); return -ENODEV; } static int ov23850_power_off(struct camera_common_data *s_data) { int err = 0; struct ov23850 *priv = (struct ov23850 *)s_data->priv; struct camera_common_power_rail *pw = &priv->power; struct device *dev = &priv->i2c_client->dev; dev_dbg(dev, "%s: power off\n", __func__); if (priv->pdata->power_off) { err = priv->pdata->power_off(pw); if (!err) goto power_off_done; else dev_err(dev, "%s failed.\n", __func__); return err; } usleep_range(1, 2); if (pw->reset_gpio) gpio_set_value(pw->reset_gpio, 0); if (pw->pwdn_gpio) gpio_set_value(pw->pwdn_gpio, 0); usleep_range(1, 2); if (pw->vcmvdd) regulator_disable(pw->vcmvdd); if (pw->iovdd) regulator_disable(pw->iovdd); if (pw->dvdd) regulator_disable(pw->dvdd); if (pw->avdd) regulator_disable(pw->avdd); power_off_done: pw->state = SWITCH_OFF; return 0; } static int ov23850_power_get(struct ov23850 *priv) { struct camera_common_power_rail *pw = &priv->power; struct camera_common_pdata *pdata = priv->pdata; struct device *dev = &priv->i2c_client->dev; const char *mclk_name; struct clk *parent; int err = 0; mclk_name = priv->pdata->mclk_name ? priv->pdata->mclk_name : "cam_mclk1"; pw->mclk = devm_clk_get(dev, mclk_name); if (IS_ERR(pw->mclk)) { dev_err(dev, "unable to get clock %s\n", mclk_name); return PTR_ERR(pw->mclk); } parent = devm_clk_get(dev, "pllp_grtba"); if (IS_ERR(parent)) dev_err(dev, "devm_clk_get failed for pllp_grtba"); else clk_set_parent(pw->mclk, parent); /* ananlog 2.7v */ err |= camera_common_regulator_get(dev, &pw->avdd, pdata->regulators.avdd); /* digital 1.2v */ err |= camera_common_regulator_get(dev, &pw->dvdd, pdata->regulators.dvdd); /* IO 1.8v */ err |= camera_common_regulator_get(dev, &pw->iovdd, pdata->regulators.iovdd); if (!err) { pw->reset_gpio = pdata->reset_gpio; pw->pwdn_gpio = pdata->pwdn_gpio; } pw->state = SWITCH_OFF; return err; } static int ov23850_set_gain(struct ov23850 *priv, s32 val); static int ov23850_set_frame_length(struct ov23850 *priv, s32 val); static int ov23850_set_coarse_time(struct ov23850 *priv, s32 val); static int ov23850_set_coarse_time_short(struct ov23850 *priv, s32 val); static int ov23850_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct camera_common_data *s_data = to_camera_common_data(&client->dev); struct ov23850 *priv = (struct ov23850 *)s_data->priv; struct v4l2_control control; int err; dev_dbg(&client->dev, "%s++\n", __func__); trace_ov23850_s_stream(sd->name, enable, s_data->mode); if (!enable) { err = ov23850_write_table(priv, mode_table[OV23850_MODE_STOP_STREAM]); if (err) return err; /* Wait for one frame to make sure sensor is set to * software standby in V-blank * * delay = frame length rows * Tline (10 us) */ usleep_range(priv->frame_length * 10, priv->frame_length * 10 + 1000); return 0; } err = ov23850_write_table(priv, mode_table[OV23850_MODE_COMMON]); if (err) goto exit; err = ov23850_write_table(priv, mode_table[s_data->mode]); if (err) goto exit; if (s_data->override_enable) { /* write list of override regs for the asking frame length, */ /* coarse integration time, and gain. */ control.id = TEGRA_CAMERA_CID_GAIN; err = v4l2_g_ctrl(&priv->ctrl_handler, &control); err |= ov23850_set_gain(priv, control.value); if (err) dev_dbg(&client->dev, "%s: error gain override\n", __func__); control.id = TEGRA_CAMERA_CID_FRAME_LENGTH; err = v4l2_g_ctrl(&priv->ctrl_handler, &control); err |= ov23850_set_frame_length(priv, control.value); if (err) dev_dbg(&client->dev, "%s: error frame length override\n", __func__); control.id = TEGRA_CAMERA_CID_COARSE_TIME; err = v4l2_g_ctrl(&priv->ctrl_handler, &control); err |= ov23850_set_coarse_time(priv, control.value); if (err) dev_dbg(&client->dev, "%s: error coarse time override\n", __func__); control.id = TEGRA_CAMERA_CID_COARSE_TIME_SHORT; err = v4l2_g_ctrl(&priv->ctrl_handler, &control); err |= ov23850_set_coarse_time_short(priv, control.value); if (err) dev_dbg(&client->dev, "%s: error coarse time short override\n", __func__); } err = ov23850_write_table(priv, mode_table[OV23850_MODE_START_STREAM]); if (err) goto exit; if (test_mode) err = ov23850_write_table(priv, mode_table[OV23850_MODE_TEST_PATTERN]); return 0; exit: dev_dbg(&client->dev, "%s: error setting stream\n", __func__); return err; } static int ov23850_g_input_status(struct v4l2_subdev *sd, u32 *status) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct camera_common_data *s_data = to_camera_common_data(&client->dev); struct ov23850 *priv = (struct ov23850 *)s_data->priv; struct camera_common_power_rail *pw = &priv->power; *status = pw->state == SWITCH_ON; return 0; } static struct v4l2_subdev_video_ops ov23850_subdev_video_ops = { .s_stream = ov23850_s_stream, .g_mbus_config = camera_common_g_mbus_config, .g_input_status = ov23850_g_input_status, }; static struct v4l2_subdev_core_ops ov23850_subdev_core_ops = { .s_power = camera_common_s_power, }; static int ov23850_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_pad_config *cfg, struct v4l2_subdev_format *format) { return camera_common_g_fmt(sd, &format->format); } static int ov23850_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_pad_config *cfg, struct v4l2_subdev_format *format) { int ret; if (format->which == V4L2_SUBDEV_FORMAT_TRY) ret = camera_common_try_fmt(sd, &format->format); else ret = camera_common_s_fmt(sd, &format->format); return ret; } static struct v4l2_subdev_pad_ops ov23850_subdev_pad_ops = { .set_fmt = ov23850_set_fmt, .get_fmt = ov23850_get_fmt, .enum_mbus_code = camera_common_enum_mbus_code, .enum_frame_size = camera_common_enum_framesizes, .enum_frame_interval = camera_common_enum_frameintervals, }; static struct v4l2_subdev_ops ov23850_subdev_ops = { .core = &ov23850_subdev_core_ops, .video = &ov23850_subdev_video_ops, .pad = &ov23850_subdev_pad_ops, }; const static struct of_device_id ov23850_of_match[] = { { .compatible = "nvidia,ov23850", }, { }, }; static struct camera_common_sensor_ops ov23850_common_ops = { .power_on = ov23850_power_on, .power_off = ov23850_power_off, .write_reg = ov23850_write_reg, .read_reg = ov23850_read_reg, }; static int ov23850_set_group_hold(struct ov23850 *priv) { struct device *dev = &priv->i2c_client->dev; int err; int gh_prev = switch_ctrl_qmenu[priv->group_hold_prev]; if (priv->group_hold_en == true && gh_prev == SWITCH_OFF) { err = ov23850_write_reg(priv->s_data, OV23850_GROUP_HOLD_ADDR, 0x00); if (err) goto fail; priv->group_hold_prev = 1; } else if (priv->group_hold_en == false && gh_prev == SWITCH_ON) { err = ov23850_write_reg(priv->s_data, OV23850_GROUP_HOLD_ADDR, 0x10); err |= ov23850_write_reg(priv->s_data, OV23850_GROUP_HOLD_ADDR, 0xE0); if (err) goto fail; priv->group_hold_prev = 0; } return 0; fail: dev_dbg(dev, "%s: Group hold control error\n", __func__); return err; } static int ov23850_set_gain(struct ov23850 *priv, s32 val) { struct device *dev = &priv->i2c_client->dev; ov23850_reg reg_list[2]; ov23850_reg reg_list_short[2]; int err; u16 gain; int i = 0; /* translate value */ gain = ov23850_to_gain((u32)val, OV23850_GAIN_SHIFT); dev_dbg(dev, "%s: val: %d\n", __func__, gain); ov23850_get_gain_reg(reg_list, gain); ov23850_get_gain_short_reg(reg_list_short, gain); ov23850_set_group_hold(priv); /* writing long gain */ for (i = 0; i < 2; i++) { err = ov23850_write_reg(priv->s_data, reg_list[i].addr, reg_list[i].val); if (err) goto fail; } /* writing short gain */ for (i = 0; i < 2; i++) { err = ov23850_write_reg(priv->s_data, reg_list_short[i].addr, reg_list_short[i].val); if (err) goto fail; } return 0; fail: dev_dbg(dev, "%s: GAIN control error\n", __func__); return err; } static int ov23850_set_frame_length(struct ov23850 *priv, s32 val) { struct device *dev = &priv->i2c_client->dev; ov23850_reg reg_list[2]; int err; u32 frame_length; int i = 0; frame_length = val; dev_dbg(dev, "%s: val: %d\n", __func__, frame_length); ov23850_get_frame_length_regs(reg_list, frame_length); ov23850_set_group_hold(priv); for (i = 0; i < 2; i++) { err = ov23850_write_reg(priv->s_data, reg_list[i].addr, reg_list[i].val); if (err) goto fail; } priv->frame_length = frame_length; return 0; fail: dev_dbg(dev, "%s: FRAME_LENGTH control error\n", __func__); return err; } static int ov23850_set_coarse_time(struct ov23850 *priv, s32 val) { struct device *dev = &priv->i2c_client->dev; ov23850_reg reg_list[2]; int err; u32 coarse_time; int i = 0; coarse_time = val; dev_dbg(dev, "%s: val: %d\n", __func__, coarse_time); ov23850_get_coarse_time_regs(reg_list, coarse_time); ov23850_set_group_hold(priv); for (i = 0; i < 2; i++) { err = ov23850_write_reg(priv->s_data, reg_list[i].addr, reg_list[i].val); if (err) goto fail; } return 0; fail: dev_dbg(dev, "%s: COARSE_TIME control error\n", __func__); return err; } static int ov23850_set_coarse_time_short(struct ov23850 *priv, s32 val) { struct device *dev = &priv->i2c_client->dev; ov23850_reg reg_list[2]; int err; struct v4l2_control hdr_control; int hdr_en; u32 coarse_time_short; int i = 0; /* check hdr enable ctrl */ hdr_control.id = TEGRA_CAMERA_CID_HDR_EN; err = camera_common_g_ctrl(priv->s_data, &hdr_control); if (err < 0) { dev_err(dev, "could not find device ctrl.\n"); return err; } hdr_en = switch_ctrl_qmenu[hdr_control.value]; if (hdr_en == SWITCH_OFF) return 0; coarse_time_short = val; dev_dbg(dev, "%s: val: %d\n", __func__, coarse_time_short); ov23850_get_coarse_time_short_regs(reg_list, coarse_time_short); ov23850_set_group_hold(priv); for (i = 0; i < 2; i++) { err = ov23850_write_reg(priv->s_data, reg_list[i].addr, reg_list[i].val); if (err) goto fail; } return 0; fail: dev_dbg(dev, "%s: COARSE_TIME_SHORT control error\n", __func__); return err; } #if 0 static int ov23850_eeprom_device_release(struct ov23850 *priv) { int i; for (i = 0; i < OV23850_EEPROM_NUM_BLOCKS; i++) { if (priv->eeprom[i].i2c_client != NULL) { i2c_unregister_device(priv->eeprom[i].i2c_client); priv->eeprom[i].i2c_client = NULL; } } return 0; } static int ov23850_eeprom_device_init(struct ov23850 *priv) { char *dev_name = "eeprom_ov23850"; static struct regmap_config eeprom_regmap_config = { .reg_bits = 8, .val_bits = 8, }; int i; int err; for (i = 0; i < OV23850_EEPROM_NUM_BLOCKS; i++) { priv->eeprom[i].adap = i2c_get_adapter( priv->i2c_client->adapter->nr); memset(&priv->eeprom[i].brd, 0, sizeof(priv->eeprom[i].brd)); strncpy(priv->eeprom[i].brd.type, dev_name, sizeof(priv->eeprom[i].brd.type)); priv->eeprom[i].brd.addr = OV23850_EEPROM_ADDRESS + i; priv->eeprom[i].i2c_client = i2c_new_device( priv->eeprom[i].adap, &priv->eeprom[i].brd); priv->eeprom[i].regmap = devm_regmap_init_i2c( priv->eeprom[i].i2c_client, &eeprom_regmap_config); if (IS_ERR(priv->eeprom[i].regmap)) { err = PTR_ERR(priv->eeprom[i].regmap); ov23850_eeprom_device_release(priv); return err; } } return 0; } static int ov23850_read_eeprom(struct ov23850 *priv) { int err, i; struct v4l2_ctrl *ctrl; ctrl = v4l2_ctrl_find(&priv->ctrl_handler, TEGRA_CAMERA_CID_EEPROM_DATA); if (!ctrl) { dev_err(&priv->i2c_client->dev, "could not find device ctrl.\n"); return -EINVAL; } for (i = 0; i < OV23850_EEPROM_NUM_BLOCKS; i++) { err = regmap_bulk_read(priv->eeprom[i].regmap, 0, &priv->eeprom_buf[i * OV23850_EEPROM_BLOCK_SIZE], OV23850_EEPROM_BLOCK_SIZE); if (err) return err; } for (i = 0; i < OV23850_EEPROM_SIZE; i++) sprintf(&ctrl->p_new.p_char[i*2], "%02x", priv->eeprom_buf[i]); return 0; } static int ov23850_write_eeprom(struct ov23850 *priv, char *string) { struct device *dev = &priv->i2c_client->dev; int err; int i; u8 curr[3]; unsigned long data; for (i = 0; i < OV23850_EEPROM_SIZE; i++) { curr[0] = string[i*2]; curr[1] = string[i*2+1]; curr[2] = '\0'; err = kstrtol(curr, 16, &data); if (err) { dev_err(dev, "invalid eeprom string\n"); return -EINVAL; } priv->eeprom_buf[i] = (u8)data; err = regmap_write(priv->eeprom[i >> 8].regmap, i & 0xFF, (u8)data); if (err) return err; msleep(20); } return 0; } #endif static int ov23850_read_otp_manual(struct ov23850 *priv, u8 *buf, u16 addr_start, u16 addr_end) { struct device *dev = &priv->i2c_client->dev; u8 status; int i; int err; int size = addr_end - addr_start + 1; u8 isp; u16 addr_start_capped = addr_start; if (addr_start > 0x6A00) addr_start_capped = 0x69FF; usleep_range(10000, 11000); err = ov23850_write_table(priv, mode_table[OV23850_MODE_START_STREAM]); if (err) return err; err = ov23850_read_reg(priv->s_data, OV23850_OTP_ISP_CTRL_ADDR, &isp); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_ISP_CTRL_ADDR, isp & 0xfe); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_MODE_CTRL_ADDR, 0x40); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_START_REG_ADDR_MSB, (addr_start_capped >> 8) & 0xff); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_START_REG_ADDR_LSB, addr_start_capped & 0xff); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_END_REG_ADDR_MSB, (addr_end >> 8) & 0xff); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_END_REG_ADDR_LSB, addr_end & 0xff); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_LOAD_CTRL_ADDR, 0x01); if (err) return err; usleep_range(10000, 11000); for (i = 0; i < size; i++) { err = ov23850_read_reg(priv->s_data, addr_start + i, &buf[i]); if (err) return err; err = ov23850_read_reg(priv->s_data, OV23850_OTP_LOAD_CTRL_ADDR, &status); if (err) return err; if (status & OV23850_OTP_RD_BUSY_MASK) { dev_err(dev, "another OTP read in progress\n"); return err; } else if (status & OV23850_OTP_BIST_ERROR_MASK) { dev_err(dev, "fuse id read error\n"); return err; } } err = ov23850_write_table(priv, mode_table[OV23850_MODE_STOP_STREAM]); if (err) return err; err = ov23850_read_reg(priv->s_data, OV23850_OTP_ISP_CTRL_ADDR, &isp); if (err) return err; err = ov23850_write_reg(priv->s_data, OV23850_OTP_ISP_CTRL_ADDR, isp | 0x01); if (err) return err; return 0; } static int ov23850_otp_setup(struct ov23850 *priv) { struct device *dev = &priv->i2c_client->dev; int err; int i; struct v4l2_ctrl *ctrl; u8 otp_buf[OV23850_OTP_SIZE]; err = ov23850_read_otp_manual(priv, otp_buf, OV23850_OTP_START_ADDR, OV23850_OTP_END_ADDR); if (err) return -ENODEV; ctrl = v4l2_ctrl_find(&priv->ctrl_handler, TEGRA_CAMERA_CID_OTP_DATA); if (!ctrl) { dev_err(dev, "could not find device ctrl.\n"); return -EINVAL; } for (i = 0; i < OV23850_OTP_SIZE; i++) sprintf(&ctrl->p_new.p_char[i*2], "%02x", otp_buf[i]); ctrl->p_cur.p_char = ctrl->p_new.p_char; return 0; } static int ov23850_fuse_id_setup(struct ov23850 *priv) { struct device *dev = &priv->i2c_client->dev; int err; int i; struct v4l2_ctrl *ctrl; u8 fuse_id[OV23850_FUSE_ID_SIZE]; err = ov23850_read_otp_manual(priv, fuse_id, OV23850_FUSE_ID_OTP_START_ADDR, OV23850_FUSE_ID_OTP_END_ADDR); if (err) return -ENODEV; ctrl = v4l2_ctrl_find(&priv->ctrl_handler, TEGRA_CAMERA_CID_FUSE_ID); if (!ctrl) { dev_err(dev, "could not find device ctrl.\n"); return -EINVAL; } for (i = 0; i < OV23850_FUSE_ID_SIZE; i++) sprintf(&ctrl->p_new.p_char[i*2], "%02x", fuse_id[i]); ctrl->p_cur.p_char = ctrl->p_new.p_char; return 0; } static int ov23850_s_ctrl(struct v4l2_ctrl *ctrl) { struct ov23850 *priv = container_of(ctrl->handler, struct ov23850, ctrl_handler); struct device *dev = &priv->i2c_client->dev; int err = 0; if (priv->power.state == SWITCH_OFF) return 0; switch (ctrl->id) { case TEGRA_CAMERA_CID_GAIN: err = ov23850_set_gain(priv, ctrl->val); break; case TEGRA_CAMERA_CID_FRAME_LENGTH: err = ov23850_set_frame_length(priv, ctrl->val); break; case TEGRA_CAMERA_CID_COARSE_TIME: err = ov23850_set_coarse_time(priv, ctrl->val); break; case TEGRA_CAMERA_CID_COARSE_TIME_SHORT: err = ov23850_set_coarse_time_short(priv, ctrl->val); break; case TEGRA_CAMERA_CID_GROUP_HOLD: if (switch_ctrl_qmenu[ctrl->val] == SWITCH_ON) { priv->group_hold_en = true; } else { priv->group_hold_en = false; err = ov23850_set_group_hold(priv); } break; case TEGRA_CAMERA_CID_HDR_EN: break; default: dev_err(dev, "%s: unknown ctrl id.\n", __func__); return -EINVAL; } return err; } static int ov23850_ctrls_init(struct ov23850 *priv) { struct i2c_client *client = priv->i2c_client; struct v4l2_ctrl *ctrl; int numctrls; int err; int i; dev_dbg(&client->dev, "%s++\n", __func__); numctrls = ARRAY_SIZE(ctrl_config_list); v4l2_ctrl_handler_init(&priv->ctrl_handler, numctrls); for (i = 0; i < numctrls; i++) { ctrl = v4l2_ctrl_new_custom(&priv->ctrl_handler, &ctrl_config_list[i], NULL); if (ctrl == NULL) { dev_err(&client->dev, "Failed to init %s ctrl\n", ctrl_config_list[i].name); continue; } if (ctrl_config_list[i].type == V4L2_CTRL_TYPE_STRING && ctrl_config_list[i].flags & V4L2_CTRL_FLAG_READ_ONLY) { ctrl->p_new.p_char = devm_kzalloc(&client->dev, ctrl_config_list[i].max + 1, GFP_KERNEL); } priv->ctrls[i] = ctrl; } priv->numctrls = numctrls; priv->subdev->ctrl_handler = &priv->ctrl_handler; if (priv->ctrl_handler.error) { dev_err(&client->dev, "Error %d adding controls\n", priv->ctrl_handler.error); err = priv->ctrl_handler.error; goto error; } err = v4l2_ctrl_handler_setup(&priv->ctrl_handler); if (err) { dev_err(&client->dev, "Error %d setting default controls\n", err); goto error; } err = camera_common_s_power(priv->subdev, true); if (err) { dev_err(&client->dev, "Error %d during power on\n", err); err = -ENODEV; goto error; } err = ov23850_otp_setup(priv); if (err) { dev_err(&client->dev, "Error %d reading otp data\n", err); goto error_hw; } err = ov23850_fuse_id_setup(priv); if (err) { dev_err(&client->dev, "Error %d reading fuse id data\n", err); goto error_hw; } camera_common_s_power(priv->subdev, false); return 0; error_hw: camera_common_s_power(priv->subdev, false); error: v4l2_ctrl_handler_free(&priv->ctrl_handler); return err; } MODULE_DEVICE_TABLE(of, ov23850_of_match); static struct camera_common_pdata *ov23850_parse_dt(struct i2c_client *client) { struct device_node *np = client->dev.of_node; struct camera_common_pdata *board_priv_pdata; const struct of_device_id *match; int gpio; int err; match = of_match_device(ov23850_of_match, &client->dev); if (!match) { dev_err(&client->dev, "Failed to find matching dt id\n"); return NULL; } board_priv_pdata = devm_kzalloc(&client->dev, sizeof(*board_priv_pdata), GFP_KERNEL); err = of_property_read_string(np, "mclk", &board_priv_pdata->mclk_name); if (err) { dev_err(&client->dev, "mclk not in DT\n"); goto error; } gpio = of_get_named_gpio(np, "pwdn-gpios", 0); if (gpio < 0) { dev_err(&client->dev, "pwdn gpios not in DT\n"); goto error; } board_priv_pdata->pwdn_gpio = (unsigned int)gpio; gpio = of_get_named_gpio(np, "reset-gpios", 0); if (gpio < 0) { dev_err(&client->dev, "reset gpios not in DT\n"); goto error; } board_priv_pdata->reset_gpio = (unsigned int)gpio; err = of_property_read_string(np, "avdd-reg", &board_priv_pdata->regulators.avdd); if (err) { dev_err(&client->dev, "avdd-reg not in DT\n"); goto error; } err = of_property_read_string(np, "dvdd-reg", &board_priv_pdata->regulators.dvdd); if (err) { dev_err(&client->dev, "dvdd-reg not in DT\n"); goto error; } err = of_property_read_string(np, "iovdd-reg", &board_priv_pdata->regulators.iovdd); if (err) { dev_err(&client->dev, "iovdd-reg not in DT\n"); goto error; } err = of_property_read_string(np, "vcmvdd-reg", &board_priv_pdata->regulators.vcmvdd); if (err) { dev_err(&client->dev, "vcmdd-reg not in DT\n"); goto error; } return board_priv_pdata; error: devm_kfree(&client->dev, board_priv_pdata); return NULL; } static int ov23850_open(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh) { struct i2c_client *client = v4l2_get_subdevdata(sd); dev_dbg(&client->dev, "%s:\n", __func__); return 0; } static const struct v4l2_subdev_internal_ops ov23850_subdev_internal_ops = { .open = ov23850_open, }; static const struct media_entity_operations ov23850_media_ops = { .link_validate = v4l2_subdev_link_validate, }; static int ov23850_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct camera_common_data *common_data; struct ov23850 *priv; int err; dev_info(&client->dev, "probing v4l2 sensor\n"); common_data = devm_kzalloc(&client->dev, sizeof(struct camera_common_data), GFP_KERNEL); priv = devm_kzalloc(&client->dev, sizeof(struct ov23850) + sizeof(struct v4l2_ctrl *) * ARRAY_SIZE(ctrl_config_list), GFP_KERNEL); priv->regmap = devm_regmap_init_i2c(client, &sensor_regmap_config); if (IS_ERR(priv->regmap)) { dev_err(&client->dev, "regmap init failed: %ld\n", PTR_ERR(priv->regmap)); return -ENODEV; } priv->pdata = ov23850_parse_dt(client); if (!priv->pdata) { dev_err(&client->dev, "unable to get platform data\n"); return -EFAULT; } common_data->ops = &ov23850_common_ops; common_data->ctrl_handler = &priv->ctrl_handler; common_data->dev = &client->dev; common_data->frmfmt = &ov23850_frmfmt[0]; common_data->colorfmt = camera_common_find_datafmt( OV23850_DEFAULT_DATAFMT); common_data->power = &priv->power; common_data->ctrls = priv->ctrls; common_data->priv = (void *)priv; common_data->numctrls = ARRAY_SIZE(ctrl_config_list); common_data->numfmts = ARRAY_SIZE(ov23850_frmfmt); common_data->def_mode = OV23850_DEFAULT_MODE; common_data->def_width = OV23850_DEFAULT_WIDTH; common_data->def_height = OV23850_DEFAULT_HEIGHT; common_data->fmt_width = common_data->def_width; common_data->fmt_height = common_data->def_height; common_data->def_clk_freq = OV23850_DEFAULT_CLK_FREQ; priv->i2c_client = client; priv->s_data = common_data; priv->subdev = &common_data->subdev; priv->subdev->dev = &client->dev; priv->s_data->dev = &client->dev; priv->group_hold_prev = 0; err = ov23850_power_get(priv); if (err) return err; err = camera_common_initialize(common_data, "ov23850"); if (err) { dev_err(&client->dev, "Failed to initialize ov23850\n"); return err; } v4l2_i2c_subdev_init(&common_data->subdev, client, &ov23850_subdev_ops); err = ov23850_ctrls_init(priv); if (err) return err; #if 0 /* eeprom interface */ err = ov23850_eeprom_device_init(priv); if (err) dev_err(&client->dev, "Failed to allocate eeprom register map: %d\n", err); #endif priv->subdev->internal_ops = &ov23850_subdev_internal_ops; priv->subdev->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE | V4L2_SUBDEV_FL_HAS_EVENTS; #if defined(CONFIG_MEDIA_CONTROLLER) priv->pad.flags = MEDIA_PAD_FL_SOURCE; priv->subdev->entity.ops = &ov23850_media_ops; err = tegra_media_entity_init(&priv->subdev->entity, 1, &priv->pad, true, true); if (err < 0) { dev_err(&client->dev, "unable to init media entity\n"); return err; } #endif err = v4l2_async_register_subdev(priv->subdev); if (err) return err; dev_info(&client->dev, "Detected OV23850 sensor\n"); return 0; } static int ov23850_remove(struct i2c_client *client) { struct camera_common_data *s_data = to_camera_common_data(&client->dev); struct ov23850 *priv = (struct ov23850 *)s_data->priv; v4l2_async_unregister_subdev(priv->subdev); #if defined(CONFIG_MEDIA_CONTROLLER) media_entity_cleanup(&priv->subdev->entity); #endif v4l2_ctrl_handler_free(&priv->ctrl_handler); camera_common_cleanup(s_data); return 0; } static const struct i2c_device_id ov23850_id[] = { { "ov23850", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ov23850_id); static struct i2c_driver ov23850_i2c_driver = { .driver = { .name = "ov23850", .owner = THIS_MODULE, .of_match_table = of_match_ptr(ov23850_of_match), }, .probe = ov23850_probe, .remove = ov23850_remove, .id_table = ov23850_id, }; module_i2c_driver(ov23850_i2c_driver); MODULE_DESCRIPTION("I2C driver for OmniVision OV23850"); MODULE_AUTHOR("David Wang <[email protected]>"); MODULE_LICENSE("GPL v2");
package com.common.api; import rx.android.schedulers.AndroidSchedulers; import rx.Observable; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; public class RxApiCallHelper { public static <T> Subscription call(Observable<T> observable, final RxApiCallback<T> rxApiCallback) { if (observable == null) { throw new IllegalArgumentException("Observable must not be null."); } if (rxApiCallback == null) { throw new IllegalArgumentException("Callback must not be null."); } return observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .onErrorResumeNext(new Func1<Throwable, Observable<? extends T>>() { @Override public Observable<? extends T> call(Throwable throwable) { return Observable.error(throwable); } }) .onErrorResumeNext(Observable.<T>empty()) .subscribe(new Action1<T>() { @Override public void call(T t) { rxApiCallback.onSuccess(t); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { rxApiCallback.onFailed(throwable.getMessage()); } }); } }
import { ReactNode } from "react"; import { Grid, Paper } from "@material-ui/core"; import { analyze } from "."; interface AnalyzedSectionProps { id?: string; values: any; visible: boolean; type: string; children: ReactNode | Array<ReactNode>; } export const AnalyzedSection = ({ children, values, id, visible, type, }: AnalyzedSectionProps) => { if (!visible) { return <>{children}</>; } return ( <Grid id={id} item> <Paper elevation={3} className="u-padding-15px u-max-width-500px u-center-horizontally" > <Grid container direction="column" spacing={2}> {children} {analyze(type, values)} </Grid> </Paper> </Grid> ); };
/* * Rustの型(文字)。 * CreatedAt: 2019-05-31 */ fn main() { let c1 = 'A'; let c2: char = 'B'; // let c3 = 'AB'; // error: character literal may only contain one codepoint // let c4: char = "A"; // error[E0308]: mismatched types println!("{} {}", c1, c2); if c1 == c2 { println!("c1 == c2"); } else { println!("c1 != c2"); } }
# coding: utf-8 require 'iciba/tools' require 'iciba/fanyi' class String def contains_cjk? !!(self.force_encoding("UTF-8") =~ /\p{Han}/) end end
module.exports = { // ...other vue-cli plugin options... pwa: { name: 'Get Peeps', themeColor: '#fff', msTileColor: '#fff', appleMobileWebAppCapable: 'yes', appleMobileWebAppStatusBarStyle: 'black', // configure the workbox plugin workboxPluginMode: 'GenerateSW', workboxOptions: { runtimeCaching: [ { urlPattern: /^https:\/\/fonts\.gstatic\.com/, handler: 'StaleWhileRevalidate', options: { cacheName: 'google-fonts-webfonts' } } ] } } }
#include "stdafx.h" #include "pseudo_gigant_step_effector.h" CPseudogigantStepEffector::CPseudogigantStepEffector(float time, float amp, float periods, float power) : CEffectorCam(eCEPseudoGigantStep, time) { total = time; max_amp = amp * power; period_number = periods; this->power = power; } BOOL CPseudogigantStepEffector::Process(Fvector &p, Fvector &d, Fvector &n, float& fFov, float& fFar, float& fAspect) { fLifeTime -= Device.fTimeDelta; if(fLifeTime<0) return FALSE; // процент оставшегося времени float time_left_perc = fLifeTime / total; // Инициализация Fmatrix Mdef; Mdef.identity (); Mdef.j.set (n); Mdef.k.set (d); Mdef.i.crossproduct (n,d); Mdef.c.set (p); float period_all = period_number * PI_MUL_2; // макс. значение цикла float k = 1 - time_left_perc + EPS_L + (1 - power); float cur_amp = max_amp * (PI / 180) / (10 * k * k); Fvector dangle; dangle.x = cur_amp/2 * _sin(period_all * (1.0f - time_left_perc)); dangle.y = cur_amp * _cos(period_all/2 * (1.0f - time_left_perc)); dangle.z = cur_amp/4 * _sin(period_all/4 * (1.0f - time_left_perc)); // Установить углы смещения Fmatrix R; R.setHPB (dangle.x,dangle.y,dangle.z); Fmatrix mR; mR.mul (Mdef,R); d.set (mR.k); n.set (mR.j); return TRUE; }