hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
9c3004ce70284d1b413359ec46b505eb946ea06f
2,982
js
JavaScript
src/storage.js
BugDiver/taiko-storage
bbf78fd1a01aa58668d0b64150058da3d348f2bc
[ "MIT" ]
8
2019-09-14T22:42:42.000Z
2021-08-11T16:26:38.000Z
src/storage.js
BugDiver/taiko-storage
bbf78fd1a01aa58668d0b64150058da3d348f2bc
[ "MIT" ]
13
2020-05-05T14:26:58.000Z
2022-02-27T17:30:06.000Z
src/storage.js
BugDiver/taiko-storage
bbf78fd1a01aa58668d0b64150058da3d348f2bc
[ "MIT" ]
3
2020-05-05T08:34:46.000Z
2021-08-10T02:36:14.000Z
let _taiko = null; let _descEmitter = null; class Storage { constructor(type) { this.type = type; } async setItem(key, value, options = {}) { await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.setItem(args.key, JSON.stringify(args.value)); }, { returnByValue: true, args: { type: this.type, key: key, value: value }, ...options }); _descEmitter.emit('success', 'Added "' + key + '" to ' + this.type + ' storage.'); } async clear(options = {}) { await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.clear(); }, { returnByValue: true, args: { type: this.type }, ...options }); _descEmitter.emit('success', 'Cleared ' + this.type + ' storage.'); } async getItem(key, options = {}) { let value = await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.getItem(args.key); }, { returnByValue: true, args: { type: this.type, key: key }, ...options }); _descEmitter.emit('success', 'Retrieve value for "' + key + '" from ' + this.type + ' storage.'); try { return JSON.parse(value); } catch (e) { _descEmitter.emit('success', 'Unable to parse value as JSON for "' + key + '" from ' + this.type + ' storage.'); return value; } } async hasItem(key, options = {}) { let res = await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.hasOwnProperty(args.key); }, { returnByValue: true, args: { type: this.type, key: key }, ...options }); _descEmitter.emit('success', 'The item "' + key + '" is available in ' + this.type + ' storage.'); return res; } async length(key, options = {}) { let res = await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.length; }, { returnByValue: true, args: { type: this.type, key: key, ...options } }); _descEmitter.emit('success', 'The length of ' + this.type + ' storage is ${res}.'); return res; } async removeItem(key, options = {}) { await _taiko.evaluate((_, args) => { let storage = args.type === 'local' ? localStorage : sessionStorage; return storage.removeItem(args.key); }, { returnByValue: true, args: { type: this.type, key: key }, ...options }); _descEmitter.emit('success', 'Removed value for "' + key + '" from ' + this.type + ' storage.'); } _setTaiko(taiko, descEmitter) { _taiko = taiko; _descEmitter = descEmitter; } } module.exports = Storage;
41.416667
125
0.556003
2a420c66ad77974f2a7f015a01e0128c3319dd6b
32,384
java
Java
device/iot-device-client/src/test/java/com/microsoft/azure/sdk/iot/device/transport/https/HttpsTransportManagerTest.java
niklas-sparfeld-gcx/azure-iot-sdk-java
711c236d07a8aecf4d762669899a7d62e4a1d130
[ "MIT" ]
187
2016-11-29T18:05:28.000Z
2022-02-23T06:38:57.000Z
device/iot-device-client/src/test/java/com/microsoft/azure/sdk/iot/device/transport/https/HttpsTransportManagerTest.java
niklas-sparfeld-gcx/azure-iot-sdk-java
711c236d07a8aecf4d762669899a7d62e4a1d130
[ "MIT" ]
1,281
2016-12-09T16:51:06.000Z
2022-03-31T23:56:55.000Z
device/iot-device-client/src/test/java/com/microsoft/azure/sdk/iot/device/transport/https/HttpsTransportManagerTest.java
niklas-sparfeld-gcx/azure-iot-sdk-java
711c236d07a8aecf4d762669899a7d62e4a1d130
[ "MIT" ]
272
2016-11-16T16:22:40.000Z
2022-03-31T11:08:17.000Z
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. package com.microsoft.azure.sdk.iot.device.transport.https; import com.microsoft.azure.sdk.iot.device.*; import com.microsoft.azure.sdk.iot.device.edge.MethodRequest; import com.microsoft.azure.sdk.iot.device.edge.MethodResult; import com.microsoft.azure.sdk.iot.device.exceptions.HubOrDeviceIdNotFoundException; import com.microsoft.azure.sdk.iot.device.exceptions.TransportException; import com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage; import com.microsoft.azure.sdk.iot.device.transport.https.HttpsIotHubConnection; import com.microsoft.azure.sdk.iot.device.transport.https.HttpsMethod; import com.microsoft.azure.sdk.iot.device.transport.https.HttpsSingleMessage; import com.microsoft.azure.sdk.iot.device.transport.https.HttpsTransportManager; import mockit.*; import org.junit.Test; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; /** * Unit test for https transport manager. * 100% methods, 95% lines covered */ public class HttpsTransportManagerTest { @Mocked private DeviceClientConfig mockConfig; @Mocked private HttpsIotHubConnection mockConn; @Mocked private Message mockMsg; @Mocked private IotHubTransportMessage mockTransportMsg; @Mocked private HttpsSingleMessage mockHttpsMessage; @Mocked private ResponseMessage mockResponseMessage; @Mocked private IotHubTransportMessage mockedTransportMessage; @Mocked private MethodRequest mockedMethodRequest; @Mocked private MethodResult mockedMethodResult; /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_001: [The constructor shall store the device client configuration `config`.] */ @Test public void constructorSucceed() { // arrange final DeviceClientConfig config = mockConfig; // act HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, config); // assert assertEquals(config, Deencapsulation.getField(httpsTransportManager, "config")); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_002: [If the provided `config` is null, the constructor shall throws IllegalArgumentException.] */ @Test (expected = IllegalArgumentException.class) public void constructorNullConfig() { // arrange final DeviceClientConfig config = null; // act Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, config); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_003: [The open shall create and store a new transport connection `HttpsIotHubConnection`.] */ @Test public void openSucceed() { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; times = 1; } }; // act Deencapsulation.invoke(httpsTransportManager, "open"); // assert assertNotNull(Deencapsulation.getField(httpsTransportManager, "httpsIotHubConnection")); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_004: [The open shall create and store a new transport connection `HttpsIotHubConnection`.] */ /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_005: [The open shall ignore the parameter `topics`.] */ @Test public void openWithTopicsSucceed() { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String[] topics = new String[]{ "a", "b"}; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; times = 1; } }; // act Deencapsulation.invoke(httpsTransportManager, "open", new Class<?>[] {String[].class}, (Object)topics); // assert assertNotNull(Deencapsulation.getField(httpsTransportManager, "httpsIotHubConnection")); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_006: [The close shall destroy the transport connection `HttpsIotHubConnection`.] */ @Test public void closeSucceed() { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); // act Deencapsulation.invoke(httpsTransportManager, "close"); // assert assertNull(Deencapsulation.getField(httpsTransportManager, "httpsIotHubConnection")); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_007: [The send shall create a new instance of the `HttpMessage`, by parsing the Message with `parseHttpsJsonMessage` from `HttpsSingleMessage`.] */ @Test public void sendCreateHttpMessageSucceed() throws IOException, TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = IotHubMethod.POST; mockTransportMsg.getUriPath(); result = uriPath; httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, (HttpsMethod)any, (String)any, (Map) any); result = mockResponseMessage; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); // assert new Verifications() { { Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); times = 1; } }; } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_008: [If send failed to parse the message, it shall bypass the exception.] */ @Test (expected = IllegalArgumentException.class) public void sendParseHttpsJsonMessageThrows() { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = new IllegalArgumentException(); } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_009: [If the IotHubMethod is `GET`, the send shall set the httpsMethod as `GET`.] */ @Test public void sendMethodGETSucceed() throws IOException, TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = IotHubMethod.GET; mockTransportMsg.getUriPath(); result = uriPath; httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, (HttpsMethod)any, (String)any, (Map) any); result = mockResponseMessage; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); // assert new Verifications() { { httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, HttpsMethod.GET, (String)any, (Map) any); times = 1; } }; } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_010: [If the IotHubMethod is `POST`, the send shall set the httpsMethod as `POST`.] */ @Test public void sendMethodPOSTSucceed() throws IOException, TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = IotHubMethod.POST; mockTransportMsg.getUriPath(); result = uriPath; httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, (HttpsMethod)any, (String)any, (Map) any); result = mockResponseMessage; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); // assert new Verifications() { { httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, HttpsMethod.POST, (String)any, (Map) any); times = 1; } }; } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_011: [If the IotHubMethod is not `GET` or `POST`, the send shall throws IllegalArgumentException.] */ @Test (expected = IllegalArgumentException.class) public void sendInvalidMethodThrows() { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = null; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_012: [The send shall set the httpsPath with the uriPath in the message.] */ /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_013: [The send shall call `sendHttpsMessage` from `HttpsIotHubConnection` to send the message.] */ @Test public void sendSucceed() throws IOException, TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = IotHubMethod.POST; mockTransportMsg.getUriPath(); result = uriPath; httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, (HttpsMethod)any, (String)any, (Map) any); result = mockResponseMessage; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); // assert new Verifications() { { httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, HttpsMethod.POST, uriPath, (Map) any); times = 1; } }; } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_014: [If `sendHttpsMessage` failed, the send shall bypass the exception.] */ @Test (expected = IOException.class) public void sendSendHttpsMessageThrows() throws IOException, TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; Deencapsulation.invoke(HttpsSingleMessage.class, "parseHttpsJsonMessage", new Class[] {Message.class}, mockTransportMsg); result = mockHttpsMessage; mockTransportMsg.getIotHubMethod(); result = IotHubMethod.POST; mockTransportMsg.getUriPath(); result = uriPath; httpsIotHubConnection.sendHttpsMessage(mockHttpsMessage, (HttpsMethod)any, (String)any, (Map) any); result = new IOException(); } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "send", new Class[] {IotHubTransportMessage.class, Map.class}, mockTransportMsg, new HashMap<String, String>()); } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_015: [The receive shall receive and bypass message from `HttpsIotHubConnection`, by calling `receiveMessage`.] */ @Test public void receiveSucceed() throws TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; httpsIotHubConnection.receiveMessage(); result = mockedTransportMessage; } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "receive"); // assert new Verifications() { { httpsIotHubConnection.receiveMessage(); times = 1; } }; } /* Tests_SRS_HTTPSTRANSPORTMANAGER_21_016: [If `receiveMessage` failed, the receive shall bypass the exception.] */ @Test (expected = IOException.class) public void receiveReceiveMessageThrows() throws TransportException { // arrange final HttpsIotHubConnection httpsIotHubConnection = mockConn; final String uriPath = "/files/notifications"; new NonStrictExpectations() { { Deencapsulation.newInstance(HttpsIotHubConnection.class, new Class[] {DeviceClientConfig.class}, mockConfig); result = httpsIotHubConnection; httpsIotHubConnection.receiveMessage(); result = new IOException(); } }; HttpsTransportManager httpsTransportManager = Deencapsulation.newInstance(HttpsTransportManager.class, new Class[] {DeviceClientConfig.class}, mockConfig); Deencapsulation.invoke(httpsTransportManager, "open"); // act Deencapsulation.invoke(httpsTransportManager, "receive"); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_017: [This function shall call invokeMethod with the provided request and // a uri in the format twins/<device id>/modules/<module id>/methods?api-version=<api_version>.] @Test public void invokeMethodOnModuleSuccess() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; final String expectedModuleId = "myModule"; final String expectedSenderDeviceId = "mySenderDevice"; final String expectedSenderModuleId = "mySenderModule"; final String expectedMethodRequestJson = "someJson"; final String expectedResponseBody = "some body"; //assert new Expectations(HttpsTransportManager.class) { { mockedMethodRequest.toJson(); result = expectedMethodRequestJson; new IotHubTransportMessage(expectedMethodRequestJson); result = mockedTransportMessage; mockedTransportMessage.setIotHubMethod(IotHubMethod.POST); mockedTransportMessage.setUriPath("/twins/" + expectedDeviceId + "/modules/" + expectedModuleId +"/methods"); mockConfig.getDeviceId(); result = expectedSenderDeviceId; mockConfig.getModuleId(); result = expectedSenderModuleId; transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; mockResponseMessage.getStatus(); result = IotHubStatusCode.OK_EMPTY; mockResponseMessage.getBytes(); result = expectedResponseBody.getBytes(StandardCharsets.UTF_8); new MethodResult(expectedResponseBody); } }; //act transportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, expectedModuleId); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_018: [If a moduleId is provided, this function shall call invokeMethod with the provided request and // a uri in the format twins/<device id>/modules/<module id>/methods?api-version=<api_version>.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_021: [This function shall set the methodrequest json as the body of the http message.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_022: [This function shall set the http method to POST.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_023: [This function shall set the http message's uri path to the provided uri path.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_024 [This function shall set a custom property of 'x-ms-edge-moduleId' to the value of <device id>/<module id> of the sending module/device.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_025 [This function shall send the built message.] //Tests_SRS_HTTPSTRANSPORTMANAGER_34_027 [If the http response doesn't contain an error code, this function return a method result with the response message body as the method result body.] @Test public void invokeMethodOnDeviceSuccess() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; final String expectedModuleId = "myModule"; final String expectedSenderDeviceId = "mySenderDevice"; final String expectedSenderModuleId = "mySenderModule"; final String expectedMethodRequestJson = "someJson"; final String expectedResponseBody = "some body"; //assert new Expectations(HttpsTransportManager.class) { { mockedMethodRequest.toJson(); result = expectedMethodRequestJson; new IotHubTransportMessage(expectedMethodRequestJson); result = mockedTransportMessage; mockedTransportMessage.setIotHubMethod(IotHubMethod.POST); mockedTransportMessage.setUriPath("/twins/" + expectedDeviceId + "/methods"); mockConfig.getDeviceId(); result = expectedSenderDeviceId; mockConfig.getModuleId(); result = expectedSenderModuleId; transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; mockResponseMessage.getStatus(); result = IotHubStatusCode.OK_EMPTY; mockResponseMessage.getBytes(); result = expectedResponseBody.getBytes(StandardCharsets.UTF_8); new MethodResult(expectedResponseBody); } }; //act transportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, ""); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_019: [If the provided method request is null, this function shall throw an IllegalArgumentException.] @Test (expected = IllegalArgumentException.class) public void invokeMethodThrowsForNullRequest() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; //act transportManager.invokeMethod(null, expectedDeviceId, ""); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_020: [If the provided uri is null or empty, this function shall throw an IllegalArgumentException.] @Test (expected = IllegalArgumentException.class) public void invokeMethodThrowsForNullUri() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; //act Deencapsulation.invoke(transportManager, "invokeMethod", new Class[] {MethodRequest.class, URI.class}, mockedMethodRequest, (URI) null); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_026 [If the http response contains an error code, this function shall throw the associated exception.] @Test (expected = HubOrDeviceIdNotFoundException.class) public void invokeMethodOnDeviceThrowsIfIotHubRespondsWithErrorCode() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; final String expectedSenderDeviceId = "mySenderDevice"; final String expectedSenderModuleId = "mySenderModule"; final String expectedMethodRequestJson = "someJson"; final String expectedResponseBody = "some body"; //assert new Expectations(HttpsTransportManager.class) { { mockedMethodRequest.toJson(); result = expectedMethodRequestJson; new IotHubTransportMessage(expectedMethodRequestJson); result = mockedTransportMessage; mockedTransportMessage.setIotHubMethod(IotHubMethod.POST); mockedTransportMessage.setUriPath("/twins/" + expectedDeviceId + "/methods"); mockConfig.getDeviceId(); result = expectedSenderDeviceId; mockConfig.getModuleId(); result = expectedSenderModuleId; transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; mockResponseMessage.getStatus(); result = IotHubStatusCode.HUB_OR_DEVICE_ID_NOT_FOUND; mockResponseMessage.getBytes(); result = expectedResponseBody.getBytes(StandardCharsets.UTF_8); } }; //act transportManager.invokeMethod(mockedMethodRequest, expectedDeviceId, ""); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_028 [This function shall set the uri path of the provided message to the // format devices/<deviceid>/modules/<moduleid>/files if a moduleId is present or // devices/<deviceid>/modules/<moduleid>/files otherwise, and then send it.] @Test public void sendFileUploadMessageSuccessWithModule() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; final String expectedModuleId = "myModule"; //assert new Expectations(HttpsTransportManager.class) { { mockConfig.getDeviceId(); result = expectedDeviceId; mockConfig.getModuleId(); result = expectedModuleId; mockedTransportMessage.setUriPath("/devices/" + expectedDeviceId + "/modules/" + expectedModuleId + "/files"); transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; } }; //act transportManager.getFileUploadSasUri(mockedTransportMessage); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_028 [This function shall set the uri path of the provided message to the // format devices/<deviceid>/modules/<moduleid>/files if a moduleId is present or // devices/<deviceid>/modules/<moduleid>/files otherwise, and then send it.] @Test public void sendFileUploadMessageSuccessWithoutModule() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; //assert new Expectations(HttpsTransportManager.class) { { mockConfig.getDeviceId(); result = expectedDeviceId; mockConfig.getModuleId(); result = ""; mockedTransportMessage.setUriPath("/devices/" + expectedDeviceId + "/files"); transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; } }; //act transportManager.getFileUploadSasUri(mockedTransportMessage); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_029 [This function shall set the uri path of the provided message to the // format devices/<deviceid>/modules/<moduleid>/files/notifications if a moduleId is present or // devices/<deviceid>/modules/<moduleid>/files/notifications otherwise, and then send it.] @Test public void sendFileUploadNotificationMessageSuccessWithModule() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; final String expectedModuleId = "myModule"; //assert new Expectations(HttpsTransportManager.class) { { mockConfig.getDeviceId(); result = expectedDeviceId; mockConfig.getModuleId(); result = expectedModuleId; mockedTransportMessage.setUriPath("/devices/" + expectedDeviceId + "/modules/" + expectedModuleId + "/files/notifications"); transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; } }; //act transportManager.sendFileUploadNotification(mockedTransportMessage); } //Tests_SRS_HTTPSTRANSPORTMANAGER_34_029 [This function shall set the uri path of the provided message to the // format devices/<deviceid>/modules/<moduleid>/files/notifications if a moduleId is present or // devices/<deviceid>/modules/<moduleid>/files/notifications otherwise, and then send it.] @Test public void sendFileUploadNotificationMessageSuccessWithoutModule() throws TransportException, IOException, URISyntaxException { //arrange final HttpsTransportManager transportManager = new HttpsTransportManager(mockConfig); final String expectedDeviceId = "myDevice"; //assert new Expectations(HttpsTransportManager.class) { { mockConfig.getDeviceId(); result = expectedDeviceId; mockConfig.getModuleId(); result = ""; mockedTransportMessage.setUriPath("/devices/" + expectedDeviceId + "/files/notifications"); transportManager.send(mockedTransportMessage, (Map) any); result = mockResponseMessage; } }; //act transportManager.sendFileUploadNotification(mockedTransportMessage); } }
44.059864
193
0.673388
ca438813d220606603af1c112855d8d3875c37fb
14,934
pkb
SQL
sql/utSQL/source/core/ut_suite_manager.pkb
AnandEmbold/biscuit_5
237b43746c16ff0f9e09d5c58310caa006aafbc2
[ "Apache-2.0" ]
null
null
null
sql/utSQL/source/core/ut_suite_manager.pkb
AnandEmbold/biscuit_5
237b43746c16ff0f9e09d5c58310caa006aafbc2
[ "Apache-2.0" ]
23
2021-06-22T12:47:27.000Z
2022-03-15T08:03:41.000Z
sql/utSQL/source/core/ut_suite_manager.pkb
AnandEmbold/biscuit_5
237b43746c16ff0f9e09d5c58310caa006aafbc2
[ "Apache-2.0" ]
4
2021-02-16T08:31:21.000Z
2022-01-07T13:22:09.000Z
create or replace package body ut_suite_manager is /* utPLSQL - Version 3 Copyright 2016 - 2018 utPLSQL Project Licensed under the Apache License, Version 2.0 (the "License"): you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ subtype tt_schema_suites is ut_suite_builder.tt_schema_suites; subtype t_object_suite_path is ut_suite_builder.t_object_suite_path; subtype t_schema_suites_info is ut_suite_builder.t_schema_suites_info; type t_schema_info is record (changed_at date, obj_cnt integer); type t_schema_cache is record( schema_suites tt_schema_suites ,changed_at date ,obj_cnt integer ,suite_paths t_object_suite_path ); type tt_schema_suites_list is table of t_schema_cache index by varchar2(128 char); g_schema_suites tt_schema_suites_list; type t_schema_paths is table of ut_varchar2_list index by varchar2(4000 char); ------------------ function get_schema_info(a_owner_name varchar2) return t_schema_info is l_info t_schema_info; l_view_name varchar2(200) := ut_metadata.get_dba_view('dba_objects'); begin execute immediate q'[ select nvl(max(t.last_ddl_time), date '4999-12-31'), count(*) from ]'||l_view_name||q'[ t where t.owner = :a_owner_name and t.object_type in ('PACKAGE')]' into l_info using a_owner_name; return l_info; end; procedure update_cache(a_owner_name varchar2, a_suites_info t_schema_suites_info, a_total_obj_cnt integer) is begin if a_suites_info.schema_suites.count > 0 then g_schema_suites(a_owner_name).schema_suites := a_suites_info.schema_suites; g_schema_suites(a_owner_name).changed_at := sysdate; g_schema_suites(a_owner_name).obj_cnt := a_total_obj_cnt; g_schema_suites(a_owner_name).suite_paths := a_suites_info.suite_paths; elsif g_schema_suites.exists(a_owner_name) then g_schema_suites.delete(a_owner_name); end if; end; function cache_valid(a_schema_name varchar2) return boolean is l_info t_schema_info; l_result boolean := true; begin if not g_schema_suites.exists(a_schema_name) then l_result := false; else l_info := get_schema_info(a_schema_name); if g_schema_suites(a_schema_name).changed_at <= l_info.changed_at or g_schema_suites(a_schema_name).obj_cnt != l_info.obj_cnt then l_result := false; else l_result := true; end if; end if; return l_result; end; function get_schema_suites(a_schema_name in varchar2) return t_schema_suites_info is l_result t_schema_suites_info; begin -- Currently cache invalidation on DDL is not implemented so schema is rescaned each time if cache_valid(a_schema_name) then l_result.schema_suites := g_schema_suites(a_schema_name).schema_suites; l_result.suite_paths := g_schema_suites(a_schema_name).suite_paths; else ut_utils.debug_log('Rescanning schema ' || a_schema_name); l_result := ut_suite_builder.build_schema_suites(a_schema_name); update_cache(a_schema_name, l_result, get_schema_info(a_schema_name).obj_cnt ); end if; return l_result; end get_schema_suites; function get_schema_ut_packages(a_schema_names ut_varchar2_rows) return ut_object_names is l_schema_ut_packages ut_object_names := ut_object_names(); l_schema_suites tt_schema_suites; l_iter varchar2(4000); procedure populate_suite_ut_packages(a_suite ut_logical_suite, a_packages in out nocopy ut_object_names) is l_sub_suite ut_logical_suite; begin if a_suite is of (ut_suite) then a_packages.extend; a_packages(a_packages.last) := ut_object_name(a_suite.object_owner, a_suite.object_name); end if; for i in 1 .. a_suite.items.count loop if a_suite.items(i) is of (ut_logical_suite) then l_sub_suite := treat(a_suite.items(i) as ut_logical_suite); populate_suite_ut_packages(l_sub_suite, a_packages); end if; end loop; end; begin if a_schema_names is not null then for i in 1 .. a_schema_names.count loop l_schema_suites := get_schema_suites(a_schema_names(i)).schema_suites; l_iter := l_schema_suites.first; while l_iter is not null loop populate_suite_ut_packages(l_schema_suites(l_iter), l_schema_ut_packages); l_iter := l_schema_suites.next(l_iter); end loop; end loop; l_schema_ut_packages := set(l_schema_ut_packages); end if; return l_schema_ut_packages; end; procedure validate_paths(a_paths in ut_varchar2_list) is l_path varchar2(32767); begin if a_paths is null or a_paths.count = 0 then raise_application_error(ut_utils.gc_path_list_is_empty, 'Path list is empty'); else for i in 1 .. a_paths.count loop l_path := a_paths(i); if l_path is null or not (regexp_like(l_path, '^[A-Za-z0-9$#_]+(\.[A-Za-z0-9$#_]+){0,2}$') or regexp_like(l_path, '^([A-Za-z0-9$#_]+)?:[A-Za-z0-9$#_]+(\.[A-Za-z0-9$#_]+)*$')) then raise_application_error(ut_utils.gc_invalid_path_format, 'Invalid path format: ' || nvl(l_path, 'NULL')); end if; end loop; end if; end; function clean_paths(a_paths ut_varchar2_list) return ut_varchar2_list is l_paths_temp ut_varchar2_list := ut_varchar2_list(); begin l_paths_temp.extend(a_paths.count); for i in 1 .. a_paths.count loop l_paths_temp(i) := trim(lower(a_paths(i))); end loop; return l_paths_temp; end; function resolve_schema_names(a_paths in out nocopy ut_varchar2_list) return ut_varchar2_rows is l_schema varchar2(4000); l_object varchar2(4000); l_schema_names ut_varchar2_rows := ut_varchar2_rows(); c_current_schema constant all_tables.owner%type := sys_context('USERENV','CURRENT_SCHEMA'); begin a_paths := set( clean_paths(a_paths) ); validate_paths(a_paths); for i in 1 .. a_paths.count loop --if path is suite-path if regexp_like(a_paths(i), '^([A-Za-z0-9$#_]+)?:') then --get schema name / path l_schema := regexp_substr(a_paths(i), '^([A-Za-z0-9$#_]+)?:',subexpression => 1); -- transform ":path1[.path2]" to "schema:path1[.path2]" if l_schema is not null then l_schema := sys.dbms_assert.schema_name(upper(l_schema)); else a_paths(i) := c_current_schema || a_paths(i); l_schema := c_current_schema; end if; else -- get schema name / object.[procedure] name -- When path is one of: schema or schema.package[.object] or package[.object] -- transform it back to schema[.package[.object]] begin l_object := regexp_substr(a_paths(i), '^[A-Za-z0-9$#_]+'); l_schema := sys.dbms_assert.schema_name(upper(l_object)); exception when sys.dbms_assert.invalid_schema_name then if ut_metadata.package_exists_in_cur_schema(upper(l_object)) then a_paths(i) := c_current_schema || '.' || a_paths(i); l_schema := c_current_schema; else raise; end if; end; end if; l_schema_names.extend; l_schema_names(l_schema_names.last) := l_schema; end loop; return l_schema_names; end; procedure resolve_schema_names(a_paths in out nocopy ut_varchar2_list) is l_schema_names ut_varchar2_rows; begin l_schema_names := resolve_schema_names(a_paths); end; function get_schema_names(a_paths ut_varchar2_list) return ut_varchar2_rows is l_paths ut_varchar2_list; begin l_paths := a_paths; return resolve_schema_names(l_paths); end; procedure filter_suite_by_path(a_suite in out nocopy ut_suite_item, a_path varchar2) is c_item_name constant varchar2(32767) := lower(regexp_substr(a_path, '[A-Za-z0-9$#_]+')); c_child_filter_path constant varchar2(32767) := regexp_substr(a_path, '\.(.+)', subexpression => 1); l_suite ut_logical_suite; l_item ut_suite_item; l_items ut_suite_items := ut_suite_items(); function find_item_in_suite(a_suite ut_logical_suite, a_item_name varchar2) return ut_suite_item is l_item_index binary_integer; begin l_item_index := a_suite.items.first; while l_item_index is not null loop if lower(a_suite.items(l_item_index).name) = a_item_name then return a_suite.items(l_item_index); end if; l_item_index := a_suite.items.next(l_item_index); end loop; return null; end; function find_item_in_suite_contexts(a_suite ut_logical_suite, a_item_name varchar2) return ut_suite_item is l_item_index binary_integer; l_context ut_suite_context; l_item ut_suite_item; begin l_item_index := a_suite.items.first; while l_item_index is not null loop if a_suite.items(l_item_index) is of (ut_suite_context) then l_item := find_item_in_suite( treat(a_suite.items(l_item_index) as ut_suite_context) , a_item_name ); end if; if l_item is not null then l_context := treat(a_suite.items(l_item_index) as ut_suite_context); l_context.items := ut_suite_items(l_item); exit; end if; l_item_index := a_suite.items.next(l_item_index); end loop; return l_context; end; begin if a_suite is of (ut_logical_suite) then l_suite := treat(a_suite as ut_logical_suite); l_item := coalesce( find_item_in_suite(l_suite, c_item_name) , find_item_in_suite_contexts(l_suite, c_item_name) ); if l_item is not null then if c_child_filter_path is not null then filter_suite_by_path(l_item, c_child_filter_path); end if; l_items.extend; l_items(l_items.count) := l_item; else raise_application_error(-20203, 'Suite item '||c_item_name||' not found'); end if; l_suite.items := l_items; a_suite := l_suite; end if; end filter_suite_by_path; function get_suite_filtered_by_path(a_path varchar2, a_schema_suites tt_schema_suites) return ut_logical_suite is l_suite ut_logical_suite; c_suite_path constant varchar2(32767) := regexp_substr(a_path, ':(.+)', subexpression => 1); c_root_suite_name constant varchar2(32767) := regexp_substr(c_suite_path, '^[A-Za-z0-9$#_]+'); c_child_filter_path constant varchar2(32767) := regexp_substr(c_suite_path, '\.(.+)', subexpression => 1); begin l_suite := a_schema_suites(c_root_suite_name); if c_child_filter_path is not null then filter_suite_by_path(l_suite, c_child_filter_path); end if; return l_suite; exception when no_data_found then raise_application_error(-20203, 'Suite ' || c_root_suite_name || ' does not exist or is invalid'); end; function convert_to_suite_path(a_path varchar2, a_suite_paths t_object_suite_path) return varchar2 is c_package_path_regex constant varchar2(100) := '^([A-Za-z0-9$#_]+)\.([A-Za-z0-9$#_]+)(\.([A-Za-z0-9$#_]+))?$'; l_schema_name varchar2(4000) := regexp_substr(a_path, c_package_path_regex, subexpression => 1); l_package_name varchar2(4000) := regexp_substr(a_path, c_package_path_regex, subexpression => 2); l_procedure_name varchar2(4000) := regexp_substr(a_path, c_package_path_regex, subexpression => 4); l_path varchar2(4000) := a_path; begin if regexp_like(l_path, c_package_path_regex) then if not a_suite_paths.exists(l_package_name) then raise_application_error(ut_utils.gc_suite_package_not_found,'Suite package '||l_schema_name||'.'||l_package_name|| ' not found'); end if; l_path := rtrim(l_schema_name || ':' || a_suite_paths(l_package_name) || '.' || l_procedure_name, '.'); end if; return l_path; end; function group_paths_by_schema(a_paths ut_varchar2_list) return t_schema_paths is l_result t_schema_paths; l_schema varchar2(4000); begin for i in 1 .. a_paths.count loop l_schema := upper(regexp_substr(a_paths(i),'^[^.:]+')); if l_result.exists(l_schema) then l_result(l_schema).extend; l_result(l_schema)(l_result(l_schema).last) := a_paths(i); else l_result(l_schema) := ut_varchar2_list(a_paths(i)); end if; end loop; return l_result; end; function configure_execution_by_path(a_paths in ut_varchar2_list) return ut_suite_items is l_paths ut_varchar2_list := a_paths; l_path varchar2(32767); l_schema varchar2(4000); l_suites_info t_schema_suites_info; l_index varchar2(4000 char); l_suite ut_logical_suite; l_objects_to_run ut_suite_items; l_schema_paths t_schema_paths; begin --resolve schema names from paths and group paths by schema name resolve_schema_names(l_paths); l_schema_paths := group_paths_by_schema(l_paths); l_objects_to_run := ut_suite_items(); l_schema := l_schema_paths.first; while l_schema is not null loop l_paths := l_schema_paths(l_schema); l_suites_info := get_schema_suites(l_schema); for i in 1 .. l_paths.count loop l_path := l_paths(i); --run whole schema if regexp_like(l_path, '^[A-Za-z0-9$#_]+$') then l_index := l_suites_info.schema_suites.first; while l_index is not null loop l_objects_to_run.extend; l_objects_to_run(l_objects_to_run.count) := l_suites_info.schema_suites(l_index); l_index := l_suites_info.schema_suites.next(l_index); end loop; else l_suite := get_suite_filtered_by_path( convert_to_suite_path( l_path, l_suites_info.suite_paths ), l_suites_info.schema_suites ); l_objects_to_run.extend; l_objects_to_run(l_objects_to_run.count) := l_suite; end if; end loop; l_schema := l_schema_paths.next(l_schema); end loop; --propagate rollback type to suite items after organizing suites into hierarchy for i in 1 .. l_objects_to_run.count loop l_objects_to_run(i).set_rollback_type( l_objects_to_run(i).get_rollback_type() ); end loop; return l_objects_to_run; end configure_execution_by_path; end ut_suite_manager; /
39.3
187
0.687157
65351167928ce81c735f063228eadca0eb91e2b5
828
py
Python
geoipgen/generate.py
christivn/INDES-devices-scan-engine
5229ac68f0b075ffaba7641e5c8fb634d42d4915
[ "MIT" ]
2
2020-09-11T11:30:49.000Z
2021-07-01T22:06:25.000Z
geoipgen/generate.py
christivn/INDES-devices-scan-engine
5229ac68f0b075ffaba7641e5c8fb634d42d4915
[ "MIT" ]
null
null
null
geoipgen/generate.py
christivn/INDES-devices-scan-engine
5229ac68f0b075ffaba7641e5c8fb634d42d4915
[ "MIT" ]
null
null
null
from . import subnetCal from . import functions from random import randint def IP(cidr): arr=subnetCal.simpleCalculate(cidr) min_host=arr[3] smin_host=min_host.split(".") max_host=arr[4] smax_host=max_host.split(".") ip="" for i in range(4): if(smin_host[i]==smax_host[i]): ip+=smin_host[i] else: ip+=str(randint(int(smin_host[i]), int(smax_host[i]))) if(i<3): ip+="." return ip def rangeIP(cidr): arr=subnetCal.simpleCalculate(cidr) min_host=arr[3] max_host=arr[4] ip_list=functions.ips(min_host, max_host) return ip_list def randomCIDR(country): folder_cidr = open('geoipgen/ipv4/'+country+'.cidr', 'r') cidr_lines = folder_cidr.readlines() return cidr_lines[randint(0,len(cidr_lines))].strip()
23.657143
66
0.629227
f7331339176c275f85c87b95fd1a1791f19f3abe
2,059
h
C
firmware/export/wm8985.h
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
24
2015-03-10T08:43:56.000Z
2022-01-05T14:09:46.000Z
firmware/export/wm8985.h
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
4
2015-07-04T18:15:33.000Z
2018-05-18T05:33:33.000Z
firmware/export/wm8985.h
Rockbox-Chinese-Community/Rockbox-RCC
a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2
[ "BSD-3-Clause" ]
15
2015-01-21T13:58:13.000Z
2020-11-04T04:30:22.000Z
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2005 by Dave Chapman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #ifndef _WM8985_H #define _WM8985_H #ifdef COWON_D2 /* FIXME: somehow something was out of sync in the .lang, settings and caps. Keep the * cutoffs disabled until someone with the device works it out. */ #define AUDIOHW_CAPS (BASS_CAP | TREBLE_CAP | LINEOUT_CAP | \ LIN_GAIN_CAP | MIC_GAIN_CAP) #else #define AUDIOHW_CAPS (BASS_CAP | TREBLE_CAP | BASS_CUTOFF_CAP | \ TREBLE_CUTOFF_CAP | LINEOUT_CAP | LIN_GAIN_CAP | \ MIC_GAIN_CAP) AUDIOHW_SETTING(BASS_CUTOFF, "", 0, 1, 1, 4, 1) AUDIOHW_SETTING(TREBLE_CUTOFF, "", 0, 1, 1, 4, 1) #endif AUDIOHW_SETTING(VOLUME, "dB", 0, 1, -90, 6, -25) AUDIOHW_SETTING(BASS, "dB", 0, 1, -12, 12, 0) AUDIOHW_SETTING(TREBLE, "dB", 0, 1, -12, 12, 0) #ifdef HAVE_RECORDING AUDIOHW_SETTING(LEFT_GAIN, "dB", 1, 1,-128, 96, 0) AUDIOHW_SETTING(RIGHT_GAIN, "dB", 1, 1,-128, 96, 0) AUDIOHW_SETTING(MIC_GAIN, "dB", 1, 1,-128, 108, 16) #endif /* HAVE_RECORDING */ void audiohw_set_aux_vol(int vol_l, int vol_r); #endif /* _WM8985_H */
41.18
85
0.53424
3462f68ce82ce780e50b2e8dd0e500e2ae079542
8,354
swift
Swift
AdventOfCode/Year2019/Day15.swift
pjcook/Advent-of-Code
8518828e1fddf77676bee381e52ca83ddecd9ee6
[ "MIT" ]
2
2021-12-28T16:27:08.000Z
2021-12-28T16:27:13.000Z
AdventOfCode/Year2019/Day15.swift
pjcook/Advent-of-Code
8518828e1fddf77676bee381e52ca83ddecd9ee6
[ "MIT" ]
null
null
null
AdventOfCode/Year2019/Day15.swift
pjcook/Advent-of-Code
8518828e1fddf77676bee381e52ca83ddecd9ee6
[ "MIT" ]
1
2019-12-10T15:00:50.000Z
2019-12-10T15:00:50.000Z
// // Day15.swift // Year2019 // // Created by PJ COOK on 15/12/2019. // Copyright © 2019 Software101. All rights reserved. // import Foundation public extension Direction { var moveValue: Int { switch self { case .N: return 1 case .S: return 2 case .W: return 3 case .E: return 4 } } var inverse: Direction { switch self { case .N: return .S case .S: return .N case .W: return .E case .E: return .W } } } public extension Point { func directionTo(_ point: Point) -> Direction { if x < point.x { return .E } if x > point.x { return .W } if y > point.y { return .S } return .N } } public enum MoveStatus: Int { case hitWall = 0 case moved = 1 case movedFoundOxygenSystem = 2 case unknown = -1 case start = 4 public var sortOrder: Int { switch self { case .unknown: return 0 case .moved, .start: return 1 case .movedFoundOxygenSystem: return 2 case .hitWall: return 3 } } } public struct MapPointStatus { public let point: Point public let state: MoveStatus public let options: Set<Direction> } public class Mapper { public private(set) var map: [Point:MapPointStatus] = [.zero:MapPointStatus(point: .zero, state: .start, options: [])] public var computer: SteppedIntComputer? public let tiles = [-1:"⚪️",0:"🟤", 1:"⚫️", 2:"🟠",3:"🟣",4:"🔴"] public let startPosition = Point.zero public private(set) var currentPosition = Point.zero private var moveValue: Direction = .E private var lastStatus: MoveStatus = .moved private var finished = false private var started = false private var route = [Direction]() public var processEntireSpace = false public init(_ input: [Int]) { computer = SteppedIntComputer( id: 1, data: input, readInput: readInput, processOutput: processOutput, completionHandler: { self.drawMapInConsole() }, forceWriteMode: false ) } public func start() { computer?.process() } public func createMapper() -> GKMapper { var newMap = [Point:Int]() _ = map.map { newMap[$0.key] = $0.value.state.rawValue } let mapper = GKMapper(newMap, wallID: 0) mapper.removeTilesNotIn([1,2,4]) return mapper } public func fillWithOxygen() -> Int { var isFull = false var minutes = 0 while !isFull { fillTilesWithOxygen() minutes += 1 isFull = allTilesContainOxygen() // drawMapInConsole() } return minutes } private func validOxygenNeighbours(_ point: Point) -> [Point] { return [ point + Direction.N.point, point + Direction.S.point, point + Direction.E.point, point + Direction.W.point ] .compactMap { map[$0] } .filter { [.moved, .start].contains($0.state) } .map { $0.point } } private func fillTilesWithOxygen() { var tiles = [Point]() _ = map .filter({ $0.value.state == .movedFoundOxygenSystem }) .map { tiles += validOxygenNeighbours($0.key) } tiles.forEach { let info = map[$0]! map[$0] = MapPointStatus(point: $0, state: .movedFoundOxygenSystem, options: info.options) } } private func allTilesContainOxygen() -> Bool { return Set(map.map { $0.value.state }).count == 2 } private func routeTo(_ point: Point) { let mapper = createMapper() var position = currentPosition _ = mapper.route(position, point).compactMap { if $0 != currentPosition { let direction = position.directionTo($0) position = position + direction.point route.append(direction) } } } private func readInput() -> Int { guard !finished else { return 99 } let currentTile = map[currentPosition]! if currentTile.options.count < 4 { route.removeAll() moveValue = Direction.all.first(where: { !currentTile.options.contains($0) })! return moveValue.moveValue } if !route.isEmpty { moveValue = route.removeFirst() return moveValue.moveValue } guard let tile = map.first(where: { $0.value.options.count < 4 && $0.value.state != .hitWall }) else { return 99 } routeTo(tile.key) moveValue = route.removeFirst() return moveValue.moveValue } private func processOutput(_ value: Int) { lastStatus = MoveStatus(rawValue: value)! let currentState = map[currentPosition]! var options = currentState.options options.insert(moveValue) map[currentPosition] = MapPointStatus(point: currentPosition, state: currentState.state, options: options) let position = currentPosition + moveValue.point var nextOptions = map[position]?.options ?? [] map[position] = MapPointStatus(point: position, state: lastStatus, options: nextOptions) switch lastStatus { case .hitWall: break case .moved: nextOptions.insert(moveValue.inverse) map[position] = MapPointStatus(point: position, state: lastStatus, options: nextOptions) currentPosition = position case .movedFoundOxygenSystem: nextOptions.insert(moveValue.inverse) map[position] = MapPointStatus(point: position, state: lastStatus, options: nextOptions) currentPosition = position if !processEntireSpace { finished = true } case .unknown, .start: break } // drawMapInConsole() } public func drawMapInConsole() { var rawMap = [Point:Int]() _ = map.map { rawMap[$0] = $1.state.rawValue } rawMap[startPosition] = 3 rawMap[currentPosition] = 4 drawMapReversed(rawMap, tileMap: tiles) } } public func drawMap(_ output: [Point:Int], tileMap: [Int:String], filename: String? = nil) { let (minX,minY,maxX,maxY) = calculateMapDimensions(output) var map = "" for y in (0...maxY-minY) { writeMapRow(maxX, minX, y, minY, output, tileMap, &map) } writeMapToFile(filename, map) if filename == nil { print(map + "\n") } } public func drawMapReversed(_ output: [Point:Int], tileMap: [Int:String], filename: String? = nil) { let (minX,minY,maxX,maxY) = calculateMapDimensions(output) var map = "" for y in (0...maxY-minY).reversed() { writeMapRow(maxX, minX, y, minY, output, tileMap, &map) } writeMapToFile(filename, map) if filename == nil { print(map + "\n") } } public func writeMapRow(_ maxX: Int, _ minX: Int, _ y: Int, _ minY: Int, _ output: [Point : Int], _ tileMap: [Int : String], _ map: inout String) { var row = "" for x in 0...maxX - minX { let dx = x + minX let dy = y + minY let value = output[Point(x: dx, y: dy)] ?? -1 let char = tileMap[value] ?? "(\(value.toAscii() ?? " ")" row += char } map += row + "\n" } public func writeMapToFile(_ filename: String?, _ map: String) { if let filename = filename { let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(filename) do { try map.write(to: url, atomically: true, encoding: .utf8) print(url) } catch { print(error) } } } public func calculateMapDimensions(_ output: [Point:Int]) -> (Int,Int,Int,Int) { let minX = output.reduce(Int.max) { min($0,$1.key.x) } let minY = output.reduce(Int.max) { min($0,$1.key.y) } let maxX = output.reduce(0) { max($0,$1.key.x) } let maxY = output.reduce(0) { max($0,$1.key.y) } return (minX,minY,maxX,maxY) }
30.268116
147
0.559612
e70d0a494568deb20d26a91618e6e40e734ccd8a
165
kt
Kotlin
idea/testData/intentions/simplifyBooleanWithConstants/withAnnotation.kt
punzki/kotlin
dd005d3c02c6d3820617e85153f5b70fa365e56d
[ "ECL-2.0", "Apache-2.0" ]
337
2020-05-14T00:40:10.000Z
2022-02-16T23:39:07.000Z
idea/testData/intentions/simplifyBooleanWithConstants/withAnnotation.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
92
2020-06-10T23:17:42.000Z
2020-09-25T10:50:13.000Z
idea/testData/intentions/simplifyBooleanWithConstants/withAnnotation.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
44
2020-05-17T10:11:11.000Z
2022-03-11T02:37:20.000Z
var b = true @Target(AnnotationTarget.EXPRESSION) @Retention(AnnotationRetention.SOURCE) annotation class Ann fun foo() { if (@Ann <caret>b == true) { } }
15
38
0.684848
c3c596b9fb098bbe6e829c74c7ef3c485e31ffd4
2,603
kt
Kotlin
app/src/test/java/io/github/wellingtoncosta/feed/app/ui/viewmodel/ListPostsViewModelTest.kt
WellingtonCosta/feed
3644d65e7b3e3338b72b25ce7a578a1eae8512e7
[ "MIT" ]
4
2019-07-12T05:01:29.000Z
2019-07-23T00:30:52.000Z
app/src/test/java/io/github/wellingtoncosta/feed/app/ui/viewmodel/ListPostsViewModelTest.kt
WellingtonCosta/feed
3644d65e7b3e3338b72b25ce7a578a1eae8512e7
[ "MIT" ]
null
null
null
app/src/test/java/io/github/wellingtoncosta/feed/app/ui/viewmodel/ListPostsViewModelTest.kt
WellingtonCosta/feed
3644d65e7b3e3338b72b25ce7a578a1eae8512e7
[ "MIT" ]
null
null
null
package io.github.wellingtoncosta.feed.app.ui.viewmodel import androidx.lifecycle.Observer import io.github.wellingtoncosta.feed.app.ui.listposts.ListPostsViewModel import io.github.wellingtoncosta.feed.domain.entity.Post import io.github.wellingtoncosta.feed.domain.interactor.PostInteractor import io.github.wellingtoncosta.feed.mock.PostMock.fivePosts import io.mockk.Runs import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Test class ListPostsViewModelTest : BaseViewModelTest() { private val interactor = mockk<PostInteractor>() private val loadingObserver = mockk<Observer<Boolean>>() private val postsObserver = mockk<Observer<List<Post>>>() private val errorObserver = mockk<Observer<Throwable>>() private val viewModel = ListPostsViewModel(interactor = interactor) @ExperimentalCoroutinesApi @Test fun `no interactions`() = runBlockingTest { every { postsObserver.onChanged(any()) } just Runs viewModel.posts.observeForever(postsObserver) coVerify(exactly = 0) { interactor.getAllPosts() } } @ExperimentalCoroutinesApi @Test fun `get posts with success`() = runBlockingTest { coEvery { interactor.getAllPosts() } returns fivePosts every { loadingObserver.onChanged(any()) } just Runs every { postsObserver.onChanged(any()) } just Runs viewModel.loading.observeForever(loadingObserver) viewModel.posts.observeForever(postsObserver) viewModel.getAllPosts() coVerify { interactor.getAllPosts() } verify(exactly = 2) { loadingObserver.onChanged(any()) } verify { postsObserver.onChanged(any()) } } @ExperimentalCoroutinesApi @Test fun `throws exception when get posts`() = runBlockingTest { coEvery { interactor.getAllPosts() } throws Exception() every { loadingObserver.onChanged(any()) } just Runs every { postsObserver.onChanged(any()) } just Runs every { errorObserver.onChanged(any()) } just Runs viewModel.loading.observeForever(loadingObserver) viewModel.posts.observeForever(postsObserver) viewModel.error.observeForever(errorObserver) viewModel.getAllPosts() coVerify { interactor.getAllPosts() } verify(exactly = 2) { loadingObserver.onChanged(any()) } verify(exactly = 0) { postsObserver.onChanged(any()) } verify { errorObserver.onChanged(any()) } } }
29.91954
73
0.71917
402ba489a55a1b859da54696bbac1d1b9600e4de
804
py
Python
U-GAT-IT/lib/loss/losses.py
gcinbis/deep-generative-models-spring20
d377bd63d5e79539477cca47c71462e5cc12adfa
[ "MIT" ]
18
2020-07-06T10:47:26.000Z
2021-05-30T11:43:17.000Z
U-GAT-IT/lib/loss/losses.py
gcinbis/deep-generative-models-course-projects
d377bd63d5e79539477cca47c71462e5cc12adfa
[ "MIT" ]
1
2022-03-12T00:39:12.000Z
2022-03-12T00:39:12.000Z
U-GAT-IT/lib/loss/losses.py
gcinbis/deep-generative-models-spring20
d377bd63d5e79539477cca47c71462e5cc12adfa
[ "MIT" ]
2
2020-07-13T20:46:44.000Z
2020-10-01T13:15:25.000Z
import torch import torch.nn as nn class LossWithValue(nn.Module): def __init__(self, loss_fn): super().__init__() self.loss_fn = loss_fn def forward(self, x, value): target = torch.empty_like(x).fill_(value).type_as(x) return self.loss_fn(x, target) class MSEWithValue(nn.Module): def __init__(self): super().__init__() self.mse = nn.MSELoss() def forward(self, x, value): target = torch.empty_like(x).fill_(value).type_as(x) return self.mse(x, target) class BCELogitsWithValue(nn.Module): def __init__(self): super().__init__() self.bce_logits = nn.BCEWithLogitsLoss() def forward(self, x, value): target = torch.empty_like(x).fill_(value) return self.bce_logits(x, target)
25.125
60
0.635572
7a29e78ccf41264b1f47a37da4441392f676093e
4,228
kt
Kotlin
app/src/androidTest/java/infixsoft/imrankst1221/android/starter/data/UserDetailsDaoTest.kt
imrankst1221/Android_starter
947ffd7eb7136e3005e745d515a69b0da04b7741
[ "MIT" ]
null
null
null
app/src/androidTest/java/infixsoft/imrankst1221/android/starter/data/UserDetailsDaoTest.kt
imrankst1221/Android_starter
947ffd7eb7136e3005e745d515a69b0da04b7741
[ "MIT" ]
null
null
null
app/src/androidTest/java/infixsoft/imrankst1221/android/starter/data/UserDetailsDaoTest.kt
imrankst1221/Android_starter
947ffd7eb7136e3005e745d515a69b0da04b7741
[ "MIT" ]
null
null
null
package infixsoft.imrankst1221.android.starter.data import androidx.room.Room import androidx.test.espresso.matcher.ViewMatchers.assertThat import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import infixsoft.imrankst1221.android.starter.data.model.UserDetails import infixsoft.imrankst1221.android.starter.data.model.UserDetailsDao import infixsoft.imrankst1221.android.starter.utilities.getLiveDataValue import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER1 import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER2 import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER3 import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER1_DETAILS import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER2_DETAILS import infixsoft.imrankst1221.android.starter.data.DummyDataSet.DUMMY_USER3_DETAILS import kotlinx.coroutines.runBlocking import org.hamcrest.CoreMatchers.equalTo import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import kotlin.jvm.Throws /** * @author imran.choudhury * 18/9/21 */ @RunWith(AndroidJUnit4::class) class UserDetailsDaoTest { private lateinit var database: AppDatabase private lateinit var userDetailsDao: UserDetailsDao @Before fun createDb() = runBlocking{ val context = InstrumentationRegistry.getInstrumentation().targetContext database = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build() userDetailsDao = database.userDetailsDao() insertUserDetails() } @After fun closeDb() { database.close() } private fun insertUserDetails() = runBlocking{ database.userDaoDao().insertAll(listOf(DUMMY_USER1, DUMMY_USER2, DUMMY_USER3)) userDetailsDao.insertUserDetails(DUMMY_USER1_DETAILS) userDetailsDao.insertUserDetails(DUMMY_USER2_DETAILS) userDetailsDao.insertUserDetails(DUMMY_USER3_DETAILS) } @Throws(InterruptedException::class) fun testUserDetailsByLogin() = runBlocking{ assertThat(getLiveDataValue(userDetailsDao.getUserDetailsByLogin(DUMMY_USER1.login)), equalTo(DUMMY_USER1_DETAILS)) assertThat(getLiveDataValue(userDetailsDao.getUserDetailsByLogin(DUMMY_USER2.login)), equalTo(DUMMY_USER2_DETAILS)) assertThat(getLiveDataValue(userDetailsDao.getUserDetailsByLogin(DUMMY_USER3.login)), equalTo(DUMMY_USER3_DETAILS)) } @Test fun testIsUserDetailsAvailable() = runBlocking { assertThat(userDetailsDao.isUserDetailsAvailable(1), equalTo(true)) assertThat(userDetailsDao.isUserDetailsAvailable(2), equalTo(true)) assertThat(userDetailsDao.isUserDetailsAvailable(3), equalTo(true)) assertThat(userDetailsDao.isUserDetailsAvailable(0), equalTo(false)) assertThat(userDetailsDao.isUserDetailsAvailable(5), equalTo(false)) assertThat(userDetailsDao.isUserDetailsAvailable(6), equalTo(false)) } @Test fun testGetUserDetails() = runBlocking { assertThat(userDetailsDao.getUserDetails(1), equalTo(DUMMY_USER1_DETAILS)) assertThat(userDetailsDao.getUserDetails(2), equalTo(DUMMY_USER2_DETAILS)) assertThat(userDetailsDao.getUserDetails(3), equalTo(DUMMY_USER3_DETAILS)) } @Test fun testUpdateAllUserDetails() = runBlocking{ val userDetailsA1 = UserDetails(1, "user1","User A", "",1, 1, "Google", "") val userDetailsB1 = UserDetails(2, "user2","User B", "",1, 1, "Google", "") val userDetailsC1 = UserDetails(3, "user3","User C", "",1, 1, "Google", "") // insert new values userDetailsDao.insertUserDetails(userDetailsA1) userDetailsDao.insertUserDetails(userDetailsB1) userDetailsDao.insertUserDetails(userDetailsC1) assertThat(userDetailsDao.getUserDetails(1), equalTo(userDetailsA1)) assertThat(userDetailsDao.getUserDetails(2), equalTo(userDetailsB1)) assertThat(userDetailsDao.getUserDetails(3), equalTo(userDetailsC1)) // back to previous value insertUserDetails() testIsUserDetailsAvailable() testGetUserDetails() } }
44.041667
123
0.769868
fb9b271fb34003556acee1d5bb8f0bde6288ea06
517
kt
Kotlin
client-lib/src/main/kotlin/com/icapps/niddler/lib/model/bodyparser/PlainTextBodyParser.kt
Chimerapps/niddler-ui
fc2e13fdc636ea3a025f75a8ed166fcf3157c06d
[ "Apache-2.0" ]
24
2020-03-25T07:50:44.000Z
2022-01-08T15:28:14.000Z
client-lib/src/main/kotlin/com/icapps/niddler/lib/model/bodyparser/PlainTextBodyParser.kt
Chimerapps/niddler-ui
fc2e13fdc636ea3a025f75a8ed166fcf3157c06d
[ "Apache-2.0" ]
21
2019-11-19T10:29:19.000Z
2022-01-05T14:05:57.000Z
client-lib/src/main/kotlin/com/icapps/niddler/lib/model/bodyparser/PlainTextBodyParser.kt
Chimerapps/niddler-ui
fc2e13fdc636ea3a025f75a8ed166fcf3157c06d
[ "Apache-2.0" ]
1
2020-09-03T18:48:39.000Z
2020-09-03T18:48:39.000Z
package com.icapps.niddler.lib.model.bodyparser import com.icapps.niddler.lib.model.BodyFormat import com.icapps.niddler.lib.model.BodyParser /** * @author Nicola Verbeeck * * Parses the body as text. If no charset was specified by the format, assumes UTF-8 */ class PlainTextBodyParser : BodyParser<String> { override fun parse(bodyFormat: BodyFormat, bytes: ByteArray): String? { if (bytes.isEmpty()) return "" return String(bytes, BodyParser.makeCharset(bodyFormat)) } }
27.210526
84
0.713733
18ea418d8ea08fb6e0eac2d820dcf1b46ab21821
920
rb
Ruby
spec/integration/installation_spec.rb
jcoyne/mods_display
36e5bf7247fd7aa7892247af48033afaee2fd76b
[ "MIT" ]
3
2017-11-29T17:37:02.000Z
2022-01-30T00:58:03.000Z
spec/integration/installation_spec.rb
jcoyne/mods_display
36e5bf7247fd7aa7892247af48033afaee2fd76b
[ "MIT" ]
46
2015-02-04T00:16:32.000Z
2022-03-08T21:43:25.000Z
spec/integration/installation_spec.rb
jcoyne/mods_display
36e5bf7247fd7aa7892247af48033afaee2fd76b
[ "MIT" ]
2
2017-07-14T13:12:31.000Z
2020-03-13T15:01:59.000Z
require 'spec_helper' describe 'Installation' do before(:all) do @pieces_of_data = 1 title_xml = '<mods><titleInfo><title>The Title of this Item</title></titleInfo></mods>' model = TestModel.new model.modsxml = title_xml controller = TestController.new @html = controller.render_mods_display(model) end it 'should return a single <dl>' do expect(@html.scan(/<dl>/).length).to eq(1) expect(@html.scan(%r{</dl>}).length).to eq(1) end it 'should return a dt/dd pair for each piece of metadata in the mods' do expect(@html.scan(/<dt/).length).to eq(@pieces_of_data) expect(@html.scan(/<dd>/).length).to eq(@pieces_of_data) end it 'should return a proper label' do expect(@html.scan(%r{<dt title='Title'>Title:</dt>}).length).to eq(1) end it 'should return a proper value' do expect(@html.scan(%r{<dd>The Title of this Item</dd>}).length).to eq(1) end end
34.074074
91
0.668478
713360180a6c3bd506f03c6617e4e110eae1b51c
5,242
ts
TypeScript
Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/settings/reverse-transaction/reverse-transaction.component.ts
MenkaChaugule/hospital-management-emr
6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d
[ "MIT" ]
1
2022-03-03T09:53:27.000Z
2022-03-03T09:53:27.000Z
Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/settings/reverse-transaction/reverse-transaction.component.ts
MenkaChaugule/hospital-management-emr
6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d
[ "MIT" ]
null
null
null
Code/Websites/DanpheEMR/wwwroot/DanpheApp/src/app/accounting/settings/reverse-transaction/reverse-transaction.component.ts
MenkaChaugule/hospital-management-emr
6c9afb0cda5ca4f8ea726e083f57b7a16a35a58d
[ "MIT" ]
3
2022-02-01T03:55:18.000Z
2022-02-02T07:31:08.000Z
import { Component } from "@angular/core"; import { FiscalYearModel } from '../shared/fiscalyear.model'; import * as moment from 'moment/moment'; import { MessageboxService } from '../../../shared/messagebox/messagebox.service'; import { CommonFunctions } from '../../../shared/common.functions'; import { ReverseTransactionModel } from '../shared/reverse-transaction.model'; import { AccountingBLService } from "../../shared/accounting.bl.service"; import { Router } from "@angular/router"; import { isNull } from "util"; import { CoreService } from '../../../core/shared/core.service'; import { SectionModel } from "../shared/section.model"; import { SettingsBLService } from "../../../settings-new/shared/settings.bl.service"; import { SecurityService } from "../../../security/shared/security.service"; import { AccountingService } from '../../shared/accounting.service'; @Component({ selector: 'reverse-transaction', templateUrl: './reverse-transaction.html' }) export class ReverseTransaction { public transaction: ReverseTransactionModel = new ReverseTransactionModel(); public calType: string = ""; public sectionList: Array<SectionModel> = []; public permissions: Array<any> = new Array<any>(); public applicationList: Array<any> = new Array<any>(); constructor(public msgBoxServ: MessageboxService, public router: Router, public accountingBLService: AccountingBLService, public coreService: CoreService, public settingsBLService: SettingsBLService, public securityService:SecurityService,public accountingService: AccountingService) { //this.transaction.TransactionDate = moment().format('YYYY-MM-DD'); //this.transaction.Section = 2; // this.LoadCalendarTypes(); this.calType = this.coreService.DatePreference; this.GetSection(); } public validDate: boolean = true; selectDate(event) { if (event) { this.transaction.TransactionDate = event.selectedDate; this.transaction.FiscalYearId = event.fiscalYearId; this.validDate = true; } else { this.validDate = false; } } UndoTransaction() { if (this.CheckValidDate()) { this.accountingBLService.UndoTransaction(this.transaction) .subscribe(res => { if (res.Status == "OK") { if (res.Results == true) { this.msgBoxServ.showMessage('success', ['Transaction is reversed successfully.']); this.Close(); } else this.msgBoxServ.showMessage('', ['No records Found..Select Different Date..']); } }, err => { this.msgBoxServ.showMessage("error", ['There is problem, please try again']); }); } } //loads CalendarTypes from Paramter Table (database) and assign the require CalendarTypes to local variable. LoadCalendarTypes() { let Parameter = this.coreService.Parameters; Parameter = Parameter.filter(parms => parms.ParameterName == "CalendarTypes"); let calendarTypeObject = JSON.parse(Parameter[0].ParameterValue); this.calType = calendarTypeObject.AccountingModule; } Close() { this.transaction = new ReverseTransactionModel(); this.router.navigate(['/Accounting/Settings']); } public CheckValidDate() { if (!this.validDate) { this.msgBoxServ.showMessage("error", ['Select proper date']); return false; } if (this.transaction.TransactionDate > moment().format('YYYY-MM-DD')) { this.msgBoxServ.showMessage("error", ["Select Valid Date."]); return false; } else if (this.transaction.Reason == null || this.transaction.Reason.length < 20) { this.msgBoxServ.showMessage('error', ['Please enter minimum 20 char reason']) return false; } else return true; } public GetSection() { this.settingsBLService.GetApplicationList() .subscribe(res => { if (res.Status == 'OK') { this.applicationList = res.Results; let sectionApplication = this.applicationList.filter(a => a.ApplicationCode == "ACC-Section" && a.ApplicationName == "Accounts-Sections")[0]; if (sectionApplication != null || sectionApplication != undefined) { this.permissions = this.securityService.UserPermissions.filter(p => p.ApplicationId == sectionApplication.ApplicationId); } let sList = this.accountingService.accCacheData.Sections.filter(sec => sec.SectionId != 4); // 4 is Manual_Voucher (FIXED for DanpheEMR) //mumbai-team-june2021-danphe-accounting-cache-change sList.forEach(s => { let sname = s.SectionName.toLowerCase(); let pp = this.permissions.filter(f => f.PermissionName.includes(sname))[0]; if (pp != null || pp != undefined) { this.sectionList.push(s); this.sectionList = this.sectionList.slice();//mumbai-team-june2021-danphe-accounting-cache-change } }) let defSection = this.sectionList.find(s => s.IsDefault == true); if (defSection) { this.transaction.Section = defSection.SectionId; } else { this.transaction.Section = this.sectionList[0].SectionId; } } }); } }
40.953125
200
0.655284
1f92d5dd394ae7fea1310c2c8784a4b2d346d92d
33
html
HTML
frontend/src/app/modules/login/login.component.html
tamasf97/Platform
b5d69d051b6e8dc7d56f723146392c49db5e99c3
[ "MIT" ]
1
2019-09-22T10:21:17.000Z
2019-09-22T10:21:17.000Z
frontend/src/app/modules/login/login.component.html
tamasf97/Platform
b5d69d051b6e8dc7d56f723146392c49db5e99c3
[ "MIT" ]
20
2019-09-26T13:54:12.000Z
2022-02-26T18:07:34.000Z
frontend/src/app/modules/login/login.component.html
tamasf97/Platform
b5d69d051b6e8dc7d56f723146392c49db5e99c3
[ "MIT" ]
1
2019-09-20T09:50:01.000Z
2019-09-20T09:50:01.000Z
<div id="login"> LOGIN </div>
11
16
0.545455
c486eac0b33f5ca84ebca0abd2dc97e8a8c15010
4,862
h
C
animer/AnimAsset.h
Benjins/GBADev
0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90
[ "MIT" ]
null
null
null
animer/AnimAsset.h
Benjins/GBADev
0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90
[ "MIT" ]
null
null
null
animer/AnimAsset.h
Benjins/GBADev
0a968a1aa1ee38b57644a1bb8d27f2c5332e3c90
[ "MIT" ]
null
null
null
typedef struct{ char* fileName; BitmapData spriteData; int duration; } AnimKeyFrame; typedef struct{ char* name; AnimKeyFrame* keyFrames; int keyFrameCount; } AnimClip; typedef struct{ AnimClip* animClips; int animClipCount; } AnimAsset; void AddAnimClip(AnimAsset* asset, AnimClip clip){ AnimClip* newAnimClips = (AnimClip*)malloc(sizeof(AnimClip)*(asset->animClipCount+1)); memcpy(newAnimClips, asset->animClips, asset->animClipCount*sizeof(AnimClip)); newAnimClips[asset->animClipCount] = clip; free(asset->animClips); asset->animClips = newAnimClips; asset->animClipCount++; } void RemoveAnimKeyFrame(AnimClip* clip, int index){ if(index > 0 && index < clip->keyFrameCount){ free(clip->keyFrames[index].spriteData.data); free(clip->keyFrames[index].fileName); for(int i = index + 1; i < clip->keyFrameCount; i++){ clip->keyFrames[i-1] = clip->keyFrames[i]; } clip->keyFrameCount--; } } void AddKeyFrame(AnimClip* clip, AnimKeyFrame keyFrame){ AnimKeyFrame* newKeyFrames = (AnimKeyFrame*)malloc(sizeof(AnimKeyFrame)*(clip->keyFrameCount+1)); memcpy(newKeyFrames, clip->keyFrames, clip->keyFrameCount*sizeof(AnimKeyFrame)); newKeyFrames[clip->keyFrameCount] = keyFrame; free(clip->keyFrames); clip->keyFrames = newKeyFrames; clip->keyFrameCount++; } void NoramlizeAnimClip(AnimClip* clip){ //Skip the first two, its duration should never be negative and it messes up the logic for(int i = 1; i < clip->keyFrameCount - 1; i++){ if(clip->keyFrames[i].duration < 0){ clip->keyFrames[i-1].duration = clip->keyFrames[i].duration + clip->keyFrames[i-1].duration; clip->keyFrames[i+1].duration = clip->keyFrames[i].duration + clip->keyFrames[i+1].duration; clip->keyFrames[i].duration *= -1; AnimKeyFrame temp = clip->keyFrames[i]; clip->keyFrames[i] = clip->keyFrames[i+1]; clip->keyFrames[i+1] = temp; } } } void ReadAnimAssetFile(AnimAsset* asset, const char* fileName, const char* dirName, int dirLength){ char fullFileName[256] = {}; sprintf(fullFileName, "%.*s/%s", dirLength, dirName, fileName); FILE* animAssetFile = fopen(fullFileName, "rb"); fseek(animAssetFile, 0, SEEK_END); int fileSize = ftell(animAssetFile); fseek(animAssetFile, 0, SEEK_SET); char* fileBuffer = (char*)malloc(fileSize+1); fread(fileBuffer, 1, fileSize, animAssetFile); fileBuffer[fileSize] = '\0'; fclose(animAssetFile); char* fileCursor = fileBuffer; while(fileCursor != NULL && fileCursor - fileBuffer < fileSize){ fileCursor += strspn(fileCursor, " \n\r\t"); AnimClip animClip = {}; char* varNameStart = fileCursor; fileCursor += strcspn(fileCursor, ": \n\r\t"); char* varNameEnd = fileCursor; int varNameLength = varNameEnd - varNameStart; char* varName = (char*)malloc(varNameLength + 1); memcpy(varName, varNameStart, varNameLength); varName[varNameLength] = '\0'; animClip.name = varName; fileCursor += strspn(fileCursor, ": \n\r\t"); char* nextNewLine = strstr(fileCursor, "\n"); if(nextNewLine == NULL){ nextNewLine = &fileBuffer[fileSize]; } while(fileCursor != NULL && fileCursor < nextNewLine){ fileCursor += strspn(fileCursor, ": \t"); char* fileNameStart = fileCursor; fileCursor += strcspn(fileCursor, " ;\t\n\r"); char* fileNameEnd = fileCursor; fileCursor += strspn(fileCursor, " ;\t"); char* keyLengthStart = fileCursor; fileCursor += strcspn(fileCursor, " ,;\t\n\r"); char* keyLengthEnd = fileCursor; fileCursor++; if(keyLengthStart != keyLengthEnd){ AnimKeyFrame keyFrame; int spriteFileNameLength = fileNameEnd - fileNameStart; char* spriteFileName = (char*)malloc(spriteFileNameLength+1); memcpy(spriteFileName, fileNameStart, spriteFileNameLength); spriteFileName[spriteFileNameLength] = '\0'; keyFrame.fileName = spriteFileName; keyFrame.duration = atoi(keyLengthStart); char spriteFullFileName[256] = {}; sprintf(spriteFullFileName, "%.*s/%s", dirLength, dirName, spriteFileName); keyFrame.spriteData = LoadBMPFile(spriteFullFileName); if(keyFrame.spriteData.data == NULL){ free(spriteFileName); } else{ AddKeyFrame(&animClip, keyFrame); } } else{ break; } } AddAnimClip(asset, animClip); fileCursor += strspn(fileCursor, " \n\r\t"); } free(fileBuffer); } void SaveAnimAssetFile(AnimAsset* asset, const char* fileName){ FILE* animAssetFile = fopen(fileName, "wb"); for(int i = 0; i < asset->animClipCount; i++){ fprintf(animAssetFile, "%s:", asset->animClips[i].name); for(int j = 0; j < asset->animClips[i].keyFrameCount; j++){ fprintf(animAssetFile, "%s%s;%d", (j == 0 ? "" : ","), asset->animClips[i].keyFrames[j].fileName, asset->animClips[i].keyFrames[j].duration); } fprintf(animAssetFile, "\n"); } }
28.769231
99
0.684081
22f896df77d15b8efde57fd97be66ed72048e726
173
h
C
GamePlatformService/ViewController.h
panshengneng/GamePlatformService
60a06148f4756544345888ffe919cbdd9b8b09c3
[ "MIT" ]
null
null
null
GamePlatformService/ViewController.h
panshengneng/GamePlatformService
60a06148f4756544345888ffe919cbdd9b8b09c3
[ "MIT" ]
null
null
null
GamePlatformService/ViewController.h
panshengneng/GamePlatformService
60a06148f4756544345888ffe919cbdd9b8b09c3
[ "MIT" ]
null
null
null
// // ViewController.h // GamePlatformService // // Created by Anonymous on 2020/10/14. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
11.533333
44
0.699422
169a9f38929648a637c807d62b930370a56d0147
897
ts
TypeScript
src/app/assignment-5/app.component.ts
marianfx/ng-udemy-files
0ee52e4e3aa9852128a10dbde82e4a08b62595fc
[ "MIT" ]
null
null
null
src/app/assignment-5/app.component.ts
marianfx/ng-udemy-files
0ee52e4e3aa9852128a10dbde82e4a08b62595fc
[ "MIT" ]
86
2020-07-16T23:38:29.000Z
2021-02-07T12:44:07.000Z
src/app/assignment-5/app.component.ts
marianfx/ng-udemy-files
0ee52e4e3aa9852128a10dbde82e4a08b62595fc
[ "MIT" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { UsersService } from './services/users.service'; import { CounterService } from './services/counter.service'; @Component({ selector: 'app-assignment-5', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { activeUsers: string[] = []; inactiveUsers: string[] = []; activeToInactive: number = 0; inactiveToActive: number = 0; constructor(private userService: UsersService, private countingService: CounterService) { } ngOnInit() { this.activeUsers = this.userService.activeUsers; this.inactiveUsers = this.userService.inactiveUsers; this.countingService.onActiveChanged.subscribe((newValue) => this.inactiveToActive = newValue); this.countingService.onInactiveChanged.subscribe((newValue) => this.activeToInactive = newValue); } }
34.5
101
0.733556
2f23d5d8b704409db5e1dcce1c2079fcb23b8e17
992
php
PHP
database/seeds/AuthorsTableSeeder.php
DiankaDS/Library
a2973aa5ae7bf624d7d646d97537d5a7eb7efd91
[ "MIT" ]
null
null
null
database/seeds/AuthorsTableSeeder.php
DiankaDS/Library
a2973aa5ae7bf624d7d646d97537d5a7eb7efd91
[ "MIT" ]
null
null
null
database/seeds/AuthorsTableSeeder.php
DiankaDS/Library
a2973aa5ae7bf624d7d646d97537d5a7eb7efd91
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Seeder; use App\Author; class AuthorsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Author::create([ 'name' => 'Agatha Christie', ]); Author::create([ 'name' => 'William Shakespeare', ]); Author::create([ 'name' => 'Stephen King', ]); Author::create([ 'name' => 'Paulo Coelho', ]); Author::create([ 'name' => 'Akira Toriyama', ]); Author::create([ 'name' => 'Danielle Steel', ]); Author::create([ 'name' => 'Georges Simenon', ]); Author::create([ 'name' => 'Edgar Allan Poe', ]); Author::create([ 'name' => 'Gilbert Patten', ]); Author::create([ 'name' => 'Leo Tolstoy', ]); } }
17.714286
44
0.417339
90a1d074d62574d9b16e548c2dd833cf49d7b326
2,650
py
Python
d3p1.py
Maselkov/advent-of-code
c7af55c51df23aa4f010fefbabdae67c8b8061d5
[ "MIT" ]
null
null
null
d3p1.py
Maselkov/advent-of-code
c7af55c51df23aa4f010fefbabdae67c8b8061d5
[ "MIT" ]
null
null
null
d3p1.py
Maselkov/advent-of-code
c7af55c51df23aa4f010fefbabdae67c8b8061d5
[ "MIT" ]
null
null
null
import math def det(a, b, c, d): return a * d - b * c class Point: def __init__(self, x, y): self.x = x self.y = y def lies_on(self, segment): return Segment(segment.a, self).length + Segment( segment.b, self).length == segment.length class Segment: def __init__(self, a, b): self.a = a self.b = b self.length = math.sqrt(((a.x - b.x)**2) + ((a.y - b.y)**2)) def find_intersection(self, other): # We look for the point of intersection between the two lines # https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection x1mx2 = self.a.x - self.b.x y3my4 = other.a.y - other.b.y y1my2 = self.a.y - self.b.y x3mx4 = other.a.x - other.b.x denom = det(x1mx2, y1my2, x3mx4, y3my4) if denom == 0: return None det_l = det(self.a.x, self.a.y, self.b.x, self.b.y) det_r = det(other.a.x, other.a.y, other.b.x, other.b.y) new_x = det(det_l, x1mx2, det_r, x3mx4) / denom new_y = det(det_l, y1my2, det_r, y3my4) / denom if not new_x and not new_y: return None point = Point(new_x, new_y) # Making sure it within both the segments if not point.lies_on(self): return None if not point.lies_on(other): return None return Point(new_x, new_y) def manhattan_distance(a, b): return int(abs(a.x - b.x) + abs(a.y - b.y)) wires = [] with open("d3.txt", "r") as f: for line in f: current_pos = Point(0, 0) segments = [] movements = line.split(",") for movement in movements: direction = movement[0] amount = int(movement[1:]) if direction == "R": new_pos = (current_pos.x + amount, current_pos.y) if direction == "L": new_pos = (current_pos.x - amount, current_pos.y) if direction == "U": new_pos = (current_pos.x, current_pos.y + amount) if direction == "D": new_pos = (current_pos.x, current_pos.y - amount) new_pos = Point(*new_pos) segments.append(Segment(current_pos, new_pos)) current_pos = new_pos wires.append(segments) dist = float("inf") for segment_1 in wires[0]: for segment_2 in wires[1]: intersection = segment_1.find_intersection(segment_2) if intersection: new_dist = manhattan_distance(Point(0, 0), intersection) if new_dist < dist: dist = new_dist print(dist)
31.927711
72
0.543396
f05627e41afebb60a0b22bc0ca7664fa52167d7c
264
js
JavaScript
util/value.js
lddias/homebridge-platform-zwave
4ba12116b47e8bd355605354dedeaec7cd7dcd71
[ "MIT" ]
11
2019-07-25T18:50:29.000Z
2022-01-20T17:34:19.000Z
util/value.js
lddias/homebridge-platform-zwave
4ba12116b47e8bd355605354dedeaec7cd7dcd71
[ "MIT" ]
17
2019-11-17T06:27:21.000Z
2022-03-11T21:29:49.000Z
util/value.js
lddias/homebridge-platform-zwave
4ba12116b47e8bd355605354dedeaec7cd7dcd71
[ "MIT" ]
7
2019-12-28T16:08:20.000Z
2021-09-05T19:24:28.000Z
function map(inMin, inMax, outMin, outMax, isInt) { if (isInt) { return x => Math.round((x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin); } return x => (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; } module.exports = { map }
22
87
0.575758
27b453e1c93a5f2be54e9cf4242950a0f6b0a1b8
159
css
CSS
css/stylish.css
Helenovs/Portfolio
e53407b31dd11958b923f9092f82d693579214f1
[ "MIT" ]
null
null
null
css/stylish.css
Helenovs/Portfolio
e53407b31dd11958b923f9092f82d693579214f1
[ "MIT" ]
null
null
null
css/stylish.css
Helenovs/Portfolio
e53407b31dd11958b923f9092f82d693579214f1
[ "MIT" ]
null
null
null
.color-1 { color: #6bffff; } .color-2 { color: #6bffff; font-size: 60px; } .image-size { height: 50px; width: 50px; } .icon-size { size: 10%; }
9.9375
18
0.553459
716f3057ffbf82379104bd89ef6078f3d9e690f5
30,054
swift
Swift
PrefControlsController.swift
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
PrefControlsController.swift
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
PrefControlsController.swift
Flames-LLC/FlamesEMU
f92287f63ad2f974f52c6ce57c4b9af22a5a31aa
[ "MIT" ]
null
null
null
// Copyright (c) 2021, OpenEmu Team // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the OpenEmu Team nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY OpenEmu Team ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL OpenEmu Team BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Cocoa import Carbon.HIToolbox.Events import OpenEmuSystem import OpenEmuKit.OESystemPlugin final class PrefControlsController: NSViewController { private let lastControlsPluginIdentifierKey = "lastControlsPlugin" private let lastControlsPlayerKey = "lastControlsPlayer" private let lastControlsDeviceTypeKey = "lastControlsDevice" private let keyboardBindingsIsSelectedKey = "OEKeyboardBindingsIsSelectedKey" private let keyboardMenuItemRepresentedObject = "org.openemu.Bindings.Keyboard" private var _selectedKey: String? var selectedKey: String? { get { return _selectedKey } set { _selectedKey = (selectedKey != newValue) ? newValue : nil CATransaction.begin() controlsSetupView.selectedKey = selectedKey controllerView?.setSelectedKey(selectedKey, animated: true) CATransaction.commit() if selectedKey != nil { view.window?.makeFirstResponder(view) } } } private var _selectedPlayer: UInt? @objc dynamic var selectedPlayer: UInt { get { return _selectedPlayer ?? 0 } set { if selectedPlayer != newValue { _selectedPlayer = newValue UserDefaults.standard.set(selectedPlayer, forKey: lastControlsPlayerKey) playerPopupButton.selectItem(withTag: Int(selectedPlayer)) updateInputPopupButtonSelection() } } } var controllerView: ControllerImageView! @IBOutlet weak var controllerContainerView: NSView! @IBOutlet weak var consolesPopupButton: NSPopUpButton! @IBOutlet weak var playerPopupButton: NSPopUpButton! @IBOutlet weak var inputPopupButton: NSPopUpButton! @IBOutlet weak var gradientOverlay: BackgroundGradientView! @IBOutlet weak var veView: NSVisualEffectView! @IBOutlet weak var controlsContainer: NSView! @IBOutlet weak var controlsSetupView: ControlsButtonSetupView! private var selectedPlugin: OESystemPlugin? private var readingEvent: OEHIDEvent? private var ignoredEvents = makeOEHIDEventSet() private var eventMonitor: Any? var currentSystemController: OESystemController? { return selectedPlugin?.controller } @objc dynamic private(set) var currentSystemBindings: OESystemBindings? private var _currentPlayerBindings: OEPlayerBindings? @objc dynamic private(set) var currentPlayerBindings: OEPlayerBindings? { get { if isKeyboardEventSelected { return currentSystemBindings?.keyboardPlayerBindings(forPlayer: selectedPlayer) } else { return currentSystemBindings?.devicePlayerBindings(forPlayer: selectedPlayer) } } set { _currentPlayerBindings = newValue } } override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> { if key == "currentPlayerBindings" { return Set<String>([ "currentSystemBindings", "currentSystemBindings.devicePlayerBindings", "selectedPlayer", ]) } else { return super.keyPathsForValuesAffectingValue(forKey: key) } } // MARK: - ViewController Overrides override var nibName: NSNib.Name? { if OEAppearance.controlsPrefs == .wood { return "PrefControlsController" } else { return "PrefControlsController2" } } override func viewDidLoad() { super.viewDidLoad() controlsSetupView.target = self controlsSetupView.action = #selector(changeInputControl(_:)) controlsSetupView.bind(NSBindingName("bindingsProvider"), to: self, withKeyPath: "currentPlayerBindings", options: nil) // Setup controls popup console list rebuildSystemsMenu() setUpInputMenu() // Restore previous state. changeInputDevice(nil) let pluginName = UserDefaults.standard.string(forKey: lastControlsPluginIdentifierKey) consolesPopupButton.selectItem(at: 0) for item in consolesPopupButton.itemArray { if item.representedObject as? String == pluginName { consolesPopupButton.select(item) break } } CATransaction.setDisableActions(true) changeSystem(consolesPopupButton) CATransaction.commit() if OEAppearance.controlsPrefs == .wood { gradientOverlay.topColor = NSColor(deviceWhite: 0, alpha: 0.3) gradientOverlay.bottomColor = NSColor(deviceWhite: 0, alpha: 0) controlsContainer.enclosingScrollView?.appearance = NSAppearance(named: .aqua) } else if OEAppearance.controlsPrefs == .woodVibrant { veView.blendingMode = .withinWindow veView.state = .active } controllerView?.wantsLayer = true let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(systemsChanged), name: .OEDBSystemAvailabilityDidChange, object: nil) nc.addObserver(self, selector: #selector(devicesDidUpdate(_:)), name: .OEDeviceManagerDidAddDeviceHandler, object: OEDeviceManager.shared) nc.addObserver(self, selector: #selector(devicesDidUpdate(_:)), name: .OEDeviceManagerDidRemoveDeviceHandler, object: OEDeviceManager.shared) nc.addObserver(self, selector: #selector(scrollerStyleDidChange), name: NSScroller.preferredScrollerStyleDidChangeNotification, object: nil) } @objc private func scrollerStyleDidChange() { controlsSetupView.layoutSubviews() } override func viewDidLayout() { super.viewDidLayout() // Fixes an issue where, if the controls pane isn't already the default selected pane on launch and the user manually selects the controls pane, the "Gameplay Buttons" ControlsSectionTitleView has a visible "highlight" artifact until the scroll view gets scrolled. controlsSetupView.layoutSubviews() } override func viewDidAppear() { super.viewDidAppear() if view.window?.isKeyWindow ?? false { setUpEventMonitor() } let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(windowDidBecomeKey(_:)), name: NSWindow.didBecomeKeyNotification, object: nil) nc.addObserver(self, selector: #selector(windowDidResignKey(_:)), name: NSWindow.didResignKeyNotification, object: nil) } override func viewWillDisappear() { super.viewWillDisappear() selectedKey = nil OEBindingsController.default.synchronize() let nc = NotificationCenter.default nc.removeObserver(self, name: NSWindow.didBecomeKeyNotification, object: view.window) nc.removeObserver(self, name: NSWindow.didResignKeyNotification, object: view.window) tearDownEventMonitor() } @objc private func windowDidBecomeKey(_ notification: Notification) { if notification.object as? NSWindow == view.window { setUpEventMonitor() } } @objc private func windowDidResignKey(_ notification: Notification) { if notification.object as? NSWindow == view.window { selectedKey = nil tearDownEventMonitor() } } private func setUpEventMonitor() { if eventMonitor != nil { return } eventMonitor = OEDeviceManager.shared.addGlobalEventMonitorHandler { _, event in self.registerEventIfNeeded(event) return false } } private func tearDownEventMonitor() { guard let eventMonitor = eventMonitor else { return } OEDeviceManager.shared.removeMonitor(eventMonitor) self.eventMonitor = nil } @objc private func systemsChanged() { let menuItem = consolesPopupButton.selectedItem let selectedSystemIdentifier = menuItem?.representedObject as? String rebuildSystemsMenu() consolesPopupButton.selectItem(at: 0) for item in consolesPopupButton.itemArray { if item.representedObject as? String == selectedSystemIdentifier { consolesPopupButton.select(item) break } } CATransaction.setDisableActions(true) changeSystem(consolesPopupButton) CATransaction.commit() } @objc private func devicesDidUpdate(_ notification: Notification) { setUpInputMenu() } // MARK: - UI Setup private func rebuildSystemsMenu() { guard let context = OELibraryDatabase.default?.mainThreadContext, let enabledSystems = OEDBSystem.enabledSystems(in: context) else { return } let consolesMenu = NSMenu() for system in enabledSystems { if let plugin = system.plugin { let item = NSMenuItem(title: plugin.systemName, action: #selector(changeSystem(_:)), keyEquivalent: "") item.target = self item.representedObject = plugin.systemIdentifier item.image = plugin.systemIcon consolesMenu.addItem(item) } } consolesPopupButton.menu = consolesMenu } private func setUpPlayerMenu(numberOfPlayers: UInt) { let playerMenu = NSMenu() for player in 0..<numberOfPlayers { let playerTitle = String(format: NSLocalizedString("Player %ld", comment: ""), player + 1) let playerItem = NSMenuItem(title: playerTitle, action: nil, keyEquivalent: "") playerItem.tag = Int(player + 1) playerMenu.addItem(playerItem) } playerPopupButton.menu = playerMenu playerPopupButton.selectItem(withTag: UserDefaults.standard.integer(forKey: lastControlsPlayerKey)) } private func setUpInputMenu() { let inputMenu = NSMenu() inputMenu.autoenablesItems = false let inputItem = inputMenu.addItem(withTitle: NSLocalizedString("Keyboard", comment: "Keyboard bindings menu item."), action: nil, keyEquivalent: "") inputItem.representedObject = keyboardMenuItemRepresentedObject inputMenu.addItem(.separator()) addControllers(to: inputMenu) inputMenu.addItem(.separator()) inputMenu.addItem(withTitle: NSLocalizedString("Add a Wiimote…", comment: "Wiimote bindings menu item."), action: #selector(searchForWiimote(_:)), keyEquivalent: "").target = self inputPopupButton.menu = inputMenu updateInputPopupButtonSelection() } private func addControllers(to inputMenu: NSMenu) { var controllers = OEDeviceManager.shared.controllerDeviceHandlers if controllers.count == 0 { inputMenu.addItem(withTitle: NSLocalizedString("No available controllers", comment: "Menu item indicating that no controllers is plugged in"), action: nil, keyEquivalent: "").isEnabled = false return } controllers.sort { ($0.deviceDescription?.name ?? "").localizedStandardCompare($1.deviceDescription?.name ?? "") == .orderedAscending } for handler in controllers { let deviceName = handler.deviceDescription?.name ?? "" let item = inputMenu.addItem(withTitle: deviceName, action: nil, keyEquivalent: "") item.representedObject = handler } } private func updateInputPopupButtonSelection() { let keyboardIsSelected = UserDefaults.standard.bool(forKey: keyboardBindingsIsSelectedKey) let currentDeviceHandler = currentSystemBindings?.devicePlayerBindings(forPlayer: selectedPlayer)?.deviceHandler let representedObject = (keyboardIsSelected || currentDeviceHandler == nil) ? keyboardMenuItemRepresentedObject as NSString : currentDeviceHandler if !keyboardIsSelected && currentDeviceHandler == nil { UserDefaults.standard.set(true, forKey: keyboardBindingsIsSelectedKey) } for item in inputPopupButton.itemArray { if item.state == .on { continue } if item.representedObject != nil { item.state = (item.representedObject as? OEDeviceHandler) == currentDeviceHandler ? .mixed : .off } } inputPopupButton.selectItem(at: Int(max(0, inputPopupButton.indexOfItem(withRepresentedObject: representedObject)))) } private func setUpControllerImageView() { let systemController = currentSystemController let imageViewLayer = controllerContainerView.layer let newControllerView = ControllerImageView(frame: controllerContainerView.bounds) newControllerView.image = systemController?.controllerImage newControllerView.imageMask = systemController?.controllerImageMask newControllerView.keyPositions = systemController?.controllerKeyPositions newControllerView.target = self newControllerView.action = #selector(changeInputControl(_:)) // Setup animation that transitions the old controller image out let pathTransitionOut = CGMutablePath() pathTransitionOut.move(to: CGPoint(x: 0, y: 0)) pathTransitionOut.addLine(to: CGPoint(x: 0, y: 450)) let outTransition = CAKeyframeAnimation(keyPath: "position") outTransition.path = pathTransitionOut outTransition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) outTransition.duration = 0.35 // Setup animation that transitions the new controller image in let pathTransitionIn = CGMutablePath() pathTransitionIn.move(to: CGPoint(x: 0, y: 450)) pathTransitionIn.addLine(to: CGPoint(x: 0, y: 0)) let inTransition = CAKeyframeAnimation(keyPath: "position") inTransition.path = pathTransitionIn inTransition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) inTransition.duration = 0.35 CATransaction.begin() CATransaction.setCompletionBlock { if self.controllerView != nil { self.controllerContainerView.replaceSubview(self.controllerView, with: newControllerView) } else { self.controllerContainerView.addSubview(newControllerView) } self.controllerView = newControllerView self.controllerContainerView.setFrameOrigin(.zero) imageViewLayer?.add(inTransition, forKey: "animatePosition") } controllerContainerView.setFrameOrigin(NSPoint(x: 0, y: 450)) imageViewLayer?.add(outTransition, forKey: "animatePosition") CATransaction.commit() controlsSetupView.layoutSubviews() } // MARK: - Actions @IBAction func changeSystem(_ sender: Any?) { let menuItem = consolesPopupButton.selectedItem let systemIdentifier = menuItem?.representedObject as? String ?? UserDefaults.standard.string(forKey: lastControlsPluginIdentifierKey) var newPlugin = OESystemPlugin(forIdentifier: systemIdentifier) if newPlugin == nil { let allPlugins = OESystemPlugin.allPlugins if allPlugins?.count ?? 0 > 0 { if let plugin = allPlugins?.first as? OESystemPlugin { newPlugin = plugin } } } if selectedPlugin != nil && newPlugin == selectedPlugin { return } selectedPlugin = newPlugin guard let systemController = currentSystemController else { assertionFailure("The systemController of the plugin \(String(describing: selectedPlugin)) with system identifier \(String(describing: selectedPlugin?.systemIdentifier)) is nil for some reason.") return } currentSystemBindings = OEBindingsController.default.systemBindings(for: systemController) // Rebuild player menu setUpPlayerMenu(numberOfPlayers: systemController.numberOfPlayers) // Make sure no key is selected before switching the system selectedKey = nil let preferenceView = controlsSetupView! preferenceView.bindingsProvider = currentPlayerBindings preferenceView.setup(withControlList: systemController.controlPageList as! [AnyHashable]) preferenceView.autoresizingMask = [.maxXMargin, .maxYMargin] let rect = NSRect(x: .zero, y: .zero, width: controlsSetupView.bounds.size.width, height: preferenceView.frame.size.height) preferenceView.frame = rect if let scrollView = controlsSetupView.enclosingScrollView { controlsSetupView.setFrameOrigin(NSPoint(x: 0, y: scrollView.frame.size.height - rect.size.height)) if controlsSetupView.frame.size.height <= scrollView.frame.size.height { scrollView.verticalScrollElasticity = .none } else { scrollView.verticalScrollElasticity = .automatic scrollView.flashScrollers() } } UserDefaults.standard.set(systemIdentifier, forKey: lastControlsPluginIdentifierKey) changePlayer(playerPopupButton) changeInputDevice(inputPopupButton) setUpControllerImageView() } @IBAction func changePlayer(_ sender: NSPopUpButton) { let player = sender.selectedTag() selectedPlayer = UInt(player) } @IBAction func changeInputDevice(_ sender: Any?) { guard let representedObject = inputPopupButton.selectedItem?.representedObject else { inputPopupButton.selectItem(at: 0) return } willChangeValue(forKey: "currentPlayerBindings") let isSelectingKeyboard = representedObject as? String == keyboardMenuItemRepresentedObject UserDefaults.standard.set(isSelectingKeyboard, forKey: keyboardBindingsIsSelectedKey) if !isSelectingKeyboard { guard let deviceHandler = representedObject as? OEDeviceHandler else { assertionFailure("Expecting instance of class OEDeviceHandler got: \(String(describing: representedObject))") return } let currentPlayerHandler = currentSystemBindings?.devicePlayerBindings(forPlayer: selectedPlayer)?.deviceHandler if deviceHandler != currentPlayerHandler { currentSystemBindings?.setDeviceHandler(deviceHandler, forPlayer: selectedPlayer) } } updateInputPopupButtonSelection() didChangeValue(forKey: "currentPlayerBindings") } @IBAction func changeInputControl(_ sender: NSView) { if let sender = sender as? ControllerImageView, sender == controllerView { selectedKey = sender.selectedKey } else if let sender = sender as? ControlsButtonSetupView, sender == controlsSetupView { selectedKey = sender.selectedKey } } @IBAction func searchForWiimote(_ sender: Any?) { updateInputPopupButtonSelection() let alert = OEAlert() if OEDeviceManager.shared.isBluetoothEnabled { alert.messageText = NSLocalizedString("Make your Wiimote discoverable", comment: "") alert.informativeText = NSLocalizedString("If there is a red button on the back battery cover, press it.\nIf not, hold down buttons ①+②.", comment: "") alert.defaultButtonTitle = NSLocalizedString("Start Scanning", comment: "") alert.alternateButtonTitle = NSLocalizedString("Cancel", comment: "") alert.otherButtonTitle = NSLocalizedString("Learn More", comment: "") let result = alert.runModal() if result == .alertFirstButtonReturn { OEDeviceManager.shared.startWiimoteSearch() } else if result == .alertThirdButtonReturn { NSWorkspace.shared.open(.userGuideWiimotePairing) } } else { alert.messageText = NSLocalizedString("Bluetooth Not Enabled", comment: "") alert.informativeText = NSLocalizedString("Bluetooth must be enabled to pair a Wii controller.", comment: "") alert.defaultButtonTitle = NSLocalizedString("OK", comment: "") alert.runModal() } } // MARK: - Input and Bindings Management private var isKeyboardEventSelected: Bool { return inputPopupButton.selectedItem?.representedObject as? String == keyboardMenuItemRepresentedObject } private func register(_ event: OEHIDEvent) { // Ignore any off state events guard !event.hasOffState, let selectedKey = selectedKey else { return } setCurrentBindings(for: event) let assignedKey = currentPlayerBindings?.assign(event, toKeyWithName: selectedKey) // automatically selecting the next button confuses VoiceOver if NSWorkspace.shared.isVoiceOverEnabled { changeInputControl(controlsSetupView) return } if let assignedKey = assignedKey as? OEKeyBindingGroupDescription { controlsSetupView.selectNextKeyAfterKeys(assignedKey.keyNames) } else { controlsSetupView.selectNextKeyButton() } changeInputControl(controlsSetupView) } private func setCurrentBindings(for event: OEHIDEvent) { willChangeValue(forKey: "currentPlayerBindings") let isKeyboardEvent = event.type == .keyboard UserDefaults.standard.set(isKeyboardEvent, forKey: keyboardBindingsIsSelectedKey) if !isKeyboardEvent { selectedPlayer = currentSystemBindings?.playerNumber(for: event) ?? 0 } updateInputPopupButtonSelection() didChangeValue(forKey: "currentPlayerBindings") } private func registerEventIfNeeded(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } // Only one event can be managed at a time, all events should be ignored until the currently read event went back to its null state // All ignored events are stored until they go back to the null state @discardableResult private func shouldRegister(_ event: OEHIDEvent) -> Bool { // The event is the currently read event, // if its state is off, nil the reading event, // in either case, this event shouldn't be registered. if readingEvent?.isUsageEqual(to: event) ?? false { if event.hasOffState { readingEvent = nil } return false } if selectedKey == nil && view != view.window?.firstResponder { view.window?.makeFirstResponder(view) } // Check if the event is ignored if ignoredEvents.contains(event) { // Ignored events going back to off-state are removed from the ignored events if event.hasOffState { ignoredEvents.remove(event) } return false } // Esc-key events are handled through NSEvent if event.isEscapeKeyEvent { return false } // Ignore keyboard events if the user hasn’t explicitly chosen to configure // keyboard bindings. See https://github.com/OpenEmu/OpenEmu/issues/403 if event.type == .keyboard && !isKeyboardEventSelected { return false } // No event currently read, if it's not off state, store it and read it if readingEvent == nil { // The event is not ignored but it's off, ignore it anyway if event.hasOffState { return false } readingEvent = event return true } if !event.hasOffState { ignoredEvents.add(event) } return false } override func axisMoved(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } override func triggerPull(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } override func triggerRelease(_ event: OEHIDEvent) { shouldRegister(event) } override func buttonDown(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } override func buttonUp(_ event: OEHIDEvent) { shouldRegister(event) } override func hatSwitchChanged(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } override func hidKeyDown(_ event: OEHIDEvent) { if shouldRegister(event) { register(event) } } override func hidKeyUp(_ event: OEHIDEvent) { shouldRegister(event) } override func mouseDown(with event: NSEvent) { if selectedKey != nil { selectedKey = selectedKey } } override func keyDown(with event: NSEvent) { guard let selectedKey = selectedKey else { return } if event.keyCode == kVK_Escape { currentPlayerBindings?.removeEventForKey(withName: selectedKey) } } override func keyUp(with event: NSEvent) { } // MARK: - func preparePane(with notification: Notification) { let userInfo = notification.userInfo let paneName = userInfo?[PreferencesWindowController.userInfoPanelNameKey] as? String guard paneName == panelTitle else { return } let systemIdentifier = userInfo?[PreferencesWindowController.userInfoSystemIdentifierKey] as? String var itemIndex = -1 for i in 0..<consolesPopupButton.itemArray.count { let item = consolesPopupButton.itemArray[i] if item.representedObject as? String == systemIdentifier { itemIndex = i break } } if itemIndex != -1 { consolesPopupButton.selectItem(at: itemIndex) changeSystem(nil) } } } // MARK: - PreferencePane extension PrefControlsController: PreferencePane { var icon: NSImage? { NSImage(named: "controls_tab_icon") } var panelTitle: String { "Controls" } var viewSize: NSSize { if OEAppearance.controlsPrefs == .wood { return NSSize(width: 755, height: 450) } else { return view.fittingSize } } } fileprivate func makeOEHIDEventSet() -> NSMutableSet { let eqCb: CFSetEqualCallBack = { (pa: UnsafeRawPointer?, pb: UnsafeRawPointer?) -> DarwinBoolean in guard let a = pa, let b = pb else { return false } let v1 = Unmanaged<OEHIDEvent>.fromOpaque(a).takeUnretainedValue() let v2 = Unmanaged<OEHIDEvent>.fromOpaque(b).takeUnretainedValue() return DarwinBoolean(v1.isUsageEqual(to: v2)) } let hashCb: CFSetHashCallBack = { (pa: UnsafeRawPointer?) -> CFHashCode in guard let a = pa else { return 0 } let v = Unmanaged<OEHIDEvent> .fromOpaque(a) .takeUnretainedValue() return v.controlIdentifier } var cb = kCFTypeSetCallBacks cb.equal = eqCb cb.hash = hashCb // We're using CFSet here because NSSet is confused by the changing state of OEHIDEvents return CFSetCreateMutable(kCFAllocatorDefault, 0, &cb) }
38.383142
272
0.636288
40cc1ed708457459d9fdfad35ca557c73d502412
11,035
html
HTML
data/political/2012-2021-house-senate-congressional-districts/index.html
brigsz/agrc.github.io
1d2d85f4d64648aa7c01c37b4a841e60c4bc691d
[ "MIT" ]
null
null
null
data/political/2012-2021-house-senate-congressional-districts/index.html
brigsz/agrc.github.io
1d2d85f4d64648aa7c01c37b4a841e60c4bc691d
[ "MIT" ]
1
2018-09-11T20:03:06.000Z
2018-09-11T23:40:25.000Z
data/political/2012-2021-house-senate-congressional-districts/index.html
brigsz/agrc.github.io
1d2d85f4d64648aa7c01c37b4a841e60c4bc691d
[ "MIT" ]
null
null
null
--- layout: page status: publish published: true title: 2012 - 2021 House, Senate, School Board, and Congressional Districts author: display_name: Jessie Pechmann login: jpechmann email: jpechmann@utah.gov url: '' author_login: jpechmann author_email: jpechmann@utah.gov wordpress_id: 4096 wordpress_url: http://gis.utah.gov/?page_id=4096 date: '2011-12-06 14:34:36 -0700' date_gmt: '2011-12-06 21:34:36 -0700' categories: [] tags: - sgid - Data - utah - gis - map - mapping - political - legislature - voting - House - senate - School Board - Election - Districts - Government - dataset - download - agrc - layer - shapefile - geodatabase - metadata - shp - gdb - kml - lyr - digital - geographic - information - database - state - statewide - representatives --- <div class="caption"><img class="size-full wp-image-4794" src="{{ "/images/SenateDistricts2012_Large_Color4.png" | prepend: site.baseurl }}" alt="PoliticalDistrictsBig" /><p class="caption-text">2012 Political Districts</p></div> <p><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/PackagedData/_Statewide/UtahPoliticalDistricts_Begin2012/" class="button medium white"><span class="button-text">Download Data Package</span></a></p> <h4><strong>2012 Political Districts</strong></h4> <p><strong>Data Type:</strong> GIS Data Layer<br /> <strong>Steward(s):</strong> AGRC and The Lieutenant Governor's Office</p> <p><strong>Abstract:</strong><br /> These new political districts will be used for election purposes beginning January 1, 2012. Elected officials representing the new districts will take office in January 2013. This dataset includes the political districts used for the Utah State Legislature (state senate districts and state house districts); state school board districts; and the new U.S congressional districts. The boundaries for all districts have changed from the <a title="2002 – 2011 House, Senate and Congressional Districts" href="{{ "/data/political/2002-2011-house-senate-congressional-districts/" | prepend: site.baseurl }}">2002-2011 political districts</a>.</p> <p><strong>Data Content:</strong><br /> The following data is available for download:</p> <div class="grid package"> <div class="grid__col grid__col--12-of-12"> <h3 id="StateHouseDistricts">State House Districts</h3> </div> <div class="grid__col grid__col--12-of-12 package-content"> <img class="productImage-Thumb" src="{{ "/images/HouseSmall2.png" | prepend: site.baseurl }}" alt="StateHouseNew" />The Utah House of Representatives is comprised of 75 men and women elected to two-year terms. Political.UtahHouseDistricts2012 shows the new house districts that elected officials will represent.</p> The DIST field contains the House district number.</p> <p>The COLOR4 field is for use in coloring districts using only 4 colors with no adjacent districts displayed with the same color.</p> <p>Statewide Political District Boundaries are drawn by the Utah Legislature and adopted into state law.</p> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel"> <i class="fa fa-pull-right fa-download fa-2x"></i> <h5 id="StateHouseDistricts-downloads">Downloads</h5> </div> <div class="panel-content">Download:</p> <ul> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahHouseDistricts2012/_Statewide/UtahHouseDistricts2012_gdb.zip">State House Districts: File Geodatabase</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahHouseDistricts2012/_Statewide/UtahHouseDistricts2012_shp.zip">State House Districts: Shapefile</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahHouseDistricts2012/_Statewide/UtahHouseDistricts2012.kmz">State House Districts: KMZ</a></li> </ul> <p>Other Links:</p> <ul> <li><a href="http://le.utah.gov/">Utah State Legislature</a></li> <li><a href="http://le.utah.gov/house2/index.html">State of Utah House of Representatives</a></li> </ul> </div> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel update"> <i class="fa fa-pull-right fa-calendar fa-2x"></i> <h5 id="StateHouseDistricts-updates">Updates</h5> </div> <div class="panel-content">This dataset was last updated in 2012.</p> </div> </div> </div><div class="grid package"> <div class="grid__col grid__col--12-of-12"> <h3 id="StateSenateDistricts">State Senate Districts</h3> </div> <div class="grid__col grid__col--12-of-12 package-content"> <img class="productImage-Thumb" src="{{ "/images/SenateDistricts2012_Small_Color4.png" | prepend: site.baseurl }}" alt="StateSenateNew" />The Utah State Senate is comprised of 29 men and women elected to four-year terms. Political.UtahSenateDistricts2012 shows the new senate districts that elected officials will represent.</p> The DIST field contains the Senate district number.</p> <p>The COLOR4 field is for use in coloring districts using only 4 colors with no adjacent districts displayed with the same color.</p> <p>Statewide Political District Boundaries are drawn by the Utah Legislature and adopted into state law.</p> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel"> <i class="fa fa-pull-right fa-download fa-2x"></i> <h5 id="StateSenateDistricts-downloads">Downloads</h5> </div> <div class="panel-content">Download:</p> <ul> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSenateDistricts2012/_Statewide/UtahSenateDistricts2012_gdb.zip">State Senate Districts: File Geodatabase</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSenateDistricts2012/_Statewide/UtahSenateDistricts2012_shp.zip">State Senate Districts: Shapefile</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSenateDistricts2012/_Statewide/UtahSenateDistricts2012.kmz">State Senate Districts: KMZ</a></li> </ul> <p>Other Links:</p> <ul> <li><a href="http://le.utah.gov/">Utah State Legislature</a></li> <li><a href="http://www.utahsenate.org/">Utah State Senate</a></li> </ul> </div> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel update"> <i class="fa fa-pull-right fa-calendar fa-2x"></i> <h5 id="StateSenateDistricts-updates">Updates</h5> </div> <div class="panel-content">This dataset was last updated in 2012.<br /> Recent update summaries:<br /> </div> </div> </div><div class="grid package"> <div class="grid__col grid__col--12-of-12"> <h3 id="StateSchoolBoardDistricts">State School Board Districts</h3> </div> <div class="grid__col grid__col--12-of-12 package-content"> <img class="productImage-Thumb" src="{{ "/images/StateSchoolBoard2012_Small_Color4.png" | prepend: site.baseurl }}" alt="StateSchoolBoardNew" />The Utah State Board of Education is compromised of 15 districts. Political.UtahSchoolBoardDistricts2012 shows the new school board districts that elected officials will represent.</p> The DIST field contains the State School Board district number.</p> <p>The COLOR4 field is for use in coloring districts using only 4 colors with no adjacent districts displayed with the same color.</p> <p>Statewide Political District Boundaries are drawn by the Utah Legislature and adopted into state law.</p> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel"> <i class="fa fa-pull-right fa-download fa-2x"></i> <h5 id="StateSchoolBoardDistricts-downloads">Downloads</h5> </div> <div class="panel-content">Download:</p> <ul> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSchoolBoardDistricts2012/_Statewide/UtahSchoolBoardDistricts2012_gdb.zip">State School Board Districts: File Geodatabase</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSchoolBoardDistricts2012/_Statewide/UtahSchoolBoardDistricts2012_shp.zip">State School Board Districts: Shapefile</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/UtahSchoolBoardDistricts2012/_Statewide/UtahSchoolBoardDistricts2012.kmz">State School Board Districts: KMZ</a></li> </ul> <p>Other Links:</p> <ul> <li><a href="http://le.utah.gov/">Utah State Legislature</a></li> <li><a href="http://www.schools.utah.gov/">Utah School Board Senate</a></li> </ul> </div> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel update"> <i class="fa fa-pull-right fa-calendar fa-2x"></i> <h5 id="StateSchoolBoardDistricts-updates">Updates</h5> </div> <div class="panel-content"> </div> </div> </div><div class="grid package"> <div class="grid__col grid__col--12-of-12"> <h3 id="UnitedStatesCongressionalDistricts">United States Congressional Districts</h3> </div> <div class="grid__col grid__col--12-of-12 package-content"> <img class="productImage-Thumb" src="{{ "/images/CongressionalDistricts2012_Small.png" | prepend: site.baseurl }}" alt="CongressNew" />Starting in the fall 2012 election, Utah will have 4 congressional districts. Political.USCongressDistricts2012 shows the new U.S congressional districts that elected officials will represent.</p> The DISTRICT field contains the US Congressional district number.</p> <p>Statewide Political District Boundaries are drawn by the Utah Legislature and adopted into state law.</p> </p> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel"> <i class="fa fa-pull-right fa-download fa-2x"></i> <h5 id="UnitedStatesCongressionalDistricts-downloads">Downloads</h5> </div> <div class="panel-content">Download:</p> <ul> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/USCongressDistricts2012/_Statewide/USCongressDistricts2012_gdb.zip">US Congress Districts: File Geodatabase</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/USCongressDistricts2012/_Statewide/USCongressDistricts2012_shp.zip">US Congress Districts: Shapefile</a></li> <li><a href="ftp://ftp.agrc.utah.gov/UtahSGID_Vector/UTM12_NAD83/POLITICAL/UnpackagedData/USCongressDistricts2012/_Statewide/USCongressDistricts2012.kmz">US Congress Districts: KMZ</a></li> </ul> </div> </div> <div class="grid__col grid__col--1-of-2"> <div class="panel update"> <i class="fa fa-pull-right fa-calendar fa-2x"></i> <h5 id="UnitedStatesCongressionalDistricts-updates">Updates</h5> </div> <div class="panel-content"></p> <p>This dataset was last updated in 2012.<br /> Recent update summaries:<br /> </div> </div> </div>
52.051887
641
0.726778
774c7c53dca0ffa973c56425cfaf0d9c032d9053
2,382
html
HTML
catalog/templates/catalog/product_details.html
cyrildzumts/django-catalog
5857c6e4ceddedfe0c5f714e4cc6b858e953feb7
[ "BSD-3-Clause" ]
null
null
null
catalog/templates/catalog/product_details.html
cyrildzumts/django-catalog
5857c6e4ceddedfe0c5f714e4cc6b858e953feb7
[ "BSD-3-Clause" ]
null
null
null
catalog/templates/catalog/product_details.html
cyrildzumts/django-catalog
5857c6e4ceddedfe0c5f714e4cc6b858e953feb7
[ "BSD-3-Clause" ]
null
null
null
{% extends "base_flat.html" %} {%block banner_extra%} <div class="card-flat-category"> <ul class="breadcrumb"> {% for c in product.cats_path %} <li><a href="{{c.get_absolute_url}}">{{c.name}}</a></li> {% endfor %} </ul> </div> {%endblock banner_extra%} {%block content_header%} <div class="col-md-12 col-sm-12 col-xs-12 flex-container bg-ebony"> <div class="p-product-name">{{product.name}} {%if product.is_available is False%} <span class="not-in-stock"> Epuisé !!! </span> {%endif%} </div> </div> {%endblock content_header%} {% block MAINCONTENT %} <div class="product-card bordered"> <div class="flat-product-image bordered"> <div class="image-container"> <img class="img-responsive" src="{{product.image.url}}" alt="{{product.name}}" /> </div> </div> <div class="product-details bordered"> <div class="detail-content"> <p>Marque: <strong><em>{{product.brand}}</em> </strong></p> {% if product.size is not None %} <p>Taille: {{product.size}}</p> {%endif%} {% if product.template_name is not None%} {% include product.template_name %} {%endif%} {% if product.old_price is True %} <p class="invalid">Coûtait : {{product.old_price}} CFA </p> {% endif %} <p>Prix : <strong>{{product.price}} CFA </strong></p> <div class="popover" id="cart-popover" data-toggle="popover" title="Message" data-content=""> </div> <div class="btn-box" data-itemid="{{product.id}}" data-name="{{product.name}}"> <span class="add-to-cart add-btn text-box glyphicon glyphicon-shopping-cart bordered bg-success" data-available="{{product.is_available}}" data-itemid="{{product.id}}" title="Ajouter dans le Panier"> Ajouter dans le panier </span> <span class="add-to-wishlist add-btn text-box glyphicon glyphicon-heart bordered" data-itemid="{{product.id}}" data-name="{{product.name}}" title="Ajouter dans la wishlist"> Ajouter dans la wishlist </span> </div> <div class="description"> <h3> Description du produit </h3> <p>{{product.description}}</p> </div> </div> </div> </div> {% endblock MAINCONTENT%}
31.76
114
0.569689
f653b34021c7e662d769199dfc57552e367f75a6
3,887
asm
Assembly
Transynther/x86/_processed/US/_zr_un_/i3-7100_9_0x84_notsx.log_867_1366.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/US/_zr_un_/i3-7100_9_0x84_notsx.log_867_1366.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/US/_zr_un_/i3-7100_9_0x84_notsx.log_867_1366.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r15 push %rbp push %rbx push %rdi // Store lea addresses_A+0x1d32c, %r10 nop nop xor %r15, %r15 mov $0x5152535455565758, %r11 movq %r11, %xmm1 vmovups %ymm1, (%r10) xor $29832, %r15 // Store lea addresses_A+0x629c, %rbx nop nop nop dec %rbp mov $0x5152535455565758, %r11 movq %r11, %xmm6 movups %xmm6, (%rbx) add %r12, %r12 // Faulty Load lea addresses_US+0x1543c, %r15 cmp $35064, %rdi movups (%r15), %xmm1 vpextrq $0, %xmm1, %rbp lea oracles, %r12 and $0xff, %rbp shlq $12, %rbp mov (%r12,%rbp,1), %rbp pop %rdi pop %rbx pop %rbp pop %r15 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'same': False, 'size': 1, 'congruent': 0, 'NT': True, 'AVXalign': True}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 32, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_US', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'00': 16, 'e2': 48, 'd0': 803} 00 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 e2 d0 e2 d0 d0 d0 d0 d0 e2 e2 e2 00 e2 d0 d0 d0 d0 00 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 00 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 00 d0 e2 d0 d0 e2 e2 d0 00 e2 e2 d0 e2 e2 d0 d0 d0 00 e2 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 e2 e2 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 e2 d0 e2 00 e2 e2 d0 d0 d0 e2 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 00 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 00 00 d0 d0 d0 d0 d0 00 d0 d0 e2 d0 d0 d0 d0 00 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 e2 e2 00 e2 d0 d0 d0 d0 e2 e2 d0 d0 d0 e2 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 e2 d0 d0 d0 d0 d0 d0 00 d0 d0 d0 d0 d0 d0 00 d0 d0 e2 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 d0 */
58.893939
2,600
0.658348
f71daa48c1b874a70df257a5582efcffa3d58f6c
254
h
C
src/workflow/get_mnemonic_passphrase.h
conte91/bitbox02-firmware
8a3b311583c33e70fd8a99e2247004d8eaf406df
[ "Apache-2.0" ]
null
null
null
src/workflow/get_mnemonic_passphrase.h
conte91/bitbox02-firmware
8a3b311583c33e70fd8a99e2247004d8eaf406df
[ "Apache-2.0" ]
null
null
null
src/workflow/get_mnemonic_passphrase.h
conte91/bitbox02-firmware
8a3b311583c33e70fd8a99e2247004d8eaf406df
[ "Apache-2.0" ]
null
null
null
#ifndef _GET_MNEMONIC_PASSPHRASE_H #define _GET_MNEMONIC_PASSPHRASE_H #include <stdbool.h> #include "workflow.h" workflow_t* workflow_get_mnemonic_passphrase(void (*callback)(char*, void*), void* callback_param); #endif // _GET_MNEMONIC_PASSPHRASE_H
23.090909
99
0.811024
400e567e3e0141a2004ade382fb77d87fe771212
2,219
py
Python
robo_trace_evaluation/src/experiments/b/evaluate.py
tu-darmstadt-ros-pkg/robo_trace
60ce64d60110597a0c077aa31199481c20d164b2
[ "BSD-3-Clause" ]
null
null
null
robo_trace_evaluation/src/experiments/b/evaluate.py
tu-darmstadt-ros-pkg/robo_trace
60ce64d60110597a0c077aa31199481c20d164b2
[ "BSD-3-Clause" ]
null
null
null
robo_trace_evaluation/src/experiments/b/evaluate.py
tu-darmstadt-ros-pkg/robo_trace
60ce64d60110597a0c077aa31199481c20d164b2
[ "BSD-3-Clause" ]
null
null
null
import os import logging import sys sys.path.append('../../') from loader import * from parameters import * from plotting import * logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) def create_tag_provider(include_topic): def get_tags(name): tags = name.split("/")[-1].split("_") result = { 'robot': tags[1], 'idx': int(tags[2].replace(".csv", "")), 'downsampling': int(tags[3].replace('D', '')), 'encrypted': tags[4] == "E0" } if include_topic: result['topic'] = ('_'.join(tags[5:])).replace(".csv", "") return result return get_tags def print_sys_data(sys): logging.info("System Utilization Stats") for topic in sys["topic"].unique(): logging.info(f" + topic: {topic}") rdat = sys[sys["topic"] == topic] for encryption in sys["encrypted"].unique(): logging.info(f" = encryption: {encryption}") edata = rdat[rdat["encrypted"] == encryption] for downsampling in sys["downsampling"].unique(): logging.info(f" = downsampling: {downsampling}") ddat = edata[edata["downsampling"] == downsampling] cpu = ddat["cpu"].to_numpy() mem = ddat["memory"].to_numpy() logging.info(f" CPU in %") logging.info(f" CPU Mean: {np.mean(cpu)}") logging.info(f" CPU Std: {np.std(cpu)}") logging.info(f" CPU Med: {np.median(cpu)}") logging.info(f" MEM in MB") logging.info(f" MEM Mean: {np.mean(mem)}") logging.info(f" MEM Std: {np.std(mem)}") logging.info(f" MEM Med: {np.median(mem)}") # # Table on "System Utiliencryptedzation". # utilization_dump = get_dump( name="two", file_regex=f"{FILE_NAME_PREFIX_UTILIZATION}*.csv", processor=[ processor_exclude_topics, processor_adjust_memory, processor_adjust_topic_name ], tag_extractor=create_tag_provider(True) ) print_sys_data(utilization_dump)
27.395062
75
0.541685
85b4a044771cf40c388755b5e3a6c02de7ccb1f1
14,291
c
C
class/me3616/at_socket_me3616.c
liukangcc/at_device
86390375518a421e5d58ec481ced484c349e8a76
[ "Apache-2.0" ]
null
null
null
class/me3616/at_socket_me3616.c
liukangcc/at_device
86390375518a421e5d58ec481ced484c349e8a76
[ "Apache-2.0" ]
null
null
null
class/me3616/at_socket_me3616.c
liukangcc/at_device
86390375518a421e5d58ec481ced484c349e8a76
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2006-2022, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2019-12-30 qiyongzhong first version */ #include <stdio.h> #include <string.h> #include <at_device_me3616.h> #define LOG_TAG "at.skt.me3616" #include <at_log.h> #if defined(AT_DEVICE_USING_ME3616) && defined(AT_USING_SOCKET) #define ME3616_MODULE_SEND_MAX_SIZE 512 static int me3616_socket_fd[AT_DEVICE_ME3616_SOCKETS_NUM] = {0}; static at_evt_cb_t at_evt_cb_set[] = { [AT_SOCKET_EVT_RECV] = NULL, [AT_SOCKET_EVT_CLOSED] = NULL, }; static int me3616_get_socket_idx(int sock) { int i; if (sock < 0) { return(-1); } for (i=0; i<AT_DEVICE_ME3616_SOCKETS_NUM; i++) { if (me3616_socket_fd[i] == sock) return(i); } return(-1); } /** * close socket by AT commands. * * @param current socket * * @return 0: close socket success * -1: send AT commands error * -2: wait socket event timeout * -5: no memory */ static int me3616_socket_close(struct at_socket *socket) { int result = RT_EOK; at_response_t resp = RT_NULL; int device_socket = (int) socket->user_data; struct at_device *device = (struct at_device *) socket->device; if (me3616_socket_fd[device_socket] == -1) { return RT_EOK; } resp = at_create_resp(64, 0, rt_tick_from_millisecond(300)); if (resp == RT_NULL) { LOG_E("no memory for resp create."); return -RT_ENOMEM; } result = at_obj_exec_cmd(device->client, resp, "AT+ESOCL=%d", me3616_socket_fd[device_socket]); me3616_socket_fd[device_socket] = -1; at_delete_resp(resp); return result; } /** * create TCP/UDP client or server connect by AT commands. * * @param socket current socket * @param ip server or client IP address * @param port server or client port * @param type connect socket type(tcp, udp) * @param is_client connection is client * * @return 0: connect success * -1: connect failed, send commands error or type error * -2: wait socket event timeout * -5: no memory */ static int me3616_socket_connect(struct at_socket *socket, char *ip, int32_t port, enum at_socket_type type, rt_bool_t is_client) { #define CONN_RESP_SIZE 128 int type_code = 0; int result = RT_EOK; at_response_t resp = RT_NULL; int device_socket = (int) socket->user_data; struct at_device *device = (struct at_device *) socket->device; int sock = -1; RT_ASSERT(ip); RT_ASSERT(port >= 0); if ( ! is_client) { return -RT_ERROR; } switch(type) { case AT_SOCKET_TCP: type_code = 1; break; case AT_SOCKET_UDP: type_code = 2; break; default: LOG_E("%s device socket(%d) connect type error.", device->name, device_socket); return -RT_ERROR; } resp = at_create_resp(CONN_RESP_SIZE, 0, rt_tick_from_millisecond(300)); if (resp == RT_NULL) { LOG_E("no memory for resp create."); return -RT_ENOMEM; } if (me3616_socket_fd[device_socket] != -1) { at_obj_exec_cmd(device->client, resp, "AT+ESOCL=%d", me3616_socket_fd[device_socket]); me3616_socket_fd[device_socket] = -1; } if (at_obj_exec_cmd(device->client, resp, "AT+ESOC=1,%d,1", type_code) < 0) { result = -RT_ERROR; goto __exit; } if (at_resp_parse_line_args_by_kw(resp, "+ESOC=", "+ESOC=%d", &sock) <= 0) { result = -RT_ERROR; goto __exit; } at_resp_set_info(resp, CONN_RESP_SIZE, 0, (45*RT_TICK_PER_SECOND)); if (at_obj_exec_cmd(device->client, resp, "AT+ESOCON=%d,%d,\"%s\"", sock, port, ip) < 0) { at_resp_set_info(resp, CONN_RESP_SIZE, 0, rt_tick_from_millisecond(300)); at_obj_exec_cmd(device->client, resp, "AT+ESOCL=%d", sock); result = -RT_ERROR; goto __exit; } me3616_socket_fd[device_socket] = sock; __exit: if (resp) { at_delete_resp(resp); } return result; } static int at_get_send_size(struct at_socket *socket, size_t *nacked) { int result = 0; at_response_t resp = RT_NULL; int device_socket = (int) socket->user_data; struct at_device *device = (struct at_device *) socket->device; int remain_size; resp = at_create_resp(64, 0, rt_tick_from_millisecond(300)); if (resp == RT_NULL) { LOG_E("no memory for resp create.", device->name); return -RT_ENOMEM; } if (at_obj_exec_cmd(device->client, resp, "AT+ESOTCPBUF=%d", me3616_socket_fd[device_socket]) < 0) { result = -RT_ERROR; goto __exit; } if (at_resp_parse_line_args_by_kw(resp, "+ESOTCPBUF=", "+ESOTCPBUF=%d", &remain_size) <= 0) { result = -RT_ERROR; goto __exit; } *nacked = 4096 - remain_size; __exit: if (resp) { at_delete_resp(resp); } return result; } static int at_wait_send_finish(struct at_socket *socket, rt_tick_t timeout) { rt_tick_t last_time = rt_tick_get(); size_t nacked = 0xFFFF; while (rt_tick_get() - last_time <= timeout) { at_get_send_size(socket, &nacked); if (nacked == 0) { return RT_EOK; } rt_thread_mdelay(50); } return -RT_ETIMEOUT; } /** * send data to server or client by AT commands. * * @param socket current socket * @param buff send buffer * @param bfsz send buffer size * @param type connect socket type(tcp, udp) * * @return >=0: the size of send success * -1: send AT commands error or send data error * -2: waited socket event timeout * -5: no memory */ static int me3616_socket_send(struct at_socket *socket, const char *buff, size_t bfsz, enum at_socket_type type) { #define SEND_RESP_SIZE 128 int result = 0; size_t cur_pkt_size = 0, sent_size = 0; at_response_t resp = RT_NULL; int device_socket = (int) socket->user_data; struct at_device *device = (struct at_device *) socket->device; rt_mutex_t lock = device->client->lock; RT_ASSERT(buff); resp = at_create_resp(SEND_RESP_SIZE, 2, RT_TICK_PER_SECOND/2); if (resp == RT_NULL) { LOG_E("no memory for resp create."); return -RT_ENOMEM; } rt_mutex_take(lock, RT_WAITING_FOREVER); while (sent_size < bfsz) { if (bfsz - sent_size < ME3616_MODULE_SEND_MAX_SIZE) { cur_pkt_size = bfsz - sent_size; } else { cur_pkt_size = ME3616_MODULE_SEND_MAX_SIZE; } at_resp_set_info(resp, SEND_RESP_SIZE, 2, RT_TICK_PER_SECOND/2); if (at_obj_exec_cmd(device->client, resp, "AT+ESOSENDRAW=%d,%d", me3616_socket_fd[device_socket], (int)cur_pkt_size) < 0) { result = -RT_ERROR; goto __exit; } if (at_resp_get_line_by_kw(resp, "CONNECT") == RT_NULL) { result = -RT_ERROR; goto __exit; } rt_thread_mdelay(5);//delay at least 4 ms /* send the real data to server or client */ result = (int) at_client_obj_send(device->client, buff + sent_size, cur_pkt_size); if (result == 0) { result = -RT_ERROR; goto __exit; } /* wait respone "NO CARRIER ... OK " */ at_resp_set_info(resp, SEND_RESP_SIZE, 0, (2*RT_TICK_PER_SECOND)); if (at_obj_exec_cmd(device->client, resp, "") < 0) { result = -RT_ERROR; goto __exit; } if (type == AT_SOCKET_TCP) { at_wait_send_finish(socket, (5*RT_TICK_PER_SECOND)); } else { rt_thread_mdelay(10);//delay at least 10 ms } sent_size += cur_pkt_size; } __exit: rt_mutex_release(lock); if (resp) { at_delete_resp(resp); } return result > 0 ? sent_size : result; } /** * domain resolve by AT commands. * * @param name domain name * @param ip parsed IP address, it's length must be 16 * * @return 0: domain resolve success * -1: send AT commands error or response error * -2: wait socket event timeout * -5: no memory */ static int me3616_domain_resolve(const char *name, char ip[16]) { int result; at_response_t resp = RT_NULL; struct at_device *device = RT_NULL; RT_ASSERT(name); RT_ASSERT(ip); device = at_device_get_first_initialized(); if (device == RT_NULL) { LOG_E("get first init device failed."); return -RT_ERROR; } resp = at_create_resp(128, 0, (15 * RT_TICK_PER_SECOND)); if (!resp) { LOG_E("no memory for resp create."); return -RT_ENOMEM; } result = at_obj_exec_cmd(device->client, resp, "AT+EDNS=\"%s\"", name); if (result != RT_EOK) { LOG_E("%s device \"AT+EDNS=\"%s\"\" cmd error.", device->name, name); goto __exit; } if (at_resp_parse_line_args_by_kw(resp, "IPV4:", "IPV4:%s\r", ip) <= 0) { LOG_E("%s device prase \"AT+EDNS=\"%s\"\" cmd error.", device->name, name); result = -RT_ERROR; goto __exit; } ip[15] = 0; if (rt_strlen(ip) < 8) { result = -RT_ERROR; } else { result = RT_EOK; } __exit: if (resp) { at_delete_resp(resp); } return result; } /** * set AT socket event notice callback * * @param event notice event * @param cb notice callback */ static void me3616_socket_set_event_cb(at_socket_evt_t event, at_evt_cb_t cb) { if (event < sizeof(at_evt_cb_set) / sizeof(at_evt_cb_set[1])) { at_evt_cb_set[event] = cb; } } static void urc_close_func(struct at_client *client, const char *data, rt_size_t size) { int sock = -1; int err_code = 0; int device_socket = 0; struct at_socket *socket = RT_NULL; struct at_device *device = RT_NULL; char *client_name = client->device->parent.name; RT_ASSERT(data && size); device = at_device_get_by_name(AT_DEVICE_NAMETYPE_CLIENT, client_name); if (device == RT_NULL) { LOG_E("get device(%s) failed.", client_name); return; } sscanf(data, "+ESOERR=%d,%d", &sock, &err_code); device_socket = me3616_get_socket_idx(sock); if (device_socket < 0 || err_code < 0 || err_code > 4) { return; } /* get at socket object by device socket descriptor */ socket = &(device->sockets[device_socket]); /* notice the socket is disconnect by remote */ if (at_evt_cb_set[AT_SOCKET_EVT_CLOSED]) { at_evt_cb_set[AT_SOCKET_EVT_CLOSED](socket, AT_SOCKET_EVT_CLOSED, NULL, 0); } } static void urc_recv_func(struct at_client *client, const char *data, rt_size_t size) { int sock = -1; int device_socket = 0; rt_int32_t timeout; rt_size_t bfsz = 0, temp_size = 0; char *recv_buf = RT_NULL, temp[8] = {0}; struct at_socket *socket = RT_NULL; struct at_device *device = RT_NULL; char *client_name = client->device->parent.name; RT_ASSERT(data && size); device = at_device_get_by_name(AT_DEVICE_NAMETYPE_CLIENT, client_name); if (device == RT_NULL) { LOG_E("get device(%s) failed.", client_name); return; } sscanf(data, "+ESONMI=%d,", &sock); device_socket = me3616_get_socket_idx(sock); if (device_socket < 0) { return; } while(temp_size < sizeof(temp)) { at_client_obj_recv(client, temp+temp_size, 1, 10); if ( *(temp+temp_size) == ',') { *(temp+temp_size) = 0; break; } temp_size++; } if (temp_size == sizeof(temp)) { return; } sscanf(temp, "%d", (int *)&bfsz); if(bfsz == 0) { return; } timeout = bfsz > 10 ? bfsz : 10; recv_buf = (char *) rt_calloc(1, bfsz); if (recv_buf == RT_NULL) { LOG_E("no memory for URC receive buffer(%d).", bfsz); /* read and clean the coming data */ temp_size = 0; while (temp_size < bfsz) { if (bfsz - temp_size > sizeof(temp)) { at_client_obj_recv(client, temp, sizeof(temp), timeout); } else { at_client_obj_recv(client, temp, bfsz - temp_size, timeout); } temp_size += sizeof(temp); } return; } if (at_client_obj_recv(client, recv_buf, bfsz, timeout) != bfsz) { LOG_E("%s device receive size(%d) data failed.", device->name, bfsz); rt_free(recv_buf); return; } /* read end "\r\n" */ at_client_obj_recv(client, temp, 2, 5); /* get at socket object by device socket descriptor */ socket = &(device->sockets[device_socket]); /* notice the receive buffer and buffer size */ if (at_evt_cb_set[AT_SOCKET_EVT_RECV]) { at_evt_cb_set[AT_SOCKET_EVT_RECV](socket, AT_SOCKET_EVT_RECV, recv_buf, bfsz); } } static const struct at_urc urc_table[] = { {"+ESOERR=", "\r\n", urc_close_func}, {"+ESONMI=", ",", urc_recv_func}, }; static const struct at_socket_ops me3616_socket_ops = { me3616_socket_connect, me3616_socket_close, me3616_socket_send, me3616_domain_resolve, me3616_socket_set_event_cb, #if defined(AT_SW_VERSION_NUM) && AT_SW_VERSION_NUM > 0x10300 RT_NULL, #endif }; int me3616_socket_init(struct at_device *device) { RT_ASSERT(device); rt_memset(me3616_socket_fd, -1, sizeof(me3616_socket_fd)); /* register URC data execution function */ at_obj_set_urc_table(device->client, urc_table, sizeof(urc_table) / sizeof(urc_table[0])); return RT_EOK; } int me3616_socket_class_register(struct at_device_class *class) { RT_ASSERT(class); class->socket_num = AT_DEVICE_ME3616_SOCKETS_NUM; class->socket_ops = &me3616_socket_ops; return RT_EOK; } #endif /* AT_DEVICE_USING_ME3616 && AT_USING_SOCKET */
24.47089
129
0.601078
22d4898413efb6c685e61286cc3f58b6520cf130
2,943
h
C
db/rocksdb_db.h
ldeng-ustc/YCSB-C
b1efdf1a27548ee04f61e6404e3a85b717271fb6
[ "Apache-2.0" ]
null
null
null
db/rocksdb_db.h
ldeng-ustc/YCSB-C
b1efdf1a27548ee04f61e6404e3a85b717271fb6
[ "Apache-2.0" ]
null
null
null
db/rocksdb_db.h
ldeng-ustc/YCSB-C
b1efdf1a27548ee04f61e6404e3a85b717271fb6
[ "Apache-2.0" ]
null
null
null
// // rocksdb_db.h // YCSB-C // #ifndef YCSB_C_ROCKSDB_DB_H_ #define YCSB_C_ROCKSDB_DB_H_ #include "core/db.h" #include <iostream> #include <string> #include <vector> #include <mutex> #include "core/properties.h" #include "tbb/concurrent_unordered_map.h" #include "rocksdb/db.h" namespace ycsbc { class RocksDB : public DB { public: RocksDB(utils::Properties &props); void Init(); void Close(); int Read(const std::string &table, const std::string &key, const std::vector<std::string> *fields, std::vector<KVPair> &result); int Scan(const std::string &table, const std::string &key, int len, const std::vector<std::string> *fields, std::vector<std::vector<KVPair>> &result); int Update(const std::string &table, const std::string &key, std::vector<KVPair> &values); int Insert(const std::string &table, const std::string &key, std::vector<KVPair> &values); int Delete(const std::string &table, const std::string &key); private: struct ColumnFamily { rocksdb::ColumnFamilyHandle *handle; rocksdb::ColumnFamilyOptions options; ColumnFamily() = default; ColumnFamily(rocksdb::ColumnFamilyHandle *handle, rocksdb::ColumnFamilyOptions options) : handle(handle), options(options) {} }; static inline const std::string kPropertyRocksdbDir = "rocksdb.dir"; static inline const std::string kPropertyRocksdbOptionsFile = "rocksdb.optionsfile"; static inline const std::string kColumnFamilyNamesFilename = "CF_NAMES"; static inline std::string rocksdb_dir_ = ""; static inline std::string option_file_ = ""; static inline rocksdb::DBOptions db_options_{}; static inline rocksdb::DB *rocksdb_ = nullptr; static inline int references_ = 0; static inline std::mutex mutex_{}; static inline tbb::concurrent_unordered_map<std::string, ColumnFamily> column_families_{}; static inline tbb::concurrent_unordered_map<std::string, std::recursive_mutex*> column_family_locks_{}; /// /// Initializes and opens the RocksDB database. /// Should only be called by the thread owns mutex_. /// /// @return The initialized and open RocksDB instance. /// rocksdb::DB* InitRocksDBWithOptionsFile(); /// /// Initializes and opens the RocksDB database. /// Should only be called by the thread owns mutex_. /// /// @return The initialized and open RocksDB instance. /// rocksdb::DB* InitRocksDB(); void SaveColumnFamilyNames(); std::vector<std::string> LoadColumnFamilyNames(); void CreateColumnFamily(const std::string & name); rocksdb::ColumnFamilyOptions GetDefaultColumnFamilyOptions(const std::string & name); std::string SerializeValues(const std::vector<KVPair> & values); void DeserializeValues(const rocksdb::Slice & values, const std::vector<std::string> * fields, std::vector<KVPair> * result); }; } // ycsbc #endif // YCSB_C_REDIS_DB_H_
28.852941
105
0.700985
d17e46389337ccc98ef2d4556149880add918a7e
2,631
swift
Swift
plugin_mods/speechrecognition/org.apache.cordova.speech.speechrecognition/src/ios/CDVSpeechRecognition.swift
fq-selbach/sepia-html-client-app
624b8fc6ec703cc2bd4f7253b64c9fbca0385f6c
[ "MIT" ]
38
2018-06-19T07:39:03.000Z
2022-03-14T18:44:25.000Z
plugin_mods/speechrecognition/org.apache.cordova.speech.speechrecognition/src/ios/CDVSpeechRecognition.swift
fq-selbach/sepia-html-client-app
624b8fc6ec703cc2bd4f7253b64c9fbca0385f6c
[ "MIT" ]
5
2018-12-18T18:03:36.000Z
2021-04-24T07:51:54.000Z
plugin_mods/speechrecognition/org.apache.cordova.speech.speechrecognition/src/ios/CDVSpeechRecognition.swift
fq-selbach/sepia-html-client-app
624b8fc6ec703cc2bd4f7253b64c9fbca0385f6c
[ "MIT" ]
10
2019-01-03T18:12:49.000Z
2022-03-09T09:50:49.000Z
/** # Cordova Plugin Speech Recognition for iOS. Add the voice recognition function to the application using the Siri API. Target OS Version : iOS(ver 10.0 or Higher) copyright (C) 2016 SOHKAKUDO Ltd. All Rights Reserved. */ @objc(CDVSpeechRecognition) class SpeechRecognition : CDVPlugin, SpeechRecognitionDelegate { private var srvc : CDVSpeechRecognitionViewController = CDVSpeechRecognitionViewController() private var enabled: Bool = false private var thisCommand: CDVInvokedUrlCommand = CDVInvokedUrlCommand() func initialize(_ command: CDVInvokedUrlCommand) { super.pluginInitialize() srvc = CDVSpeechRecognitionViewController() srvc.delegate = self } func start(_ command: CDVInvokedUrlCommand) { thisCommand = command if(srvc.isEnabled()) { let lang = command.argument(at: 0) as! String if(lang is String == false) { returnResult(statusIsOK: false, returnString: "langIsNotString", messageType: "error") return } let micOpenDest = command.argument(at: 1) if(micOpenDest is String == false) { returnResult(statusIsOK: false, returnString: "micOpenDestIsNotString", messageType: "error") return } let micCloseDest = command.argument(at: 2) if(micCloseDest is String == false) { returnResult(statusIsOK: false, returnString: "micCloseDestIsNotString", messageType: "error") return } srvc.setRequiredVariables(micO: micOpenDest as! String, micC: micCloseDest as! String) srvc.recordButtonTapped(language: lang) } else { returnResult(statusIsOK: false, returnString: "pluginIsDisabled", messageType: "error") } } func stop(_ command: CDVInvokedUrlCommand) { srvc.InterruptEvent() } /** SpeechRecognizer time up Handler. */ func timeOut() { returnResult(statusIsOK: false, returnString: "timeOut", messageType: "error") } /** returns the result to the calling app. */ func returnResult(statusIsOK: Bool, returnString: String, messageType: String) -> Void { let sendStatus = statusIsOK ? CDVCommandStatus_OK : CDVCommandStatus_ERROR let event = ["type": messageType, "message": returnString] let result = CDVPluginResult(status: sendStatus, messageAs: event) result!.setKeepCallbackAs(true); self.commandDelegate!.send(result, callbackId:thisCommand.callbackId) } }
41.109375
110
0.647662
269e0002d5411dd5771a9a067a9b5d52fd5b785f
1,595
java
Java
src/dao/custom/impl/OrderDetailDAOImpl.java
IrushiSalwathura/point-of-sales-system-layered
74f4fcc6febf6239ebe93d54014fc0d049c9c3fd
[ "MIT" ]
null
null
null
src/dao/custom/impl/OrderDetailDAOImpl.java
IrushiSalwathura/point-of-sales-system-layered
74f4fcc6febf6239ebe93d54014fc0d049c9c3fd
[ "MIT" ]
null
null
null
src/dao/custom/impl/OrderDetailDAOImpl.java
IrushiSalwathura/point-of-sales-system-layered
74f4fcc6febf6239ebe93d54014fc0d049c9c3fd
[ "MIT" ]
null
null
null
package dao.custom.impl; import dao.CrudUtil; import dao.custom.OrderDetailDAO; import entity.OrderDetail; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class OrderDetailDAOImpl implements OrderDetailDAO { public List<OrderDetail> findAll() throws Exception { ResultSet rst = CrudUtil.execute("SELECT * from OrderDetail"); ArrayList<OrderDetail> orderDetails = new ArrayList<>(); while(rst.next()){ orderDetails.add(new OrderDetail(rst.getString(1),rst.getString(2),rst.getInt(3),rst.getBigDecimal(4))); } return orderDetails; } public OrderDetail find(String pk) throws Exception { ResultSet rst = CrudUtil.execute("SELECT * FROM OrderDetail WHERE id=?"); while(rst.next()){ return new OrderDetail(rst.getString(1),rst.getString(2),rst.getInt(3),rst.getBigDecimal(4)); } return null; } public boolean save(OrderDetail entity) throws Exception { return CrudUtil.execute("INSERT INTO OrderDetail VALUES (?,?,?,?)",entity.getOrderId(),entity.getItemCode(),entity.getQty(),entity.getUnitPrice()); } public boolean update(OrderDetail entity) throws Exception { return CrudUtil.execute("UPDATE OrderDetail SET qty=?,uniPrice=? WHERE orderId=? AND itemCode=?",entity.getQty(),entity.getUnitPrice(),entity.getOrderId(),entity.getItemCode()); } public boolean delete(String pk) throws Exception { return CrudUtil.execute("DELETE FROM OrderDetail WHERE id=?",pk); } }
37.97619
185
0.697806
4be993361ede6ddc6f90a12dff57d0bc747c4039
424
swift
Swift
Framework/Framework.swift
eunikolsky/XCTestExtensions
9fd40d3ce0d8e13bfb98f09c460b19802e07d0f0
[ "MIT" ]
null
null
null
Framework/Framework.swift
eunikolsky/XCTestExtensions
9fd40d3ce0d8e13bfb98f09c460b19802e07d0f0
[ "MIT" ]
null
null
null
Framework/Framework.swift
eunikolsky/XCTestExtensions
9fd40d3ce0d8e13bfb98f09c460b19802e07d0f0
[ "MIT" ]
null
null
null
// // Framework.swift // Framework // // Created by u on 28.11.20. // Copyright (c) 2020 yes. All rights reserved. // import Foundation /// Framework's public namespace. public enum Framework {} public extension Framework { /// The magic number defined by this framework. static let magicNumber = 42 /// A magic string that is calculated by this framework. static let magicString: String? = "foobar" }
20.190476
60
0.688679
166e84622a2b59f4382edcdf58a9488278db483e
2,140
ts
TypeScript
scripts/components/LviReview.ts
smartface/sample-mcommerce
4d3321e35445a171af489b56d9320dcfc852ad9b
[ "MIT" ]
2
2021-12-22T12:16:15.000Z
2022-03-01T10:50:03.000Z
scripts/components/LviReview.ts
smartface/sample-mcommerce
4d3321e35445a171af489b56d9320dcfc852ad9b
[ "MIT" ]
3
2022-01-18T15:21:12.000Z
2022-03-09T07:52:59.000Z
scripts/components/LviReview.ts
smartface/sample-mcommerce
4d3321e35445a171af489b56d9320dcfc852ad9b
[ "MIT" ]
2
2021-12-19T19:35:45.000Z
2022-01-17T06:07:02.000Z
import Screen from '@smartface/native/device/screen'; import { REVIEW_MAX_LINE } from 'constants'; import LviReviewDesign from 'generated/my-components/LviReview'; import { setTextDimensions } from 'lib/setTextDimensions'; import { themeService } from 'theme'; const { paddingBottom: reviewPaddingBottom, paddingTop: reviewPaddingTop, paddingLeft, paddingRight } = themeService.getNativeStyle('.flReview'); const titleHeight = themeService.getNativeStyle('.flReview-flHeader').height; const { height: lblDateHeight, marginBottom: lblDateMarginBottom } = themeService.getNativeStyle('.flReview-lblDate'); const { height: separatorHeight } = themeService.getNativeStyle('.separator'); const { font: lblFont } = themeService.getNativeStyle('.review.lblComment'); const commentMaxWidth = Screen.width - (paddingLeft + paddingRight); export default class LviReview extends LviReviewDesign { pageName?: string | undefined; constructor(props?: any, pageName?: string) { super(props); this.pageName = pageName; } static getHeight(comment: string): number { const { height: commentHeight } = setTextDimensions(comment, lblFont, { maxLines: REVIEW_MAX_LINE, maxWidth: commentMaxWidth }); return reviewPaddingTop + reviewPaddingBottom + titleHeight + lblDateHeight + lblDateMarginBottom + commentHeight + separatorHeight; } get name(): string { return this.flReview.name; } set name(value: string) { this.flReview.name = value; } get star(): string { return this.flReview.star; } set star(value: string) { this.flReview.star = value; } get date(): string { return this.flReview.lblDate.text; } set date(value: string) { this.flReview.lblDate.text = value; } get comment(): string { return this.flReview.comment; } set comment(value: string) { this.flReview.comment = value; } get showSeparator(): boolean { return this.flReview.showSeparator; } set showSeparator(value: boolean) { this.flReview.showSeparator = value; } }
36.271186
140
0.689252
331f06145206acb198e0044dbd6333cd441dd2cf
1,073
py
Python
doc/programming/parts/python-columninfo.py
laigor/sqlrelay-non-english-fixes-
7803f862ddbf88bca078c50d621c64c22fc0a405
[ "PHP-3.01", "CC-BY-3.0" ]
16
2018-04-23T09:58:33.000Z
2022-01-31T13:40:20.000Z
doc/programming/parts/python-columninfo.py
laigor/sqlrelay-non-english-fixes-
7803f862ddbf88bca078c50d621c64c22fc0a405
[ "PHP-3.01", "CC-BY-3.0" ]
null
null
null
doc/programming/parts/python-columninfo.py
laigor/sqlrelay-non-english-fixes-
7803f862ddbf88bca078c50d621c64c22fc0a405
[ "PHP-3.01", "CC-BY-3.0" ]
4
2020-12-23T12:17:54.000Z
2022-01-04T20:46:34.000Z
from SQLRelay import PySQLRClient con=PySQLRClient.sqlrconnection('sqlrserver',9000,'/tmp/example.socket','user','password',0,1) cur=PySQLRClient.sqlrcursor(con) cur.sendQuery('select * from my_table') con.endSession() for i in range(0,cur.colCount()-1): print 'Name: ', cur.getColumnName(i) print 'Type: ', cur.getColumnType(i) print 'Length: ', cur.getColumnLength(i) print 'Precision: ', cur.getColumnPrecision(i) print 'Scale: ', cur.getColumnScale(i) print 'Longest Field: ', cur.getLongest(i) print 'Nullable: ', cur.getColumnIsNullable(i) print 'Primary Key: ', cur.getColumnIsPrimaryKey(i) print 'Unique: ', cur.getColumnIsUnique(i) print 'Part Of Key: ', cur.getColumnIsParyOfKey(i) print 'Unsigned: ', cur.getColumnIsUnsigned(i) print 'Zero Filled: ', cur.getColumnIsZeroFilled(i) print 'Binary: ', cur.getColumnIsBinary(i) print 'Auto Increment:', cur.getColumnIsAutoIncrement(i)
44.708333
94
0.629077
1cfbeab2c4345333ce57fe3e20b3c09ff5015f89
963
swift
Swift
Sources/Client/Named.swift
Bloombox/Swift
f69072ce6854cd617bdb9d4c9290698d861bffba
[ "Apache-2.0" ]
6
2017-12-16T19:25:30.000Z
2021-08-19T05:19:51.000Z
Sources/Client/Named.swift
Bloombox/Swift
f69072ce6854cd617bdb9d4c9290698d861bffba
[ "Apache-2.0" ]
49
2018-02-09T02:23:46.000Z
2020-03-10T09:11:56.000Z
Sources/Client/Named.swift
Bloombox/Swift
f69072ce6854cd617bdb9d4c9290698d861bffba
[ "Apache-2.0" ]
3
2017-12-15T23:51:20.000Z
2018-10-16T22:14:34.000Z
/** * Copyright 2019, Momentum Ideas, Co. All rights reserved. * Source and object computer code contained herein is the private intellectual * property of Momentum Ideas Co., a Delaware Corporation. Use of this * code in source form requires permission in writing before use or the * assembly, distribution, or publishing of derivative works, for commercial * purposes or any other purpose, from a duly authorized officer of Momentum * Ideas Co. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation /// Indicates that an object is named/known, and supplies a string name if needed. public protocol Named { /// Name for this object or item. var name: String? { get } }
38.52
82
0.76947
bfb63fbdfb2a37f1d78b87f821478b3251c2ab1c
14,266
sql
SQL
Wornak.sql
Smarty-pro/wornak
2944154c437d963d5340dd5a46bd0c0cc5074e8d
[ "MIT" ]
null
null
null
Wornak.sql
Smarty-pro/wornak
2944154c437d963d5340dd5a46bd0c0cc5074e8d
[ "MIT" ]
5
2021-05-22T10:23:35.000Z
2022-02-27T09:06:48.000Z
Wornak.sql
Smarty-pro/wornak
2944154c437d963d5340dd5a46bd0c0cc5074e8d
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Hôte : localhost -- Généré le : Dim 27 déc. 2020 à 22:51 -- Version du serveur : 10.4.10-MariaDB -- Version de PHP : 7.3.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `Wornak` -- -- -------------------------------------------------------- -- -- Structure de la table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `full_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `mail` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `tel` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Structure de la table `company` -- CREATE TABLE `company` ( `id` int(11) NOT NULL, `roles` longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:json)', `employees_number` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `company_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` longtext COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `company` -- INSERT INTO `company` (`id`, `roles`, `employees_number`, `company_name`, `description`) VALUES (3, '[]', '0-100', 'test', 'test'); -- -------------------------------------------------------- -- -- Structure de la table `doctrine_migration_versions` -- CREATE TABLE `doctrine_migration_versions` ( `version` varchar(191) COLLATE utf8_unicode_ci NOT NULL, `executed_at` datetime DEFAULT NULL, `execution_time` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Déchargement des données de la table `doctrine_migration_versions` -- INSERT INTO `doctrine_migration_versions` (`version`, `executed_at`, `execution_time`) VALUES ('App\\Migrations\\Version20201220152725', '2020-12-20 16:32:45', 7132), ('App\\Migrations\\Version20201226103637', '2020-12-26 11:37:13', 833), ('App\\Migrations\\Version20201226110807', '2020-12-26 12:08:24', 571), ('App\\Migrations\\Version20201226111005', '2020-12-26 12:10:23', 2258), ('App\\Migrations\\Version20201227211936', '2020-12-27 22:19:55', 2471), ('App\\Migrations\\Version20201227214525', '2020-12-27 22:45:29', 757), ('App\\Migrations\\Version20201227214734', '2020-12-27 22:47:38', 1883); -- -------------------------------------------------------- -- -- Structure de la table `job_post` -- CREATE TABLE `job_post` ( `id` int(11) NOT NULL, `company` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `job_title` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `description` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `reference` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `exp_date` date NOT NULL, `job_zone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `training` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `contract_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `published_at` datetime NOT NULL, `salary` int(11) NOT NULL, `sector` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `study_level_required` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `job_post` -- INSERT INTO `job_post` (`id`, `company`, `job_title`, `description`, `reference`, `exp_date`, `job_zone`, `training`, `contract_type`, `published_at`, `salary`, `sector`, `study_level_required`) VALUES (1, 'test', 'test', 'test', 'test', '2020-09-10', 'test', 'test', 'test', '2020-09-10 15:33:32', 0, '', ''), (2, 'Anapec', 'Conseiller en emploi', 'pas de description', '07A07D61CS6', '2020-09-10', 'Casablanca', 'pas d\'exp requise', 'CDI', '2020-09-10 15:33:32', 0, '', ''), (3, 'Federal Bureau of Investigation', 'Special Agent', 'no description', 'Z048054V7', '2020-09-11', 'New York', 'no training needed', 'CDI', '2020-09-11 15:47:28', 0, '', ''), (4, 'Amazon', 'Secretary', 'secretary of Amazon', '0F47D0V8', '2020-09-17', 'Silicon Valley, California', 'no training needed', 'CDI', '2020-09-11 15:50:43', 0, '', ''), (5, 'Activision', 'Senior Developper', 'senior developer of the studio Treyarch', '07F5ZD64', '2020-09-11', 'Los Angeles, California', '3 years of developement in any studio', 'CDI', '2020-09-11 15:52:55', 0, '', ''), (6, 'Maroc Telecom', 'Telephone Operator', 'telephone operator of Maroc Telecom', '05F98ZA\r\n', '2020-09-11', 'Marrakech', 'no training needed', 'CDI', '2020-09-11 15:54:49', 0, '', ''), (7, 'DECATHLON', 'Cashier', 'Cashier of Decathlon-Nantes', '08REC64D', '2020-09-01', 'Nantes, France', 'no training needed', 'CDD', '2020-09-11 15:56:33', 0, '', ''), (8, 'Athwab Hanane', 'Assistant', 'no description', '0DF68ZF\r\n', '2020-09-11', 'BenGuerir, Morocco', 'no training needed', 'CDD', '2020-09-11 16:03:15', 0, '', ''), (9, 'OCP', 'Engineer', 'engineer in the biggest company in Morocco', '0F84FZ49F9', '2020-09-11', 'BenGuerir, Morocco', '5 years of experience', 'CDI', '2020-09-11 16:04:58', 0, '', ''), (10, 'Renault', 'Presenter of cars', 'no description', 'FEF886B', '2020-09-30', 'Casablanca, Morocco', 'no training needed', 'CDD', '2020-09-11 16:30:00', 0, '', ''), (11, 'Alphabet Inc.', 'Secretary', 'no description', 'F44VE8R', '2020-09-29', 'Silicon Valley, California ', 'no training needed', 'CDI', '2020-09-11 16:33:04', 0, '', ''), (12, 'Alstom', 'Engineer', 'engineer in Alstom-Paris', '7F5ZD84V', '2020-10-07', 'Paris, France', 'no training needed', 'CDD', '2020-09-12 21:43:21', 0, '', ''), (13, 'Alsa', 'Bus Driver', 'Bus driver in Casablanca', '4D9VE3B8T', '2020-09-22', 'Casablanca, Morocco', 'no training needed', 'CDI', '2020-09-02 21:44:49', 0, '', ''), (14, 'Africom', 'Computer Scientist', 'no description', 'F6FC48A', '2020-09-29', ' Stuttgart, Germany', '10 years of exp', 'CDI', '2020-09-11 21:56:42', 0, '', ''), (15, 'Marjane Holding', 'Cashier', 'cashier in Marjane', 'Z2D457DC', '2020-09-29', 'Tangier, Morocco', 'no training needed', 'CDD', '2020-09-13 11:26:47', 6000, '', ''), (16, 'test', 'Engineer', 'no description', '418e441898d7045dde986836c62c33a3', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-18 23:40:20', 20000, '18', 'Bac+4'), (17, 'test', 'Engineer', 'no description', 'd4830e65651bc2365f0e0b6d8508e94b', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 11:53:18', 20000, '10', 'Bac+3'), (18, 'test', 'Engineer', 'no description', '000d0d1f0abb40909c7d89380e7a1dc0', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 12:12:40', 20000, '01', 'Bac+2'), (19, 'test', 'Engineer', 'no description', '88d6a658013827806ed6773627d1c110', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 12:16:26', 20000, '01', 'Bac'), (20, 'test', 'Engineer', 'no description', 'd12e79f614c8e66a3b973693f9d0a2c9', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 16:43:21', 20000, '01', 'Bac'), (21, 'test', 'Engineer', 'no description', 'eb8de89f1e382b1a66d046cb15ff3e30', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 16:47:54', 20000, '01', 'Bac'), (22, 'test', 'Engineer', 'no description', 'db967d0f7992ceba375bd5d00835e5d4', '2021-01-01', 'Morocco', 'no', 'CDI', '2020-12-26 16:49:15', 20000, '01', 'Bac'); -- -------------------------------------------------------- -- -- Structure de la table `job_seeker` -- CREATE TABLE `job_seeker` ( `id` int(11) NOT NULL, `roles` longtext COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:json)', `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `birthday_date` date NOT NULL, `address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `mobility` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `handicap` tinyint(1) NOT NULL, `diploma` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `skills` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `job_seeker` -- INSERT INTO `job_seeker` (`id`, `roles`, `first_name`, `last_name`, `gender`, `birthday_date`, `address`, `mobility`, `handicap`, `diploma`, `skills`) VALUES (28, '[]', 'test', 'test', 'male', '1900-01-01', 'test', 'local', 1, 'test', 'test'), (29, '[]', 'Adnane', 'Lourhzal', 'male', '2007-01-11', 'Marrakech', 'international', 1, 'nope', NULL); -- -------------------------------------------------------- -- -- Structure de la table `search_bar` -- CREATE TABLE `search_bar` ( `id` int(11) NOT NULL, `search_content` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `search_bar` -- INSERT INTO `search_bar` (`id`, `search_content`) VALUES (1, 'test'), (2, 'Cash'), (3, 'Cashier'), (4, 't'), (5, 't'), (6, 't'), (7, 't'), (8, 't'), (9, 't'), (10, 'o'), (11, 'Cash'), (12, 'Co'), (13, 'S'), (14, 'Agent'), (15, 'empl'), (16, 'agent'), (17, 'c'), (18, 'e'), (19, 'c'), (20, 'cdi'), (21, 'CDI'), (22, 'c'); -- -------------------------------------------------------- -- -- Structure de la table `user` -- CREATE TABLE `user` ( `id` int(11) NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `activation_token` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `tel` int(11) DEFAULT NULL, `companies_id` int(11) DEFAULT NULL, `jobseeker_id` int(11) DEFAULT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `roles` longtext COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '(DC2Type:json)' ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Déchargement des données de la table `user` -- INSERT INTO `user` (`id`, `email`, `password`, `activation_token`, `tel`, `companies_id`, `jobseeker_id`, `uuid`, `roles`) VALUES (38, 'test@test.test', '$argon2id$v=19$m=65536, t = 4, p = 1$iyhhHtpy + sA3GFGLGV75VQ$87lkpckfxhXf5QzJyKLWtZR4Pn3uR9pX7PTY9h2HTNk', '508e26791d837d017d4691072f15646f', 7, 3, NULL, '5f943fa05dbab', '[\"ROLE_EM\"]'), (39, 'test@test.test', '$argon2id$v=19$m=65536,t=4,p=1$CPdjL3VTxdK8FWoxApzZmg$kK+DGhc1RZ09wU0Nir+SoKwlWPBc0HJ/wE7yAey5WWQ', '58cbf106c92b167e74961cfb9b234635', 7, NULL, NULL, '5f944041eca2c', NULL), (40, 'test@test.test', '$argon2id$v=19$m=65536,t=4,p=1$DdehmrGVfQCR9D6+kJbvVA$kpl0D3Ekd+1+r1auGWija/7OeSjamjfb0jqO4b0uPb0', '188c782eb9aef696cf7bc62865f772f1', 7, NULL, 28, '5f944070863c4', '[\"ROLE_JOS\"]'), (42, 'lourhzaladnane@gmail.com', '$argon2id$v=19$m=65536,t=4,p=1$bLKPf2xDhUJWuhE4XvapDA$WIbHoXipLCF8/2ut5w/B/zb/bKpwm9RbXoHfVFQ64GE', 'd5ff49329cda6aabf026e20568e1b4f3', 770444209, NULL, 29, '5fb8e872893e4', '[\"ROLE_JOS\"]'); -- -- Index pour les tables déchargées -- -- -- Index pour la table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `UNIQ_880E0D76A76ED395` (`user_id`); -- -- Index pour la table `company` -- ALTER TABLE `company` ADD PRIMARY KEY (`id`); -- -- Index pour la table `doctrine_migration_versions` -- ALTER TABLE `doctrine_migration_versions` ADD PRIMARY KEY (`version`); -- -- Index pour la table `job_post` -- ALTER TABLE `job_post` ADD PRIMARY KEY (`id`); -- -- Index pour la table `job_seeker` -- ALTER TABLE `job_seeker` ADD PRIMARY KEY (`id`); -- -- Index pour la table `search_bar` -- ALTER TABLE `search_bar` ADD PRIMARY KEY (`id`); -- -- Index pour la table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `UNIQ_8D93D649D17F50A6` (`uuid`), ADD KEY `IDX_8D93D6496AE4741E` (`companies_id`), ADD KEY `IDX_8D93D6494CF2B5A9` (`jobseeker_id`); -- -- AUTO_INCREMENT pour les tables déchargées -- -- -- AUTO_INCREMENT pour la table `admin` -- ALTER TABLE `admin` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `company` -- ALTER TABLE `company` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT pour la table `job_post` -- ALTER TABLE `job_post` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- AUTO_INCREMENT pour la table `job_seeker` -- ALTER TABLE `job_seeker` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- AUTO_INCREMENT pour la table `search_bar` -- ALTER TABLE `search_bar` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; -- -- AUTO_INCREMENT pour la table `user` -- ALTER TABLE `user` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43; -- -- Contraintes pour les tables déchargées -- -- -- Contraintes pour la table `admin` -- ALTER TABLE `admin` ADD CONSTRAINT `FK_880E0D76A76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`); -- -- Contraintes pour la table `user` -- ALTER TABLE `user` ADD CONSTRAINT `FK_8D93D6494CF2B5A9` FOREIGN KEY (`jobseeker_id`) REFERENCES `job_seeker` (`id`), ADD CONSTRAINT `FK_8D93D6496AE4741E` FOREIGN KEY (`companies_id`) REFERENCES `company` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
40.185915
198
0.646712
10a974cb7690097fec9ed3869840115b7e337cf9
2,928
asm
Assembly
programs/oeis/085/A085462.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/085/A085462.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/085/A085462.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A085462: Number of 5-tuples (v1,v2,v3,v4,v5) of nonnegative integers less than n such that v1<=v4, v1<=v5, v2<=v4 and v3<=v4. ; 1,14,77,273,748,1729,3542,6630,11571,19096,30107,45695,67158,96019,134044,183260,245973,324786,422617,542717,688688,864501,1074514,1323490,1616615,1959516,2358279,2819467,3350138,3957863,4650744,5437432,6327145,7329686,8455461,9715497,11121460,12685673,14421134,16341534,18461275,20795488,23360051,26171607,29247582,32606203,36266516,40248404,44572605,49260730,54335281,59819669,65738232,72116253,78979978,86356634,94274447,102762660,111851551,121572451,131957762,143040975,154856688,167440624,180829649,195061790,210176253,226213441,243214972,261223697,280283718,300440406,321740419,344231720,367963595,392986671,419352934,447115747,476329868,507051468,539338149,573248962,608844425,646186541,685338816,726366277,769335490,814314578,861373239,910582764,962016055,1015747643,1071853706,1130412087,1191502312,1255205608,1321604921,1390784934,1462832085,1537834585,1615882436,1697067449,1781483262,1869225358,1960391083,2055079664,2153392227,2255431815,2361303406,2471113931,2584972292,2702989380,2825278093,2951953354,3083132129,3218933445,3359478408,3504890221,3655294202,3810817802,3971590623,4137744436,4309413199,4486733075,4669842450,4858881951,5053994464,5255325152,5463021473,5677233198,5898112429,6125813617,6360493580,6602311521,6851429046,7108010182,7372221395,7644231608,7924212219,8212337119,8508782710,8813727923,9127354236,9449845692,9781388917,10122173138,10472390201,10832234589,11201903440,11581596565,11971516466,12371868354,12782860167,13204702588,13637609063,14081795819,14537481882,15004889095,15484242136,15975768536,16479698697,16996265910,17525706373,18068259209,18624166484,19193673225,19777027438,20374480126,20986285307,21612700032,22253984403,22910401591,23582217854,24269702555,24973128180,25692770356,26428907869,27181822682,27951799953,28739128053,29544098584,30367006397,31208149610,32067829626,32946351151,33844022212,34761154175,35698061763,36655063074,37632479599,38630636240,39649861328,40690486641,41752847422,42837282397,43944133793,45073747356,46226472369,47402661670,48602671670,49826862371,51075597384,52349243947,53648172943,54972758918,56323380099,57700418412,59104259500,60535292741,61993911266,63480511977,64995495565,66539266528,68112233189,69714807714,71347406130,73010448343,74704358156,76429563287,78186495387,79975590058,81797286871,83652029384,85540265160,87462445785,89419026886,91410468149,93437233337,95499790308,97598611033,99734171614,101906952302,104117437515,106366115856,108653480131,110980027367,113346258830,115752680043,118199800804,120688135204,123218201645,125790522858,128405625921,131064042277,133766307752,136512962573,139304551386,142141623274,145024731775,147954434900 mov $2,$0 add $2,1 mul $2,2 add $0,$2 cal $0,5585 ; 5-dimensional pyramidal numbers: n(n+1)(n+2)(n+3)(2n+3)/5!. mul $0,2 mov $1,$0 sub $1,54 div $1,54 add $1,1
209.142857
2,638
0.877732
2a0caab19813bd2949c17249a304e651752c4bf5
3,565
java
Java
src/main/java/io/drakon/flightpath/forge/ASMDataTableLocator.java
Emberwalker/Flightpath
0024d1a93642e316553efb048527213d5294cfab
[ "MIT" ]
1
2016-02-07T17:31:23.000Z
2016-02-07T17:31:23.000Z
src/main/java/io/drakon/flightpath/forge/ASMDataTableLocator.java
Emberwalker/Flightpath
0024d1a93642e316553efb048527213d5294cfab
[ "MIT" ]
2
2016-01-03T22:16:16.000Z
2017-01-23T14:24:32.000Z
src/main/java/io/drakon/flightpath/forge/ASMDataTableLocator.java
Emberwalker/Flightpath
0024d1a93642e316553efb048527213d5294cfab
[ "MIT" ]
null
null
null
package io.drakon.flightpath.forge; import com.google.common.collect.ImmutableSet; import com.google.common.collect.SetMultimap; import io.drakon.flightpath.Airdrop; import io.drakon.flightpath.ISubscriberLocator; import io.drakon.flightpath.lib.AnnotationLocator; import io.drakon.flightpath.lib.Pair; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.discovery.ASMDataTable; import net.minecraftforge.fml.common.discovery.ASMDataTable.ASMData; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * EXPERIMENTAL alternative locator implementation for Minecraft Forge-based mods. Classes that are intended to be event * handlers MUST have a ForgepathHandler annotation and zero-param constructor. * * This is untested - USE AT YOUR OWN RISK! (and report bugs please) * * @author Arkan <arkan@drakon.io> */ @ParametersAreNonnullByDefault @SuppressWarnings("unused") public class ASMDataTableLocator implements ISubscriberLocator { private static final Set<Pair<Object, Map<Class, Set<Method>>>> NO_SUBSCRIBERS = new HashSet<Pair<Object, Map<Class, Set<Method>>>>(); private AnnotationLocator innerLocator; private ASMDataTable asmTable; /** * Constructor. Scans the given ASM data table for candidate event handlers carrying the given Annotation. * * @param asmTable The ASM data table (from FMLPreinitializationEvent) * @param ann The annotation class to look for */ public ASMDataTableLocator(ASMDataTable asmTable, Class<? extends Annotation> ann) { this.innerLocator = new AnnotationLocator(ann); this.asmTable = asmTable; } /** * Constructor. Scans the given ASM data table for candidate event handlers carrying the Airdrop annotation. * @param asmTable The ASM data table (from FMLPreinitializationEvent) */ public ASMDataTableLocator(ASMDataTable asmTable) { this(asmTable, Airdrop.class); } @Nonnull @Override public Map<Class, Set<Method>> findSubscribers(Object obj) { return innerLocator.findSubscribers(obj); } @Nonnull @Override public Set<Pair<Object, Map<Class, Set<Method>>>> findSubscribers() { SetMultimap<String, ASMData> allAnnotationsInContainer = asmTable.getAnnotationsFor( Loader.instance().activeModContainer()); if (!allAnnotationsInContainer.containsKey(ForgepathHandler.class.getCanonicalName())) return NO_SUBSCRIBERS; Set<ASMData> asmDataSet = allAnnotationsInContainer.get(ForgepathHandler.class.getName()); // Goddamnit Java and your stupidly long types ImmutableSet.Builder<Pair<Object, Map<Class, Set<Method>>>> mapBuilder = new ImmutableSet.Builder<Pair<Object, Map<Class, Set<Method>>>>(); for (ASMData asmData : asmDataSet) { String cname = asmData.getClassName(); Object obj; try { obj = Class.forName(cname).newInstance(); } catch (Exception ex) { continue; // SKIP! } Map<Class, Set<Method>> subscribers = innerLocator.findSubscribers(obj); mapBuilder.add(new Pair<Object, Map<Class, Set<Method>>>(obj, subscribers)); } return mapBuilder.build(); } }
39.611111
139
0.696494
852a3df002d64f338f11e6425c812b48751a497b
123
lua
Lua
src/Core/Shared/Modules/Serializer.lua
Hasnain123Raza/core
71c8da01eb964d1ce35d3e834b46af1a6857ed87
[ "MIT" ]
null
null
null
src/Core/Shared/Modules/Serializer.lua
Hasnain123Raza/core
71c8da01eb964d1ce35d3e834b46af1a6857ed87
[ "MIT" ]
null
null
null
src/Core/Shared/Modules/Serializer.lua
Hasnain123Raza/core
71c8da01eb964d1ce35d3e834b46af1a6857ed87
[ "MIT" ]
null
null
null
local main = require(game.Nanoblox) local Serializer = require(main.shared.Packages.UserStore.Serializer) return Serializer
41
69
0.837398
2694b3a5ca74cde69851218db9ca2c3a12184fa1
11,873
java
Java
src/core/mwin_modules/TranslationModule.java
tradfursten/MonkeyCrypt
2cdc44118430acb9b5c48c2e21aff60efbcc209e
[ "MIT" ]
null
null
null
src/core/mwin_modules/TranslationModule.java
tradfursten/MonkeyCrypt
2cdc44118430acb9b5c48c2e21aff60efbcc209e
[ "MIT" ]
null
null
null
src/core/mwin_modules/TranslationModule.java
tradfursten/MonkeyCrypt
2cdc44118430acb9b5c48c2e21aff60efbcc209e
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package core.mwin_modules; import frame.*; import core.Translator; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; /** * * @author Jonas */ public class TranslationModule { public MoCr_Frame localFrame; public TranslationModule(MoCr_Frame f) { localFrame = f; } public void renew() { Translator t = Translator.getInstance(); if(t.getcurrentLangIndex() != t.getlastLangIndex()) { renewFrame(); renewListM(); renewListD(); renewSettings(); localFrame.localCredits.refreshCredits(); localFrame.localSupport.refreshSupport(); renewTooltips(); } } public void renewFrame() { localFrame.MoCr_Gen_Choicemenu1.setText(Translator.getInstance().getString("settings")); localFrame.MoCr_Gen_Choicemenu2.setText(Translator.getInstance().getString("credits")); localFrame.MoCr_MPstaticIO_InField.setText(Translator.getInstance().getString("input")); localFrame.MoCr_MPstaticIO_OutField.setText(Translator.getInstance().getString("output")); localFrame.MoCr_CaesarSub_LabelSchluessel.setText(Translator.getInstance().getString("key")); localFrame.MoCr_MPButtonpanel_LearnButton.setText(Translator.getInstance().getString("learn")); localFrame.MoCr_MPButtonpanel_ExerciseButton.setText(Translator.getInstance().getString("exercise")); localFrame.MoCr_MPButtonpanel_IOChange.setText(Translator.getInstance().getString("invert")); localFrame.MoCr_MPButtonpanel_Help.setText(Translator.getInstance().getString("help")); localFrame.MoCr_MultiplikaitvSub_KeyPointer.setText(Translator.getInstance().getString("key")); localFrame.MoCr_MultiplikaitvSub_KeyGenButton.setText(Translator.getInstance().getString("generateKey")); localFrame.MoCr_VigenereSub_LabelSchluessel.setText(Translator.getInstance().getString("key")); localFrame.MoCr_OTPSub_LabelSchluessel.setText(Translator.getInstance().getString("key")); localFrame.MoCr_OTPSub_Generator.setText(Translator.getInstance().getString("generateKey")); localFrame.MoCr_TranspositionSub_SpaltelButton.setText(Translator.getInstance().getString("trans1")); localFrame.MoCr_TranspositionSub_GartenzaunButton.setText(Translator.getInstance().getString("trans2")); localFrame.MoCr_TranspositionSub_AnagrammButton.setText(Translator.getInstance().getString("trans3")); localFrame.MoCr_TranspositionSub_DoppelwuerfelButton.setText(Translator.getInstance().getString("trans4")); localFrame.MoCr_TranspositionSub_PermutaButton.setText(Translator.getInstance().getString("trans5")); localFrame.MoCr_TranspositionKey_1KeyLabel.setText(Translator.getInstance().getString("key")); localFrame.MoCr_TranspositionSub_2KeyLabel.setText(Translator.getInstance().getString("keys")); localFrame.MoCr_TranspositionSub_MatrixKeyLabel.setText(Translator.getInstance().getString("keymatrix")); localFrame.MoCr_PermSub_Label.setText(Translator.getInstance().getString("matrixsize")); localFrame.MoCr_CodierungenSub_MorseButton.setText(Translator.getInstance().getString("code1")); localFrame.MoCr_CodierungenSub_ASCIIButton.setText(Translator.getInstance().getString("code2")); localFrame.MoCr_CodierungenSub_BinaerButton.setText(Translator.getInstance().getString("code3")); localFrame.MoCr_CodierungenSub_BinToHexButton.setText(Translator.getInstance().getString("code4")); localFrame.MoCr_CodierungenSub_AlphaButton.setText(Translator.getInstance().getString("code5")); localFrame.MoCr_CodierungenSub_NATOButton.setText(Translator.getInstance().getString("code6")); localFrame.MoCr_CodierungenSub_ADFGXButton.setText(Translator.getInstance().getString("code7")); localFrame.MoCr_CodierungenSub_ADFGXFiller.setText(Translator.getInstance().getString("fill")); localFrame.MoCr_SpielsprachenMP_BiButton.setText(Translator.getInstance().getString("fun1")); localFrame.MoCr_SpielsprachenMP_BobButton.setText(Translator.getInstance().getString("fun2")); localFrame.MoCr_SpielsprachenMP_LoeffelButton.setText(Translator.getInstance().getString("fun3")); localFrame.MoCr_HillSub_SizeLab.setText(Translator.getInstance().getString("matrixsize")); localFrame.MoCr_SteganoSub_BaconButton.setText(Translator.getInstance().getString("stegano1")); localFrame.MoCr_SteganoSub_PseudoButton.setText(Translator.getInstance().getString("stegano2")); localFrame.MoCr_SteganoSub_BaconKeyHeading.setText(Translator.getInstance().getString("baconhead")); localFrame.MoCr_AffChiffSub_KeyLabel.setText(Translator.getInstance().getString("keychar")); localFrame.MoCr_AffChiffSub_Functionpointer.setText(Translator.getInstance().getString("function")); localFrame.jButton1.setText(Translator.getInstance().getString("distribution")); localFrame.MoCr_Did_Returnerbutton.setText(Translator.getInstance().getString("back")); localFrame.Toolsmenu.setText(Translator.getInstance().getString("tools")); } public void renewListM() { DefaultListModel<String> lm = new DefaultListModel<String>(); lm.add(0, Translator.getInstance().getString("caesar")); lm.add(1, Translator.getInstance().getString("multi")); lm.add(2, Translator.getInstance().getString("vigenere")); lm.add(3, Translator.getInstance().getString("otp")); lm.add(4, Translator.getInstance().getString("transpositions")); lm.add(5, Translator.getInstance().getString("code")); lm.add(6, Translator.getInstance().getString("fun")); lm.add(7, Translator.getInstance().getString("hill")); lm.add(8, Translator.getInstance().getString("steganography")); lm.add(9, Translator.getInstance().getString("affine")); lm.add(10, Translator.getInstance().getString("cryptoanalysis")); localFrame.MoCr_Gen_Sidelister.setModel(lm); } public void renewListD() { DefaultListModel<String> lm = new DefaultListModel<String>(); lm.add(0, Translator.getInstance().getString("maths")); lm.add(1, Translator.getInstance().getString("steganography")); lm.add(2, Translator.getInstance().getString("fun")); lm.add(3, Translator.getInstance().getString("cryptology")); lm.add(4, Translator.getInstance().getString("cryptoanalysis")); lm.add(5, Translator.getInstance().getString("cryptography")); lm.add(6, Translator.getInstance().getString("assym")); lm.add(7, Translator.getInstance().getString("RSA")); lm.add(8, Translator.getInstance().getString("ete")); lm.add(9, Translator.getInstance().getString("sym")); lm.add(10, Translator.getInstance().getString("transpositions")); lm.add(11, Translator.getInstance().getString("sub")); lm.add(12, Translator.getInstance().getString("code")); lm.add(13, Translator.getInstance().getString("cipher")); lm.add(14, Translator.getInstance().getString("mono")); lm.add(15, Translator.getInstance().getString("caesar")); lm.add(16, Translator.getInstance().getString("multi")); lm.add(17, Translator.getInstance().getString("poly")); lm.add(18, Translator.getInstance().getString("vigenere")); lm.add(19, Translator.getInstance().getString("enigma")); lm.add(20, Translator.getInstance().getString("otp")); lm.add(21, Translator.getInstance().getString("hill")); lm.add(22, Translator.getInstance().getString("affine")); localFrame.MoCr_Gen_DidLister.setModel(lm); } public void renewSettings() { MoCr_Frame_Settings ls = localFrame.localSettings; ls.MoCr_SettingsFrame_Heading1.setText(Translator.getInstance().getString("changeAlph")); ls.MoCr_SettingsFrame_ResetButton.setText(Translator.getInstance().getString("baseAlph")); ls.MoCr_SettingsFrame_Validation.setText(Translator.getInstance().getString("savechanges")); ls.MoCr_SettingsFrame_TabbedPane.setTitleAt(0, Translator.getInstance().getString("encryption")); ls.MoCr_SettingsFrame_TabbedPane.setTitleAt(1, Translator.getInstance().getString("show")); ls.MoCr_SettingsFrame_TabbedPane.setTitleAt(2, Translator.getInstance().getString("exclusion")); ls.Heading1.setText(Translator.getInstance().getString("framecol")); ls.Heading2.setText(Translator.getInstance().getString("scriptsize")); ls.MoCr_Settings_LangLabel.setText(Translator.getInstance().getString("lang")); ls.MoCr_SettingsFrame_TipCheck.setText(Translator.getInstance().getString("tip")); ls.MoCr_SettingsFrame_Checkbox.setText(Translator.getInstance().getString("resize")); DefaultComboBoxModel<String> bm1 = new DefaultComboBoxModel<String>(); bm1.addElement(Translator.getInstance().getString("blue")); bm1.addElement(Translator.getInstance().getString("green")); bm1.addElement(Translator.getInstance().getString("yellow")); bm1.addElement(Translator.getInstance().getString("pink")); int index = ls.MoCr_SettingsFrame_Colourbox.getSelectedIndex(); ls.MoCr_SettingsFrame_Colourbox.setModel(bm1); ls.MoCr_SettingsFrame_Colourbox.setSelectedIndex(index); DefaultComboBoxModel<String> bm2 = new DefaultComboBoxModel<String>(); bm2.addElement(Translator.getInstance().getString("empty1")); bm2.addElement(Translator.getInstance().getString("empty2")); bm2.addElement(Translator.getInstance().getString("empty3")); bm2.addElement(Translator.getInstance().getString("empty4")); bm2.addElement(Translator.getInstance().getString("empty5")); ls.MoCr_SettingsFrame_ClearBox.setModel(bm2); ls.AlphOnlyCheckbox.setText(Translator.getInstance().getString("alphonly")); DefaultComboBoxModel<String> bm3 = new DefaultComboBoxModel<String>(); bm3.addElement(Translator.getInstance().getString("script1")); bm3.addElement(Translator.getInstance().getString("script2")); bm3.addElement(Translator.getInstance().getString("script3")); bm3.addElement(Translator.getInstance().getString("script4")); ls.ScriptCombobox.setModel(bm3); ls.ExclusionLabel.setText(Translator.getInstance().getString("exclude")); } public void renewTooltips() { localFrame.MoCr_MPstaticIO_InField.setToolTipText(Translator.getInstance().getString("tt1")); localFrame.MoCr_MPstaticIO_OutField.setToolTipText(Translator.getInstance().getString("tt2")); localFrame.MoCr_EncryptButton.setToolTipText(Translator.getInstance().getString("tt3")); localFrame.MoCr_DecryptButton.setToolTipText(Translator.getInstance().getString("tt4")); localFrame.MoCr_MPButtonpanel_LearnButton.setToolTipText(Translator.getInstance().getString("tt5")); localFrame.MoCr_MPButtonpanel_ExerciseButton.setToolTipText(Translator.getInstance().getString("tt6")); localFrame.MoCr_MPButtonpanel_IOChange.setToolTipText(Translator.getInstance().getString("tt7")); localFrame.MoCr_MPButtonpanel_Help.setToolTipText(Translator.getInstance().getString("tt8")); } public void renewDid() { localFrame.localSModule.setLearningContent(); } }
66.702247
116
0.717763
1337e1df33b423b76cbc6e55c527b19bc1906ea1
95
c
C
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr43661.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
178
2016-03-03T12:31:18.000Z
2021-11-05T22:36:55.000Z
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr43661.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
106
2016-03-03T13:11:42.000Z
2018-09-27T13:01:51.000Z
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr43661.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
21
2016-03-03T14:21:36.000Z
2020-04-09T01:19:17.000Z
int func (int x) { return 0 ? (unsigned short) (0 ? : 1 * (signed char) (x ^ x) >= 0) : 1; }
15.833333
73
0.494737
c7b9ebf28ebb3f6f21a8d6ac646757b821959b97
1,608
py
Python
module4/MyRen.py
SelimBenIsmail/tac
162956a54d3dfd61a0b772ca86c694503c672554
[ "MIT" ]
null
null
null
module4/MyRen.py
SelimBenIsmail/tac
162956a54d3dfd61a0b772ca86c694503c672554
[ "MIT" ]
null
null
null
module4/MyRen.py
SelimBenIsmail/tac
162956a54d3dfd61a0b772ca86c694503c672554
[ "MIT" ]
null
null
null
"""Named-entity recognition with SpaCy""" from collections import defaultdict import sys import os import spacy from spacy.lang.fr.examples import sentences nlp = spacy.load('fr_core_news_sm') def test(): """Basic test on sample sentences""" for sent in sentences: doc = nlp(sent) entities = [] for ent in doc.ents: entities.append(f"{ent.text} ({ent.label_})") if entities: print(f"'{doc.text}' contains the following entities: {', '.join(entities)}") else: print(f"'{doc.text}' contains no entities") def search(file): text = open(f"{dataP}{file}").read()[:1000000] doc = nlp(text) people = defaultdict(int) for ent in doc.ents: if ent.label_ == "PER" and len(ent.text) > 3: people[ent.text] += 1 sorted_people = sorted(people.items(), key=lambda kv: kv[1], reverse=True) for person, freq in sorted_people[:15]: print(f"{person},{freq}") with open("../data/1950/REN.txt", "a") as output: output.write(f"\n{person},{freq},{file}") if __name__ == "__main__": dataP = "../data/1950/" files = os.listdir(dataP) try: if sys.argv[1] == "test": test() elif sys.argv[1] == "search": for i in sorted(files): if (i.startswith("cluster")) : print(f"{i} : ") search(i) else: print("Unknown option, please use either 'test' or 'search'") except IndexError: print("No option, please specify either 'test' or 'search'")
30.923077
89
0.563433
907f0a6773e5dc92e4ce3a0c5c1b24e345787a9f
1,389
py
Python
satori.core/satori/core/management/commands/start.py
Cloud11665/satori-git
ea1855a920c98b480423bf247bce6e5626985c4a
[ "MIT" ]
4
2021-01-05T01:35:36.000Z
2021-12-13T00:05:14.000Z
satori.core/satori/core/management/commands/start.py
Cloud11665/satori-git
ea1855a920c98b480423bf247bce6e5626985c4a
[ "MIT" ]
2
2020-06-06T01:12:07.000Z
2020-06-06T01:16:01.000Z
satori.core/satori/core/management/commands/start.py
Cloud11665/satori-git
ea1855a920c98b480423bf247bce6e5626985c4a
[ "MIT" ]
2
2021-01-05T01:33:30.000Z
2021-03-06T13:48:21.000Z
# vim:ts=4:sts=4:sw=4:expandtab from django.conf import settings from django.core.management.base import NoArgsCommand from optparse import make_option import os from setproctitle import setproctitle from signal import signal, SIGINT, SIGHUP, SIGTERM import signal as signal_module import sys signalnames = dict((k, v) for v, k in signal_module.__dict__.iteritems() if v.startswith('SIG')) class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--daemon', action='store_true', dest='daemon', default=False, help='Creates a daemon process.'), ) def handle_noargs(self, **options): setproctitle('satori: foreground') from satori.core.management.master_process import SatoriMasterProcess daemon = options.get('daemon', False) process = SatoriMasterProcess(daemon) if daemon: process.start() # do not call atexit os._exit(0) else: def handle_signal(signum, frame): print 'foreground caught signal {0}'.format(signalnames.get(signum, signum)) process.terminate() signal(SIGINT, handle_signal) signal(SIGHUP, handle_signal) signal(SIGTERM, handle_signal) process.start() process.join()
28.346939
96
0.634269
fcda12b729e7cbc817c6e3facf028035aac8cc72
3,560
css
CSS
docs/dragscroll.css
xaunvih/dragscroll
7b1225ce4d7ce1bb4c90c0b0f88b444119c9ae11
[ "MIT" ]
6
2021-01-20T08:56:13.000Z
2021-12-31T08:36:31.000Z
docs/dragscroll.css
xaunvih/dragscroll
7b1225ce4d7ce1bb4c90c0b0f88b444119c9ae11
[ "MIT" ]
null
null
null
docs/dragscroll.css
xaunvih/dragscroll
7b1225ce4d7ce1bb4c90c0b0f88b444119c9ae11
[ "MIT" ]
null
null
null
/*! * * Copyright (c) 2020 XuanVinh * name: dragscroll-ts * license: MIT * author: vinhmai <vinhmai079@gmail.com> * repository: git+https://github.com/xaunvih/dragscroll-ts * version: 1.0.3 */ button,input,optgroup,select,textarea{font:inherit;font-family:inherit;font-size:100%;margin:0;padding:0;border:none;outline:none}button:focus,input:focus,optgroup:focus,select:focus,textarea:focus{outline-offset:0}button,select{text-transform:none;background-color:transparent}button{-webkit-appearance:none;cursor:pointer;border-style:none}textarea{overflow:auto;vertical-align:top}main,header,footer,aside,article,section,details{display:block}*{box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box}*:focus{outline:none}*[hidden]{display:none}h1,h2,h3,h4,h5,h6,b,strong{font-weight:bold;margin:0;padding:0}ul,ol,p{margin:0;padding:0;list-style:none}a{background-color:transparent;cursor:pointer}body{margin:0;padding:0;font-weight:normal;line-height:1.4;-ms-scroll-chaining:none;overscroll-behavior:none;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-overflow-scrolling:touch;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;background-color:transparent;font-size:16px;font-family:sans-serif}body{background-color:#000;color:purple;overflow:auto}body h2{padding:20px 20px 10px}body p{padding:0 20px 10px}body .menu{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:flex;-webkit-box-align:center;-webkit-align-items:center;-moz-box-align:center;align-items:center}body .menu li{padding:10px 20px;-webkit-flex-shrink:0;flex-shrink:0}body .menu li a{display:block}.container .drag-scroll{display:-webkit-box;display:-webkit-flex;display:-moz-box;display:flex;overflow:hidden;width:100vw;border:1px solid purple}.container .drag-scroll.drag-scroll-vertical{height:80vh;max-width:500px;margin:0 auto;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;-moz-box-orient:vertical;-moz-box-direction:normal;flex-direction:column}.container .drag-scroll.drag-scroll-vertical ul{display:block}.container .drag-scroll.drag-scroll-vertical ul li{margin-bottom:20px;margin-right:0;width:500px;height:500px}.container .drag-scroll.drag-scroll-all{height:80vh;width:50vw;margin:0 auto}.container .drag-scroll.drag-scroll-all .img-wrapper{position:relative;width:200%;height:200%;-webkit-flex-shrink:0;flex-shrink:0}.container .drag-scroll.drag-scroll-all .img-wrapper img{width:100%;height:100%;position:absolute;top:0;left:0;-o-object-fit:cover;object-fit:cover}.container .drag-scroll ul{padding:0;margin:0;list-style-type:none;display:-webkit-box;display:-webkit-flex;display:-moz-box;display:flex;white-space:nowrap}.container .drag-scroll ul li{width:300px;height:250px;-webkit-flex-shrink:0;flex-shrink:0;margin-right:20px;position:relative}.container .drag-scroll ul li:last-child{margin-right:0}.container .drag-scroll ul li input,.container .drag-scroll ul li textarea{width:100%;height:50%;padding:10px}.container .drag-scroll ul li input:focus,.container .drag-scroll ul li textarea:focus{border:1px solid purple}.container .drag-scroll ul li input{height:40px}.container .drag-scroll ul li label{cursor:pointer;display:block;width:100%;text-transform:capitalize;background-color:purple;color:#000;padding:10px}.container .drag-scroll ul li img{width:100%;height:100%;position:absolute;top:0;left:0;-o-object-fit:cover;object-fit:cover}
323.636364
3,333
0.797472
9d3d2d64f28ac83598b1ad830fcda16f944acaf5
7,637
html
HTML
external/SFMT-src-1.4/jump/html/namespacesfmt.html
suomela/types
b85c6e623b4a3a463b90b850494a2cfd4c83c595
[ "MIT", "Unlicense", "BSD-2-Clause", "BSD-3-Clause" ]
4
2015-05-06T06:01:14.000Z
2021-09-07T13:21:43.000Z
external/SFMT-src-1.4/jump/html/namespacesfmt.html
suomela/types
b85c6e623b4a3a463b90b850494a2cfd4c83c595
[ "MIT", "Unlicense", "BSD-2-Clause", "BSD-3-Clause" ]
2
2016-02-20T23:34:06.000Z
2018-10-29T22:46:38.000Z
external/SFMT-src-1.4/jump/html/namespacesfmt.html
suomela/types
b85c6e623b4a3a463b90b850494a2cfd4c83c595
[ "MIT", "Unlicense", "BSD-2-Clause", "BSD-3-Clause" ]
1
2016-02-25T12:21:32.000Z
2016-02-25T12:21:32.000Z
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>SFMT-jump: sfmt Namespace Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">SFMT-jump &#160;<span id="projectnumber">0.1</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.8.0 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Namespace&#160;List</span></a></li> <li><a href="namespacemembers.html"><span>Namespace&#160;Members</span></a></li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">sfmt Namespace Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:a7a631ec08437571ac1865b7c665cfdd3"><td class="memItemLeft" align="right" valign="top">static void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacesfmt.html#a7a631ec08437571ac1865b7c665cfdd3">polytostring</a> (std::string &amp;x, NTL::GF2X &amp;polynomial)</td></tr> <tr class="memdesc:a7a631ec08437571ac1865b7c665cfdd3"><td class="mdescLeft">&#160;</td><td class="mdescRight">converts polynomial to string for convenient use in C language. <a href="#a7a631ec08437571ac1865b7c665cfdd3"></a><br/></td></tr> <tr class="memitem:ab47757f3b6e878834b2be9f2cb1f1b2c"><td class="memItemLeft" align="right" valign="top">static void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacesfmt.html#ab47757f3b6e878834b2be9f2cb1f1b2c">stringtopoly</a> (NTL::GF2X &amp;poly, std::string &amp;str)</td></tr> <tr class="memdesc:ab47757f3b6e878834b2be9f2cb1f1b2c"><td class="mdescLeft">&#160;</td><td class="mdescRight">converts string to polynomial <a href="#ab47757f3b6e878834b2be9f2cb1f1b2c"></a><br/></td></tr> <tr class="memitem:aa110d91a210e06c3f5b3b4b6446bee05"><td class="memItemLeft" align="right" valign="top">static void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacesfmt.html#aa110d91a210e06c3f5b3b4b6446bee05">calc_jump</a> (std::string &amp;jump_str, NTL::ZZ &amp;step, NTL::GF2X &amp;characteristic)</td></tr> <tr class="memdesc:aa110d91a210e06c3f5b3b4b6446bee05"><td class="mdescLeft">&#160;</td><td class="mdescRight">calculate the jump polynomial. <a href="#aa110d91a210e06c3f5b3b4b6446bee05"></a><br/></td></tr> </table> <hr/><h2>Function Documentation</h2> <a class="anchor" id="aa110d91a210e06c3f5b3b4b6446bee05"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">static void <a class="el" href="namespacesfmt.html#aa110d91a210e06c3f5b3b4b6446bee05">sfmt::calc_jump</a> </td> <td>(</td> <td class="paramtype">std::string &amp;&#160;</td> <td class="paramname"><em>jump_str</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">NTL::ZZ &amp;&#160;</td> <td class="paramname"><em>step</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">NTL::GF2X &amp;&#160;</td> <td class="paramname"><em>characteristic</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [inline, static]</code></td> </tr> </table> </div> <div class="memdoc"> <p>calculate the jump polynomial. </p> <p>SFMT generates 4 32-bit integers from one internal state. </p> <dl class="params"><dt><b>Parameters:</b></dt><dd> <table class="params"> <tr><td class="paramname">jump_str</td><td>output string which represents jump polynomial. </td></tr> <tr><td class="paramname">step</td><td>jump step of internal state </td></tr> <tr><td class="paramname">characteristic</td><td>polynomial </td></tr> </table> </dd> </dl> <p>References <a class="el" href="namespacesfmt.html#a7a631ec08437571ac1865b7c665cfdd3">polytostring()</a>.</p> </div> </div> <a class="anchor" id="a7a631ec08437571ac1865b7c665cfdd3"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">static void <a class="el" href="namespacesfmt.html#a7a631ec08437571ac1865b7c665cfdd3">sfmt::polytostring</a> </td> <td>(</td> <td class="paramtype">std::string &amp;&#160;</td> <td class="paramname"><em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">NTL::GF2X &amp;&#160;</td> <td class="paramname"><em>polynomial</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [inline, static]</code></td> </tr> </table> </div> <div class="memdoc"> <p>converts polynomial to string for convenient use in C language. </p> <dl class="params"><dt><b>Parameters:</b></dt><dd> <table class="params"> <tr><td class="paramname">x</td><td>output string </td></tr> <tr><td class="paramname">polynomial</td><td></td></tr> </table> </dd> </dl> <p>Referenced by <a class="el" href="namespacesfmt.html#aa110d91a210e06c3f5b3b4b6446bee05">calc_jump()</a>.</p> </div> </div> <a class="anchor" id="ab47757f3b6e878834b2be9f2cb1f1b2c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">static void <a class="el" href="namespacesfmt.html#ab47757f3b6e878834b2be9f2cb1f1b2c">sfmt::stringtopoly</a> </td> <td>(</td> <td class="paramtype">NTL::GF2X &amp;&#160;</td> <td class="paramname"><em>poly</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">std::string &amp;&#160;</td> <td class="paramname"><em>str</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td><code> [inline, static]</code></td> </tr> </table> </div> <div class="memdoc"> <p>converts string to polynomial </p> <dl class="params"><dt><b>Parameters:</b></dt><dd> <table class="params"> <tr><td class="paramname">str</td><td>string </td></tr> <tr><td class="paramname">poly</td><td>output polynomial </td></tr> </table> </dd> </dl> </div> </div> </div><!-- contents --> <hr class="footer"/><address class="footer"><small> Generated on Fri Jun 29 2012 13:59:35 for SFMT-jump by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.0 </small></address> </body> </html>
37.806931
343
0.616865
9d403b3d24d1c49d17a7ea3b72e811928fc4a3f3
1,259
kt
Kotlin
src/main/kotlin/SpecialSync/App.kt
minionprocyk/SpecialSync
bebab02579d37b781eb52e79ec25982a83248c0a
[ "MIT" ]
null
null
null
src/main/kotlin/SpecialSync/App.kt
minionprocyk/SpecialSync
bebab02579d37b781eb52e79ec25982a83248c0a
[ "MIT" ]
null
null
null
src/main/kotlin/SpecialSync/App.kt
minionprocyk/SpecialSync
bebab02579d37b781eb52e79ec25982a83248c0a
[ "MIT" ]
null
null
null
package SpecialSync import SpecialSync.modules.SyncModule import com.authzee.kotlinguice4.getInstance import com.google.inject.Guice import main.kotlin.SpecialSync.SyncHandler import java.nio.file.Paths fun usage() { print(""" Usage: sps <source> <outdir> e.g. specialsync /home/user/documents /mnt/media/documents Synchronizes two folders such that all files from the source directory are contained in the provided output directory. Folder structure is not maintained with this sync, however if a given folder does not exist in the <outdir> then one is created. If an already existing file exists in the <outdir> then that file will be replaced with the new original file from <source>. Options: -f force overwrite for already existing files in the <outdir> """.trimIndent()) } fun main(args: Array<String>) { //validate inputs and spit usage //TODO: validate input with regex -- solving happy case for now if(args.size==2 &&(args[0].isNotBlank().and(args[1].isNotBlank()))) { val injector = Guice.createInjector(SyncModule()) injector.getInstance<SyncHandler>().sync(Paths.get(args[0]), Paths.get(args[1])) } else { usage() } }
35.971429
120
0.692613
8c3fe33e4c104df947ae9476d654aa1e04500117
479
swift
Swift
Package.swift
Hengyu/Onboarding
274b655d4345b5109c41db954bdbc3f4fb1dc051
[ "MIT" ]
null
null
null
Package.swift
Hengyu/Onboarding
274b655d4345b5109c41db954bdbc3f4fb1dc051
[ "MIT" ]
null
null
null
Package.swift
Hengyu/Onboarding
274b655d4345b5109c41db954bdbc3f4fb1dc051
[ "MIT" ]
null
null
null
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Onboarding", platforms: [.iOS(.v11), .tvOS(.v11)], products: [ .library(name: "Onboarding", targets: ["Onboarding"]) ], targets: [ .target(name: "Onboarding", dependencies: []), .testTarget(name: "OnboardingTests", dependencies: ["Onboarding"]) ] )
28.176471
96
0.647182
b74cdef749d1ef6ba1fb26300984066e3a966ec9
1,307
swift
Swift
UnsplashPhotoPicker/UnsplashPhotoPicker/Classes/Controllers/UnsplashPhotoPickerPreviewViewController.swift
CraftizLtd/unsplash-photopicker-ios
46d6a2508f065f9a6ca7b2c9561a6f3eab4a960e
[ "MIT" ]
null
null
null
UnsplashPhotoPicker/UnsplashPhotoPicker/Classes/Controllers/UnsplashPhotoPickerPreviewViewController.swift
CraftizLtd/unsplash-photopicker-ios
46d6a2508f065f9a6ca7b2c9561a6f3eab4a960e
[ "MIT" ]
null
null
null
UnsplashPhotoPicker/UnsplashPhotoPicker/Classes/Controllers/UnsplashPhotoPickerPreviewViewController.swift
CraftizLtd/unsplash-photopicker-ios
46d6a2508f065f9a6ca7b2c9561a6f3eab4a960e
[ "MIT" ]
1
2021-04-01T07:23:56.000Z
2021-04-01T07:23:56.000Z
// // UnsplashPhotoPickerPreviewViewController.swift // UnsplashPhotoPicker // // Created by Bichon, Nicolas on 2018-11-04. // Copyright © 2018 Unsplash. All rights reserved. // import UIKit import AVFoundation class UnsplashPhotoPickerPreviewViewController: UIViewController { private lazy var photoImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.image = image imageView.backgroundColor = .clear return imageView }() private let image: UIImage private let ratio: CGSize init(image: UIImage) { self.image = image ratio = .init(width: image.size.width / image.size.height, height: 1) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .clear view.addSubview(photoImageView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let maxFitFrame = AVMakeRect(aspectRatio: ratio, insideRect: view.bounds) preferredContentSize = maxFitFrame.size photoImageView.frame = maxFitFrame } }
27.229167
81
0.674063
26ab619f3e11407f500dd61f2f813043604018ec
958
java
Java
core/src/sk/tuke/gamedev/iddqd/tukequest/levels/PorubanFirstLevel.java
scscgit/TukeQuest
d743a8bac2beb4fb94e38d2050fcd984ae9534ca
[ "Apache-2.0" ]
2
2017-05-02T13:14:15.000Z
2018-03-06T13:06:51.000Z
core/src/sk/tuke/gamedev/iddqd/tukequest/levels/PorubanFirstLevel.java
scscgit/TukeQuest
d743a8bac2beb4fb94e38d2050fcd984ae9534ca
[ "Apache-2.0" ]
46
2017-03-24T14:31:17.000Z
2017-05-02T10:29:13.000Z
core/src/sk/tuke/gamedev/iddqd/tukequest/levels/PorubanFirstLevel.java
scscgit/TukeQuest
d743a8bac2beb4fb94e38d2050fcd984ae9534ca
[ "Apache-2.0" ]
2
2019-11-30T13:11:54.000Z
2021-02-07T00:07:12.000Z
package sk.tuke.gamedev.iddqd.tukequest.levels; import com.badlogic.gdx.math.Vector2; import sk.tuke.gamedev.iddqd.tukequest.actors.game.Background; import sk.tuke.gamedev.iddqd.tukequest.actors.game.VerticalWall; import sk.tuke.gamedev.iddqd.tukequest.actors.game.platforms.Platform; import sk.tuke.gamedev.iddqd.tukequest.actors.game.player.Player; import sk.tuke.gamedev.iddqd.tukequest.actors.game.teachers.Poruban; /** * Created by Steve on 01.05.2017. */ public class PorubanFirstLevel extends Level { public PorubanFirstLevel() { super( "Porubanov level", Platform.PlatformTexture.CHIMNEY, 150, Poruban.class, Background.BackgroundTexture.ICY_TOWER, VerticalWall.WallTexture.BINARY); } @Override public void levelAchieved(Player player) { super.levelAchieved(player); player.getGameScreen().setGravity(new Vector2(0, -25)); } }
29.9375
70
0.706681
3be8d499a099cb654035e499ca9c00bfa7b6f940
324
h
C
openwrt-18.06/target/linux/at91/image/dfboot/src/config.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
1,144
2018-12-18T09:46:47.000Z
2022-03-07T14:51:46.000Z
openwrt-18.06/target/linux/at91/image/dfboot/src/config.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
16
2019-01-28T06:08:40.000Z
2019-12-04T10:26:41.000Z
openwrt-18.06/target/linux/at91/image/dfboot/src/config.h
bingchunjin/1806_SDK
d5ed0258fc22f60e00ec025b802d175f33da6e41
[ "MIT" ]
129
2018-12-18T09:46:50.000Z
2022-03-30T07:30:13.000Z
#ifndef _CONFIG_H #define _CONFIG_H //#define PAGESZ_1056 1 #undef PAGESZ_1056 #define SPI_LOW_SPEED 1 #define AT91C_DELAY_TO_BOOT 1500 #define CRC_RETRIES 0x100 #define AT91C_MASTER_CLOCK 59904000 #define AT91C_BAUD_RATE 115200 #define AT91C_ALTERNATE_USART AT91C_BASE_US0 #endif
18
48
0.740741
3c1b2a7e37a58161103aca706a945e2972f2e27a
1,972
swift
Swift
Sources/App/routes.swift
kishikawakatsumi/xcresulttool-file
639b27510f8c4c4519620da0f18cba53424c5e10
[ "MIT" ]
null
null
null
Sources/App/routes.swift
kishikawakatsumi/xcresulttool-file
639b27510f8c4c4519620da0f18cba53424c5e10
[ "MIT" ]
null
null
null
Sources/App/routes.swift
kishikawakatsumi/xcresulttool-file
639b27510f8c4c4519620da0f18cba53424c5e10
[ "MIT" ]
null
null
null
import Vapor import Foundation func routes(_ app: Application) throws { app.get { _ in healthCheck() } app.get("health") { _ in healthCheck() } func healthCheck() -> [String: String] { ["status": "pass"] } app.get("f") { (req) -> Response in guard let key = req.query[String.self, at: "k"] else { throw Abort(.badRequest) } let filepath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(key) guard let data = try? Data(contentsOf: filepath) else { throw Abort(.notFound) } return Response( status: .ok, headers: ["Content-Type": "image/png"], body: Response.Body( buffer: ByteBuffer(data: data) ) ) } app.get("file") { (req) -> Response in guard let key = req.query[String.self, at: "key"] else { throw Abort(.badRequest) } let filepath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(key) guard let data = try? Data(contentsOf: filepath) else { throw Abort(.notFound) } return Response( status: .ok, headers: ["Content-Type": "image/png"], body: Response.Body( buffer: ByteBuffer(data: data) ) ) } app.on(.POST, "file", body: .collect(maxSize: "100mb")) { (req) -> FileUploadResponse in guard let parameter = req.body.string else { throw Abort(.badRequest) } let filename = ShortUUID.generate() let filepath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename) guard let data = Data(base64Encoded: parameter) else { throw Abort(.badRequest) } try data.write(to: filepath) return FileUploadResponse(link: "https://xcresulttool-file.herokuapp.com/f?k=\(filename)") } } struct FileUploadRequestParameter: Content { let file: String } struct FileUploadResponse: Content { let link: String }
32.866667
100
0.614097
85ad0179bc707a9b141ab5069ebd31f6f32b785b
4,440
js
JavaScript
public/js/script-halaman-search.js
rafiqprogrammer/tripmate-website-laravel-8
4dfc35b8a6f7d575d8e062d6a5e772a02e88cfdf
[ "MIT" ]
null
null
null
public/js/script-halaman-search.js
rafiqprogrammer/tripmate-website-laravel-8
4dfc35b8a6f7d575d8e062d6a5e772a02e88cfdf
[ "MIT" ]
null
null
null
public/js/script-halaman-search.js
rafiqprogrammer/tripmate-website-laravel-8
4dfc35b8a6f7d575d8e062d6a5e772a02e88cfdf
[ "MIT" ]
null
null
null
const slider1 = document.getElementById("slider1"); const slider2 = document.getElementById("slider2"); noUiSlider.create(slider1, { start: [0, 13], connect: true, step: 1, range: { min: 0, max: 13, }, format: wNumb({ decimals: 0, suffix: " j", }), }); noUiSlider.create(slider2, { start: [0, 13], connect: true, step: 1, range: { min: 0, max: 13, }, format: wNumb({ decimals: 0, suffix: " j", }), }); // Ubah durasi per transit ketika nilai input range di update slider1.noUiSlider.on("update", function (values, handle) { $("#section2Content .text-duration .text-hour").html( values[0] + " - " + values[1] ); }); // Ubah total durasi perjalanan ketika input range di update slider2.noUiSlider.on("update", function (values, handle) { $("#section7Content .text-duration .text-hour").html( values[0] + " - " + values[1] ); }); // Plugin Input Spinner let config = { incrementButton: "<i class='fa fa-plus'></i>", decrementButton: "<i class='fa fa-minus'></i>", buttonsClass: "border btn-outline-warning btn-passenger", buttonsOnly: true, groupClass: "input-passenger", }; $("input[type='number']").inputSpinner(config); /** * Cek apakah input kosong atau tidak * jika kosong, maka isi kembali dengan nilai sebelumnya */ // const bandaraAsal = $("#inputBandaraAsal").val(); // const bandaraTujuan = $("#inputBandaraTujuan").val(); // $(".box-flightform-airport .form-control").blur(function () { // if (!$(this).val()) { // if ($(this).attr("id") == "inputBandaraAsal") { // $(this).val(bandaraAsal); // } else { // $(this).val(bandaraTujuan); // } // } // }); //Ini digunakan untuk mengisi kembali inputan tanggal yang kosong let tanggalBerangkat = $("#inputTanggalBerangkat").val(); let tanggalPulang = $("#inputTanggalPulang").val(); $("input[id*='inputTanggal']").on("hide", function (e) { if (!$(e.target).val()) { if ($(e.target).attr("id") == "inputTanggalBerangkat") { $(e.target).val(tanggalBerangkat); } else { $(e.target).val(tanggalPulang); } } }); $(".cabin-class").on("click", function () { let kelasKabin = $.trim($(this).text().toLowerCase()); $("input[name='class']").val(kelasKabin); }); function formatBandara(bandara) { if (!bandara.id) { return bandara.text; } let $bandara = $( `<i class="fa fa-city mr-2"></i><span>${bandara.text} </span><span class="dropdown-option-code ml-auto text-center">${bandara.id}</span>` ); return $bandara; } $("#selectBoxBandara1").select2({ dropdownParent: $("#containerBandaraAsal"), templateResult: formatBandara, }); $("#selectBoxBandara2").select2({ dropdownParent: $("#containerBandaraTujuan"), templateResult: formatBandara, }); $("#selectBoxBandara1").on("select2:select", function (e) { let data = e.params.data; $("input[name='nama_bandara_asal']").val(data.text); }); $("#selectBoxBandara2").on("select2:select", function (e) { let data = e.params.data; $("input[name='nama_bandara_tujuan']").val(data.text); }); // $.ajaxSetup({ // headers: { // "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"), // }, // }); // $(".change s").on("submit", function (e) { // $.ajax({ // url: "/pesawat/search/edit", // method: "get", // dataType: "json", // data: $(this).serialize(), // success: function (data) { // console.log(data); // let persen = 0; // $(".progress").removeClass("d-none"); // let timer = setInterval(function () { // persen = persen + 20; // progressBarProcess(persen, timer); // }, 500); // let request = data.request; // // Tutup modal ubah penerbangan // $("#changeSearchModal").modal("hide"); // }, // }); // }); // function progressBarProcess(persen, timer) { // $(".progress-bar").css("width", persen + "%"); // if (persen > 100) { // clearInterval(timer); // $(".progress").addClass("d-none"); // $(".progress-bar").css("width", "0%"); // } // } $("#selectBoxBandaraAsal").select2({ dropdownParent: $("#containerBandaraAsal"), });
27.924528
145
0.556306
179c2ee6a801bbfdc9bc41801bd09a539cb5905c
545
kt
Kotlin
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/interpreter/TypeTest.kt
benetti-smeup/jariko
c11a45fa2b540df092abf94b0ab1014ca1ef3410
[ "Apache-2.0" ]
40
2019-11-26T16:35:55.000Z
2022-02-15T08:35:20.000Z
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/interpreter/TypeTest.kt
benetti-smeup/jariko
c11a45fa2b540df092abf94b0ab1014ca1ef3410
[ "Apache-2.0" ]
28
2019-12-02T13:32:20.000Z
2021-12-17T09:34:56.000Z
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/interpreter/TypeTest.kt
benetti-smeup/jariko
c11a45fa2b540df092abf94b0ab1014ca1ef3410
[ "Apache-2.0" ]
9
2019-12-10T06:40:59.000Z
2021-10-18T08:55:29.000Z
package com.smeup.rpgparser.interpreter import org.junit.Test import kotlin.test.assertEquals class TypeTest { @Test fun aSmallerIntIsAssignableToALargerInt() { val valueType = NumberType(1, 0) val targetType = NumberType(8, 0) assertEquals(true, targetType.canBeAssigned(valueType)) } @Test fun twoSameNumberTypesAreAssignableToEachOther() { val valueType = NumberType(8, 3) val targetType = NumberType(8, 3) assertEquals(true, targetType.canBeAssigned(valueType)) } }
25.952381
63
0.695413
c48f4ca3fcfe47f0064df3fbfe007e26ee5c1acb
53
h
C
src/uml/usage.h
Quicksilver-Project/quicksilveruml
c9019443360c98c61edbd60c93cf2c1701912c2e
[ "MIT" ]
null
null
null
src/uml/usage.h
Quicksilver-Project/quicksilveruml
c9019443360c98c61edbd60c93cf2c1701912c2e
[ "MIT" ]
null
null
null
src/uml/usage.h
Quicksilver-Project/quicksilveruml
c9019443360c98c61edbd60c93cf2c1701912c2e
[ "MIT" ]
1
2021-04-02T21:35:06.000Z
2021-04-02T21:35:06.000Z
#include "dependency.h" /**~common structure~ * **/
17.666667
23
0.622642
53e4d08943563b029f0d8bf6472d0d1541fb216d
371
asm
Assembly
oeis/010/A010227.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/010/A010227.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/010/A010227.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A010227: Continued fraction for sqrt(185). ; Submitted by Jamie Morken(s3) ; 13,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1,26,1,1,1,1 mov $4,$0 add $0,5 gcd $0,$4 mov $2,$0 lpb $2 div $0,4 lpb $4 mov $0,2 mov $4,$3 lpe mul $0,13 mov $2,1 lpe
20.611111
166
0.560647
85612568428dbf7c7092fd04e70f4928ffd2dc3a
418
js
JavaScript
exercises/practice/binary-search/.meta/proof.ci.js
dotnil/javascript
f881eced6ef3439c0e119d57bfa8a1fa8e533210
[ "MIT" ]
435
2017-06-23T03:35:46.000Z
2022-03-27T06:24:20.000Z
exercises/practice/binary-search/.meta/proof.ci.js
dotnil/javascript
f881eced6ef3439c0e119d57bfa8a1fa8e533210
[ "MIT" ]
1,096
2017-06-24T07:08:13.000Z
2022-03-31T20:44:13.000Z
exercises/practice/binary-search/.meta/proof.ci.js
dotnil/javascript
f881eced6ef3439c0e119d57bfa8a1fa8e533210
[ "MIT" ]
538
2017-06-20T16:40:25.000Z
2022-03-31T15:24:00.000Z
export const find = (array, element) => { let start = 0; let end = array.length - 1; let middle; while (start <= end) { middle = Math.floor((start + end) / 2); if (element === array[middle]) { return middle; } else if (element < array[middle]) { end = middle - 1; } else if (element > array[middle]) { start = middle + 1; } } throw new Error('Value not in array'); };
24.588235
43
0.550239
7fa605e3f52b61710bdac00f4f09f7d60832cefd
1,140
rs
Rust
src/commands/lorri.rs
anakos/nixd
121a25a7b9e368ba2d1bff53920759aadd15118c
[ "MIT" ]
null
null
null
src/commands/lorri.rs
anakos/nixd
121a25a7b9e368ba2d1bff53920759aadd15118c
[ "MIT" ]
null
null
null
src/commands/lorri.rs
anakos/nixd
121a25a7b9e368ba2d1bff53920759aadd15118c
[ "MIT" ]
null
null
null
use { crate::types as nixd, std::io::{self, Write}, }; /// Runs `lorri init` from the current working directory and /// sets the content of shell.nix to the provided content. pub fn init() -> nixd::Result<()> { check()?; super::exec("lorri", |mut cmd| cmd.arg("init").output())?; write_nixpkgs_nix()?; update_nix_shell()?; Ok(()) } /// Runs `lorri init` from the current working directory and /// sets the content of shell.nix to the provided content. pub fn shell() -> nixd::Result<()> { super::exec("lorri", |mut cmd| cmd.arg("shell").output())?; Ok(()) } /// Used to verify that lorri is installed on the current system. fn check() -> nixd::Result<()> { super::exec("lorri", |mut cmd| cmd.arg("-V").output()) } /// writes shell.nix to CWD. fn write_nixpkgs_nix() -> io::Result<()> { let mut sources = std::fs::File::create("nix/nixpkgs.nix")?; sources.write_all(nixd::SOURCES_SRC.as_bytes())?; Ok(()) } /// writes shell.nix to CWD. fn update_nix_shell() -> io::Result<()> { std::fs::File::create("shell.nix")?.write_all(nixd::TRIVIAL_SHELL_SRC.as_bytes())?; Ok(()) }
25.333333
87
0.616667
5b154333a6d157333ee1d53f9efa9bde4659b6e8
1,435
h
C
src/core/genericpropertyparameter.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
null
null
null
src/core/genericpropertyparameter.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
5
2015-11-04T21:56:04.000Z
2015-11-10T19:58:18.000Z
src/core/genericpropertyparameter.h
LuboO/iCalendar-parser_PA193_Rteam
affd994fb33a23d3dac4e83cfedbfc82f3143143
[ "MIT" ]
null
null
null
#ifndef ICAL_CORE_GENERICPROPERTYPARAMETER_H #define ICAL_CORE_GENERICPROPERTYPARAMETER_H #include "withpos.h" #include "parserexception.h" #include <string> #include <vector> namespace ical { namespace core { class GenericPropertyParameter { private: WithPos<std::string> name; std::vector<WithPos<std::string>> values; public: const WithPos<std::string> &getName() const noexcept { return name; } const std::vector<WithPos<std::string>> &getValues() const noexcept { return values; } const WithPos<std::string> &getValue() const { if (values.size() > 1) { throw ParserException(values.at(1).pos(), "Only a single property value expected!"); } /* sanity check: */ if (values.size() == 0) { throw std::logic_error("Generic property parameter shouldn't have no values!"); } return values[0]; } GenericPropertyParameter(const WithPos<std::string> &name, const std::vector<WithPos<std::string>> &values) : name(name), values(values) { } GenericPropertyParameter(WithPos<std::string> &&name, std::vector<WithPos<std::string>> &&values) : name(std::move(name)), values(std::move(values)) { } }; } // namespace core } // namespace ical #endif // ICAL_CORE_GENERICPROPERTYPARAMETER_H
25.625
91
0.609059
87a1c1eebedfcefdb67c81ee8e851a8755c167ef
1,033
kt
Kotlin
app/src/main/kotlin/com/konkuk/boost/presentation/viewmodels/InfoViewModel.kt
sys09270883/ku-boost-android
958c79ca4d345473f872bc050c16bb6b49761e0f
[ "MIT" ]
21
2021-02-13T17:49:36.000Z
2022-01-05T04:26:00.000Z
app/src/main/kotlin/com/konkuk/boost/presentation/viewmodels/InfoViewModel.kt
sys09270883/ku-boost-android
958c79ca4d345473f872bc050c16bb6b49761e0f
[ "MIT" ]
166
2021-02-14T01:31:58.000Z
2022-01-04T12:29:50.000Z
app/src/main/kotlin/com/konkuk/boost/presentation/viewmodels/InfoViewModel.kt
sys09270883/ku-boost-android
958c79ca4d345473f872bc050c16bb6b49761e0f
[ "MIT" ]
2
2021-07-26T11:22:03.000Z
2021-09-10T09:44:49.000Z
package com.konkuk.boost.presentation.viewmodels import androidx.lifecycle.* import com.konkuk.boost.domain.model.auth.PersonalInformation import com.konkuk.boost.domain.usecase.* import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class InfoViewModel @Inject constructor( getStdNoUseCase: GetStdNoUseCase, getNameUseCase: GetNameUseCase, getDeptUseCase: GetDeptUseCase, getStateUseCase: GetStateUseCase, getPersonalInfoUseCase: GetPersonalInfoUseCase, ) : ViewModel() { val stdNo = getStdNoUseCase().asLiveData() val name = getNameUseCase().asLiveData() val dept = getDeptUseCase().asLiveData() val state = getStateUseCase().asLiveData() private val _personalInfoList = MutableLiveData<List<PersonalInformation>>() val personalInfoList: LiveData<List<PersonalInformation>> get() = _personalInfoList init { getPersonalInfoUseCase(viewModelScope) { _personalInfoList.postValue(it.data ?: emptyList()) } } }
31.30303
87
0.757018
7afddbc72ba863519127bf0cb11fde8e2dd819d4
1,728
rb
Ruby
spec/rbtype/lint/multiple_definitions_spec.rb
EiNSTeiN-/rbtype
83cbc830f66b38d86c60324337f4475989c54c4f
[ "MIT" ]
1
2018-03-08T22:39:51.000Z
2018-03-08T22:39:51.000Z
spec/rbtype/lint/multiple_definitions_spec.rb
EiNSTeiN-/rbtype
83cbc830f66b38d86c60324337f4475989c54c4f
[ "MIT" ]
null
null
null
spec/rbtype/lint/multiple_definitions_spec.rb
EiNSTeiN-/rbtype
83cbc830f66b38d86c60324337f4475989c54c4f
[ "MIT" ]
null
null
null
require 'spec_helper' require 'rbtype' describe Rbtype::Lint::MultipleDefinitions do let(:require_locations) { [] } let(:rails_autoload_locations) { [] } let(:processed_source) { build_processed_source(source) } let(:sources) { [processed_source] } let(:source_set) { Rbtype::SourceSet.new } let(:runtime) do runtime = Rbtype::Deps::RuntimeLoader.new(source_set, require_locations, rails_autoload_locations) runtime.load_sources(sources) runtime end let(:lint_constants) { [] } let(:linter) { described_class.new(runtime, constants: lint_constants, files: []) } before { linter.run } describe 'errors' do subject { linter.errors } context 'when a class has multiple definitions with relevant code' do let(:lint_constants) { [const_ref(nil, :B)] } let(:source) { <<~EOF } class B a() end class B b() end EOF it { expect(subject.size).to eq 1 } it { expect(subject[0].linter).to be linter } it { expect(subject[0].message).to eq <<~ERR } `::B` has multiple relevant definitions (not used for namespacing). This is not always an error, these classes or modules may be re-opened for monkey-patching, but it may also indicate a problem with your namespace. All definitions reproduced below: test.rb:1 `class B` test.rb:4 `class B` ERR end context 'when a class is reopened for namespacing' do let(:lint_constants) { [const_ref(nil, :B)] } let(:source) { <<~EOF } class B a() end class B class C b() end end EOF it { expect(subject).to be_empty } end end end
30.857143
257
0.62037
40bc9ee7b88823a897e7d9861ed839b3c557396e
1,302
py
Python
feed.py
duarte-pompeu/best-r-jokes
b2d371b95ca67453f3f2046deb42e0774e1ace19
[ "MIT" ]
2
2016-02-05T21:29:25.000Z
2016-02-05T21:29:29.000Z
feed.py
duarte-pompeu/best-r-jokes
b2d371b95ca67453f3f2046deb42e0774e1ace19
[ "MIT" ]
6
2015-12-04T02:17:22.000Z
2016-02-08T15:28:40.000Z
feed.py
duarte-pompeu/best-r-jokes
b2d371b95ca67453f3f2046deb42e0774e1ace19
[ "MIT" ]
null
null
null
#!/usr/bin/env python2 # coding=utf-8 import xml.etree.ElementTree as ET from email.Utils import formatdate import config TREE = None CHANNEL = None def init(): global TREE, CHANNEL TREE = ET.parse(config.feed_path) root = TREE.getroot() CHANNEL = root.findall("channel")[0] def close(): trim_feed(config.max_feeds) TREE.write(config.feed_path) # uncomment to debug #~ ET.dump(TREE) def item_in_feed(url): items = CHANNEL.findall("item") for item in items: link = item.find("link").text if link == url: return True else: return False def add_entry(title, link, text): item = ET.SubElement(CHANNEL, "item") ti = ET.SubElement(item, "title") ti.text = title l = ET.SubElement(item, "link") l.text = link formatted_text = ""; for line in text.split("\n"): formatted_text += line + "<br>" de = ET.SubElement(item, "description") te = "<p>" + formatted_text + "</p>" te += "<a href='" + link + "'>" + "comments" + "</a>" de.text = te pd = ET.SubElement(item, "pubDate") pd.text = get_time_stamp() # uncomment to debug #~ ET.dump(item) def trim_feed(max_entries): entries = CHANNEL.findall("item") n_to_remove = len(entries) - max_entries for entry in entries[0:n_to_remove]: CHANNEL.remove(entry) def get_time_stamp(): return formatdate()
17.36
54
0.670507
d28a6185afa79132560734fe884fe5a6db9ceb4d
162
kt
Kotlin
projectrss/app/src/main/java/com/lello/gokkucan/rrscan/Model/RSSObject.kt
goksucan/goksucanerkoc04
44e6a534ad34eb4c5398c12b611d9d9088f40ca1
[ "MIT" ]
null
null
null
projectrss/app/src/main/java/com/lello/gokkucan/rrscan/Model/RSSObject.kt
goksucan/goksucanerkoc04
44e6a534ad34eb4c5398c12b611d9d9088f40ca1
[ "MIT" ]
null
null
null
projectrss/app/src/main/java/com/lello/gokkucan/rrscan/Model/RSSObject.kt
goksucan/goksucanerkoc04
44e6a534ad34eb4c5398c12b611d9d9088f40ca1
[ "MIT" ]
null
null
null
package com.lello.gokkucan.rrscan.Model /** * Created by gokkucan on 7.01.2018. */ data class RSSObject(val status:String, val feed:Feed, val items:List<Item>)
27
76
0.740741
842f7bd2de00b54f923a052b05db26977bf3bd84
2,558
html
HTML
_posts/2008-02-24-zoho.html
poloolop/poloolop.github.com
82ae887b53687f5a74a8f80f300fc307a46a497c
[ "MIT" ]
null
null
null
_posts/2008-02-24-zoho.html
poloolop/poloolop.github.com
82ae887b53687f5a74a8f80f300fc307a46a497c
[ "MIT" ]
null
null
null
_posts/2008-02-24-zoho.html
poloolop/poloolop.github.com
82ae887b53687f5a74a8f80f300fc307a46a497c
[ "MIT" ]
null
null
null
--- layout: post title: Zoho date: '2008-02-24T11:05:00.001+05:30' author: Umang Saini tags: - Technology modified_time: '2008-02-24T12:21:29.523+05:30' blogger_id: tag:blogger.com,1999:blog-12129362.post-7211072384670761949 blogger_orig_url: http://www.umangsaini.in/2008/02/zoho.html --- <div style="text-align: justify;">Just came across the story of <a href="http://www.adventnet.com/">AdventNet's</a> CEO Sridhar Vembu, on Forbes - <a href="http://www.forbes.com/technology/2008/02/22/mitra-zoho-india-tech-inter-cx_sm_0222mitra.html?feed=rss_popstories">The smartest unknown Indian Entrepreneur</a>.<br /><br />The article tracks AdventNet's success in Network management products and now CRM /productivity suite <a href="http://www.zoho.com/">Zoho</a>.<br /><br />Even though I've used Zoho, I never knew that it was made by Chennai based, 600 employee strong AdventNet and was actually founded way back in 1996. Forbes article places its revenues at $40 million and profits at a stunning $12 million. That is roughly Rs. 8 lacs per annum of profit per employee, and this is not the sweetest part of the story.<br /><br />AdventNet's Zoho is competing with CRM behemoth <a href="http://www.salesforce.com/">Salesforce.com</a> and Google's Document suite. The cost differential - $10 of Zoho vs. $65 per month of Salesforce.com. All this by a privately owned Indian firm which is rewriting rules in Software as a Service (SaaS) market.<br /><br />Stunning and Bold.<br /><br />Zoho CRM, Projects, Business, Meeting, Mail, Chat, Planner, Wiki, Notebook, DB and Reports, Creator, Show, Sheet and Writer. Phew. <span style="font-weight: bold;">14 in total</span>. This is still less than their Network Management product line-up.<br /><br />I will be trying out more Zoho products. As far as their corporate motto goes "<span style="font-weight: bold;">Excellence Matters</span>", its worth a try.<br /><br />Do give the Forbes article a read. <a href="http://www.forbes.com/technology/2008/02/22/mitra-zoho-india-tech-inter-cx_sm_0222mitra.html?feed=rss_popstories">Link again</a>. (It's much well written). It also has a link to Sramana Mitra's 7 part interview of Sridhar Vembu -<a href="http://sramanamitra.com/2007/07/10/happily-bootstrapping-zoho-ceo-sridhar-vembu-part-1/"><span style="font-size:100%;">Happily Bootstrapping: Zoho CEO Sridhar Vembu</span></a><h1 style="font-weight: normal;" class="title" id="post-1205"></h1><br />--<br />US<br /><br />Update: I missed Zoho24x7, Viewer, Polls and Challenge. That makes it 18 in all.<br /></div>
196.769231
2,267
0.746286
f3b1931b0d0dd9168d5d14d2729cda96a4b67855
2,521
kt
Kotlin
app/src/main/java/br/com/alura/aluraesporte/ui/fragment/DetalhesProdutoFragment.kt
clacosta/android-navigation-features
b99ead1d6bd22ad77c402d8e47077a143b3a40fd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/br/com/alura/aluraesporte/ui/fragment/DetalhesProdutoFragment.kt
clacosta/android-navigation-features
b99ead1d6bd22ad77c402d8e47077a143b3a40fd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/br/com/alura/aluraesporte/ui/fragment/DetalhesProdutoFragment.kt
clacosta/android-navigation-features
b99ead1d6bd22ad77c402d8e47077a143b3a40fd
[ "Apache-2.0" ]
null
null
null
package br.com.alura.aluraesporte.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import br.com.alura.aluraesporte.R import br.com.alura.aluraesporte.extensions.formatParaMoedaBrasileira import br.com.alura.aluraesporte.ui.viewmodel.ComponentesVisuais import br.com.alura.aluraesporte.ui.viewmodel.DetalhesProdutoViewModel import br.com.alura.aluraesporte.ui.viewmodel.EstadoAppViewModel import kotlinx.android.synthetic.main.detalhes_produto.* import org.koin.android.viewmodel.ext.android.sharedViewModel import org.koin.android.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class DetalhesProdutoFragment : BaseFragment() { private val argumentos by navArgs<DetalhesProdutoFragmentArgs>() private val produtoId by lazy { argumentos.produtoId } private val viewModel: DetalhesProdutoViewModel by viewModel { parametersOf(produtoId) } private val estadoAppviewModel: EstadoAppViewModel by sharedViewModel() private val controlador by lazy { findNavController() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.detalhes_produto, container, false ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) estadoAppviewModel.temComponentes = ComponentesVisuais(appBar = true) buscaProduto() configuraBotaoComprar() } private fun configuraBotaoComprar() { detalhes_produto_botao_comprar.setOnClickListener { viewModel.produtoEncontrado.value?.let { vaiParaPagamento() } } } private fun vaiParaPagamento() { val direcao = DetalhesProdutoFragmentDirections .acaoDetalhesProdutoParaPagamento(produtoId) controlador.navigate(direcao) } private fun buscaProduto() { viewModel.produtoEncontrado.observe(this, Observer { it?.let { produto -> detalhes_produto_nome.text = produto.nome detalhes_produto_preco.text = produto.preco.formatParaMoedaBrasileira() } }) } }
34.067568
92
0.721142
d9988361a102f064328f7c55ff2a8c439a1c3ecd
13,694
rs
Rust
node/src/utils/round_robin.rs
bradjohnl/casper-node
dd260c86aad94ea3a9e958080558778e8aee9f40
[ "Apache-2.0" ]
106
2020-09-15T07:16:28.000Z
2021-08-20T02:32:38.000Z
node/src/utils/round_robin.rs
AlexeyGas1979/casper-node
dd260c86aad94ea3a9e958080558778e8aee9f40
[ "Apache-2.0" ]
1,061
2020-09-14T23:09:28.000Z
2021-04-23T20:41:02.000Z
node/src/utils/round_robin.rs
AlexeyGas1979/casper-node
dd260c86aad94ea3a9e958080558778e8aee9f40
[ "Apache-2.0" ]
92
2020-09-14T17:08:24.000Z
2021-04-20T00:13:27.000Z
//! Weighted round-robin scheduling. //! //! This module implements a weighted round-robin scheduler that ensures no deadlocks occur, but //! still allows prioritizing events from one source over another. The module uses `tokio`'s //! synchronization primitives under the hood. use std::{ collections::{HashMap, VecDeque}, fmt::Debug, fs::File, hash::Hash, io::{self, BufWriter, Write}, num::NonZeroUsize, sync::atomic::{AtomicBool, AtomicUsize, Ordering}, }; use enum_iterator::IntoEnumIterator; use serde::{ser::SerializeMap, Serialize, Serializer}; use tokio::sync::{Mutex, MutexGuard, Semaphore}; use tracing::warn; /// Weighted round-robin scheduler. /// /// The weighted round-robin scheduler keeps queues internally and returns an item from a queue /// when asked. Each queue is assigned a weight, which is simply the amount of items maximally /// returned from it before moving on to the next queue. /// /// If a queue is empty, it is skipped until the next round. Queues are processed in the order they /// are passed to the constructor function. /// /// The scheduler keeps track internally which queue needs to be popped next. #[derive(Debug)] pub struct WeightedRoundRobin<I, K> { /// Current iteration state. state: Mutex<IterationState<K>>, /// A list of slots that are round-robin'd. slots: Vec<Slot<K>>, /// Actual queues. queues: HashMap<K, QueueState<I>>, /// Number of items in all queues combined. total: Semaphore, /// Whether or not the queue is sealed (not accepting any more items). sealed: AtomicBool, } /// State that wraps queue and its event count. #[derive(Debug)] struct QueueState<I> { /// A queue's event counter. /// /// Do not modify this unless you are holding the `queue` lock. event_count: AtomicUsize, queue: Mutex<VecDeque<I>>, } impl<I> QueueState<I> { fn new() -> Self { QueueState { event_count: AtomicUsize::new(0), queue: Mutex::new(VecDeque::new()), } } /// Remove all events from a queue. async fn drain(&self) -> Vec<I> { let mut guard = self.queue.lock().await; let events: Vec<I> = guard.drain(..).collect(); self.event_count.fetch_sub(events.len(), Ordering::SeqCst); events } #[inline] async fn push_back(&self, element: I) { self.queue.lock().await.push_back(element); self.event_count.fetch_add(1, Ordering::SeqCst); } #[inline] fn dec_count(&self) { self.event_count.fetch_sub(1, Ordering::SeqCst); } #[inline] fn event_count(&self) -> usize { self.event_count.load(Ordering::SeqCst) } } /// The inner state of the queue iteration. #[derive(Copy, Clone, Debug)] struct IterationState<K> { /// The currently active slot. /// /// Once it has no tickets left, the next slot is loaded. active_slot: Slot<K>, /// The position of the active slot. Used to calculate the next slot. active_slot_idx: usize, } /// An internal slot in the round-robin scheduler. /// /// A slot marks the scheduling position, i.e. which queue we are currently polling and how many /// tickets it has left before the next one is due. #[derive(Copy, Clone, Debug)] struct Slot<K> { /// The key, identifying a queue. key: K, /// Number of items to return before moving on to the next queue. tickets: usize, } impl<I, K> WeightedRoundRobin<I, K> where I: Serialize, K: Copy + Clone + Eq + Hash + IntoEnumIterator + Serialize, { /// Create a snapshot of the queue by locking it and serializing it. /// /// The serialized events are streamed directly into `serializer`. /// /// # Warning /// /// This function locks all queues in the order defined by the order defined by /// `IntoEnumIterator`. Calling it multiple times in parallel is safe, but other code that locks /// more than one queue at the same time needs to be aware of this. pub async fn snapshot<S: Serializer>(&self, serializer: S) -> Result<(), S::Error> { // Lock all queues in order get a snapshot, but release eagerly. This way we are guaranteed // to have a consistent result, but we also allow for queues to be used again earlier. let mut locks = Vec::new(); for kind in K::into_enum_iter() { let queue_guard = self .queues .get(&kind) .expect("missing queue while snapshotting") .queue .lock() .await; locks.push((kind, queue_guard)); } let mut map = serializer.serialize_map(Some(locks.len()))?; // By iterating over the guards, they are dropped in order. for (kind, guard) in locks { let vd = &*guard; map.serialize_key(&kind)?; map.serialize_value(vd)?; } map.end()?; Ok(()) } } impl<I, K> WeightedRoundRobin<I, K> where I: Debug, K: Copy + Clone + Eq + Hash + IntoEnumIterator + Debug, { /// Dump the contents of the queues (`Debug` representation) to a given file. pub async fn debug_dump(&self, file: &mut File) -> Result<(), io::Error> { let locks = self.lock_queues().await; let mut writer = BufWriter::new(file); for (kind, guard) in locks { let queue = &*guard; writer.write_all(format!("Queue: {:?} ({}) [\n", kind, queue.len()).as_bytes())?; for event in queue.iter() { writer.write_all(format!("\t{:?}\n", event).as_bytes())?; } writer.write_all(b"]\n")?; } writer.flush() } /// Lock all queues in a well-defined order to avoid deadlocks conditions. async fn lock_queues(&self) -> Vec<(K, MutexGuard<'_, VecDeque<I>>)> { let mut locks = Vec::new(); for kind in K::into_enum_iter() { let queue_guard = self .queues .get(&kind) .expect("missing queue while locking") .queue .lock() .await; locks.push((kind, queue_guard)); } locks } } impl<I, K> WeightedRoundRobin<I, K> where K: Copy + Clone + Eq + Hash, { /// Creates a new weighted round-robin scheduler. /// /// Creates a queue for each pair given in `weights`. The second component of each `weight` is /// the number of times to return items from one queue before moving on to the next one. pub(crate) fn new(weights: Vec<(K, NonZeroUsize)>) -> Self { assert!(!weights.is_empty(), "must provide at least one slot"); let queues = weights .iter() .map(|(idx, _)| (*idx, QueueState::new())) .collect(); let slots: Vec<Slot<K>> = weights .into_iter() .map(|(key, tickets)| Slot { key, tickets: tickets.get(), }) .collect(); let active_slot = slots[0]; WeightedRoundRobin { state: Mutex::new(IterationState { active_slot, active_slot_idx: 0, }), slots, queues, total: Semaphore::new(0), sealed: AtomicBool::new(false), } } /// Pushes an item to a queue identified by key. /// /// ## Panics /// /// Panics if the queue identified by key `queue` does not exist. pub(crate) async fn push(&self, item: I, queue: K) { if self.sealed.load(Ordering::SeqCst) { warn!("queue sealed, dropping item"); return; } self.queues .get(&queue) .expect("tried to push to non-existent queue") .push_back(item) .await; // We increase the item count after we've put the item into the queue. self.total.add_permits(1); } /// Returns the next item from queue. /// /// Asynchronously waits until a queue is non-empty or panics if an internal error occurred. pub(crate) async fn pop(&self) -> (I, K) { // Safe to `expect` here as the only way for acquiring a permit to fail would be if the // `self.total` semaphore were closed. self.total.acquire().await.expect("should acquire").forget(); let mut inner = self.state.lock().await; // We know we have at least one item in a queue. loop { let queue_state = self .queues // The queue disappearing should never happen. .get(&inner.active_slot.key) .expect("the queue disappeared. this should not happen"); let mut current_queue = queue_state.queue.lock().await; if inner.active_slot.tickets == 0 || current_queue.is_empty() { // Go to next queue slot if we've exhausted the current queue. inner.active_slot_idx = (inner.active_slot_idx + 1) % self.slots.len(); inner.active_slot = self.slots[inner.active_slot_idx]; continue; } // We have hit a queue that is not empty. Decrease tickets and pop. inner.active_slot.tickets -= 1; let item = current_queue .pop_front() // We hold the queue's lock and checked `is_empty` earlier. .expect("item disappeared. this should not happen"); queue_state.dec_count(); break (item, inner.active_slot.key); } } /// Drains all events from a specific queue. pub(crate) async fn drain_queue(&self, queue: K) -> Vec<I> { let events = self .queues .get(&queue) .expect("queue to be drained disappeared") .drain() .await; // TODO: This is racy if someone is calling `pop` at the same time. self.total .acquire_many(events.len() as u32) .await .expect("could not acquire tickets during drain") .forget(); events } /// Drains all events from all queues. pub async fn drain_queues(&self) -> Vec<I> { let mut events = Vec::new(); let keys: Vec<K> = self.queues.keys().cloned().collect(); for kind in keys { events.extend(self.drain_queue(kind).await); } events } /// Seals the queue, preventing it from accepting any more items. /// /// Items pushed into the queue via `push` will be dropped immediately. pub fn seal(&self) { self.sealed.store(true, Ordering::SeqCst); } /// Returns the number of events currently in the queue. #[cfg(test)] pub(crate) fn item_count(&self) -> usize { self.total.available_permits() } /// Returns the number of events in each of the queues. pub(crate) fn event_queues_counts(&self) -> HashMap<K, usize> { self.queues .iter() .map(|(key, queue)| (*key, queue.event_count())) .collect() } } #[cfg(test)] mod tests { use std::num::NonZeroUsize; use futures::{future::FutureExt, join}; use super::*; #[repr(usize)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] enum QueueKind { One = 1, Two, } fn weights() -> Vec<(QueueKind, NonZeroUsize)> { unsafe { vec![ (QueueKind::One, NonZeroUsize::new_unchecked(1)), (QueueKind::Two, NonZeroUsize::new_unchecked(2)), ] } } #[tokio::test] async fn should_respect_weighting() { let scheduler = WeightedRoundRobin::<char, QueueKind>::new(weights()); // Push three items on to each queue let future1 = scheduler .push('a', QueueKind::One) .then(|_| scheduler.push('b', QueueKind::One)) .then(|_| scheduler.push('c', QueueKind::One)); let future2 = scheduler .push('d', QueueKind::Two) .then(|_| scheduler.push('e', QueueKind::Two)) .then(|_| scheduler.push('f', QueueKind::Two)); join!(future2, future1); // We should receive the popped values in the order a, d, e, b, f, c assert_eq!(('a', QueueKind::One), scheduler.pop().await); assert_eq!(('d', QueueKind::Two), scheduler.pop().await); assert_eq!(('e', QueueKind::Two), scheduler.pop().await); assert_eq!(('b', QueueKind::One), scheduler.pop().await); assert_eq!(('f', QueueKind::Two), scheduler.pop().await); assert_eq!(('c', QueueKind::One), scheduler.pop().await); } #[tokio::test] async fn can_seal_queue() { let scheduler = WeightedRoundRobin::<char, QueueKind>::new(weights()); assert_eq!(scheduler.item_count(), 0); scheduler.push('a', QueueKind::One).await; assert_eq!(scheduler.item_count(), 1); scheduler.push('b', QueueKind::Two).await; assert_eq!(scheduler.item_count(), 2); scheduler.seal(); assert_eq!(scheduler.item_count(), 2); scheduler.push('c', QueueKind::One).await; assert_eq!(scheduler.item_count(), 2); scheduler.push('d', QueueKind::One).await; assert_eq!(scheduler.item_count(), 2); assert_eq!(('a', QueueKind::One), scheduler.pop().await); assert_eq!(scheduler.item_count(), 1); assert_eq!(('b', QueueKind::Two), scheduler.pop().await); assert_eq!(scheduler.item_count(), 0); assert!(scheduler.drain_queues().await.is_empty()); } }
32.450237
100
0.578648
0cddc6fcdac1a04a9f2296ecc74335e532a712c0
2,624
py
Python
recipes/libmount/all/conanfile.py
KristianJerpetjon/conan-center-index
f368200c30fb3be44862e2e709be990d0db4d30e
[ "MIT" ]
null
null
null
recipes/libmount/all/conanfile.py
KristianJerpetjon/conan-center-index
f368200c30fb3be44862e2e709be990d0db4d30e
[ "MIT" ]
1
2019-11-26T10:55:31.000Z
2019-11-26T10:55:31.000Z
recipes/libmount/all/conanfile.py
KristianJerpetjon/conan-center-index
f368200c30fb3be44862e2e709be990d0db4d30e
[ "MIT" ]
1
2019-10-31T19:29:14.000Z
2019-10-31T19:29:14.000Z
from conans import ConanFile, tools, AutoToolsBuildEnvironment from conans.errors import ConanInvalidConfiguration import os class LibmountConan(ConanFile): name = "libmount" description = "The libmount library is used to parse /etc/fstab, /etc/mtab and /proc/self/mountinfo files, manage the mtab file, evaluate mount options, etc" topics = ("conan", "mount", "libmount", "linux", "util-linux") url = "https://github.com/conan-io/conan-center-index" homepage = "https://git.kernel.org/pub/scm/utils/util-linux/util-linux.git" license = "GPL-2.0-or-later" settings = "os", "arch", "compiler", "build_type" options = {"shared": [True, False], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} _source_subfolder = "source_subfolder" _autotools = None def configure(self): del self.settings.compiler.libcxx del self.settings.compiler.cppstd if self.settings.os != "Linux": raise ConanInvalidConfiguration("only Linux is supported") def source(self): tools.get(**self.conan_data["sources"][self.version]) extracted_dir = "util-linux-" + self.version os.rename(extracted_dir, self._source_subfolder) def _configure_autotools(self): if not self._autotools: args = ["--disable-all-programs", "--enable-libmount", "--enable-libblkid"] if self.options.shared: args.extend(["--disable-static", "--enable-shared"]) else: args.extend(["--disable-shared", "--enable-static"]) self._autotools = AutoToolsBuildEnvironment(self) self._autotools.configure(args=args) return self._autotools def build(self): with tools.chdir(self._source_subfolder): env_build = self._configure_autotools() env_build.make() def package(self): with tools.chdir(self._source_subfolder): env_build = self._configure_autotools() env_build.install() self.copy(pattern="COPYING", dst="licenses", src=self._source_subfolder) tools.rmdir(os.path.join(self.package_folder, "sbin")) tools.rmdir(os.path.join(self.package_folder, "share")) tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig")) os.remove(os.path.join(self.package_folder, "lib", "libblkid.la")) os.remove(os.path.join(self.package_folder, "lib", "libmount.la")) def package_info(self): self.cpp_info.libs = ["mount", "blkid"] self.cpp_info.includedirs.append(os.path.join("include", "libmount"))
43.733333
161
0.651296
90d292b303b3bafde97adf42402f2eb1a9e456af
15,595
py
Python
mentor/userform/views.py
JarettSutula/GoatBoat
53dd978048c6757b537e5988793b29a5ef1b7b52
[ "MIT" ]
null
null
null
mentor/userform/views.py
JarettSutula/GoatBoat
53dd978048c6757b537e5988793b29a5ef1b7b52
[ "MIT" ]
null
null
null
mentor/userform/views.py
JarettSutula/GoatBoat
53dd978048c6757b537e5988793b29a5ef1b7b52
[ "MIT" ]
null
null
null
from re import sub import bcrypt from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from utils import collection_link, start_db, restructure_day_array, create_day_array, log_warning from userform.models import UserForm, EditProfile, ResetPassword, LogInForm, ProfileSearch from utils import start_db, collection_link, create_day_array, get_profile_snapshot from django import db, forms from django.shortcuts import render import bcrypt db_handle = start_db() users = collection_link(db_handle, 'users') logins = collection_link(db_handle, 'logins') # Create your views here. def homePageView(request): """View of the home page.""" return render(request,'home.html') def loginView(request): "View for the login page." return render(request,'loginheader.html') def myProfileView(request): """View for the user's profile. This will return relevant user object fields to the html page. """ # before checking anything, initialize blank context. If they don't log in and # still find themselves on profile, blank context will remove errors. context = {} # if they are logged in, make the object to pass to html. if 'username' in request.session: db = start_db() users = collection_link(db, 'users') result = users.find_one({'username': request.session['username']}) # object for html context = { 'username': result['username'], 'firstname': result['firstname'], 'lastname': result['lastname'], 'email': result['email'], 'profession': result['profession'], 'major': result['major'], 'mentorclasschoice': result['mentorclasschoice'], 'menteeclasschoice': result['menteeclasschoice'], 'currentmatches': result['currentmatches'] } else: log_warning("User is not signed in.") return render(request,'myprofile.html', {'context':context}) def userSuccess(request): submitbutton= request.POST.get("submit") firstname='' lastname='' emailvalue='' form= UserForm(request.POST or None) if form.is_valid(): firstname= form.cleaned_data.get("first_name") lastname= form.cleaned_data.get("last_name") emailvalue= form.cleaned_data.get("email") context= {'form': form, 'firstname': firstname, 'lastname':lastname, 'submitbutton': submitbutton, 'emailvalue':emailvalue} else: log_warning("Form is not valid") return render(request, 'form.html', context) def editProfileView(request): """Pulls up an editable profile, with previously inputted values placed already in the form. """ profile_context = {} form = EditProfile() submitted = False if 'username' in request.session and request.method == 'POST': form = EditProfile(request.POST) if form.is_valid(): # Base form fields firstname = form.cleaned_data.get("firstname") lastname = form.cleaned_data.get("lastname") email = form.cleaned_data.get("email") profession = form.cleaned_data.get("profession") major = form.cleaned_data.get("major") # Schedule-based form fields mondaystart = form.cleaned_data.get("mondaystart") mondayend = form.cleaned_data.get("mondayend") tuesdaystart = form.cleaned_data.get("tuesdaystart") tuesdayend = form.cleaned_data.get("tuesdayend") wednesdaystart = form.cleaned_data.get("wednesdaystart") wednesdayend = form.cleaned_data.get("wednesdayend") thursdaystart = form.cleaned_data.get("thursdaystart") thursdayend = form.cleaned_data.get("thursdayend") fridaystart = form.cleaned_data.get("fridaystart") fridayend = form.cleaned_data.get("fridayend") saturdaystart = form.cleaned_data.get("saturdaystart") saturdayend = form.cleaned_data.get("saturdayend") sundaystart = form.cleaned_data.get("sundaystart") sundayend = form.cleaned_data.get("sundayend") # Create arrays of objects with 1-hour block objects. monday = create_day_array(mondaystart, mondayend) tuesday = create_day_array(tuesdaystart, tuesdayend) wednesday = create_day_array(wednesdaystart, wednesdayend) thursday = create_day_array(thursdaystart, thursdayend) friday = create_day_array(fridaystart, fridayend) saturday = create_day_array(saturdaystart, saturdayend) sunday = create_day_array(sundaystart, sundayend) # Object to be passed into users user_context= { 'username': request.session['username'], 'firstname': firstname, 'lastname':lastname, 'email':email, 'profession':profession, 'major':major, 'schedule':{ 'monday': monday, 'tuesday': tuesday, 'wednesday': wednesday, 'thursday': thursday, 'friday': friday, 'saturday': saturday, 'sunday': sunday } } # update database object. db = start_db() users = collection_link(db, 'users') # update the user from their username and whatever fields they changed. users.update_one({'username': request.session['username']}, {'$set': user_context}) # tell HTML that we are submitted. submitted = True # if we are logged in, fill the form with current profile values. elif 'username' in request.session: db = start_db() users = collection_link(db, 'users') current_profile = users.find_one({'username': request.session['username']}) # need to translate current schedule to mondaystart, mondayend ... etc # without it, form will not display proper schedule. mondaystart, mondayend = restructure_day_array(current_profile['schedule']['monday']) tuesdaystart, tuesdayend = restructure_day_array(current_profile['schedule']['tuesday']) wednesdaystart, wednesdayend = restructure_day_array(current_profile['schedule']['wednesday']) thursdaystart, thursdayend = restructure_day_array(current_profile['schedule']['thursday']) fridaystart, fridayend = restructure_day_array(current_profile['schedule']['friday']) saturdaystart, saturdayend = restructure_day_array(current_profile['schedule']['saturday']) sundaystart, sundayend = restructure_day_array(current_profile['schedule']['sunday']) # pass the relevant user profile form fields into an object. profile_context = { 'username': current_profile['username'], 'firstname': current_profile['firstname'], 'lastname': current_profile['lastname'], 'email': current_profile['email'], 'profession': current_profile['profession'], 'major': current_profile['major'], 'mentorclasschoice': current_profile['mentorclasschoice'], 'menteeclasschoice': current_profile['menteeclasschoice'], 'mondaystart': mondaystart, 'mondayend': mondayend, 'tuesdaystart': tuesdaystart, 'tuesdayend': tuesdayend, 'wednesdaystart': wednesdaystart, 'wednesdayend': wednesdayend, 'thursdaystart': thursdaystart, 'thursdayend': thursdayend, 'fridaystart': fridaystart, 'fridayend': fridayend, 'saturdaystart': saturdaystart, 'saturdayend': saturdayend, 'sundaystart': sundaystart, 'sundayend': sundayend } form = EditProfile(initial= profile_context) else: log_warning("User is not logged in.") form = EditProfile() return render(request, 'editprofile.html', {'form':form, 'submitted':submitted}) def changePasswordView(request): """Allows user to change their password.""" form = ResetPassword() submitted = False if 'username' in request.session and request.method == 'POST': form = ResetPassword(request.POST) if form.is_valid(): submitted = True newpassword = form.cleaned_data.get("newpassword") db = start_db() logins = collection_link(db, 'logins') # encode and hash the new password new_pass = newpassword.encode('UTF-8') new_pass_hashed = bcrypt.hashpw(new_pass, bcrypt.gensalt()) # pass the new password into the db. logins.update_one({'username': request.session['username']}, {'$set': {'password':new_pass_hashed}}) submitted = True elif 'username' in request.session: # load the form with the current logged-in username. form = ResetPassword(initial={'username': request.session['username']}) else: log_warning("User is not logged in.") form = ResetPassword() return render(request, 'resetpassword.html', {'form':form, 'submitted':submitted}) def createUserView(request): """Validates user creation form and returns appropriate response. If the form is valid, insert inputs into database and return a HTTPResponseRedirect. If not, return the previously filled form values and alert user of validation errors. """ submitted = False if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): # Base form fields username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") firstname = form.cleaned_data.get("firstname") lastname = form.cleaned_data.get("lastname") email = form.cleaned_data.get("email") profession = form.cleaned_data.get("profession") major = form.cleaned_data.get("major") # Schedule-based form fields mondaystart = form.cleaned_data.get("mondaystart") mondayend = form.cleaned_data.get("mondayend") tuesdaystart = form.cleaned_data.get("tuesdaystart") tuesdayend = form.cleaned_data.get("tuesdayend") wednesdaystart = form.cleaned_data.get("wednesdaystart") wednesdayend = form.cleaned_data.get("wednesdayend") thursdaystart = form.cleaned_data.get("thursdaystart") thursdayend = form.cleaned_data.get("thursdayend") fridaystart = form.cleaned_data.get("fridaystart") fridayend = form.cleaned_data.get("fridayend") saturdaystart = form.cleaned_data.get("saturdaystart") saturdayend = form.cleaned_data.get("saturdayend") sundaystart = form.cleaned_data.get("sundaystart") sundayend = form.cleaned_data.get("sundayend") # Create arrays of objects with 1-hour block objects. monday = create_day_array(mondaystart, mondayend) tuesday = create_day_array(tuesdaystart, tuesdayend) wednesday = create_day_array(wednesdaystart, wednesdayend) thursday = create_day_array(thursdaystart, thursdayend) friday = create_day_array(fridaystart, fridayend) saturday = create_day_array(saturdaystart, saturdayend) sunday = create_day_array(sundaystart, sundayend) # Object to be passed into users user_context= { 'username': username, 'firstname': firstname, 'lastname':lastname, 'email':email, 'profession':profession, 'major':major, 'mentorclasschoice':[], 'menteeclasschoice':[], 'currentmentors': [], 'currentmentees': [], 'schedule':{ 'monday': monday, 'tuesday': tuesday, 'wednesday': wednesday, 'thursday': thursday, 'friday': friday, 'saturday': saturday, 'sunday': sunday }, 'suggestedmatches': [], 'currentmatches': [] } # Make sure the user's username/password is stored safely in logins. # Hash it in binary string first! byte_password = password.encode('UTF-8') hashed_password = bcrypt.hashpw(byte_password, bcrypt.gensalt()) login_context = { 'username': username, 'password': hashed_password } users.insert_one(user_context) logins.insert_one(login_context) return HttpResponseRedirect('/createuser?submitted=True') else: form = UserForm() if 'submitted' in request.GET: submitted = True return render(request, 'form.html', {'form': form, 'submitted': submitted}) def loginFormView(request): """Provides login form for new users. Creates a session if the login information is correct. """ form = LogInForm() if request.method == 'POST': form = LogInForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = form.cleaned_data.get("username") # if cleaners pass, that means the login should be successful. # create session with username for use across web server. request.session['username'] = username # set session expiration time for 10 minutes. request.session.set_expiry(600) # redirect user home. return HttpResponseRedirect('/') elif request.method == 'GET': # see if the session has a username. if 'username' in request.session: # if we are back here while we are logged in, delete the session. request.session.flush() # if we want to go back to home instead of log in page after, uncomment this. # return HttpResponseRedirect('/') else: form = LogInForm() return render(request, 'loginform.html', {'form': form}) def profileSearchView(request): """Provides snapshot of a user's profile.""" # initialize the resulting profile as blank, in case we don't get anything. profile = {} form = ProfileSearch() if request.method == 'POST': form = ProfileSearch(request.POST) if form.is_valid(): cd = form.cleaned_data username = form.cleaned_data.get("username") # fill profile with snapshot information, use False to dictate only a snapshot. profile = get_profile_snapshot(username, False) # return route, if necessary. # return HttpResponseRedirect('/') else: # just return the form. form = ProfileSearch() return render(request, 'profilesearch.html', {'form': form, 'profile': profile})
41.586667
102
0.601667
f777586b4d4b06b524568898cb0f5858826807e1
884
h
C
include/cpp-sort/detail/memcpy_cast.h
ChandanKSingh/cpp-sort
ce9b49e77eec7fe44a18da937bea0807d6c3e5f4
[ "MIT" ]
519
2015-08-01T12:25:41.000Z
2022-03-27T09:02:37.000Z
include/cpp-sort/detail/memcpy_cast.h
ChandanKSingh/cpp-sort
ce9b49e77eec7fe44a18da937bea0807d6c3e5f4
[ "MIT" ]
148
2015-09-20T10:24:15.000Z
2022-03-03T19:07:20.000Z
include/cpp-sort/detail/memcpy_cast.h
ChandanKSingh/cpp-sort
ce9b49e77eec7fe44a18da937bea0807d6c3e5f4
[ "MIT" ]
52
2015-11-10T14:40:13.000Z
2022-03-20T02:35:23.000Z
/* * Copyright (c) 2017 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_MEMCPY_CAST_H_ #define CPPSORT_DETAIL_MEMCPY_CAST_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <cstring> #include <memory> #include <type_traits> namespace cppsort { namespace detail { template<typename To, typename From> auto memcpy_cast(const From& value) -> To { static_assert(std::is_trivially_copyable<From>::value, ""); static_assert(std::is_trivially_copyable<To>::value, ""); static_assert(sizeof(From) == sizeof(To), ""); To result; std::memcpy(std::addressof(result), std::addressof(value), sizeof(From)); return result; } }} #endif // CPPSORT_DETAIL_MEMCPY_CAST_H_
24.555556
67
0.552036
5f09e3b0f52a2cd7919aa4f3b182dedeb33934bd
33
ts
TypeScript
frontend/pages/admin/AppSettingsPage/cards/Sso/index.ts
sentri-cloud/fleet
fe48533918910738a7225b2101f2dea450886bd7
[ "MIT" ]
null
null
null
frontend/pages/admin/AppSettingsPage/cards/Sso/index.ts
sentri-cloud/fleet
fe48533918910738a7225b2101f2dea450886bd7
[ "MIT" ]
null
null
null
frontend/pages/admin/AppSettingsPage/cards/Sso/index.ts
sentri-cloud/fleet
fe48533918910738a7225b2101f2dea450886bd7
[ "MIT" ]
null
null
null
export { default } from "./Sso";
16.5
32
0.606061
e6240703a348d47852fa30bc5dcc4b0775261920
496
sql
SQL
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/load/sql/create_drop_database.sql
lintzc/GPDB
b48c8b97da18f495c10065d0853db87960aebae2
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/load/sql/create_drop_database.sql
lintzc/GPDB
b48c8b97da18f495c10065d0853db87960aebae2
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/load/sql/create_drop_database.sql
lintzc/GPDB
b48c8b97da18f495c10065d0853db87960aebae2
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
-- start_ignore SET gp_create_table_random_default_distribution=off; -- end_ignore --start_ignore DROP DATABASE sto_db1; --end_ignore CREATE DATABASE sto_db1; \c sto_db1 CREATE TABLE sto_db_tb1 ( text_col text, bigint_col bigint, char_vary_col character varying(30), numeric_col numeric ) with(appendonly= true) DISTRIBUTED RANDOMLY; insert into sto_db_tb1 values ('0_zero', 0, '0_zero', 0); select * from sto_db_tb1; \c template1 select current_database(); DROP DATABASE sto_db1;
19.84
57
0.780242
dd7783e4c8bbb04f19c9dedff1ef1422106195d8
599
php
PHP
Products.php
aldi96/Belajar
c7a3a66ad5a394b19a41a014d22f134b80086b81
[ "MIT" ]
null
null
null
Products.php
aldi96/Belajar
c7a3a66ad5a394b19a41a014d22f134b80086b81
[ "MIT" ]
null
null
null
Products.php
aldi96/Belajar
c7a3a66ad5a394b19a41a014d22f134b80086b81
[ "MIT" ]
null
null
null
<?php include "Database.php"; class Products{ private $tablename; public $db; public function __construct(){ $this->tablename= "products"; $this->db = Database::getInstance()->getConnection(); } public function lisProducts(){ $result = $this->db->query("SELECT * FROM ".$this->tablename); return $result; } } $kategori = new Products(); $result=$kategori->lisProducts(); $data='<h3>Data Categories</h3>'; $data.='<ol>'; while($row = $result->fetch_object()){ $data .= '<li>'.$row->ProductName.'</li>'; } $data .= '</ol>'; echo $data; ?>
22.185185
68
0.589316
ce059fd8fd4f3d3ce136b00b3df4ff86219b51de
28,928
h
C
firmware/coreboot/src/mainboard/intel/harcuvar/hsio.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
1
2019-11-04T07:11:25.000Z
2019-11-04T07:11:25.000Z
firmware/coreboot/src/mainboard/intel/harcuvar/hsio.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
13
2018-10-12T21:29:09.000Z
2018-10-25T20:06:51.000Z
firmware/coreboot/src/mainboard/intel/harcuvar/hsio.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
/* * This file is part of the coreboot project. * * Copyright (C) 2016-2017 Intel Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef _MAINBOARD_HSIO_H #define _MAINBOARD_HSIO_H #include <fsp/util.h> #ifndef __ACPI__ const BL_HSIO_INFORMATION harcuvar_hsio_config[] = { /* * Supported Lanes: * 20 * * Bifurcation: * PCIE cluster #0: x8 * PCIE cluster #1: x4x4 * * FIA MUX config: * Lane[00:07]->x8 PCIE slot * Lane[08:11]->a x4 PCIe slot * Lane[12:15]->a 2nd x4 PCIe slot * Lane[16]->a SATA connector with pin7 to 5V adapter capable * Lane[17:18] -> 2 SATA connectors * Lane[19]->USB3 rear I/O panel connector */ /* SKU HSIO 20 (pcie [0-15] sata [16-18] usb [19]) */ {BL_SKU_HSIO_20, {PCIE_BIF_CTRL_x8, PCIE_BIF_CTRL_x4x4}, {/* ME_FIA_MUX_CONFIG */ {BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE00) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE01) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE02) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE03) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE04) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE05) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE06) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE07) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE08) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE09) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE10) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE11) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE12) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE13) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE14) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE15) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE16) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE17) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE18) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_XHCI, BL_FIA_LANE19)}, /* ME_FIA_SATA_CONFIG */ {BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE04) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE05) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE06) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE07) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE08) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE09) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE10) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE11) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE12) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE13) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE14) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE15) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE16) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE17) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE18) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE19)}, /* ME_FIA_PCIE_ROOT_PORTS_CONFIG */ {BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_7) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_7)} } }, /* SKU HSIO 12 (pcie [0-3, 8-9, 12-13] sata [16-18] usb [19]) */ {BL_SKU_HSIO_12, {PCIE_BIF_CTRL_x4x4, PCIE_BIF_CTRL_x2x2x2x2}, {/*ME_FIA_MUX_CONFIG */ {BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE00) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE01) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE02) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE03) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE04) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE05) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE06) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE07) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE08) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE09) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE10) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE11) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE12) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE13) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE14) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE15) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE16) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE17) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE18) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_XHCI, BL_FIA_LANE19)}, /* ME_FIA_SATA_CONFIG */ {BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE04) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE05) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE06) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE07) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE08) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE09) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE10) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE11) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE12) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE13) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE14) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE15) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE16) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE17) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE18) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE19)}, /* ME_FIA_PCIE_ROOT_PORTS_CONFIG */ {BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_7) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_7)} } }, /* SKU HSIO 10 (pcie [0-3, 8-9, 12] sata [16-17] usb [19]) */ {BL_SKU_HSIO_10, {PCIE_BIF_CTRL_x4x4, PCIE_BIF_CTRL_x2x2x2x2}, {/* ME_FIA_MUX_CONFIG */ {BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE00) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE01) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE02) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE03) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE04) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE05) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE06) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE07) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE08) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE09) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE10) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE11) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE12) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE13) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE14) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE15) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE16) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE17) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE18) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_XHCI, BL_FIA_LANE19)}, /* ME_FIA_SATA_CONFIG */ {BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE04) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE05) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE06) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE07) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE08) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE09) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE10) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE11) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE12) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE13) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE14) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE15) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE16) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE17) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE18) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE19)}, /* ME_FIA_PCIE_ROOT_PORTS_CONFIG */ {BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_7) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_X1, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_7)} } }, /* SKU HSIO 8 (pcie [0-1, 8-9, 12] sata [16-17] usb [19]) */ {BL_SKU_HSIO_08, {PCIE_BIF_CTRL_x2x2x2x2, PCIE_BIF_CTRL_x2x2x2x2}, {/* ME_FIA_MUX_CONFIG */ {BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE00) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE01) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE02) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE03) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE04) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE05) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE06) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE07) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE08) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE09) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE10) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE11) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE12) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE13) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE14) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE15) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE16) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE17) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE18) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_XHCI, BL_FIA_LANE19)}, /* ME_FIA_SATA_CONFIG */ {BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE04) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE05) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE06) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE07) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE08) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE09) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE10) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE11) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE12) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE13) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE14) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE15) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE16) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE17) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE18) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE19)}, /* ME_FIA_PCIE_ROOT_PORTS_CONFIG */ {BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_7) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_X1, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_7)} } }, /* SKU HSIO 6 (pcie [0-1, 8, 12] sata [16] usb [19]) */ {BL_SKU_HSIO_06, {PCIE_BIF_CTRL_x2x2x2x2, PCIE_BIF_CTRL_x2x2x2x2}, {/* ME_FIA_MUX_CONFIG */ {BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE00) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE01) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE02) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE03) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE04) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE05) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE06) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE07) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE08) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE09) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE10) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE11) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_PCIE, BL_FIA_LANE12) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE13) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE14) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE15) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_SATA, BL_FIA_LANE16) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE17) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_DISCONNECTED, BL_FIA_LANE18) | BL_FIA_LANE_CONFIG(BL_ME_FIA_MUX_LANE_XHCI, BL_FIA_LANE19)}, /* ME_FIA_SATA_CONFIG */ {BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE04) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE05) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE06) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE07) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE08) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE09) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE10) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE11) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE12) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE13) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE14) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE15) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_ASSIGNED, BL_FIA_SATA_LANE16) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE17) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE18) | BL_FIA_SATA_LANE_CONFIG(BL_ME_FIA_SATA_CONTROLLER_LANE_NOT_ASSIGNED, BL_FIA_SATA_LANE19)}, /* ME_FIA_PCIE_ROOT_PORTS_CONFIG */ {BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_ENABLED, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_STATE, BL_ME_FIA_PCIE_ROOT_PORT_DISABLED, BL_FIA_PCIE_ROOT_PORT_7) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_0) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_1) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_2) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_3) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_X1, BL_FIA_PCIE_ROOT_PORT_4) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_5) | BL_FIA_PCIE_ROOT_PORT_CONFIG(BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_X1, BL_FIA_PCIE_ROOT_PORT_6) | BL_FIA_PCIE_ROOT_PORT_CONFIG( BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH, BL_ME_FIA_PCIE_ROOT_PORT_LINK_WIDTH_BICTRL, BL_FIA_PCIE_ROOT_PORT_7)} } } }; #endif #endif /* _MAINBOARD_HSIO_H */
46.2848
72
0.815404
39d7c7ca00c934147d19a4f28b621083105588eb
3,247
java
Java
samples/src/main/java/com/inqbarna/tablefixheaders/samples/HourlyCheckTable.java
PhamTruongHung/Utility_Record
d1287d2085aba5a901b3c268c238e4a1c2fbf340
[ "Apache-2.0" ]
null
null
null
samples/src/main/java/com/inqbarna/tablefixheaders/samples/HourlyCheckTable.java
PhamTruongHung/Utility_Record
d1287d2085aba5a901b3c268c238e4a1c2fbf340
[ "Apache-2.0" ]
null
null
null
samples/src/main/java/com/inqbarna/tablefixheaders/samples/HourlyCheckTable.java
PhamTruongHung/Utility_Record
d1287d2085aba5a901b3c268c238e4a1c2fbf340
[ "Apache-2.0" ]
null
null
null
package com.inqbarna.tablefixheaders.samples; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import com.inqbarna.tablefixheaders.TableFixHeaders; import com.inqbarna.tablefixheaders.samples.adapters.MatrixTableAdapter; import com.inqbarna.tablefixheaders.samples.adapters.hourlyCheckType; import java.util.ArrayList; import static android.content.ContentValues.TAG; public class HourlyCheckTable extends Activity { Database database; ArrayList<hourlyCheckType> hourlyCheckTypeArrayList; hourlyCheckType hourlyCheckTypeTmp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table); // Database duoc tao o mainactivity nhung vao day phai goi lai moi chay duoc database = new Database(this, "data.sqlite", null, 1); //Tao array list boiler de nhan du lieu tu database hourlyCheckTypeArrayList = new ArrayList<>(); Cursor dataFromDatabase = database.GetData("SELECT * FROM hourly_check"); while (dataFromDatabase.moveToNext()){ int id = dataFromDatabase.getInt(0); String dateOfCheck = dataFromDatabase.getString(1); String timeOfCheck = dataFromDatabase.getString(2); String location = dataFromDatabase.getString(3); String personCheck = dataFromDatabase.getString(4); hourlyCheckTypeTmp = new hourlyCheckType(id, dateOfCheck, timeOfCheck, location, personCheck); hourlyCheckTypeArrayList.add(hourlyCheckTypeTmp); Log.d(TAG, "onCreate:id " + id + " dateOfCheck: " + dateOfCheck + " timeOfCheck: " + timeOfCheck + " location: " + location + " personCheck: " + personCheck); } //Lay data tu database de dua vao array list boiler int row = 0; int col_MAX = 5; //So cot (thuoc tinh) cua du lieu duoc luu trong bang String dataIntable[][] = new String[hourlyCheckTypeArrayList.size()][col_MAX]; // Cong them mot de chua cho cho header for (row = 0; row < hourlyCheckTypeArrayList.size(); row++){ if (row == 0){ dataIntable[row][0] = "ID"; dataIntable[row][1] = "Date"; dataIntable[row][2] = "Time"; dataIntable[row][3] = "Location"; dataIntable[row][4] = "Person"; } else { dataIntable[row][0] = String.valueOf(hourlyCheckTypeArrayList.get(row).getId()); dataIntable[row][1] = String.valueOf(hourlyCheckTypeArrayList.get(row).getDateOfCheck()); dataIntable[row][2] = String.valueOf(hourlyCheckTypeArrayList.get(row).getTimeOfCheck()); dataIntable[row][3] = String.valueOf(hourlyCheckTypeArrayList.get(row).getLocation()); dataIntable[row][4] = String.valueOf(hourlyCheckTypeArrayList.get(row).getPersonCheck()); } } TableFixHeaders tableFixHeaders = (TableFixHeaders) findViewById(R.id.table); MatrixTableAdapter<String> matrixTableAdapter = new MatrixTableAdapter<>(this, dataIntable); tableFixHeaders.setAdapter(matrixTableAdapter); } }
42.723684
170
0.670465
c7e2bb3e967f0c86cfdfab243917a5ea1805eb5d
784
py
Python
jaraco/email/smtp.py
jaraco/jaraco.email
0a1b4b05934e0123931671dbfe65d19896550dad
[ "MIT" ]
null
null
null
jaraco/email/smtp.py
jaraco/jaraco.email
0a1b4b05934e0123931671dbfe65d19896550dad
[ "MIT" ]
null
null
null
jaraco/email/smtp.py
jaraco/jaraco.email
0a1b4b05934e0123931671dbfe65d19896550dad
[ "MIT" ]
null
null
null
import smtpd import asyncore import argparse def _get_args(): p = argparse.ArgumentParser() p.add_argument('-p', '--port', type=int, help="Bind to port", default=25) return p.parse_args() class DebuggingServer(smtpd.DebuggingServer): def process_message(self, peer, mailfrom, rcpttos, data): # seriously, why doesn't a debugging server just print everything? print('peer:', peer) print('mailfrom:', mailfrom) print('rcpttos:', rcpttos) smtpd.DebuggingServer.process_message(self, peer, mailfrom, rcpttos, data) def start_simple_server(): "A simple mail server that sends a simple response" args = _get_args() addr = ('', args.port) DebuggingServer(addr, None) asyncore.loop()
29.037037
83
0.656888
1ef029e1ccee778a116e52d4a028aa640eed5ca1
2,767
swift
Swift
BxInputController/Sources/Rows/Date/View/BxInputChildSelectorDateRowBinder.swift
ByteriX/BxInputController
5243afad15d7d3923170b0c6f5cb12179e591434
[ "MIT" ]
5
2018-01-12T10:06:35.000Z
2019-04-11T06:12:57.000Z
BxInputController/Sources/Rows/Date/View/BxInputChildSelectorDateRowBinder.swift
ByteriX/BxInputController
5243afad15d7d3923170b0c6f5cb12179e591434
[ "MIT" ]
2
2018-04-13T12:04:32.000Z
2018-08-29T11:34:03.000Z
BxInputController/Sources/Rows/Date/View/BxInputChildSelectorDateRowBinder.swift
ByteriX/BxInputController
5243afad15d7d3923170b0c6f5cb12179e591434
[ "MIT" ]
1
2017-11-06T00:22:28.000Z
2017-11-06T00:22:28.000Z
/** * @file BxInputChildSelectorDateRowBinder.swift * @namespace BxInputController * * @details Binder for BxInputChildSelectorDateRow subclasses * @date 06.03.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Binder for BxInputChildSelectorDateRow subclasses open class BxInputChildSelectorDateRowBinder<Row: BxInputChildSelectorDateRow, Cell: BxInputChildSelectorDateCell, ParentRow: BxInputSelectorDateRow> : BxInputChildSelectorRowBinder<Row, Cell, ParentRow>, BxInputChildSelectorDateDelegate { /// update cell from model data, in inherited cell need call super! override open func update() { super.update() guard let cell = cell else { return } cell.delegate = self cell.datePicker.minimumDate = parentRow.minimumDate cell.datePicker.maximumDate = parentRow.maximumDate if #available(iOS 13.4, *) { cell.datePicker.preferredDatePickerStyle = .wheels } else { // Fallback on earlier versions } DispatchQueue.main.async { [weak self] () -> Void in self?.updateDate(animated: false) } } open func updateDate(animated: Bool) { guard let cell = cell else { return } if let date = parentRow.value { cell.datePicker.setDate(date, animated: animated) changeDate() } else { cell.datePicker.setDate(parentRow.firstSelectionDate, animated: animated) editedDate() } } /// event of change isEnabled override open func didSetEnabled(_ value: Bool) { super.didSetEnabled(value) guard let cell = cell else { return } cell.datePicker.isEnabled = value cell.datePicker.isUserInteractionEnabled = value // UI part if needChangeDisabledCell { if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler { changeViewEnableHandler(cell.datePicker, isEnabled) } else { cell.datePicker.alpha = value ? 1 : alphaForDisabledView } } else { cell.datePicker.alpha = 1 } } func changeDate() { parentRow.value = cell?.datePicker.date owner?.updateRow(parentRow) } // MARK - BxInputChildSelectorDateDelegate /// editing date from Picker open func editedDate() { changeDate() parentRowBinder.didChangeValue() tryToClose() } }
30.406593
237
0.625949
cb21c9d5d9bc6ddeee344dbe78ad2c26fa3df010
394
go
Go
controllers/places/repository.go
snowtoslow/scameiki-and-places
50091cc4be479a57181b706b0a6bb2b2dd8bad5b
[ "MIT" ]
null
null
null
controllers/places/repository.go
snowtoslow/scameiki-and-places
50091cc4be479a57181b706b0a6bb2b2dd8bad5b
[ "MIT" ]
null
null
null
controllers/places/repository.go
snowtoslow/scameiki-and-places
50091cc4be479a57181b706b0a6bb2b2dd8bad5b
[ "MIT" ]
null
null
null
package places import ( "context" "scameiki-and-places/models" ) type PlaceRepository interface { CreatePlace(ctx context.Context,place *models.Place) error GetPlaces(ctx context.Context) (*models.Places,error) DeletePlace(ctx context.Context, id int) error GetPlaceById(ctx context.Context,id int) (*models.Place,error) UpdatePlace(ctx context.Context,id int) (*models.Place,error) }
26.266667
63
0.77665
1a8c679c49cc24efa2ccc3765632977aa09bfbb1
563
asm
Assembly
oeis/212/A212769.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/212/A212769.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/212/A212769.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A212769: p*q modulo (p+q) with p, q consecutive primes. ; 1,7,11,5,23,11,35,17,43,59,59,35,83,41,91,103,119,119,65,143,143,77,163,77,95,203,101,215,107,191,125,259,275,263,299,299,311,161,331,343,359,347,383,191,395,169,181,221,455,227,463,479,467,499,511,523,539,539,275,563,551,551,305,623,311,599,659,659,695,347,703,347,731,743,377,763,377,395,389,803,839,827,863,863,437,883,437,455,923,461,437,467,485,479,497,1003,479,1043,983,1079 mov $2,$0 add $0,1 seq $0,40 ; The prime numbers. mov $1,$0 seq $2,40 ; The prime numbers. mul $0,$2 add $1,$2 mod $0,$1
46.916667
382
0.698046
3bf68675670395595a60fc8cb658984ce8804d2a
3,117
swift
Swift
WeiboSwift/WeiboSwift/Classes/Home/PopView/PoperAnimatedTransitioning.swift
zhenyiyi/weibo
868b5d0e7162d00cd32e843af15fea11528c1821
[ "MIT" ]
null
null
null
WeiboSwift/WeiboSwift/Classes/Home/PopView/PoperAnimatedTransitioning.swift
zhenyiyi/weibo
868b5d0e7162d00cd32e843af15fea11528c1821
[ "MIT" ]
null
null
null
WeiboSwift/WeiboSwift/Classes/Home/PopView/PoperAnimatedTransitioning.swift
zhenyiyi/weibo
868b5d0e7162d00cd32e843af15fea11528c1821
[ "MIT" ]
null
null
null
// // PoperAnimatedTransitioning.swift // WeiboSwift // // Created by fenglin on 2016/10/8. // Copyright © 2016年 fenglin. All rights reserved. // import UIKit class PoperAnimatedTransitioning: NSObject { var completion : (_ isPresent : Bool)->Void ; var presentedViewFrame = CGRect(x: 0, y: 0, width: 0, height: 0); init(animatedCompletion: @escaping (_ isPresent : Bool)-> Void) { self.completion = animatedCompletion; } } extension PoperAnimatedTransitioning : UIViewControllerTransitioningDelegate{ // 改变自定义View的尺寸 func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController?{ let vc = WBPresentationController(presentedViewController: presented, presenting: presenting); vc.presentedViewFrame = self.presentedViewFrame; return vc; } // 弹出动画 func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self; } // 消息动画 func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{ return self; } } extension PoperAnimatedTransitioning : UIViewControllerAnimatedTransitioning{ func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{ return 0.25; } func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ // UITransitionContextFromViewKey, and UITransitionContextToViewKey // UITransitionContextToViewKey 弹出的view // UITransitionContextFromViewKey 消失的view if let presentedView = transitionContext.view(forKey: UITransitionContextViewKey.to){ // 1. 添加View; transitionContext.containerView.addSubview(presentedView); // 2. 添加动画; presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0); // 设置锚点 presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0); UIView.animate(withDuration:self.transitionDuration(using: transitionContext) , animations: { presentedView.transform = CGAffineTransform.identity; }) { (finished: Bool) in transitionContext.completeTransition(true); self.completion(true); }; }else if let dismissView = transitionContext.view(forKey: UITransitionContextViewKey.from) { UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: { dismissView.transform = CGAffineTransform(scaleX: 1.0, y: 0.00001); }, completion: { (finished) in dismissView.removeFromSuperview(); transitionContext.completeTransition(true); self.completion(false); }) } } }
37.554217
170
0.660571
ad581818b3d64df03e64c4d929386032cabc3381
100
rs
Rust
third_party/rust_crates/vendor/cxx/tests/ui/extern_type_lifetime_bound.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/rust_crates/vendor/cxx/tests/ui/extern_type_lifetime_bound.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
539
2020-01-08T17:28:04.000Z
2022-03-29T20:34:26.000Z
third_party/rust_crates/vendor/cxx/tests/ui/extern_type_lifetime_bound.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
#[cxx::bridge] mod ffi { extern "C++" { type Complex<'a, 'b: 'a>; } } fn main() {}
11.111111
33
0.42
d7e7545c1d69e26d01f421519029fc394a600e0a
13,443
lua
Lua
projekt/main.lua
iCarrrot/Lua
f04d5159db027f8d7b75b9b713d0e8e56ad45ff2
[ "MIT" ]
null
null
null
projekt/main.lua
iCarrrot/Lua
f04d5159db027f8d7b75b9b713d0e8e56ad45ff2
[ "MIT" ]
null
null
null
projekt/main.lua
iCarrrot/Lua
f04d5159db027f8d7b75b9b713d0e8e56ad45ff2
[ "MIT" ]
null
null
null
kolorki = { nr = 4, {241 / 255, 114 / 255, 23 / 255}, {128 / 255, 218 / 255, 54 / 255}, {35 / 255, 116 / 255, 254 / 255}, {217 / 255, 43 / 255, 187 / 255}, {221 / 255, 0 / 255, 17 / 255} } kolorki.red = {221 / 255, 0 / 255, 17 / 255} kolorki.orange = {241 / 255, 114 / 255, 23 / 255} kolorki.yellow = {240 / 255, 210 / 255, 20 / 255} kolorki.green = {128 / 400, 218 / 400, 54 / 400} kolorki.blue = {35 / 255, 116 / 255, 254 / 255} kolorki.purple = {217 / 255, 43 / 255, 187 / 255} kolorki.white = {1.0, 1.0, 1.0} Shot = require "shot" Player = require "player" Enemy = require "enemy" Box = require "box" Bonus = require "bonus" function love.load() newGame(false) end function love.draw() if not help then if gameStarted then love.graphics.setBackgroundColor(1, 1, 1) box:draw() objects.player:draw(kolorki.red) for i = 1, #enemys do enemys[i]:draw() end bonus:draw() for i = 1, #shots do shots[i]:draw() end love.graphics.setColor(kolorki[shotColor]) shotsString = "" .. (currentShotNo - #shots) shotsText = love.graphics.newText(font40, shotsString) shotsText:setf(shotsString, width, "right") love.graphics.draw(shotsText) love.graphics.draw(love.graphics.newText(font40, "" .. score), 0) elseif startTextDeley > 0.5 then love.graphics.setColor(255, 255, 255) startGameText1 = love.graphics.newText(font40, 'Welcome to "Lata i strzela"!') love.graphics.draw( startGameText1, math.floor(width / 2 - startGameText1:getWidth() / 2), math.floor(height / 2 - startGameText1:getHeight() / 2) ) startGameText2 = love.graphics.newText(font20, "Press anykey to start") love.graphics.draw( startGameText2, math.floor(width / 2 - startGameText2:getWidth() / 2), math.floor(height / 2 - startGameText2:getHeight() / 2 + startGameText1:getHeight()) ) legendDraw() else love.graphics.setColor(255, 255, 255) startGameText1 = love.graphics.newText(font40, 'Welcome to "Lata i strzela"!') love.graphics.draw( startGameText1, math.floor(width / 2 - startGameText1:getWidth() / 2), math.floor(height / 2 - startGameText1:getHeight() / 2) ) startGameText2 = love.graphics.newText(font20, "Press anykey to start") legendDraw() end if gameOver then love.graphics.setColor(255, 0, 0) scoreText = love.graphics.newText(font60, "" .. score) love.graphics.draw( scoreText, math.floor(width / 2 - scoreText:getWidth() / 2), math.floor(height / 2 - scoreText:getHeight() / 2) ) gameOverText = love.graphics.newText(font60, "GAME OVER!") love.graphics.draw( gameOverText, math.floor(width / 2 - gameOverText:getWidth() / 2), math.floor(height / 2 - gameOverText:getHeight() / 2 - scoreText:getHeight()) ) end if gameOver and startTextDeley > 0.5 then gameOverText2 = love.graphics.newText(font20, "Press anykey to restart") love.graphics.draw( gameOverText2, math.floor(width / 2 - gameOverText2:getWidth() / 2), math.floor(height / 2 - gameOverText2:getHeight() / 2 + gameOverText:getHeight()) ) end else helpDraw() end end function love.update(dt) width, height = love.graphics.getDimensions() startTextDeley = (startTextDeley + dt > 1 and 0) or startTextDeley + dt if not gameOver and gameStarted and not help then world:update(dt) --this puts the world into motion newBonus = math.random(0, 1000) if not activeBonus and newBonus > 1000 - 2 and not bonus.onScreen then bonus = Bonus(true) end shotDelay = shotDelay + dt / 10 if activeBonus == "tripple shot" then currentShotNo = basicShotNo elseif activeBonus == "infinity ammo" then currentShotNo = math.huge else currentShotNo = basicShotNo end bonus:update(dt) lastColor = (shotColor ~= 5 and shotColor) or lastColor if activeBonus == "red shot" then shotColor = 5 else shotColor = lastColor end if activeBonus == "reversed grav" then world:setGravity(0, -gravity) else world:setGravity(0, gravity) end if world:getGravity() < 0 then objects.player.body:setGravityScale(-1) else objects.player.body:setGravityScale(1) end if love.keyboard.isDown("space") and ((not activeBonus == "tripple shot" and #shots < currentShotNo) or #shots + 3 < currentShotNo) and shotDelay > maxShotDeley then shots[#shots + 1] = Shot(objects.player.body:getX(), objects.player.body:getY() - 5, shotColor, kolorki, "up") if activeBonus == "tripple shot" and #shots + 1 < currentShotNo then shots[#shots + 1] = Shot(objects.player.body:getX(), objects.player.body:getY() - 5, shotColor, kolorki, "right") shots[#shots + 1] = Shot(objects.player.body:getX(), objects.player.body:getY() - 5, shotColor, kolorki, "left") end shotDelay = 0 end objects.player:update() harder = harder + dt * harderInd enemyCounter = enemyCounter + dt + harder if enemyCounter >= 1 then enemys[#enemys + 1] = Enemy(kolorki) if activeBonus ~= "less enemys" then enemys[#enemys + 1] = Enemy(kolorki) end enemyCounter = 0 end local temp2 = {} for i = 1, #enemys do enemys[i]:update(dt, level) if not enemys[i].fixture:isDestroyed() then temp2[#temp2+1]=enemys[i] end end enemys = temp2 local temp = {} for i = 1, #shots do shots[i]:update(dt) if not shots[i].fixture:isDestroyed() then temp[#temp + 1] = shots[i] end end shots = temp else love.graphics.setColor(255, 0, 0) love.graphics.print("GAME OVER!", width / 2 - 50, height / 2 - 50, 0, 5, 5) end end function love.keypressed(key) if key == "escape" then love.event.quit() elseif key == "z" then shotColor = 1 elseif key == "x" then shotColor = 2 elseif key == "c" then shotColor = 3 elseif key == "v" then shotColor = 4 elseif key == "h" then help = true elseif key and not gameStarted then gameStarted = true elseif key and gameOver then newGame(true) elseif key and help then help = false end end function beginContact(f1, f2, contact) local shotF = nil local enemyF = nil local ceilingF = nil local groundF = nil local bonusF = nil local playerF = nil if f1:getUserData() and f2:getUserData() then shotF = (f1:getUserData().typeF == "shot" and f1) or (f2:getUserData().typeF == "shot" and f2) enemyF = (f1:getUserData().typeF == "enemy" and f1) or (f2:getUserData().typeF == "enemy" and f2) ceilingF = (f1:getUserData().typeF == "ceiling" and f1) or (f2:getUserData().typeF == "ceiling" and f2) groundF = (f1:getUserData().typeF == "ground" and f1) or (f2:getUserData().typeF == "ground" and f2) bonusF = (f1:getUserData().typeF == "bonus" and f1) or (f2:getUserData().typeF == "bonus" and f2) playerF = (f1:getUserData().typeF == "player" and f1) or (f2:getUserData().typeF == "player" and f2) if shotF and enemyF then if contact:isTouching() and (shotF:getUserData().color == enemyF:getUserData().color or shotF:getUserData().color == kolorki[5]) then enemyF:getShape():setRadius(enemyF:getShape():getRadius() - 10) score = score + 1 if enemyF:getShape():getRadius() < 10 then enemyF:destroy() score = score + 5 end shotF:destroy() end elseif shotF and ceilingF and contact:isTouching() then shotF:destroy() elseif enemyF and groundF and contact:isTouching() then gameOver = true elseif bonusF and playerF then if contact:isTouching() then local bonusType = bonusF:getUserData().bonusType activeBonus = bonusType bonus:destroy() end end end end function love.resize(w, h) box:resize(w, h) end function newGame(ifStarted) -----------------const--------- level = 5 basicShotNo = 60 currentShotNo = basicShotNo maxShotDeley = 0.003 gravity = 5 harderInd = level / 500000 font60 = love.graphics.newFont("neuropol_x_rg.ttf", 60) font40 = love.graphics.newFont("neuropol_x_rg.ttf", 40) font20 = love.graphics.newFont("neuropol_x_rg.ttf", 20) font15 = love.graphics.newFont("neuropol_x_rg.ttf", 15) math.randomseed(os.time()) love.window.setMode(800, 600, {resizable = true, vsync = true, minwidth = 400, minheight = 300}) love.physics.setMeter(64) --the height of a meter our worlds will be 64px world = love.physics.newWorld(0, gravity, true) world:setCallbacks(beginContact, nil, nil, nil) box = Box() ---------------counters--------- enemyCounter = 0 shotDelay = 0 score = 0 gameStarted = ifStarted gameOver = false startTextDeley = 0 shotColor = 1 lastColor = shotColor activeBonus = nil harder = 0 help = false objects = {} shots = {} enemys = {} bonus = Bonus(false) width, height = love.graphics.getDimensions() x, y = math.floor(width / 2), height - 10 objects.player = Player(x, y, 0.15) end function legendDraw() textHeigh = height / 2 + startGameText1:getHeight() + startGameText2:getHeight() + 100 love.graphics.setColor(kolorki.orange) legendText1 = love.graphics.newText(font20, "z") textHeigh = textHeigh - legendText1:getHeight() / 2 love.graphics.draw(legendText1, math.floor(width / 2 - legendText1:getWidth() * 2.5), math.floor(textHeigh)) love.graphics.setColor(kolorki.green) legendText2 = love.graphics.newText(font20, "x") love.graphics.draw(legendText2, math.floor(width / 2 - legendText2:getWidth()), math.floor(textHeigh)) love.graphics.setColor(kolorki.blue) legendText3 = love.graphics.newText(font20, "c") love.graphics.draw(legendText3, math.floor(width / 2 + legendText3:getWidth()), math.floor(textHeigh)) love.graphics.setColor(kolorki.purple) legendText4 = love.graphics.newText(font20, "v") love.graphics.draw(legendText4, math.floor(width / 2 + legendText4:getWidth() * 2.5), math.floor(textHeigh)) love.graphics.setColor(255, 255, 255) legendText5 = love.graphics.newText(font20, "space to shot") textHeigh = textHeigh + legendText1:getHeight() * 1.5 - legendText5:getHeight() / 2 love.graphics.draw(legendText5, math.floor(width / 2 - legendText5:getWidth() / 2), math.floor(textHeigh)) legendText6 = love.graphics.newText(font20, "press h for help") textHeigh = textHeigh + legendText5:getHeight() *1.5 - legendText6:getHeight() / 2 + 20 love.graphics.draw(legendText6, math.floor(width / 2 - legendText6:getWidth() / 2), math.floor(textHeigh)) end function helpDraw() textHeigh = 400 love.graphics.setBackgroundColor({0,0,0}) love.graphics.setColor(kolorki.white) helpText1 = love.graphics.newText(font40, "Pomoc") helpText2 = love.graphics.newText(font15, "") helpText2:addf("\n\n\nTwoim zadaniem jest zestrzelenie jak największej liczby przeciwników.\n\n".. "Przeciwnika możesz zestrzelić tylko jego własnym kolorem.\n\n".. "Wybierz z, x, c, v aby wybrać odpowiednio kolor: pomarańczowy, zielony, niebieski i fioletowy.\n\n".. "Naciśnij spację, aby strzelić", 700, "left") helpText3 = love.graphics.newText(font40, "Bonusy") helpText4 = love.graphics.newText(font15, "") helpText4:addf("\n\n\ntripple shot - potrójny strzał".. "\n\ninfinity ammo - nieskończona amunicja".. "\n\nred shot - strzał czerwony, zabija wszystkich przeciwników".. "\n\nreversed grav - odwrócona grawitacja".. "\n\nless enemys - pojawia się dwa razy mniej przeciwników", 700, "left") helpText5 = love.graphics.newText(font20, "Naciśnij dowolny klawisz aby wrócić do gry") love.graphics.draw(helpText1,30,30) love.graphics.draw(helpText2,30,30) love.graphics.draw(helpText3,30,260) love.graphics.draw(helpText4,30,260) love.graphics.draw(helpText5,30,550) love.graphics.setColor(kolorki.green) end
37.033058
120
0.588262
ae7f9d11f2b42be1e2164b4b3ace228ab17c2b08
401
kt
Kotlin
app/src/main/java/code_setup/app_models/events_/RIDESTATUS.kt
himalayanDev/HPDT-Taxi
5c318e92bf68e39ea6b4310f2a84b601f0e4199d
[ "Apache-2.0" ]
1
2022-03-23T07:02:27.000Z
2022-03-23T07:02:27.000Z
app/src/main/java/code_setup/app_models/events_/RIDESTATUS.kt
himalayanDev/Template
5c318e92bf68e39ea6b4310f2a84b601f0e4199d
[ "Apache-2.0" ]
null
null
null
app/src/main/java/code_setup/app_models/events_/RIDESTATUS.kt
himalayanDev/Template
5c318e92bf68e39ea6b4310f2a84b601f0e4199d
[ "Apache-2.0" ]
null
null
null
package code_setup.app_models.other_.event class RIDESTATUS { companion object { val RIDESTATUS_ACCEPTED: String = "ACCEPTED" val RIDESTATUS_IN_PROGRESS: String = "INPROGRESS" val TRIP_DESTINATIONS: Int = 101 val REQUEST_NEW_TOUR_JOB: Int = 102 val REQUEST_START_MOVING_VIEW: Int = 103 val REQUEST_TOUR_DESTINATIONS_VIEW: Int = 104 } }
19.095238
57
0.680798
041663160a9bf9d1946bced13b60a553ec5d41ea
413
swift
Swift
LBFM-Swift/Controller/Home(首页)/广播/View/组头尾视图/LBFMRadioFooterView.swift
FighterLightning/LBXMLYFM-Swift
ace2bf906a4f52e5ce69d24d23483625038c5b53
[ "Apache-2.0" ]
2
2019-10-11T07:15:49.000Z
2020-02-10T14:57:52.000Z
LBFM-Swift/Controller/Home(首页)/广播/View/组头尾视图/LBFMRadioFooterView.swift
mohsinalimat/LBXMLYFM-Swift
ace2bf906a4f52e5ce69d24d23483625038c5b53
[ "Apache-2.0" ]
null
null
null
LBFM-Swift/Controller/Home(首页)/广播/View/组头尾视图/LBFMRadioFooterView.swift
mohsinalimat/LBXMLYFM-Swift
ace2bf906a4f52e5ce69d24d23483625038c5b53
[ "Apache-2.0" ]
null
null
null
// // LBFMRadioFooterView.swift // LBFM-Swift // // Created by liubo on 2019/2/27. // Copyright © 2019 刘博. All rights reserved. // import UIKit class LBFMRadioFooterView: UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = LBFMDownColor } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
19.666667
53
0.656174
daa846e102571f9f0c4e1a3ed32eb60a47107077
1,089
lua
Lua
scripts/globals/abilities/pets/somnolence.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
6
2021-06-01T04:17:10.000Z
2021-06-01T04:32:21.000Z
scripts/globals/abilities/pets/somnolence.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
5
2020-04-10T19:33:53.000Z
2021-06-27T17:50:05.000Z
scripts/globals/abilities/pets/somnolence.lua
PaulAnthonyReitz/topaz
ffa3a785f86ffdb2f6a5baf9895b649e3e3de006
[ "FTL" ]
2
2020-04-11T16:56:14.000Z
2021-06-26T12:21:12.000Z
--------------------------------------------------- -- Somnolence --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/magic") --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0 end function onPetAbility(target, pet, skill) local dmg = 10 + pet:getMainLvl() * 2 local resist = applyPlayerResistance(pet,-1,target, 0, tpz.skill.ELEMENTAL_MAGIC, tpz.magic.ele.DARK) local duration = 120 dmg = dmg*resist dmg = mobAddBonuses(pet,spell,target,dmg, tpz.magic.ele.DARK) dmg = finalMagicAdjustments(pet,target,spell,dmg) if (resist < 0.15) then --the gravity effect from this ability is more likely to land than Tail Whip resist = 0 end duration = duration * resist if (duration > 0 and target:hasStatusEffect(tpz.effect.WEIGHT) == false) then target:addStatusEffect(tpz.effect.WEIGHT, 50, 0, duration) end return dmg end
30.25
105
0.609734
4a390284d85470a4be9c89be1a7e539a5248c777
2,069
js
JavaScript
js/cultsboons.js
slowglass/TheGiddyLimit.github.io
9ef74db99dad7c25c42002045ac961aaf44a8570
[ "MIT" ]
null
null
null
js/cultsboons.js
slowglass/TheGiddyLimit.github.io
9ef74db99dad7c25c42002045ac961aaf44a8570
[ "MIT" ]
null
null
null
js/cultsboons.js
slowglass/TheGiddyLimit.github.io
9ef74db99dad7c25c42002045ac961aaf44a8570
[ "MIT" ]
null
null
null
"use strict";function cultBoonTypeToFull(a){return"cult"===a?"Cult":"Demonic Boon"}class CultsBoonsPage extends ListPage{constructor(){const a=getSourceFilter(),b=new Filter({header:"Type",items:["boon","cult"],displayFn:cultBoonTypeToFull});super({dataSource:"data/cultsboons.json",filters:[a,b],filterSource:a,listValueNames:["name","source","type","uniqueid"],listClass:"cultsboons",sublistValueNames:["type","name","source","id"],sublistClass:"subcultsboons",dataProps:["cult","boon"]}),this._sourceFilter=a}getListItem(a,b){return this._sourceFilter.addItem(a.source),` <li class="row" ${FLTR_ID}="${b}" onclick="ListUtil.toggleSelected(event, this)" oncontextmenu="ListUtil.openContextMenu(event, this)"> <a id="${b}" href="#${UrlUtil.autoEncodeHash(a)}" title="${a.name}"> <span class="type col-3 text-center pl-0">${cultBoonTypeToFull(a.__prop)}</span> <span class="name col-7">${a.name}</span> <span class="source col-2 text-center ${Parser.sourceJsonToColor(a.source)} pr-0" title="${Parser.sourceJsonToFull(a.source)}" ${BrewUtil.sourceJsonToStyle(a.source)}>${Parser.sourceJsonToAbv(a.source)}</span> <span class="uniqueid hidden">${a.uniqueId?a.uniqueId:b}</span> </a> </li>`}handleFilterChange(){const a=this._filterBox.getValues();this._list.filter(b=>{const c=this._dataList[$(b.elm).attr(FLTR_ID)];return this._filterBox.toDisplay(a,c.source,c.__prop)}),FilterBox.selectFirstVisible(this._dataList)}getSublistItem(a,b){return` <li class="row" ${FLTR_ID}="${b}" oncontextmenu="ListUtil.openSubContextMenu(event, this)"> <a href="#${UrlUtil.autoEncodeHash(a)}" title="${a.name}"> <span class="name col-12 px-0">${a.name}</span> <span class="id hidden">${b}</span> </a> </li> `}doLoadHash(a){const b=this._dataList[a];$("#pagecontent").empty().append(RenderCultsBoons.$getRenderedCultBoon(b)),ListUtil.updateSelected()}doLoadSubHash(a){a=this._filterBox.setFromSubHashes(a),ListUtil.setFromSubHashes(a)}}const cultsBoonsPage=new CultsBoonsPage;window.addEventListener("load",()=>cultsBoonsPage.pOnLoad());
121.705882
574
0.725955
d9a366575ddd39568c914e9bfc2c86abdf242e51
248
rs
Rust
src/bin/tuples.rs
Kreyren/Fe203
149963cb60e6687de37c66299ba72640cff91f33
[ "MIT" ]
null
null
null
src/bin/tuples.rs
Kreyren/Fe203
149963cb60e6687de37c66299ba72640cff91f33
[ "MIT" ]
null
null
null
src/bin/tuples.rs
Kreyren/Fe203
149963cb60e6687de37c66299ba72640cff91f33
[ "MIT" ]
null
null
null
fn main() { let tupl = (69, "test", 69.69, false, (1, 2, 5)); println!("{}", tupl.1); println!("{}", (tupl.4).1); let tupl2 = (69, "test", 69.69); let (a, b, c) = tupl2; println!("A is {}", a); println!("B is {}", b); }
24.8
53
0.431452
f8bc7e9674a5e627cff74b3f9ba20bfd29a9eb84
373
kt
Kotlin
app/src/main/java/com/fredrikbogg/notesapp/ui/main/MainFoldersBindings.kt
dgewe/Notes-App-Android
cb0eecece6487441e37b4f9174d60481ef140efe
[ "MIT" ]
5
2021-05-03T14:25:42.000Z
2022-03-15T00:03:16.000Z
app/src/main/java/com/fredrikbogg/notesapp/ui/main/MainFoldersBindings.kt
dgewe/Notes-App-Android
cb0eecece6487441e37b4f9174d60481ef140efe
[ "MIT" ]
null
null
null
app/src/main/java/com/fredrikbogg/notesapp/ui/main/MainFoldersBindings.kt
dgewe/Notes-App-Android
cb0eecece6487441e37b4f9174d60481ef140efe
[ "MIT" ]
2
2020-10-02T20:43:20.000Z
2022-03-04T17:25:17.000Z
package com.fredrikbogg.notesapp.ui.main import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.fredrikbogg.notesapp.data.db.entity.Folder @BindingAdapter("folder_items") fun bindSetFolderItems(listView: RecyclerView, items: List<Folder>?) { items?.let { (listView.adapter as MainFoldersAdapter).submitList(items) } }
31.083333
77
0.815013
b2d981ecabea84bee53271f8bc9c6bdef3c97cef
3,533
py
Python
supervised/preprocessing/datetime_transformer.py
sourcery-ai-bot/mljar-supervised
f60f4ac65516ac759e4b84a198205480a56ada64
[ "MIT" ]
null
null
null
supervised/preprocessing/datetime_transformer.py
sourcery-ai-bot/mljar-supervised
f60f4ac65516ac759e4b84a198205480a56ada64
[ "MIT" ]
null
null
null
supervised/preprocessing/datetime_transformer.py
sourcery-ai-bot/mljar-supervised
f60f4ac65516ac759e4b84a198205480a56ada64
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd import datetime import json class DateTimeTransformer(object): def __init__(self): self._new_columns = [] self._old_column = None self._min_datetime = None self._transforms = [] def fit(self, X, column): self._old_column = column self._min_datetime = np.min(X[column]) values = X[column].dt.year if len(np.unique(values)) > 1: self._transforms += ["year"] new_column = column + "_Year" self._new_columns += [new_column] values = X[column].dt.month if len(np.unique(values)) > 1: self._transforms += ["month"] new_column = column + "_Month" self._new_columns += [new_column] values = X[column].dt.day if len(np.unique(values)) > 1: self._transforms += ["day"] new_column = column + "_Day" self._new_columns += [new_column] values = X[column].dt.weekday if len(np.unique(values)) > 1: self._transforms += ["weekday"] new_column = column + "_WeekDay" self._new_columns += [new_column] values = X[column].dt.dayofyear if len(np.unique(values)) > 1: self._transforms += ["dayofyear"] new_column = column + "_DayOfYear" self._new_columns += [new_column] values = X[column].dt.hour if len(np.unique(values)) > 1: self._transforms += ["hour"] new_column = column + "_Hour" self._new_columns += [new_column] values = (X[column] - self._min_datetime).dt.days if len(np.unique(values)) > 1: self._transforms += ["days_diff"] new_column = column + "_Days_Diff_To_Min" self._new_columns += [new_column] def transform(self, X): column = self._old_column if "year" in self._transforms: new_column = column + "_Year" X[new_column] = X[column].dt.year if "month" in self._transforms: new_column = column + "_Month" X[new_column] = X[column].dt.month if "day" in self._transforms: new_column = column + "_Day" X[new_column] = X[column].dt.day if "weekday" in self._transforms: new_column = column + "_WeekDay" X[new_column] = X[column].dt.weekday if "dayofyear" in self._transforms: new_column = column + "_DayOfYear" X[new_column] = X[column].dt.dayofyear if "hour" in self._transforms: new_column = column + "_Hour" X[new_column] = X[column].dt.hour if "days_diff" in self._transforms: new_column = column + "_Days_Diff_To_Min" X[new_column] = (X[column] - self._min_datetime).dt.days X.drop(column, axis=1, inplace=True) return X def to_json(self): return { "new_columns": list(self._new_columns), "old_column": self._old_column, "min_datetime": str(self._min_datetime), "transforms": list(self._transforms), } def from_json(self, data_json): self._new_columns = data_json.get("new_columns", None) self._old_column = data_json.get("old_column", None) d = data_json.get("min_datetime", None) self._min_datetime = None if d is None else pd.to_datetime(d) self._transforms = data_json.get("transforms", [])
32.712963
69
0.565242
b3895b0ea50d2a49d871ffbe5084562af9d0197e
20,683
rb
Ruby
spec/api/projects_spec.rb
Orasi/DevOpsTraining-Seed
e5d4404171bc135113a09d9d7eb25e0745f49d28
[ "BSD-4-Clause" ]
null
null
null
spec/api/projects_spec.rb
Orasi/DevOpsTraining-Seed
e5d4404171bc135113a09d9d7eb25e0745f49d28
[ "BSD-4-Clause" ]
null
null
null
spec/api/projects_spec.rb
Orasi/DevOpsTraining-Seed
e5d4404171bc135113a09d9d7eb25e0745f49d28
[ "BSD-4-Clause" ]
null
null
null
require "spec_helper" describe "PROJECTS API::" , :type => :api do let (:team) {FactoryGirl.create(:team)} let (:user) {team.users.first} let (:project) { team.projects.first } let (:admin) {FactoryGirl.create(:user, :admin)} describe 'list all projects' do context 'as a non-admin' do before do FactoryGirl.create(:project) FactoryGirl.create(:team, users_count: 0).users << user header 'User-Token', user.user_tokens.first.token get "/projects" end it 'responds successfully' do expect(last_response.status).to eq 200 end it 'should return all users projects' do expect(json).to include('projects') expect(json['projects'].count).to eq user.projects.count end it 'does not return all projects' do expect(json).to include('projects') expect(json['projects'].count).to_not eq Project.count end it 'does get project from multiple teams' do expect(json).to include('projects') expect(json['projects'].count).to be > team.projects.count end end context 'as an admin' do before do 5.times do FactoryGirl.create(:project) end header 'User-Token', admin.user_tokens.first.token get "/projects" end it 'responds successfully', :show_in_doc do expect(last_response.status).to eq 200 end it 'should return all projects' do expect(json).to include('projects') expect(json['projects'].count).to eq Project.count end end context 'without user token' do before do header 'User-Token', nil get "/projects" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects" end it_behaves_like 'an unauthenticated request' end end describe 'get project details' do context 'with invalid project id' do before do header 'User-Token', user.user_tokens.first.token get "/projects/-1" end it_behaves_like 'a not found request' end context 'as an admin' do before do other_project = FactoryGirl.create(:project) header 'User-Token', admin.user_tokens.first.token get "/projects/#{other_project.id}" end it 'responds succesfully', :show_in_doc do expect(last_response.status).to eq 200 expect(json).to include('project') end it 'should have executions, testcases, and environments' do expect(json).to include('project') expect(json['project']).to include('executions') expect(json['project']).to include('testcases') expect(json['project']).to include('environments') end it 'should access any project regardless of team' do expect(last_response.status).to eq 200 end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token end it 'should be able to access project viewable by user' do get "/projects/#{project.id}" expect(last_response.status).to eq 200 expect(json).to include('project') expect(json['project']).to include('executions') expect(json['project']).to include('testcases') expect(json['project']).to include('environments') end it 'should not be able to access project not viewable by user' do other_project = FactoryGirl.create(:project) get "/projects/#{other_project.id}" expect(last_response.status).to eq 403 expect(json).to include('error') end end context 'without user token' do before do header 'User-Token', nil get "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end end describe 'create new project' do context 'as an admin' do before do header 'User-Token', admin.user_tokens.first.token end it 'responds successfully', :show_in_doc do post "/projects", {project: FactoryGirl.attributes_for(:project)}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(last_response.status).to eq 200 expect(json).to include 'project' end it 'should create project' do expect { post "/projects", {project: FactoryGirl.attributes_for(:project)}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } } .to change { Project.count }.by(1) end context 'without' do context 'name' do it 'should fail' do post "/projects", {project: FactoryGirl.attributes_for(:project, name: nil)}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(last_response.status).to eq 400 expect(json).to include('error') end end end end context 'with duplicate name' do it 'should return an error' do header 'User-Token', admin.user_tokens.first.token post "/projects", {project: {name: project.name}}.to_json , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(last_response.status).to eq 400 expect(json).to include 'error' end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token post "/projects", FactoryGirl.attributes_for(:project).to_json , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'a forbidden request' end context 'without user token' do before do header 'User-Token', nil post "/projects", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token post "/projects", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' post "/projects", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end end describe 'update existing project' do context 'as an admin' do before do header 'User-Token', admin.user_tokens.first.token end it 'responds successfully', :show_in_doc do put "/projects/#{project.id}", {project: {name: 'Some New Name'}}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(last_response.status).to eq 200 expect(json).to include 'project' end it 'should update attributes' do project = FactoryGirl.create(:project) put "/projects/#{project.id}", {project: {name: 'New Name'}}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(json['project']).to include 'project_name' expect(json['project']['project_name']).to eq ('New Name') expect(Project.last.name).to eq ('New Name') end end context 'with invalid project id' do before do header 'User-Token', admin.user_tokens.first.token put "/projects/-1", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'a not found request' end context 'with duplicate name' do it 'should return an error' do name = FactoryGirl.create(:project).name header 'User-Token', admin.user_tokens.first.token post "/projects", {project: {name: name}}.to_json , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } expect(last_response.status).to eq 400 expect(json).to include 'error' end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token put "/projects/#{project.id}", {project: {name: 'A New Name'}}.to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'a forbidden request' end context 'without user token' do before do header 'User-Token', nil put "/projects/#{project.id}", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token put "/projects/#{project.id}", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' put "/projects/#{project.id}", FactoryGirl.attributes_for(:project).to_json, { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' } end it_behaves_like 'an unauthenticated request' end end describe 'delete existing project' do context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token delete "/projects/#{project.id}" end it_behaves_like 'a forbidden request' end context 'with invalid id' do before do header 'User-Token', admin.user_tokens.first.token delete "/projects/-1" end it_behaves_like 'a not found request' end context 'as an admin' do before do header 'User-Token', admin.user_tokens.first.token delete "/projects/#{project.id}" end it 'responds succesfully' do expect(last_response.status).to eq 200 end it 'returns user details', :show_in_doc do expect(json).to include('project') end end context 'without user token' do before do header 'User-Token', nil delete "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token delete "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' delete "/projects/#{project.id}" end it_behaves_like 'an unauthenticated request' end end describe 'get all environment' do context 'with invalid project id' do before do header 'User-Token', user.user_tokens.first.token get "/projects/-1/environments" end it_behaves_like 'a not found request' end context 'as an admin' do before do other_project = FactoryGirl.create(:project) header 'User-Token', admin.user_tokens.first.token get "/projects/#{other_project.id}/environments" end it 'responds succesfully', :show_in_doc do expect(last_response.status).to eq 200 expect(json).to include('environments') end it 'should access any project regardless of team' do expect(last_response.status).to eq 200 end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token end it 'should be able to access project viewable by user' do get "/projects/#{project.id}/environments" expect(last_response.status).to eq 200 expect(json).to include('environments') end it 'should not be able to access project not viewable by user' do other_project = FactoryGirl.create(:project) get "/projects/#{other_project.id}/environments" expect(last_response.status).to eq 403 expect(json).to include('error') end end context 'without user token' do before do header 'User-Token', nil get "/projects/#{project.id}/environments" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects/#{project.id}/environments" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects/#{project.id}/environments" end it_behaves_like 'an unauthenticated request' end end describe 'get all executions' do context 'with invalid project id' do before do header 'User-Token', user.user_tokens.first.token get "/projects/-1/executions" end it_behaves_like 'a not found request' end context 'as an admin' do before do other_project = FactoryGirl.create(:project) header 'User-Token', admin.user_tokens.first.token get "/projects/#{other_project.id}/executions" end it 'responds succesfully', :show_in_doc do expect(last_response.status).to eq 200 expect(json).to include('executions') end it 'should access any project regardless of team' do expect(last_response.status).to eq 200 end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token end it 'should be able to access project viewable by user' do get "/projects/#{project.id}/executions" expect(last_response.status).to eq 200 expect(json).to include('executions') end it 'should not be able to access project not viewable by user' do other_project = FactoryGirl.create(:project) get "/projects/#{other_project.id}/executions" expect(last_response.status).to eq 403 expect(json).to include('error') end end context 'without user token' do before do header 'User-Token', nil get "/projects/#{project.id}/executions" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects/#{project.id}/executions" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects/#{project.id}/executions" end it_behaves_like 'an unauthenticated request' end end describe 'get all testcases' do context 'with invalid project id' do before do header 'User-Token', user.user_tokens.first.token get "/projects/-1/testcases" end it_behaves_like 'a not found request' end context 'as an admin' do before do other_project = FactoryGirl.create(:project) header 'User-Token', admin.user_tokens.first.token get "/projects/#{other_project.id}/testcases" end it 'responds succesfully', :show_in_doc do expect(last_response.status).to eq 200 expect(json).to include('testcases') end it 'should access any project regardless of team' do expect(last_response.status).to eq 200 end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token end it 'should be able to access project viewable by user' do get "/projects/#{project.id}/testcases" expect(last_response.status).to eq 200 expect(json).to include('testcases') end it 'should not be able to access project not viewable by user' do other_project = FactoryGirl.create(:project) get "/projects/#{other_project.id}/testcases" expect(last_response.status).to eq 403 expect(json).to include('error') end end context 'without user token' do before do header 'User-Token', nil get "/projects/#{project.id}/testcases" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects/#{project.id}/testcases" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects/#{project.id}/testcases" end it_behaves_like 'an unauthenticated request' end end describe 'get all keywords' do context 'with invalid project id' do before do header 'User-Token', user.user_tokens.first.token get "/projects/-1/keywords" end it_behaves_like 'a not found request' end context 'as an admin' do before do other_project = FactoryGirl.create(:project) header 'User-Token', admin.user_tokens.first.token get "/projects/#{other_project.id}/keywords" end it 'responds succesfully', :show_in_doc do expect(last_response.status).to eq 200 expect(json).to include('keywords') end it 'should access any project regardless of team' do expect(last_response.status).to eq 200 end end context 'as a non-admin' do before do header 'User-Token', user.user_tokens.first.token end it 'should be able to access project viewable by user' do get "/projects/#{project.id}/keywords" expect(last_response.status).to eq 200 expect(json).to include('keywords') end it 'should not be able to access project not viewable by user' do other_project = FactoryGirl.create(:project) get "/projects/#{other_project.id}/keywords" expect(last_response.status).to eq 403 expect(json).to include('error') end end context 'without user token' do before do header 'User-Token', nil get "/projects/#{project.id}/keywords" end it_behaves_like 'an unauthenticated request' end context 'with expired user token' do before do admin.user_tokens.first.update(expires: DateTime.now - 1.day) header 'User-Token', admin.user_tokens.first.token get "/projects/#{project.id}/keywords" end it_behaves_like 'an unauthenticated request' end context 'with invalid user token' do before do header 'User-Token', 'asdfasdfasdfasdf' get "/projects/#{project.id}/keywords" end it_behaves_like 'an unauthenticated request' end end end
27.577333
170
0.633032
5c1d4a16c45ad7b6244bdd3c21182d6f41f86c9b
38
asm
Assembly
asminator/Debug/rawdatatest.asm
mgohde/MiniMicroII
28351912580956551041fe00ebcbd320562a617e
[ "BSD-2-Clause" ]
null
null
null
asminator/Debug/rawdatatest.asm
mgohde/MiniMicroII
28351912580956551041fe00ebcbd320562a617e
[ "BSD-2-Clause" ]
null
null
null
asminator/Debug/rawdatatest.asm
mgohde/MiniMicroII
28351912580956551041fe00ebcbd320562a617e
[ "BSD-2-Clause" ]
null
null
null
>lbl1 . 1,2 >lbl2 nop #lbl1 nop #lbl2
6.333333
9
0.631579
77449e0d9658e6a22ecad01301a1e96be7ba5f9a
10,891
html
HTML
docs/diff_match_SandwichMatcher.js.html
Toemmsche/process-tree-diff
9e10e547eb70ca2a1aa4434c97c64e8ea866f73a
[ "Apache-2.0" ]
null
null
null
docs/diff_match_SandwichMatcher.js.html
Toemmsche/process-tree-diff
9e10e547eb70ca2a1aa4434c97c64e8ea866f73a
[ "Apache-2.0" ]
null
null
null
docs/diff_match_SandwichMatcher.js.html
Toemmsche/process-tree-diff
9e10e547eb70ca2a1aa4434c97c64e8ea866f73a
[ "Apache-2.0" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: diff/match/SandwichMatcher.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: diff/match/SandwichMatcher.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>import {DiffConfig} from '../../config/DiffConfig.js'; /** * A matching module that reconsiders unmatched nodes for a match * if certain conditions are met. * @implements {MatcherInterface} */ export class SandwichMatcher { /** * Extend the matching with matches that can be inferred from the matching * of surrounding nodes, e.g., if a node is vertically or horizontally * sandwiched between matches. To detect fuzzy matches, the comparison * threshold is raised for this matching module only. * @param {Node} oldTree The root of the old (original) process tree * @param {Node} newTree The root of the new (changed) process tree * @param {Matching} matching The existing matching to be extended * @param {Comparator} comparator The comparator used for comparisons. */ match(oldTree, newTree, matching, comparator) { const newInners = newTree .nonPropertyNodes() .filter((node) => !matching.isMatched(node)); for (const newNode of newInners) { const parentMatch = matching.getMatch(newNode.parent); let minCV = 1; let minCVNode = null; newNode.children.forEach((node) => { if (matching.isMatched(node)) { const match = matching.getMatch(node); if (match.parent.label === newNode.label &amp;&amp; !matching.isMatched(match.parent) &amp;&amp; match.parent.parent === parentMatch) { const CV = comparator.compare(newNode, match.parent); if (CV &lt; minCV) { minCVNode = match.parent; minCV = CV; } } } }); // Vertical sandwich has priority. if (minCVNode != null) { matching.matchNew(newNode, minCVNode); } else { const leftSibling = newNode.getLeftSibling(); const rightSibling = newNode.getRightSibling(); // Left or right sibling must either not exist, or be matched if ((leftSibling != null &amp;&amp; !matching.isMatched(leftSibling)) || (rightSibling != null &amp;&amp; !matching.isMatched(rightSibling))) { continue; } const rightSiblingMatch = matching.getMatch(rightSibling); const leftSiblingMatch = matching.getMatch(leftSibling); let potentialMatch; // Case 1: Node has both a right and a left sibling if (leftSibling != null &amp;&amp; rightSibling != null) { if (rightSiblingMatch.getLeftSibling() == null || rightSiblingMatch.getLeftSibling() !== leftSiblingMatch.getRightSibling()) { continue; } potentialMatch = rightSiblingMatch.getLeftSibling(); // Case 2: Node has a left, but no right sibling } else if (rightSibling == null &amp;&amp; leftSibling != null) { if (leftSiblingMatch.getRightSibling() == null) { continue; } potentialMatch = leftSiblingMatch.getRightSibling(); // Potential match cannot have a right sibling if (potentialMatch.getRightSibling() != null) { continue; } // Case 3: Node has a right, but no left sibling } else if (rightSibling != null &amp;&amp; leftSibling == null) { if (rightSiblingMatch.getLeftSibling() == null) { continue; } potentialMatch = rightSiblingMatch.getLeftSibling(); // Potential match cannot have a left sibling if (potentialMatch.getLeftSibling() != null) { continue; } // Case 4: Node has neither a left nor a right sibling, but the parent // is matched } else if (matching.isMatched(newNode.parent)) { const parentMatch = matching.getMatch(newNode.parent); if (parentMatch.degree() === 1) { potentialMatch = parentMatch.getChild(0); } else { continue; } } else { continue; } // Potential match must be unmatched and have the same label if (potentialMatch.label === newNode.label &amp;&amp; !matching.isMatched(potentialMatch) &amp;&amp; (!(newNode.isCall() || newNode.isScript()) || comparator.compareContent(newNode, potentialMatch) &lt;= DiffConfig.RELAXED_THRESHOLD)) { matching.matchNew(newNode, potentialMatch); } } } } } </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="AbstractActual.html">AbstractActual</a></li><li><a href="AbstractAdapter.html">AbstractAdapter</a></li><li><a href="AbstractEvaluation.html">AbstractEvaluation</a></li><li><a href="AbstractExpected.html">AbstractExpected</a></li><li><a href="AbstractTestCase.html">AbstractTestCase</a></li><li><a href="AbstractTestResult.html">AbstractTestResult</a></li><li><a href="ActualDiff.html">ActualDiff</a></li><li><a href="ActualMatching.html">ActualMatching</a></li><li><a href="ActualMerge.html">ActualMerge</a></li><li><a href="AggregateMatchResult.html">AggregateMatchResult</a></li><li><a href="AggregateMergeResult_AggregateMergeResult.html">AggregateMergeResult</a></li><li><a href="AverageDiffResult.html">AverageDiffResult</a></li><li><a href="AverageGenMatchResult.html">AverageGenMatchResult</a></li><li><a href="CallProperties.html">CallProperties</a></li><li><a href="CallPropertyExtractor.html">CallPropertyExtractor</a></li><li><a href="ChangeParameters.html">ChangeParameters</a></li><li><a href="Comparator.html">Comparator</a></li><li><a href="Confidence.html">Confidence</a></li><li><a href="CpeeDiff.html">CpeeDiff</a></li><li><a href="CpeeDiffAdapter.html">CpeeDiffAdapter</a></li><li><a href="CpeeDiffLocalAdapter.html">CpeeDiffLocalAdapter</a></li><li><a href="CpeeMatchAdapter.html">CpeeMatchAdapter</a></li><li><a href="CpeeMerge.html">CpeeMerge</a></li><li><a href="CpeeMergeAdapter.html">CpeeMergeAdapter</a></li><li><a href="DeltaNode.html">DeltaNode</a></li><li><a href="DeltaTreeGenerator.html">DeltaTreeGenerator</a></li><li><a href="DiffAdapter.html">DiffAdapter</a></li><li><a href="DiffEvaluation.html">DiffEvaluation</a></li><li><a href="DiffTestCase.html">DiffTestCase</a></li><li><a href="DiffTestResult.html">DiffTestResult</a></li><li><a href="DiffXmlAdapter.html">DiffXmlAdapter</a></li><li><a href="DomHelper.html">DomHelper</a></li><li><a href="EditOperation.html">EditOperation</a></li><li><a href="EditScript.html">EditScript</a></li><li><a href="EditScriptGenerator.html">EditScriptGenerator</a></li><li><a href="ElementSizeExtractor.html">ElementSizeExtractor</a></li><li><a href="ExpectedDiff.html">ExpectedDiff</a></li><li><a href="ExpectedGenMatching.html">ExpectedGenMatching</a></li><li><a href="ExpectedMatching.html">ExpectedMatching</a></li><li><a href="ExpectedMerge.html">ExpectedMerge</a></li><li><a href="FixedMatcher.html">FixedMatcher</a></li><li><a href="GeneratedDiffEvaluation.html">GeneratedDiffEvaluation</a></li><li><a href="GeneratedMatchingEvaluation.html">GeneratedMatchingEvaluation</a></li><li><a href="GeneratorParameters.html">GeneratorParameters</a></li><li><a href="GenMatchTestCase.html">GenMatchTestCase</a></li><li><a href="GenMatchTestResult.html">GenMatchTestResult</a></li><li><a href="HashExtractor.html">HashExtractor</a></li><li><a href="HashMatcher.html">HashMatcher</a></li><li><a href="IdExtractor.html">IdExtractor</a></li><li><a href="LeafSetExtractor.html">LeafSetExtractor</a></li><li><a href="Logger.html">Logger</a></li><li><a href="LogMessage.html">LogMessage</a></li><li><a href="MatchAdapter.html">MatchAdapter</a></li><li><a href="Matching.html">Matching</a></li><li><a href="MatchingEvaluation.html">MatchingEvaluation</a></li><li><a href="MatchPipeline.html">MatchPipeline</a></li><li><a href="MatchTestCase.html">MatchTestCase</a></li><li><a href="MatchTestResult.html">MatchTestResult</a></li><li><a href="MergeAdapter.html">MergeAdapter</a></li><li><a href="MergeEvaluation.html">MergeEvaluation</a></li><li><a href="MergeNode.html">MergeNode</a></li><li><a href="MergeTestCase.html">MergeTestCase</a></li><li><a href="MergeTestResult.html">MergeTestResult</a></li><li><a href="Node.html">Node</a></li><li><a href="Patcher.html">Patcher</a></li><li><a href="PathMatcher.html">PathMatcher</a></li><li><a href="Preprocessor.html">Preprocessor</a></li><li><a href="PropertyMatcher.html">PropertyMatcher</a></li><li><a href="SandwichMatcher.html">SandwichMatcher</a></li><li><a href="SimilarityMatcher.html">SimilarityMatcher</a></li><li><a href="SizeExtractor.html">SizeExtractor</a></li><li><a href="TreeGenerator.html">TreeGenerator</a></li><li><a href="Update.html">Update</a></li><li><a href="VariableExtractor.html">VariableExtractor</a></li><li><a href="XccAdapter.html">XccAdapter</a></li><li><a href="XccPatchAdapter.html">XccPatchAdapter</a></li><li><a href="XmlDiffAdapter.html">XmlDiffAdapter</a></li><li><a href="XyDiffAdapter.html">XyDiffAdapter</a></li></ul><h3>Interfaces</h3><ul><li><a href="ExtractorInterface.html">ExtractorInterface</a></li><li><a href="MatcherInterface.html">MatcherInterface</a></li><li><a href="XmlSerializable.html">XmlSerializable</a></li></ul><h3>Global</h3><ul><li><a href="global.html#DiffConfig">DiffConfig</a></li><li><a href="global.html#Dsl">Dsl</a></li><li><a href="global.html#EvalConfig">EvalConfig</a></li><li><a href="global.html#getLcsLength">getLcsLength</a></li><li><a href="global.html#getLcsLengthFast">getLcsLengthFast</a></li><li><a href="global.html#getLis">getLis</a></li><li><a href="global.html#getPrimes">getPrimes</a></li><li><a href="global.html#persistBestMatches">persistBestMatches</a></li><li><a href="global.html#primeList">primeList</a></li><li><a href="global.html#stringHash">stringHash</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.7</a> on Thu Sep 09 2021 16:54:06 GMT+0200 (Central European Summer Time) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>
65.215569
5,343
0.668809
53dd2a09738aa02390cd513f4a682a045970100f
1,280
java
Java
streaming/java/streaming-api/src/main/java/io/ray/streaming/api/stream/DataStreamSource.java
77loopin/ray
9322f6aab53f4ca5baf5a3573e1ffde12feae519
[ "Apache-2.0" ]
21,382
2016-09-26T23:12:52.000Z
2022-03-31T21:47:45.000Z
streaming/java/streaming-api/src/main/java/io/ray/streaming/api/stream/DataStreamSource.java
77loopin/ray
9322f6aab53f4ca5baf5a3573e1ffde12feae519
[ "Apache-2.0" ]
19,689
2016-09-17T08:21:25.000Z
2022-03-31T23:59:30.000Z
streaming/java/streaming-api/src/main/java/io/ray/streaming/api/stream/DataStreamSource.java
gramhagen/ray
c18caa4db36d466718bdbcb2229aa0b2dc03da1f
[ "Apache-2.0" ]
4,114
2016-09-23T18:54:01.000Z
2022-03-31T15:07:32.000Z
package io.ray.streaming.api.stream; import io.ray.streaming.api.context.StreamingContext; import io.ray.streaming.api.function.impl.SourceFunction; import io.ray.streaming.api.function.internal.CollectionSourceFunction; import io.ray.streaming.operator.impl.SourceOperatorImpl; import java.util.Collection; /** * Represents a source of the DataStream. * * @param <T> The type of StreamSource data. */ public class DataStreamSource<T> extends DataStream<T> implements StreamSource<T> { private DataStreamSource(StreamingContext streamingContext, SourceFunction<T> sourceFunction) { super(streamingContext, new SourceOperatorImpl<>(sourceFunction)); } public static <T> DataStreamSource<T> fromSource( StreamingContext context, SourceFunction<T> sourceFunction) { return new DataStreamSource<>(context, sourceFunction); } /** * Build a DataStreamSource source from a collection. * * @param context Stream context. * @param values A collection of values. * @param <T> The type of source data. * @return A DataStreamSource. */ public static <T> DataStreamSource<T> fromCollection( StreamingContext context, Collection<T> values) { return new DataStreamSource<>(context, new CollectionSourceFunction<>(values)); } }
33.684211
97
0.755469
40dbf60cb13a9e3b4a5ab72770011eb1e12447c5
540
py
Python
myvenv/lib/python3.5/site-packages/allauth/socialaccount/providers/asana/tests.py
tuvapp/tuvappcom
5ca2be19f4b0c86a1d4a9553711a4da9d3f32841
[ "MIT" ]
1
2020-07-26T17:21:16.000Z
2020-07-26T17:21:16.000Z
myvenv/lib/python3.5/site-packages/allauth/socialaccount/providers/asana/tests.py
tuvapp/tuvappcom
5ca2be19f4b0c86a1d4a9553711a4da9d3f32841
[ "MIT" ]
6
2020-06-05T18:44:19.000Z
2022-01-13T00:48:56.000Z
myvenv/lib/python3.5/site-packages/allauth/socialaccount/providers/asana/tests.py
tuvapp/tuvappcom
5ca2be19f4b0c86a1d4a9553711a4da9d3f32841
[ "MIT" ]
1
2022-02-01T17:19:28.000Z
2022-02-01T17:19:28.000Z
from allauth.socialaccount.tests import create_oauth2_tests from allauth.tests import MockedResponse from allauth.socialaccount.providers import registry from .provider import AsanaProvider class AsanaTests(create_oauth2_tests( registry.by_id(AsanaProvider.id))): def get_mocked_response(self): return MockedResponse(200, """ {"data": {"photo": null, "workspaces": [{"id": 31337, "name": "test.com"}, {"id": 3133777, "name": "Personal Projects"}], "email": "test@test.com", "name": "Test Name", "id": 43748387}}""")
33.75
74
0.716667
de3fccb740b0deeffeef1b5e384e29d626042ef6
5,132
asm
Assembly
src/loader_init.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
src/loader_init.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
src/loader_init.asm
onslaught-demogroup/ons_paddo_music_disk
6a945f918fd1220b325385d14327b5e1ee86295d
[ "MIT" ]
null
null
null
.namespace __loader_init{ /* ZP used by this code */ .const ZPL=$9e .const ZPH=$9f /* Load drivecode into the drive Entry point */ init: jsr i_open_chn lda #<drivecode ldx #>drivecode sta ZPL stx ZPH i_cc11: jsr i_cc72 ldy #$00 i_cc16: lda (ZPL),y jsr i_write_byte iny cpy #$10 bne i_cc16 lda #$0d jsr i_write_byte jsr i_close_chn jsr i_open_chn lda ZPL clc adc #$10 sta ZPL bcc i_cc36 inc ZPH i_cc36: cmp #<(end_drivecode - 1) lda ZPH sbc #>(end_drivecode - 1) bcc i_cc11 jsr i_cc9a jsr i_close_chn lda #$c7 sta $dd00 //bank 0, 232 out, data in, clock in ldx #$00 i_cc4b: dey bne i_cc4b dex bne i_cc4b rts i_open_chn: ldx #$08 lda #$0f tay jsr $ffba //SETLFS. Set file parameters. 15,8,15 lda #$00 jsr $ffbd //SETNAM. Set file name parameters. jsr $ffc0 //OPEN. Open file. (Must call SETLFS and SETNAM beforehands.) ldx #$0f jsr $ffc9 //CHKOUT. Define file as default output. (Must call OPEN beforehands.) 15 rts i_write_byte: sty i_tmp jsr $ffd2 //CHROUT. Write byte to default output. (If not screen, must call OPEN and CHKOUT beforehands.) ldy i_tmp rts i_cc72: lda #$4d //M jsr i_write_byte lda #$2d //- jsr i_write_byte lda #$57 //W jsr i_write_byte lda ZPL sec sbc # <drivecode //$b7 php clc jsr i_write_byte plp lda ZPH sbc # (>drivecode) - 5 //$c7 clc jsr i_write_byte lda #$10 //number of bytes to send jsr i_write_byte rts i_cc9a: ldy #$00 i_cc9c: lda i_cca8,y jsr i_write_byte iny cpy #$06 bne i_cc9c rts i_cca8: .byte $4d, $2d, $45, $00, $05, $0d //M-E 00 05 <return> /* cca8 4d 2d 45 eor $452d ccab 00 brk ccac 05 0d ora $0d */ i_close_chn: jsr $ffcc //CLRCHN. Close default input/output files (for serial bus, send UNTALK and/or UNLISTEN); restore default input/output to keyboard/screen. lda #$0f jsr $ffc3 //CLOSE. Close file. rts i_tmp: .byte $00 drivecode: .pseudopc $0500 { jsr dc_067f dc_0503: jsr dc_05c3 lda $0e sta dc_06a5 lda $0f sta dc_06a6 ldy #$01 dc_0512: ldx #$12 stx $0e sty $0f jsr dc_05fb ldy #$02 dc_051d: lda $0700,y and #$83 cmp #$82 bne dc_0539 lda $0703,y cmp dc_06a5 bne dc_0539 lda $0704,y cmp dc_06a6 bne dc_0539 jmp dc_0561 dc_0539: tya clc adc #$20 tay bcc dc_051d ldy $0701 bpl dc_0512 dc_0545: lda #$00 sta $1800 ldx #$fe jsr dc_062f ldx #$fe jsr dc_062f ldx #$ac jsr dc_062f ldx #$f7 jsr dc_062f jmp dc_0503 dc_0561: lda $0701,y sta $0e lda $0702,y sta $0f dc_056b: jsr dc_05fb ldy #$00 lda $0700 sta $0e bne dc_057b ldy $0701 iny dc_057b: sty dc_06a5 lda $0701 sta $0f ldy #$02 lda #$00 sta $1800 dc_058a: ldx $0700,y cpx #$ac bne dc_0596 jsr dc_062f ldx #$ac dc_0596: jsr dc_062f iny cpy dc_06a5 bne dc_058a lda $0700 beq dc_05b6 ldx #$ac jsr dc_062f ldx #$c3 jsr dc_062f lda #$08 sta $1800 jmp dc_056b dc_05b6: ldx #$ac jsr dc_062f ldx #$ff jsr dc_062f jmp dc_0503 dc_05c3: lda #$08 sta $1800 lda $1c00 and #$f7 sta $1c00 cli lda #$01 dc_05d3: bit $1800 beq dc_05d3 sei lda #$00 sta $1800 jsr dc_065d pha jsr dc_065d sta $0e jsr dc_065d sta $0f lda #$08 sta $1800 lda $1c00 ora #$08 sta $1c00 pla rts dc_05fb: ldy #$05 sty $8b dc_05ff: cli lda #$80 sta $04 dc_0604: lda $04 bmi dc_0604 cmp #$01 beq dc_062d dec $8b ldy $8b bmi dc_0628 cpy #$02 bne dc_061a lda #$c0 sta $04 dc_061a: lda $16 sta $12 lda $17 sta $13 dc_0622: lda $04 bmi dc_0622 bpl dc_05ff dc_0628: pla pla jmp dc_0545 dc_062d: sei rts dc_062f: stx $14 lda #$04 jsr dc_063c jsr dc_063c jsr dc_063c dc_063c: lsr $14 ldx #$02 bcc dc_0644 ldx #$00 dc_0644: bit $1800 bne dc_0644 stx $1800 lsr $14 ldx #$02 bcc dc_0654 ldx #$00 dc_0654: bit $1800 beq dc_0654 stx $1800 rts dc_065d: ldy #$04 dc_065f: lda #$04 dc_0661: bit $1800 beq dc_0661 lda $1800 lsr ror $14 lda #$04 dc_066e: bit $1800 bne dc_066e lda $1800 lsr ror $14 dey bne dc_065f lda $14 rts dc_067f: sei cld ldy #$08 dc_0683: lda #$10 sta $1800 dc_0688: dex bne dc_0688 lda #$00 sta $1800 dc_0690: dex bne dc_0690 dey bne dc_0683 dc_0696: lda $1800 and #$05 bne dc_0696 lda $1800 and #$05 bne dc_0696 rts dc_06a5: .byte $00 dc_06a6: .byte $00 dc_06a7: .byte $00 } end_drivecode: .byte $00 /* ce5e 00 brk */ }
14.497175
152
0.558652
fe35cb9215b97f8e39a6c35f67b8d21bfd2b8e5b
4,355
asm
Assembly
mp1/mp1.asm
Candy-Crusher/ece220
18001a82a46711b0451d37b3dd2c747f85abad69
[ "MIT" ]
null
null
null
mp1/mp1.asm
Candy-Crusher/ece220
18001a82a46711b0451d37b3dd2c747f85abad69
[ "MIT" ]
1
2021-04-26T10:50:25.000Z
2021-04-26T10:50:25.000Z
mp2/mp1.asm
Candy-Crusher/ece220
18001a82a46711b0451d37b3dd2c747f85abad69
[ "MIT" ]
null
null
null
.ORIG X3000 ;PRINT_SLOT: ;A number from 0 to 14 is passed to this subroutine in R1. ;The subroutine prints the time corresponding to the specified slot.(R1+6) ;If R1=0, for example, your subroutine must print “0600” ;preceded by three spaces (ASCII x20) and followed by two trailing spaces. PRINT_SLOT ;store R0-R7 ST R0,STORE_REGISTER0 ST R1,STORE_REGISTER1 ST R2,STORE_REGISTER2 ST R3,STORE_REGISTER3 ST R4,STORE_REGISTER4 ST R5,STORE_REGISTER5 ST R6,STORE_REGISTER6 ST R7,STORE_REGISTER7 ;print preceded spaces LD R0,SPACE OUT OUT OUT ;print numbers ;test if R1<=3 ADD R2,R1,#-3 BRp FIRSTN_NOT_ZERO ;if R1<=3, first digit should be 0,print LD R0,ZERO OUT ;if R1<=3,second digit should be R1+6;print LD R2,START_TIME ADD R0,R1,R2 OUT BRnzp LATTER ;go to print followed zeros and spaces FIRSTN_NOT_ZERO ;test if R1=14 ADD R2,R1,#-14 BRn FIRSTN_1 ;if R1=14,the first digit should be 2,print LD R0,ZERO ADD R0,R0,#2 OUT ;if R1=14,the second digit should be 0,print LD R0,ZERO OUT BRnzp LATTER ;go to print followed zeros and spaces FIRSTN_1 ;if 3<=R1<14,the first digit should be 1 LD R0,ZERO ADD R0,R0,#1 OUT ;if 3<=R1<14,the second digit should be R1-4 LD R0,ZERO ADD R2,R1,#-4 ADD R0,R0,R2 OUT ;print followed zeros and spaces LATTER LD R0,ZERO OUT OUT LD R0,SPACE OUT OUT ;load back LD R0,STORE_REGISTER0 LD R1,STORE_REGISTER1 LD R2,STORE_REGISTER2 LD R3,STORE_REGISTER3 LD R4,STORE_REGISTER4 LD R5,STORE_REGISTER5 LD R6,STORE_REGISTER6 LD R7,STORE_REGISTER7 RET ;The second subroutine is PRINT_CENTERED. ;A string (the address of the first ASCII character ;in sequence terminated by an ASCII NUL, x00) is passed to your subroutine in R1. ;Your subroutine must print exactly nine characters. ;If the string is longer than nine characters, ;your subroutine must print the first nine characters. ;If the string is shorter than nine characters, ;your subroutine must print additional spaces ;around the string to bring the total length to nine characters. ;If the number of spaces needed is odd, ;the subroutine must use one more leading space than trailing space. PRINT_CENTERED ;store R0-R7 ST R0,STORE_REGISTER0 ST R1,STORE_REGISTER1 ST R2,STORE_REGISTER2 ST R3,STORE_REGISTER3 ST R4,STORE_REGISTER4 ST R5,STORE_REGISTER5 ST R6,STORE_REGISTER6 ST R7,STORE_REGISTER7 ;initialize AND R2,R2,#0 ADD R4,R1,#0;copy R1 to R4 ;count the length of the string COUNT_LENGTH LDR R3,R1,#0;load first character to R3 BRz COMPARE ; check if the string ends ADD R2,R2,#1;the length of the string is stored in R2 ADD R1,R1,#1 BRnzp COUNT_LENGTH ;go to check next character ;compare the length of the string with 9 COMPARE ADD R1,R4,#0;copy the address of the first character to R1 ADD R4,R2,#-9;R4 <- R2-9 BRzp NOT_SMALLER_THAN_9 SMALLER_TAHN_9 NOT R4,R4;R4 <- 9-R2-1 ADD R4,R4,#1;R4 <- 9-R2 AND R5,R5,#0 AND R3,R3,#0 ADD R3,R4,#0;R3 is 9-R2 CULCULATE_SPACE ADD R5,R5,#1;R5 as former spaces counter ADD R4,R4,#-2;R4/2 BRp CULCULATE_SPACE AND R6,R6,#0 ADD R6,R5,R6 ;print former spaces FORMER_SPACE BRz PRINT_STRING LD R0,SPACE OUT ADD R5,R5,#-1 BRnzp FORMER_SPACE ;print string PRINT_STRING ADD R2,R2,#0 BRz LATTER_SPACE1 LDR R0,R1,#0 OUT ADD R1,R1,#1 ADD R2,R2,#-1 BRnzp PRINT_STRING ;print latter spaces LATTER_SPACE1 NOT R6,R6;R6 was the number of former spaces ADD R6,R6,#1 ADD R5,R3,R6;R5 is 9-string length-former spaces length=latter spaces length LATTER_SPACE2 BRz DONE LD R0,SPACE OUT ADD R5,R5,#-1 BRnzp LATTER_SPACE2 NOT_SMALLER_THAN_9 AND R4,R4,#0 ADD R4,R4,#9;R4 as a counter of 9 ;print first 9 characters FIRST_9 BRz DONE LDR R0,R1,#0 ADD R1,R1,#1 OUT ADD R4,R4,#-1 BRnzp FIRST_9 DONE ;load back LD R0,STORE_REGISTER0 LD R1,STORE_REGISTER1 LD R2,STORE_REGISTER2 LD R3,STORE_REGISTER3 LD R4,STORE_REGISTER4 LD R5,STORE_REGISTER5 LD R6,STORE_REGISTER6 LD R7,STORE_REGISTER7 RET SPACE .FILL X20 START_TIME .FILL X36 ZERO .FILL X30 STORE_REGISTER0 .BLKW #1 STORE_REGISTER1 .BLKW #1 STORE_REGISTER2 .BLKW #1 STORE_REGISTER3 .BLKW #1 STORE_REGISTER4 .BLKW #1 STORE_REGISTER5 .BLKW #1 STORE_REGISTER6 .BLKW #1 STORE_REGISTER7 .BLKW #1 .END
22.219388
82
0.725373
e72b30134914da395087ed26afef202edb441a30
13,528
js
JavaScript
backend/config/globals.js
jamespagedev/labs10-discussion-board
9e06b10bf9041f4fcbd27d05a3889781e241cb45
[ "MIT" ]
2
2019-07-08T18:45:16.000Z
2019-08-21T22:23:21.000Z
backend/config/globals.js
jamespagedev/labs10-discussion-board
9e06b10bf9041f4fcbd27d05a3889781e241cb45
[ "MIT" ]
null
null
null
backend/config/globals.js
jamespagedev/labs10-discussion-board
9e06b10bf9041f4fcbd27d05a3889781e241cb45
[ "MIT" ]
null
null
null
// Variables const numOfFakeUsers = 500; const numOfHashes = 10; const numOfDiscussions = 29; const numOfDefaultCategories = 7; const numOfPosts = 59; const numOfPostVotes = 500; // must be same as numOfFakeUsers const numOfDiscussionVotes = 5000; const tokenOptionExpiration = '24h'; const tokenTimeLeftRefresh = 3; // in hrs const maxNumOfNotifications = 5; const numOfReplies = 50; const numOfReplyVotes = 500; const categoryIcons = [ 'fas fa-book-open', 'fas fa-scroll', 'fas fa-map-marked-alt', 'fas fa-comment', 'fas fa-cog', 'fas fa-bullhorn', 'fas fa-archive', 'fab fa-angular', 'fas fa-pager', 'fab fa-android', 'fab fa-apple', 'fas fa-atom', 'fas fa-laptop', 'fas fa-award', 'fas fa-bell', 'fas fa-chart-line', 'fas fa-male', 'fas fa-camera', ]; const allowedAvatarTypes = [ 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/tiff' ]; // prettier-ignore const safeUsrnameSqlLetters = [ '-', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ' ', ]; // prettier-ignore const safePwdSqlLetters = [ '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ]; const accountStatusTypes = ['inactive', 'active', 'banned']; // be careful when adding new things or changing order const subscriptionPlans = ['free', 'silver', 'gold']; // same order as subscriptionPrices // prettier-ignore const accountUserTypes = ['user', 'silver_member', 'gold_member', 'admin']; // Must match with globals on front end const subSilverStartIndex = 1; // Must match with globals on front end // prettier-ignore const permissionTypes = ['basic', accountUserTypes[0], accountUserTypes[1], accountUserTypes[2], accountUserTypes[3], 'super_moderator', 'moderator', accountUserTypes[accountUserTypes.length - 1]]; // prettier-ignore const categoryPermissions = permissionTypes.slice(); // prettier-ignore const discussionPermissions = permissionTypes.slice(); // prettier-ignore const postPermissions = permissionTypes.slice(); // prettier-ignore const votePermissions = permissionTypes.slice(); // prettier-ignore const followPermissions = permissionTypes.slice(); // Methods const getRandomIntInclusive = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive }; const getRandomUserId = () => { min = 1; max = numOfFakeUsers; return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive }; // Seeds // prettier-ignore const categoryNames = ['Tech Talk', 'Sports', 'Cars', 'Anime', 'TV Shows', 'Movies', 'Music']; // must match defaultAvatar on frontend globals const defaultAvatar = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAACXBIWXMAAAsTAAALEwEAmpwYAAAZm0lEQVR4nO2de5wcRbXHf6d6dnaXJBsSl+ymp3t2QzaJAgqyQkSRiDzkorwMBHwB8jCggPgKAiIgQuD6AkSe4SPi5UIELpBwucgbREEgV4EEDASyO93TyYa9ELLZ7Gu6zv1jegXCdHX3TPfMJuT7+eSPbFdXnZ5zpqa66jyAbWxjG9vYxja28UGEai1ADaHm5ubxANDb27sRANdYnpqwVRrA9OktU4aHxSxmbRYRZgE8C+CpRDSBGU0AJgAYh3eenwH0A+gjwgZm7gNoDUArmbGSyF2ZTsuVr73Ws65Wz5QUW4MBCNM0O4n4c8xyX4D2BDApobHeAvgZZjxCpD1qWdYyADKhsarCFmkA06e3TBka0uYR0QEA9gGwfY1EWQ/gCWZ+sL7e/eOWOENsMQbQ0dFRPzw8cKiUOI4InweQqrVMm1Fgxp+EwO/T6cYlq1atGqq1QGEY8wZgmuYugDwNwNGo3Tc9KusBLAbEVZZlLa+1MCrGrAGYprkHwOcCfCjGsJwBMED3AHSxZVnP1VqYUoy5D9YwjDlEfC6AA2otS7zQA54hPFFrSd7NmDEAwzA6iORVAH0+5q7fALASoFeI0MvMfUTUxyz7iGgjADDzeCIxgZkneK+KzQDPBDALwA7xisP3M4vTbdteFW+/5VFzA2hvb2+QsnA2M58FoL7C7hwiflRK8RgzL9c0bWUul3urkg6z2ewk13VnEdEuQsjPMtO+APQK5RwiokuFSF3a1dU1WGFfFVFTAzAM4yAivgrA9DK7GAFwP8D3axoe6epy/hmjeL60t+sfdl18DqCDABwEoK7MrlYx0+m2bd8fo3iRqIkBGIbRKIS8kplOKrOLvwH8B9fFYsdxemMVLiK6rjdrGo4G6FgAe5bTBxEvklKcYdv2QMziBY9d7QF1XZ+laXQ7gI9GvHUTM25gxtX5fP6VJGSrFF3XZwlBpxLhmwAaI97+ouvyUY7jrExCNj+qagCGYXyNiK8BMD7sPUTok5Kvrq93f7Wl7LR5O5XfE4K+xYwJEW7dyEyn2LZ9S2LCbUa1DEAzzcxvAcyPcM8AgF8Qab+udCFXK7LZ7CRm97sAfoBoM8J1lpX/NgA3GcneIXEDMAyjkYgXAzgkwm1LNc09o6trbVdCYlWVtraWaa6bupIIX4xw2xJmOibpdUGiBtDe3r69644sBbB3yFu6iPiMXM5ZmqRctcI09UMBugJAe8hbntS0ukO6urrWJyVTYgZgmqYOyD8B2CWUIMSLCgV8x3GcTUnJNBbQdX07TRNXAnxiyFteBMRBlmU5SciTiAEUlc9PAjwtRPOqL3zGAoZhfJWIr0WoBTGtBmjvJIwgdgPwFj5PINw3/wXX5XnVfvUZK0R8JV5OpO0T94JYxNmZYRiNUrr3IpzylzDTJz+oygcAx3FWMtNsAEtCNN+F2V1qGEbU/QUlcc4AKcPI3E2EL4QY9kbLsuejCq85ANDS0jKuoSE1W0rsBmAGEbLMmIx3Xs0GiPAmM3IAXhUC/xgcLPytp6envxryAdBM07ge4BOCGjLjXtvOHwGgEMfAsRmAaRqLQi5sFlpW/py4xvXDMIwMER8D0GEA74XoHkQFgJ4C+B5mus227XwScr4bw9AXEtGPgtoR8aJczjk5jjFjMYBsNnMcM24KasfMC2zb+XkcY/rL0roTs3YRgMMR30+cBHA3kXteLrf2pZj6LIlh6AuI6LKgdkQ4LpfL31zpeBUbQPFkjJ5D0c3aF2a+1Ladsysdz4/iNx4XAnw8AC2hYVyAbmLG+UnOCIahX0pEZwU063dd7qx0DVWRAbS3tze47sgzCFzF0o2WZZd78qekpaVlXDqdOhfAmYh+AFMuAwAuHx4uXJzUOsE0jRtDrAle0LS62ZX4FFT0TRk/ftxviXCwuhXdY1n215FA5M20aVPbiLQHARyJ8s/ky6EOwGc0TXxh/PgJ9/X19b0d9wAbNmz474kTm3ZD0SvJjxZmucOGDX33ljtO2b+Rpqkf6B17qniBGV9GAqv9bFbfu1AQzwLYNe6+I7CrEPRsNqt/OoG+XWY6BsCLAe3mm6Z+YLmDlPUT0NHRUT80NLAcQIei2UbX5U8k8Z5vGPqJRHQ1gHTUe5nRTcT/BGgNEfcV/0YTAJ7KTB8mQlsZIg0z87ds27mxjHuVeJtFz0G9Y/hqfX3jR8uJRSgruGJwcNOPiEilfDDTfMfJx65808ycAuCaCLcME2EpM9+ZTrsPB/kUFOMKtf2IaC4zDkE4I0sT0SLTzNRZVv7aCLIF4jjOSsMwTiHi/1A0mzE4uOksAD+N2n/kGaDovcsvAmjw7TTG99R3k8lk9hUCDyCc4Y4AdF06PXJRuY4kRWOoOw/g+Qi3xihIiQPz+fyj5YynIsQ+yyAgdrEs67Uo/UY2ANPU/8dzhvSjy3V557hP9UzTnA7IZwBMDtH8dmY6Jy7Xa8MwOgBeSIQjQzR/ExB7RlVEELqubycEvaT+ieL7Lcv5tyj9RjIAL2jjMXUrPsyynDB726Hp6JjcNDTU+DSAjwQ0HSLCN+PYIClFNps5lhnXI9B9nV6qr9+016pVb26Ic3zT1A8D6G51KzEnSvBJpLcAL2JHxdK4lQ8AQ0ONlyFY+WuYaU5SygeAXC5/s5T4LMBr1S15p6GhxkvjHt+ynHuYEfDKF6ij9xB6BijG6slnFE0GNM3dKW43Lm8VvBzq333bdflTjuNYcY6tkMnUNHoKQEbRrCAldo7bg7mtrWWalKkVUG56iT3CxiJGmAECLesXSfjwaRpdArXyB4jk4dVSPgA4jmMRycNQ3BH0I6VpuCTusbu7e1YD+KW6VfhZINQM4IVov+DXngh9gNYWt7NCJpPZSwj8VdWGCEfncvk/xjluWExTPxqg21RtpMRe+Xz+6TjHNQxjMhF3w39vgAHxsTCh6SFnAHkalMZC1yThui0EFqquF183a6N8ALAsZzERL1K1EQKxrwVs236TiFR7IeTpLJBAA+jo6KhHMTmDHwN1dSMBU1J0DMP4KIA5iiabmLXz4x43Kp4Mqp+COd6zxIqmDf8yYNx5nu6UBBrA8PDAoVBk5iDiRUlE7AiBrwU0uSIpT9koWJblMPMVqjYhniUyq1ev6wmYfSYNDw8ExmIEGoCUOE7ZgcDVQX2UAzMfobj8dl1dfaDTRLVIpxsuBeB7IhjwLGXjhdn5EqQ7IMAApk9vmeIlZPLj2SRCstvaWqYBmKFocsvrr78e+xFsuXiyqNzaZ7S3t7bHPW5395qXAfZ93SPCQdOnt0xR9aE0gKEhbR4Ur2DMnMimi+vWKY9XpcQdSYxbCUEyFQqpsNFRkWAWKh2khoe1o1T3Kw3Ay8Pnxwgz3aq6v1yIeHfF5YHW1tYnkxi3EjyZfBdlAc9UNlLKW1FMlOGDUOZaUhmABvUq/P58Pv9/qs7LhRkzFdf+vmzZMsUD14Zly5aNMOPvftdVz1QJjuP0MuNP/i14DhR69r1gmubuACYqOk4srYnqxEsITtQrtxJUspXpaBIKIqUutvd0WRJfAyDiz6kG1TQ8EkK2clEc+Yqav/r5o5QtzDF2eaMKVuqC2fXVpa8BFBMv++IknJDJ18WcmcfM6n9zAmRTus1XQvFtAGv8rhPBV5eKNQDN9u+QY/d42XwExcWxnNdfIZvymeIYWqETf12WNADv3dF3909K8Vh4wcqBVVucofML1QCFbDLRvAfMQvWlnNTa2loy4WVJAxgeFipfdDBzwgmQSfV20Zrs2BWhkE28meTAzLxCdT2dLq3TkgbArCkNQNO0hEO62TfsilkZKFFT1LL5P1McEJFSJ1KWlq2kARTLrPjyRvJZu8jXi4YInYg5r0FMCE82H/yfKQ5s234TgG/STCEizADFGju+JJ7QgRnPKy5vn81O/XjSMkTFk8l33RTwTHHhqxvm0jr1M4Cp/mMka8kAIIRQegExiy8lLUNUgmQKeqaYUOmmpE59fgLIN7slkf80Exe5XG4FFO+1AI7t7OysZjCoEk+WYxVN1njPlChE5Ksbv4ylPotANPl3VIynqwIq93Kjp2dNlKyjidLT03MKAEPR5J5qyKHSDVFpnfotphQzAFXFAAJi4UBEP2lubo6ShzcRmpubJxDxeao2RFyVFHhF51zfa6FnAIJyK1ZWxQByOedJgFQHPzs0Ntb/sBqyqGhsrF8AZVUReqn4LMkjpf8MwIzxKOHY+z4D8Mqp+m5bjpZZqQbM8lcBTRZkMpm9qiJMCbyxlUYY4hliQwjl7PyvUrnvuSfqIMw8HPWecmlpmXpzMUumL/VC4C5d181qyTSKruumELgLyjhBWl18hupQjm7eZwBBhZSJqGoFG5ctWzZCxEFp01qEoHtaWloSO21734AtLeNSKVoCoEXVjoh/VE3nlQDdSE+376HUDMBEUE3z20WWrAKKgR/0gKoNET6eTtc9bhiGKlYvFjKZjJFOp55gxm7qlvRADYJWFLqhkl9sv9dA398SKUnhJZQMritPRrEapwLuJOJnDcMoq25PGAzDmC0EPwsgyL9vvSdzVVHrpvQC0c8AfOPaiTjmOnrBOI6TY6YTEOwLMJWIHzfNzLm6rsc2U+m6vp1pZs4t5kagoNNIZqYTHMfJxTV+WAJ0U1KnfodBvgbAHLrYQazYtn0XM18QomkDgJ9pGq3KZjPzUVmR6ZRpZk7RNFoF4GdQpMUZhZkvsG37rgrGLBsiqNLzl9Sp34fToxhkxyhCxYltOz81zYyOcLWHpjLjWtM0zmKWNwmRujPsdmw2m91ZysJcInF8yJoHo1xn207kRE1xISV2VPgdlQzf8zEAWgmwX1xZlA8kdiwrf6phZChEjkIPnkZEFzK7F5qmvpaZniPCSgB55uKeBhGPB5Bhxiwi/gSz20pEiOJ9xozrbTt/avQnig/VDEBEJX04SxoAs/wn+ZvSVMMwGmtR5NCDbTs/P5s11jBzxOhgavUKN30RAIjeq+DiI0d33SOiCy3LviDyjTFSrCPAvusTZlnSAEquAYSAyuOXAHwsmnjxk8vZFzDTXACRkyPGyBAzzc3l7AtqKAMAgJl3hcJ6/XRacgaQUry8+bdjs85mA/hbRBljw8sb9FWAv4LKC05XQj0R/7tpZnZzXb6lltVPNI1mM/vrjDn1cqm/+1qMaWbWwfeQg261LPsr0USsDC8z+fEAnQSwwvWqltAygBdpWt1N1a4KbpqZWwEcU+oaM9bZdr7krqXiLICXKa75+pnHTXNz8wTD0Be47vBqANeMXeUDnmzXuO7wasPQF1T3uFoZx/G/ftdUh0EPK67tOG3a1MRi3YBiahrTzJzT2FjfXaygEbgBM4agViK6rLGxPmeamR+HSdVSCUVdqF5X6SG/K74GIKX/TQDgutphYYQrh2xW339oaOAFABcDmJTUOFVgewAXDQ0NvJjN6sow7UpwXe1w1XUp4atL1TsPeeuA5lIXmfGIbef3CydiOLzkzJcD/OUYulsD4B8AXkaxEpgF8JqREbzR0NCwYdKkSZtGT+o6Ozvr3nrrre0GBweb6uqwA0BTpYSJYpaSjwDYDT5OlRG5LZ0ufCfunErZbOYRZt/4vzcsK98Cn00N5UuvaWYWA5jnc7lApE2JK0bAywl4BwC9zC4cAEsBfpRZPBl3TZ9iTSK5N0D7olgIu1w581LiyLhyB3o5A3vgv6u72LLyJReHUNwEAGCmB4nYzwBSUsq5AJR58sJgmplTAVyO6AUgBgC+C9ButizrISRYh9AzqMXev2+bprk/wMcBfDii1SrKCIHHTTPznZhqC3wJyjQ+6p9y5QzQ2tq6Q12dlod/rvxnLStfyfGryGb1a5kp6tHpk8x8U0PD4O1xZ+SOSkfH5KbBwe3mEfFxCF8lHQBAxDfkcs4pKJalKwvT1J8F6BM+l0dGRtzM2rVr3/CVIXgA426AfRd8QvDu3d2Ob2oUBcI0MzcCOD7CPc8Lge91d+eTTE5RNtlsZj9m/ArRdkp/Z1n5E1FG2Htbm767lKR4Xae7LctWpqgL4RMob1JelVSOfz6ZpnEDwiu/h5lOtqz87mNV+QCQy+Uftqz8x70ZzfdEdTO+4X0WkQ8hXDfos1frDmEG7ezsrFu3bm0e/q7P/a7L7Y7jhI4Yymb1K5np9BBNXWb++eDg8CW9vb3VCkiJhebm5gkNDelziGgBQnzRiPg3uZxzRtj+vZ/n1fBx4fd2/zIIqDEcKJj3qqQKbBiXSonQ/vmGYXw1nPJpAzMdatvO2Vua8gGgt7e3z7ads5npEFXAxijMdLphGKG319Pp1A+hiN8gwi0IUWA61LTj1eNdrmjfn04Xdgx6v/X6eQaB+XJoNZE4pBrxdNUgm83uzCyXhnAu6RdC7uHl/PGluF+SWg1/J1AmcncJU+c4VFxAsSNW1aoZNzycUta6NQyjkVm7A8HK/7Pryj23FuUDxWDXkZHCbABBEULjpNTuKJ7t++N91iqfx7vCFrkOHRgiJf0U6pXqt4rVtXx7+CEC6v4Q4b6mpon7R1lPbCmsXbv2jaam7fcjwn3qlrwTEf/A76r3GX9b1YGU4esHhjaAfD7/DwBLFU0aiORvSl0o7qLRAvUI/FyhwEetWLGiapFH1WbFihXDhQIfpUrw7HGWaZoldxqJ5FVQRyMtyefzoZNRRAoNE4IvVLegg7LZzPtq6xHxJVBP/b1S0hFx1xociziOs0lKOgKKdC4AxgHyffWGstnMUQCpsrdDCBnJKbWMwpGZJSjuhfuRr6ur33k0nbvnvfOyeiw+3LKcqsTQjxVC1ABkKfHh0apjO+6448SRkaEVUFcqW2JZ+UintJGDQ4m0M6EuVZIZGRm6bvQ/miZOgtrQbv+gKR8o1gAEcLuiCWkanTT6n5GRoeuhVv4AkfbdqHJoUW94++2335o4sYkBqI6Cd2lqmmDPmDFz+caNG39P5Dv9D6VS8tD16zeO2fSvSfKhD41/Rko6Ff6HOR0zZsy8QtO0E4hwtqovIpyfy9mqNVpJIhsAAMyYMfPp/v6NRwDwrUZBRPv392+URMqfixu6u53/LEeGrYH16ze+PXFikw5gD58m4/v7Nw4R4RKoi1cvnzKl9bg1a9ZEPlQqO39tW5v+KSnpyQr6eM9v3AeVTCYz03PZruRz/HQ+n3+qnJvLTrjY3e38FYCyaFEAf/2gKx8AvM+gkhRy15SrfKDCjJuaVvd9VZWMAO6sZOytjLI+C2b8XdPqvl/JwBUZQFdX16AQ2pEIjN1/P0GeKh8kyvws3tK0wtxK4w8qzrmby+VeJ+JjEc2hod+27a1mr79SvM+iP8ItTIRjvULSFRFL0uVczlkKhK+Ry4xXUIEb1FaI9D6TsCzM5fL3xjFwbFm3LSt/HkChNnSISI6lVK+1prOzs46IQn4h6G7Lyv8krrHjTLvu1tc3HA34ByG8A3euW9fzsF8Viw8S06e3TFm3rufhkCFvD9XXNxyDGL2fY69j09LSMi6dTj0E4JMhmueE4MPLdCrd4vGcOu8GEJjnkAhPDQ0VDujp6YmyVggk9sILPT09/UTawQBeCNE8KyX9xTT1b8Qtx1jHNPVveBtpYZJcPi9E3cFxKx9IYAYYxXNb+gsAhZPIe0S5J5Uanr969bqw3rRbJNOmTWkpFOquB3BoyFtWpdOFT8cdTjZKYqVXXnutZ53r8l4AHg93Bx9WKNQtNwxjblIy1ZpsNnNkoVC3HOGV/5jr8l5JKR9IuPaO4zi9U6a0HgDgdyFvaSbiOwwjs7StbarSfWxLoq1t6kcMI7OUGbfDJ9i2BL+bMqX1wKTd4xIuZvgO2axxFjMvjDBmAcCidLpwfpLfgCTxfgYvBHAywp+8MhGdncvZlyUo2r+omgEAgGEYXyLimxGhjCoR+phxFSCusixrDNcNfoeiP588jQin+ZVq8aGfmY61bfu/EhNuM6pqAEDRq9WrBhI1zcwIERYT8a+7ux3flCe1pK1N350Z32OmeVCf35fiaWb6um3bq5KQzY+qG4BHyjD0c4noxygjlSsRngLoNiFSf+zq6lqbgHyhaW9vb5WyMA/gY5hRTvGKAjNfZNvOxUgwvN2PWhkAAMAwjD2J+A8AZpbZhQTwBIDFgHjQsqzX4pPOH9M0pwPyAABHA9gH5S+mX/G+9c/EJ100amoAQDEZ1PDw4JkAnxvx97IUawD8mZn/TKQ9XV/f/0ql+QM6OiY3DQ2Nm8nsfpKIPgPgM6gwXQwR+qTknzU0bHfFqlWrapnosvYGMEp7e3ur6xYuBvh4xPh6yox1RHgVwKsAbCLqlxL9RHIjEfUX2/A4ZjFeCIxj5nEoloCbwYwZRP5+j2UgAboplRo+Z6xseI0ZAxiluD8uFgJ8YK1liRd6QAh59lhbwI45Axglk8nspmn8A2Y6GpXl/K8lBSJe7Lr08yjhWtVkzBrAKLquZzWNzgToRIB9K5qOLWgDwDe6Ll9ei8ohURjzBjBKe3t7Q6FQOFgI/gozvoAQ1TuqzCAz7gXo1lQqdV+1cwWXyxZjAO+mo2Ny0/Bw4xHMmIvia1jVC1l5vA3gCSLcmU4P3FXrjGXlsEUawGaItjZ9V2aaw0xzAN4HwOSExnoToCeI+HEifry723keW7hv49ZgAO+jra1tqpRyBjPPFAIzmDET4CyAJoDHAzQBxQwbo8/PADYVS6vRRgAbAMoR4RUp8SoRvSKEeLW7u1tV0n6LZKs0gJCI5ubmcQDQ29vbjy38m7yNbWxjG9vYxja2EYX/B1Ks+llEzUoiAAAAAElFTkSuQmCC'; // environment variables const secureKey = process.env.SECURE_KEY; const frontEndUrl = process.env.FRONTEND_URL; const nodeMailerHost = process.env.NODEMAILER_HOST; const nodeMailerPort = process.env.NODEMAILER_PORT; const nodeMailerUser = process.env.NODEMAILER_USER; const nodeMailerPass = process.env.NODEMAILER_PASS; const backendStripePkToken = process.env.BACKEND_STRIPE_TOKEN; const pusherAppId = process.env.PUSHER_APP_ID; const pusherKey = process.env.PUSHER_KEY; const pusherSecret = process.env.PUSHER_SECRET; const pusherCluster = process.env.PUSHER_CLUSTER; module.exports = { // variables subSilverStartIndex, numOfDiscussions, numOfDefaultCategories, numOfPosts, numOfFakeUsers, numOfHashes, numOfPostVotes, numOfDiscussionVotes, numOfReplies, numOfReplyVotes, maxNumOfNotifications, safeUsrnameSqlLetters, safePwdSqlLetters, accountStatusTypes, subscriptionPlans, accountUserTypes, tokenOptionExpiration, tokenTimeLeftRefresh, allowedAvatarTypes, categoryIcons, // methods getRandomIntInclusive, getRandomUserId, // seeds categoryNames, defaultAvatar, // environment variables secureKey, frontEndUrl, nodeMailerHost, nodeMailerPort, nodeMailerUser, nodeMailerPass, backendStripePkToken, pusherAppId, pusherKey, pusherSecret, pusherCluster, };
85.081761
8,871
0.862581
dd7bc63f631ac268cce6900cd3e8f5deb8e547a9
1,578
go
Go
archiver/metadata_archiver.go
bboozzoo/artifacts-1
e8d3700885dc92ba9bfa7b19f656630a46bf0f59
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
archiver/metadata_archiver.go
bboozzoo/artifacts-1
e8d3700885dc92ba9bfa7b19f656630a46bf0f59
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
archiver/metadata_archiver.go
bboozzoo/artifacts-1
e8d3700885dc92ba9bfa7b19f656630a46bf0f59
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2016 Mender Software AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package archiver import ( "bytes" "encoding/json" "errors" "github.com/mendersoftware/mender-artifact/metadata" ) // NewMetadataArchiver creates streamArchiver used for storing metadata elements // inside tar archive. // data is the data structure implementing Validater interface and must be // a struct that can be converted to JSON (see getJSON below) // archivePath is the relatve path inside the archive (see tar.Header.Name) func NewMetadataArchiver(data metadata.WriteValidator, archivePath string) *StreamArchiver { j, err := convertToJSON(data) if err != nil { return &StreamArchiver{} } return &StreamArchiver{archivePath, bytes.NewReader(j)} } // gets data which is Validated before converting to JSON func convertToJSON(data metadata.WriteValidator) ([]byte, error) { if data == nil { return nil, errors.New("archiver: empty data") } if err := data.Validate(); err != nil { return nil, err } return json.Marshal(data) }
32.875
92
0.734474
8779c6da3038d53dd621299c7afaab1f4e548220
3,334
html
HTML
Templates/control-pager.html
Cleancodefactory/BindKraft
1f7bdb00f9cf17c21bdb1dfbe751a353a3a8986e
[ "MIT" ]
13
2019-03-28T14:48:32.000Z
2020-12-22T10:38:25.000Z
Templates/control-pager.html
Cleancodefactory/BindKraft
1f7bdb00f9cf17c21bdb1dfbe751a353a3a8986e
[ "MIT" ]
31
2019-04-11T18:04:10.000Z
2022-03-07T18:30:32.000Z
Templates/control-pager.html
Cleancodefactory/BindKraft
1f7bdb00f9cf17c21bdb1dfbe751a353a3a8986e
[ "MIT" ]
5
2019-05-09T13:59:55.000Z
2020-11-23T08:17:04.000Z
<!--container--> <table class="bk-pager-container" data-bind-elementvisibility="{read source=__control path=$visible readdata=$pagerupdateevent}"> <!--class="c_width_207"--> <tr> <td class="bk-pager-element-holder" style="cursor:pointer;"> <!--go to first button--> <div data-class="SvgY svgpath='/node/raw/bindkraftstyles/images/angleDouble-left-icon.svg' width='25px' height='25px'" style="padding-top:5px;" class="bk-svg-avatar-box " data-bind-elementdisabled="{read source=__control path=$hasprevpage format=InverseFormatter readdata=$pagerupdateevent}" data-on-click="{bind source=__control path=gotoFirstPage}"></div><!--class="c_pager_double_left"--> </td> <td class="bk-pager-element-holder" style="cursor:pointer;"> <!--go to previous button--> <div data-class="SvgY svgpath='/node/raw/bindkraftstyles/images/angle-left-icon.svg' width='25px' height='25px'" style="padding-top:5px; " class="bk-svg-avatar-box " data-bind-elementdisabled="{read source=__control path=$hasprevpage format=InverseFormatter readdata=$pagerupdateevent}" data-on-click="{bind source=__control path=gotoPrevPage}"></div><!--class="c_pager_one_left"--></td> <td class="bk-pager-element-holder" style="cursor:pointer;"> <!--class="padding_left_6 c_padding_right_6" style="padding-left:3px;"--> <!--drop down control--> <div data-class="VirtualDropDownControl keyproperty='key' descproperty='value' templateName='bindkraftstyles/control-vdropdown'" data-key="allPages" class="bk-margin-normal" data-bind-$items="{read source=__control path=$pages readdata(1)=$pagerupdateevent}" data-bind-$value="{read(10) source=__control path=$currentpage readdata(2)=$pagerupdateevent writedata=__control:$applypageevent format=IntegerFormatter}" data-on-$activatedevent="{bind source=__control path=OnTriggerApplyPage ref[page]=self@value }"> </div> </td> <td class="bk-pager-element-holder" style="cursor:pointer;"> <!--style="padding-right:0px;"--> <!--go to next button--> <div data-class="SvgY svgpath='/node/raw/bindkraftstyles/images/angle-right-icon.svg' width='25px' height='25px'" style="padding-top:5px;" class="bk-svg-avatar-box " data-bind-elementdisabled="{read source=__control path=$hasnextpage format=InverseFormatter readdata=$pagerupdateevent}" data-on-click="{bind source=__control path=gotoNextPage}"> <!--class="c_pager_one_right"--> </div> </td> <td class="bk-pager-element-holder" style="cursor:pointer;"> <!--style="padding-left:0px"--> <!--go to last button--> <div data-class="SvgY svgpath='/node/raw/bindkraftstyles/images/angleDouble-right-icon.svg' width='25px' height='25px'" style="padding-top:5px;" class="bk-svg-avatar-box " data-bind-elementdisabled="{read source=__control path=$haslastpage format=InverseFormatter readdata=$pagerupdateevent}" data-on-click="{bind source=__control path=gotoLastPage}"></div><!--class="c_pager_double_right"--></td> </tr> </table>
74.088889
183
0.64997
58cd57c66fea78b81642708859b2a10c33e50b1c
3,219
swift
Swift
Sources/TuistKit/Services/ExecService.swift
leszko11/tuist
3b1d6de7f247866d22b0afa1a3de7312242c77c7
[ "MIT" ]
null
null
null
Sources/TuistKit/Services/ExecService.swift
leszko11/tuist
3b1d6de7f247866d22b0afa1a3de7312242c77c7
[ "MIT" ]
null
null
null
Sources/TuistKit/Services/ExecService.swift
leszko11/tuist
3b1d6de7f247866d22b0afa1a3de7312242c77c7
[ "MIT" ]
null
null
null
import Foundation import ProjectDescription import TSCBasic import TuistCore import TuistGraph import TuistLoader import TuistPlugin import TuistSupport import TuistTasks enum ExecError: FatalError, Equatable { case taskNotFound(String, [String]) var description: String { switch self { case let .taskNotFound(task, tasks): return "Task \(task) not found. Available tasks are: \(tasks.joined(separator: ", "))" } } var type: ErrorType { switch self { case .taskNotFound: return .abort } } } struct ExecService { private let manifestLoader: ManifestLoading private let tasksLocator: TasksLocating init( manifestLoader: ManifestLoading = ManifestLoader(), tasksLocator: TasksLocating = TasksLocator() ) { self.manifestLoader = manifestLoader self.tasksLocator = tasksLocator } func run( _ taskName: String, options: [String: String], path: String? ) throws { let path = self.path(path) let taskPath = try task(with: taskName, path: path) let runArguments = try manifestLoader.taskLoadArguments(at: taskPath) + [ "--tuist-task", String(data: try JSONEncoder().encode(options), encoding: .utf8)!, ] try ProcessEnv.chdir(path) try System.shared.runAndPrint( runArguments, verbose: false, environment: Environment.shared.manifestLoadingVariables ) } func loadTaskOptions( taskName: String, path: String? ) throws -> [String] { let path = self.path(path) let taskPath = try task(with: taskName, path: path) let taskContents = try FileHandler.shared.readTextFile(taskPath) let optionsRegex = try NSRegularExpression(pattern: "\\.option\\(\"([^\"]*)\"\\),?", options: []) var options: [String] = [] optionsRegex.enumerateMatches( in: taskContents, options: [], range: NSRange(location: 0, length: taskContents.count) ) { match, _, _ in guard let match = match, match.numberOfRanges == 2, let range = Range(match.range(at: 1), in: taskContents) else { return } options.append( String(taskContents[range]) ) } return options } // MARK: - Helpers private func task(with name: String, path: AbsolutePath) throws -> AbsolutePath { let tasks: [String: AbsolutePath] = try tasksLocator.locateTasks(at: path) .reduce(into: [:]) { acc, current in acc[current.basenameWithoutExt.camelCaseToKebabCase()] = current } guard let task = tasks[name] else { throw ExecError.taskNotFound(name, tasks.map(\.key).sorted()) } return task } private func path(_ path: String?) -> AbsolutePath { if let path = path { return AbsolutePath(path, relativeTo: FileHandler.shared.currentPath) } else { return FileHandler.shared.currentPath } } }
29.805556
107
0.58776
394e0b4988609ce1bcd4b328d38987692f863455
596
html
HTML
_includes/meilleurs-actualites.html
ETIBER/site-dinsic
c18c30aae4443fc2e3324f8c165b8b4c10800423
[ "MIT" ]
17
2018-10-05T09:17:41.000Z
2022-01-14T10:19:31.000Z
_includes/meilleurs-actualites.html
Indianajaune/numerique.gouv.fr
0c4b9c0978da0320a7875c3bd54a1d241e3bba71
[ "MIT" ]
10
2018-10-15T07:50:38.000Z
2022-02-26T04:18:49.000Z
_includes/meilleurs-actualites.html
Indianajaune/numerique.gouv.fr
0c4b9c0978da0320a7875c3bd54a1d241e3bba71
[ "MIT" ]
9
2018-10-12T12:43:01.000Z
2021-11-12T20:34:08.000Z
<div id="meilleures-actualites" class="grid-container"> {% assign actualite_principal = sorted_actualites.first %} <div class="grid-x grid-margin-x grid-margin-y margin-bottom-2"> {% include components/carte-double.html carte-double=actualite_principal %} <ul class="cell remove-bullet large-12 grid-x grid-margin-x margin-0 width-100"> {% for actualite in sorted_actualites limit:3 offset:1 %} <li class="cell large-4 medium-6 small-12"> {% include components/carte.html data=actualite is_image=true %} </li> {% endfor %} </ul> </div> </div>
42.571429
84
0.676174
0bc25628bdeee646aae0cedd3efc79f8829fa812
4,963
py
Python
scripts/corpinfo.py
HiroshiOhta/GetCorporationInfo
3c64ba44a15d481c652da70d62f7127372ac6d1e
[ "Apache-2.0" ]
1
2020-05-24T02:41:24.000Z
2020-05-24T02:41:24.000Z
scripts/corpinfo.py
HiroshiOhta/GetCorporationInfo
3c64ba44a15d481c652da70d62f7127372ac6d1e
[ "Apache-2.0" ]
null
null
null
scripts/corpinfo.py
HiroshiOhta/GetCorporationInfo
3c64ba44a15d481c652da70d62f7127372ac6d1e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # 標準ライブラリ from pathlib import Path from re import search, sub from sys import exit, argv from xml.etree import ElementTree as ET import csv # サードパーティライブラリ from requests import get from requests.exceptions import Timeout, RequestException # ローカルなライブラリ from constants import ENC_API_KEY, NTA_API_URL from crypt_string import decrypt_strings def validate_number(corp_number: str) -> bool: """ 指定された法人番号の妥当性をチェックデジットを用いて検証する。 Parameters ---------- corp_number : str 13桁の法人番号 Returns ------- bool 指定された法人番号が正しい場合はtrue、誤っている場合はfalseを返す """ tmp_corp_num_lst = list(corp_number) corp_num_lst = list(map(int, tmp_corp_num_lst)) # 最上位1桁目のチェックデジットを取得 check_degit = corp_num_lst[0] del corp_num_lst[0] # STEP1: 最下位から偶数桁の和 × 2 + 最下位から奇数桁の和 を求める。 degit_step1 = sum(corp_num_lst[-2::-2]) * 2 + sum(corp_num_lst[-1::-2]) # STEP2: STEP1で求めた数を9で割ったあまりを求める。 degit_step2 = degit_step1 % 9 # STEP3: 9から STEP2 で求めた数を引いた数 degit = 9 - degit_step2 if check_degit == degit: return True else: return False def get_corp_info(api_key: str, corp_number: str) -> str: """ [summary] Parameters ---------- api_key : str [description] corp_number : str [description] Returns ------- str [description] """ # クエリーパラメータの作成 # ------------------------------------------------------------------------------ params = { 'id': api_key, 'number': corp_number, 'type': '12', 'history': '0', } # 法人情報の取得 # ------------------------------------------------------------------------------ try: response = get(NTA_API_URL, params=params, timeout=3.0) response.raise_for_status() except Timeout as err: # TODO: logging で出力するように変更する。要学習。 print(err) print("タイムアウトしました。") exit(11) except RequestException as err: # TODO: logging で出力するように変更する。要学習。 print(err) exit(12) # XMLの解析と出力 # ------------------------------------------------------------------------------ root = ET.fromstring(response.text) num = 4 corp_info_list = [["法人番号", "最終更新年月日", "商号又は名称", "本店又は主たる事務所の所在地", "郵便番号", "商号又は名称(フリガナ)"]] if num >= len(root): # TODO: logging で出力するように変更する。要学習。 print("指定された法人番号(" + corp_number + ")のデータが存在しません。") else: while num < len(root): corp_info_list.append([root[num][1].text, root[num][4].text, root[num][6].text, root[num][9].text + root[num][10].text + root[num][11].text, sub(r'([0-9]{3})([0-9]{4})', r'\1-\2', root[num][15].text), root[num][28].text]) num += 1 for corp_info in corp_info_list[1:]: print("{0: <14} : {1}".format(corp_info_list[0][0], corp_info[0])) print("{0: <14} : {1}".format(corp_info_list[0][2], corp_info[2])) print("{0: <14} : {1}".format(corp_info_list[0][5], corp_info[5])) print("{0: <14} : {1}".format(corp_info_list[0][4], corp_info[4])) print("{0: <14} : {1}".format(corp_info_list[0][3], corp_info[3])) print("{0: <14} : {1}".format(corp_info_list[0][1], corp_info[1])) print("") try: with open('../log/corp_info.csv', 'w', encoding='utf-8') as csv_out: writer = csv.writer(csv_out, lineterminator='\n') writer.writerows(corp_info_list) except FileNotFoundError as err: # TODO: logging で出力するように変更する。要学習。 print(err) except PermissionError as err: # TODO: logging で出力するように変更する。要学習。 print(err) except csv.Error as err: # TODO: logging で出力するように変更する。要学習。 print(err) if __name__ == "__main__": # Web-API利用用アプリケーションIDの復号 if Path(argv[-1]).is_file(): api_key = decrypt_strings(ENC_API_KEY, argv[-1]) del argv[-1] else: api_key = decrypt_strings(ENC_API_KEY) # 入力された法人番号の確認 if not argv[1:]: # TODO: logging で出力するように変更する。要学習。 print("法人番号が指定されてません。") exit(1) else: for corp_number in argv[1:]: if not search("^[1-9][0-9]{12}$", corp_number): # TODO: logging で出力するように変更する。要学習。 print("法人番号は13桁で指定して下さい。") exit(2) elif not validate_number(corp_number): # TODO: logging で出力するように変更する。要学習。 print("指定された法人番号(" + corp_number + ")は正しくありません。") exit(3) # 法人番号から情報を取得する。 corp_numbers = ",".join(map(str, argv[1:])) get_corp_info(api_key, corp_numbers) exit(0)
25.715026
84
0.518638