language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
4,495
3.046875
3
[]
no_license
--- description: Свойство flex-basis определяет основу флекса, которая является начальным размером элемента --- # flex-basis Свойство **`flex-basis`** определяет основу флекса, которая является начальным размером элемента. Похоже на свойства [`width`](width.md) и [`height`](height.md), к которым добавляется содержимое элемента. ??? info "Flexbox и выравнивание" <div class="col3" markdown="1"> - [flex](flex.md) - **flex-basis** - [flex-direction](flex-direction.md) - [flex-flow](flex-flow.md) - [flex-grow](flex-grow.md) - [flex-shrink](flex-shrink.md) - [flex-wrap](flex-wrap.md) - [order](order.md) </div> <div class="col3" markdown="1"> - [justify-content](justify-content.md) - [align-content](align-content.md) - [place-content](place-content.md) - [justify-items](justify-items.md) - [align-items](align-items.md) - [place-items](place-items.md) - [justify-self](justify-self.md) - [align-self](align-self.md) - [place-self](place-self.md) - [row-gap](row-gap.md) - [column-gap](column-gap.md) - [gap](gap.md) </div> ## Синтаксис ```css /* Specify <'width'> */ flex-basis: 10em; flex-basis: 3px; flex-basis: auto; /* Intrinsic sizing keywords */ flex-basis: fill; flex-basis: max-content; flex-basis: min-content; flex-basis: fit-content; /* Automatically size based on the flex item’s content */ flex-basis: content; /* Global values */ flex-basis: inherit; flex-basis: initial; flex-basis: unset; ``` ## Значения Значение по-умолчанию: `auto` Наследуется: нет Применяется к флекс-элементам Анимируется: да `auto` : Указывает автоматический размер, основанный на содержимом элемента. `<ширина>` : Задаёт ширину элемента в `px`, `mm`, `pt` или в процентах. При этом размер вычисляется относительно родителя. Отрицательное значение недопустимо. ### Примечание Safari до версии 9 поддерживает свойство `-webkit-flex-basis`. ## Спецификации - [CSS Flexible Box Layout Module](https://www.w3.org/TR/css-flexbox/#propdef-flex-basis) ## Поддержка браузерами <p class="ciu_embed" data-feature="flexbox" data-periods="future_1,current,past_1,past_2"> <a href="http://caniuse.com/#feat=flexbox">Can I Use flexbox?</a> Data on support for the flexbox feature across the major browsers from caniuse.com. </p> ## Описание и примеры ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>flex-basis</title> <style> .flex-container { display: flex; /* Флексы */ height: 300px; /* Высота */ color: #fff; /* Белый цвет текста */ font-size: 2.6em; /* Размер шрифта */ flex-flow: column wrap; /* Располагаем в виде колонок */ } .flex-item { display: flex; /* Флексы */ align-items: center; /* Выравнивание текста по вертикали */ justify-content: center; /* Выравнивание текста по горизонтали */ } .one { background: #508694; /* Цвет фона */ margin-right: 10px; /* Отступ справа */ flex-basis: 100%; order: 1; /* Первый блок */ } .two { background: #bb844c; /* Цвет фона */ margin-bottom: 10px; /* Отступ снизу */ flex: 1 1 0; order: 2; /* Второй блок */ } .three { background: #929d79; /* Цвет фона */ flex: 1 1 0; order: 3; /* Третий блок */ } </style> </head> <body> <div class="flex-container"> <div class="flex-item one">Первый</div> <div class="flex-item two">Второй</div> <div class="flex-item three">Третий</div> </div> </body> </html> ``` ## См. также - [Руководство по Flexbox](/flex/)
Java
UTF-8
2,528
2.140625
2
[]
no_license
package com.pb.riskanalysisforsmb.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import com.pb.riskanalysisforsmb.AddressWithRisk; import com.pb.riskanalysisforsmb.R; import com.pb.riskanalysisforsmb.RiskProfileItem; import com.pb.riskanalysisforsmb.adaptor.CustomExpandableListAdapter; import com.pb.riskanalysisforsmb.adaptor.ExpandableListDataPump; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; public class MultipleAddressRiskProfileActivity extends AppCompatActivity implements View.OnClickListener { ExpandableListView expandableListView; ExpandableListAdapter expandableListAdapter; LinkedHashMap<RiskProfileItem, List<RiskProfileItem>> expandableListDetail; private Button submitBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multiple_address_risk_profile); expandableListView = (ExpandableListView) findViewById(R.id.expandableListView); ArrayList<AddressWithRisk> addressWithRisks = getIntent().getParcelableArrayListExtra ("ADDRESSES_WITH_RISKS"); expandableListDetail = ExpandableListDataPump.getData(addressWithRisks); expandableListAdapter = new CustomExpandableListAdapter(this, expandableListView, expandableListDetail); expandableListView.setAdapter(expandableListAdapter); // Locate the submitFileButton in activity layout submitBtn = (Button) findViewById(R.id.next_button); submitBtn.setOnClickListener(this); } @Override public void onClick(View v) { // do something when the button is clicked // Yes we will handle click here but which button clicked??? switch (v.getId()) { case R.id.next_button: Intent intent = new Intent(this, SummaryActivity.class); intent.putExtra("CRIME_RISK_SELECTED", ((CustomExpandableListAdapter)expandableListAdapter).isCrimeRiskChecked()); intent.putExtra("WEATHER_RISK_SELECTED", ((CustomExpandableListAdapter)expandableListAdapter).isWeatherRiskChecked()); intent.putExtra("PARENT", "MULTI"); startActivity(intent); break; default: break; } } }
Go
UTF-8
2,308
2.75
3
[ "Apache-2.0" ]
permissive
package trie import ( "fmt" "github.com/iotaledger/wasp/packages/kv/codec" ) type Refcounts struct { nodes KVStore values KVStore } func newRefcounts(store KVStore) *Refcounts { return &Refcounts{ nodes: makeKVStorePartition(store, partitionRefcountNodes), values: makeKVStorePartition(store, partitionRefcountValues), } } func (r *Refcounts) Inc(node *bufferedNode) (uint32, uint32) { nodeCount, valueCount := r.incNodeAndValue(node.nodeData) node.nodeData.iterateChildren(func(i byte, commitment Hash) bool { if _, ok := node.uncommittedChildren[i]; !ok { // the new node adds a reference to an "old" node n := r.incNode(commitment) assertf(n > 1, "inconsistency") } return true }) return nodeCount, valueCount } func (r *Refcounts) incNodeAndValue(node *NodeData) (uint32, uint32) { n := r.incNode(node.Commitment) v := uint32(0) if n == 1 && node.Terminal != nil && !node.Terminal.IsValue { v = incRefcount(r.values, node.Terminal.Data) } return n, v } func (r *Refcounts) incNode(commitment Hash) uint32 { return incRefcount(r.nodes, commitment[:]) } func (r *Refcounts) Dec(node *NodeData) (deleteNode, deleteValue bool) { n := decRefcount(r.nodes, node.Commitment[:]) deleteNode = n == 0 if n == 0 && node.Terminal != nil && !node.Terminal.IsValue { nv := decRefcount(r.values, node.Terminal.Data) deleteValue = nv == 0 } return } func (r *Refcounts) DebugDump() { fmt.Print("[node refcounts]\n") r.nodes.IterateKeys(func(k []byte) bool { n := getRefcount(r.nodes, k) fmt.Printf(" %x: %d\n", k, n) return true }) fmt.Print("[value refcounts]\n") r.values.IterateKeys(func(k []byte) bool { n := getRefcount(r.values, k) fmt.Printf(" %x: %d\n", k, n) return true }) } func incRefcount(s KVStore, key []byte) uint32 { n := getRefcount(s, key) n++ setRefcount(s, key, n) return n } func decRefcount(s KVStore, key []byte) uint32 { n := getRefcount(s, key) if n == 0 { panic("inconsistency: negative refcount") } n-- setRefcount(s, key, n) return n } func getRefcount(s KVStore, key []byte) uint32 { b := s.Get(key) if b == nil { return 0 } return codec.MustDecodeUint32(b) } func setRefcount(s KVStore, key []byte, n uint32) { if n == 0 { s.Del(key) } else { s.Set(key, codec.EncodeUint32(n)) } }
C++
UTF-8
673
2.953125
3
[]
no_license
#include <stdio.h> #define MAX 100 void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void hienmang(int a[], int n) { int i; for(i = 0; i < n; i++) { printf("%d\t", a[i]); } } void sapxepnoibot(int a[], int &n) { int kt; int i,j; for (i = 0; i < n - 1; i++) { kt = 0; for(j = 0; j < n - i -1; j++) { if(a[j] > a[j + 1]) { swap(a[i], a[j + 1]); kt = 1; } } if(kt == 0) break; printf("Buoc %d:", i + 1); hienmang(a,n); printf("\n"); } } int main() { int i, n, a[MAX]; scanf("%d", &n); for(i = 0; i < n; i++) { scanf("%d", &a[i]); } sapxepnoibot(a,n); return 0; }
C++
UTF-8
4,514
3.03125
3
[]
no_license
#include "GameObject.h" #include "TextureManager.h" GameObject::GameObject(TextureType Type, const sf::Vector2f& Position, std::shared_ptr<SoundManager> SoundManager, std::shared_ptr<TextureManager> TextureManager) : m_Position(Position), m_Velocity(sf::Vector2f(0.0f, 0.0f)), m_Accel(sf::Vector2f(0.0f, 0.0f)), m_Angle(0.0f), m_CollisionRadius(0.0f), m_Destroyed(false), m_DestroyedByPowerUp(false) { m_SoundManager = SoundManager; m_TextureManager = TextureManager; // Load the Texture and Assign the Sprite if (Type < TextureType::AMOUNT) { m_Sprite.setTexture(m_TextureManager->ReturnTexture(Type)); m_Sprite.setOrigin(m_Sprite.getTextureRect().width * 0.5f, m_Sprite.getTextureRect().height * 0.5f); // ^ Set Origin to the Center of the Sprite } } void GameObject::Update(sf::RenderWindow* Window, float DeltaTime) { float s_DecelScalar = 0.5f; // Rate of Deceleration m_Velocity += m_Accel * DeltaTime; LimitVelocity(DeltaTime); ApplyDrag(DeltaTime); /* Velocity, scaled by DeltaTime, is used to Manipulate the Position */ m_Position += m_Velocity * DeltaTime; /* Make sure nothing goes off screen to infinity */ if (m_Position.x < 0) // Left { m_Position.x = (float)Window->getSize().x; WentOffEdgeOfScreen(false); } else if (m_Position.x > Window->getSize().x) // Right { m_Position.x = 0; WentOffEdgeOfScreen(false); } if (m_Position.y < 0) // Top { m_Position.y = (float)Window->getSize().y; WentOffEdgeOfScreen(true); } else if (m_Position.y > Window->getSize().y) // Bottom { m_Position.y = 0; WentOffEdgeOfScreen(true); } // Rotate and then Manipulate Position m_Sprite.setRotation(m_Angle); m_Sprite.setPosition(m_Position); } void GameObject::Draw(sf::RenderWindow* Window) { Window->draw(m_Sprite); } void GameObject::LimitVelocity(float DeltaTime) { // Calculate the Magnitude of the Velocity Vector float s_Speed = std::sqrt(m_Velocity.x * m_Velocity.x + m_Velocity.y * m_Velocity.y); if (s_Speed <= 0.1f) { return; } // Normalize the Velocity Vector sf::Vector2f s_NormalizedVelocity = sf::Vector2f(m_Velocity.x / s_Speed, m_Velocity.y / s_Speed); if (s_Speed > 500) { s_Speed = 500; // Limit the Speed } m_Velocity.x = s_NormalizedVelocity.x * s_Speed; m_Velocity.y = s_NormalizedVelocity.y * s_Speed; } void GameObject::ApplyDrag(float DeltaTime) { // If you're not trying to move the Sprite if (m_Accel.x == 0.0f && m_Accel.y == 0.0f) { float s_DragAmount = DeltaTime * 0.9f; m_Velocity.x -= s_DragAmount * m_Velocity.x; m_Velocity.y -= s_DragAmount * m_Velocity.y; } } bool GameObject::IsColliding(GameObject* Other) { /* If the Object calling the "IsColliding()" Function Is not the Same as the Other "GameObject" AND if the Object calling the "IsColliding()" Function IS NOT Destroyed OR if the Other "GameObject" IS Destroyed */ if (this != Other && !IsDestroyed() || Other->IsDestroyed()) { sf::Vector2f s_VectorToOther; s_VectorToOther = Other->GetPosition() - this->GetPosition(); // Calculate the Magnitude of the s_VectorToOther Vector float s_Distance = std::sqrt(s_VectorToOther.x * s_VectorToOther.x + s_VectorToOther.y * s_VectorToOther.y); /* If the Distance Between the Two Objects is Less Than Both of the Objects Collision Radius */ if (s_Distance < m_CollisionRadius + Other->m_CollisionRadius) { return true; } } return false; } void GameObject::Destroy() { m_Destroyed = true; } bool GameObject::IsDestroyed() { return m_Destroyed; } void GameObject::SetOwner(PlayState* Owner) { m_Owner = Owner; } void GameObject::SetAngle(float Angle) { m_Angle = Angle; } float GameObject::GetAngle() { return m_Angle; } void GameObject::SetPosition(const sf::Vector2f& Position) { m_Position = Position; } void GameObject::SetAccel(float Amount) { if (Amount > 0.0f) { /* SFML Calculates in Radians Convert the Current Angle to Radians */ float s_RotationInRadians = DEG_TO_RAD * m_Angle; m_Accel = sf::Vector2f(Amount * std::sin(s_RotationInRadians), -Amount * cos(s_RotationInRadians)); } else { m_Accel = sf::Vector2f(0.0f, 0.0f); } } void GameObject::SetVelocity(float Amount) { if (Amount > 0.0f) { /* SFML Calculates in Radians Convert the Current Angle to Radians */ float s_RotationInRadians = DEG_TO_RAD * m_Angle; m_Velocity = sf::Vector2f(Amount * std::sin(s_RotationInRadians), -Amount * cos(s_RotationInRadians)); } else { m_Velocity = sf::Vector2f(0.0f, 0.0f); } }
Markdown
UTF-8
8,553
3.671875
4
[ "MIT" ]
permissive
> Hadoop中,键值对是最基本的操作对象。同样,Spark中,针对键值对类型的RDD有非常丰富的API可以被调用。利用这些API,可以比Hadoop更方便地完成大数据任务。 ## 1. 创建Pair RDD 创建Pair RDD的方法是让RDD中的每一项都是包含两个元素的tuple。前一个元素会被当成Key,后一个元素会被当成value。 ``` val pairs = sc.parallelize(List((1, 1), (2, 3))) ``` 另外,通过map操作生成tuple也是一种很常见的做法。 ```scala val pairs = lines.map(x => (x.split(" ")(0), x)) ``` ## 2. Pair RDD的转化操作 ### (1). 聚合操作 reduceByKey()可以实现对Pair RDD的相同键的元素进行聚合,注意这在普通RDD中是个行动操作,在这里是个转化操作。下面这个例子就可以实现单词记数了。 ```scala // 单词记数 val input = sc.textFile("s3://...") val words = input.flatMap(x => x.split(" ")) val result = words.map(x => (x, 1)).reduceByKey((x, y) => x + y) ``` 第一步,利用flatMap获取由每个单词组成的RDD,再利用Map得到Pair RDD,形式为(word, 1),再把每个相同word(key)对应的value累加,就得到了对应(word, number)的Pair RDD。 ----- combineByKey()和RDD中的aggregate()类似,不过要复杂的多。它的目的也是为了使得返回值类型和输入类型不同。比如求每个键对应的平均值,我们的输入是(word, value),现在我们要通过转化操作得到(word, (sum, num)),之后再进一步由sum/num得到平均值。 ```scala //使用combineByKey求每个键对应平均值 val input = sc.parallelize(List(('a',3),('b',4),('c',5),('a',1),('a',5),('c',1))) val result = input.combineByKey( (v) => (v, 1), (acc: (Int, Int), v) => (acc._1 + v, acc._2 + 1), (acc1: (Int, Int), acc2: (Int, Int)) => (acc1._1 + acc2._1, acc1._2 + acc2._2) ).map{ case (key, value) => (key, value._1 / value._2.toFloat) } result.collectAsMap().map(println(_)) ``` combineByKey接收三个函数作为参数,第一个函数是遇到第一次出现的Key时对Value进行的操作得到NewValue,第二个函数是遇到出现过的Key之后,对NewValue执行的reduce操作;第三个函数则是由于分区操作,对每个分区的中间结果也要进行reduce操作。 注意这里的map用了新的写法,这种形式可以记一下,对比较复杂的数据形式会比较好用。 最后出现的collectAsMap是把tuple转化成Map ----- 这里的大多数操作符都能接收第二个参数,这个参数用来指定分组结果或聚合结果的 RDD 的分区数,比如 ```scala sc.parallelize(data).reduceByKey((x, y) => x + y) ``` 此外还可以将RDD用repartion()来重新分区,并用partition.size获得分区数 ``` lines.repartition(10).partitions.size ``` ### (2). 分组操作 groupByKey() 就会使用 RDD 中的键来对数据进行 分组。对于一个由类型 K 的键和类型 V 的值组成的 RDD,所得到的结果 RDD 类型会是 [K, Iterable[V]]。 ```scala val input = sc.parallelize(List(('a',3),('b',4),('c',5),('a',1),('a',5),('c',1))) input.groupByKey().collect ``` 输出为 ```scala Array[(Char, Iterable[Int])] = Array((a,CompactBuffer(3, 1, 5)), (b,CompactBuffer(4)), (c,CompactBuffer(5, 1))) ``` ### (3). 连接 Scala还提供了许多API来实现数据库中的内连接外连接等操作,非常便捷。 下面用一些伪代码来举几个例子。 ``` storeAddress = { (Store("Ritual"), "1026 Valencia St"), (Store("Philz"), "748 Van Ness Ave"), (Store("Philz"), "3101 24th St"), (Store("Starbucks"), "Seattle")} storeRating = { (Store("Ritual"), 4.9), (Store("Philz"), 4.8))} storeAddress.join(storeRating) == { (Store("Ritual"), ("1026 Valencia St", 4.9)), (Store("Philz"), ("748 Van Ness Ave", 4.8)), (Store("Philz"), ("3101 24th St", 4.8))} storeAddress.leftOuterJoin(storeRating) == {(Store("Ritual"),("1026 Valencia St",Some(4.9))), (Store("Starbucks"),("Seattle",None)), (Store("Philz"),("748 Van Ness Ave",Some(4.8))), (Store("Philz"),("3101 24th St",Some(4.8)))} ``` ### (4) 排序 sortByKey()可以对RDD进行按key的排序 ## 3. Pair RDD行动操作 相比于普通RDD而言多了以下三个操作 - countByKey(),返回(key, number),其实可以直接用来实现wordcount - collectAsMap(),把tuple转化成Map - lookup(key),返回这个key的所有value ## 4. 数据分区(进阶) Spark 可以确保同一组的键出现在同一个节点上。 通过数据分区,我们可以对一些操作进行优化,比如下面这个操作。假设这个操作每五分钟执行一次,且events一直在改变。 ```scala val userData = sc.sequenceFile[UserID, UserInfo]("hdfs://...").persist() val joined = userData.join(events) ``` 默认情况下,连接操作会将两个数据集中的所有键的哈希值都求出来,将该哈希值相同的记录通过网络传到同一台机器上,然后在那台机器上对所有键相同的记录进行连接操作。想要优化,可以执行下面操作。 ```scala val userData = sc.sequenceFile[UserID, UserInfo]("hdfs://...") .partitionBy(new HashPartitioner(100)) // 构造100个分区 .persist() ``` 当调用 userData. join(events) 时,Spark 只会对 events 进行数据混洗操作,将 events 中特定UserID 的记录发送到 userData 的对应分区所在的那台机器上。 能够从数据分区中获益的操作有cogroup()、 groupWith()、join()、leftOuterJoin()、rightOuterJoin()、groupByKey()、reduceByKey()、 combineByKey() 以及 lookup()。 此外,我们还可以自定义分区的方式。 ## 5. 综合例子PageRank PageRank 算法是以 Google 的拉里· 佩吉(Larry Page)的名字命名的,用来根据外部文档指向一个 文档的链接,对集合中每个文档的重要程度赋一个度量值。该算法可以用于对网页进行排 序,当然,也可以用于排序科技文章或社交网络中有影响的用户。 直接上代码 ```scala import org.apache.spark.HashPartitioner var links = sc.parallelize(List((1,Seq(2,3,4)), (2,Seq(1,3)), (3,Seq(1)),(4,Seq(3)))).partitionBy(new HashPartitioner(100)).persist() // 将每个页面的排序值初始化为1.0;由于使用mapValues,生成的RDD // 的分区方式会和"links"的一样 var ranks = links.mapValues(v => 1.0) // 运行10轮PageRank迭代 for(i <- 0 until 10) { val contributions = links.join(ranks).flatMap { case (pageId, (links, rank)) => links.map(dest => (dest, rank / links.size)) } ranks = contributions.reduceByKey((x, y) => x + y).mapValues(v => 0.15 + 0.85*v) } // 写出最终排名 ranks.saveAsTextFile("ranks") ``` 数据准备,我们用最简单的数据来说明,links中的数据代表了:页面1中含有页面2,3,4的链接,以此类推。我们要做的任务是算出每个页面的重要程度。 我们把ranks初始化为1.o,因此会得到`rank = (1, 1.0), (2, 1.0), (3, 1.0), (4, 1.0)`。 算法的核心是一个迭代算法,一般迭代十次左右即可达到接近最优解。每次迭代是这样的: 1. 将每个页面的排序值初始化为 1.0。 2. 在每次迭代中,对页面 p,向其每个相邻页面(有直接链接的页面)发送一个值为 rank(p)/numNeighbors(p) 的贡献值。 3. 将每个页面的排序值设为0.15 + 0.85 * contributionsReceived。 下面我们来一步步分解核心操作的每一步得到了什么 ``` 1. 命令:links.join(ranks) 得到:Array((1,(List(2, 3, 4),1.0)), (2,(List(1, 3),1.0)), (3,(List(1),1.0)), (4,(List(3),1.0))) 2. 命令:links.join(ranks).flatMap { case (pageId, (links, rank)) => links.map(dest => (dest, rank / links.size)) } 得到:Array((2,0.33), (3,0.33), (4,0.33), (1,0.5), (3,0.5), (1,1.0), (3,1.0)) 3. 命令:ranks = contributions.reduceByKey((x, y) => x + y).mapValues(v => 0.15 + 0.85*v) 得到:Array((1,1.42), (2,0.43), (3,1.71), (4,0.43)) ``` 这里第二步比较难理解,我们看`links.map()这一步`,对第一个数据而言,links=(2,3,4),注意这里的map是在对List操作,不是RDD,所以links.size就是3。之后由于是flatMap,会把其中的Sequence给展开,就得到上面的结果。 执行十次之后,结果为: ``` 1,1.515645550066273 2,0.5816554333073632 3,1.3210435833189986 4,0.5816554333073632 ``` 可以看到第1个页面最为重要,第3个页面尽管被链接次数最多,但是在被第1个页面链接中占的权重太小。
Java
UTF-8
140
2.5
2
[]
no_license
package animals; public class Frog extends Animal { @Override protected String produceSound() { return "Frogggg"; } }
Ruby
UTF-8
1,083
2.765625
3
[ "BSD-3-Clause" ]
permissive
module Spree module Stock class Prioritizer attr_reader :packages, :order def initialize(order, packages, adjuster_class=Adjuster) @order = order @packages = packages @adjuster_class = adjuster_class end def prioritized_packages sort_packages adjust_packages prune_packages packages end private def adjust_packages order.line_items.each do |line_item| adjuster = @adjuster_class.new(line_item.variant, line_item.quantity, :on_hand) visit_packages(adjuster) adjuster.status = :backordered visit_packages(adjuster) end end def visit_packages(adjuster) packages.each do |package| item = package.find_item adjuster.variant, adjuster.status adjuster.adjust(item) if item end end def sort_packages # order packages by preferred stock_locations end def prune_packages packages.reject! { |pkg| pkg.empty? } end end end end
C++
UTF-8
3,364
2.9375
3
[]
no_license
//============================================================================ // Name : inverted.cpp // Author : Baoxing Li // Version : // Copyright : bl251@uowmail.edu.au / sID: 5083497 // Description : inverted in C++, Ansi-style //============================================================================ #include <iostream> #include <fstream> #include <string> #include <cstring> #include <set> #include <map> #include <iomanip> #include <iterator> #include <algorithm> using namespace std; class PostingList { friend ostream & operator<<(ostream &out, const PostingList &obj) { out << left << setw(2) << " ( " << obj.getFreq() << " ) "; copy(obj.docIDList.begin(), obj.docIDList.end(), ostream_iterator<int>(out, " ")); return out; } private: int freq; set<int> docIDList; public: PostingList() { freq = 0; docIDList.clear(); } ; void initPostingList(int d) { docIDList.clear(); docIDList.insert(d); freq = 1; } ; int getFreq() const { return freq; } ; void add(int d) { // insert docId into posting list // and increase freq if (docIDList.insert(d).second) freq++; } }; void showUsage() { cout << "Usage: ./inverted -c collection.txt -o inverted_index.txt" << endl; } ; int main(int argc, char **argv) { // cout << "lab01-task01" << endl; // prints lab01-task01 // default parameters //string infile = "collection.txt", outfile = "inverted_index.txt"; string infile, outfile; int pindex = 1; while (pindex < argc) { if (strcmp(argv[pindex], "-c") == 0) { pindex++; if (pindex < argc) { infile = argv[pindex++]; } else { showUsage(); return 1; } } else if (strcmp(argv[pindex], "-o") == 0) { pindex++; if (pindex < argc) { outfile = argv[pindex++]; } else { showUsage(); return 1; } } else { showUsage(); return 1; } } map<string, PostingList> DictPostings; map<string, PostingList>::iterator it; pair<map<string, PostingList>::iterator, bool> ret; string line, term; int docID; PostingList p; // generate dictionary & posting list fstream inf(infile.c_str(), ios::in); if (inf.is_open()) { while (!inf.eof()) { inf >> docID; getline(inf, line); // convert to lower case transform(line.begin(), line.end(), line.begin(), ::tolower); // split word size_t pos = line.find(" "); while (pos != string::npos) { term = line.substr(0, pos); if (term != "") { // insert into posting list p.initPostingList(docID); ret = DictPostings.insert( pair<string, PostingList>(term, p)); if (!ret.second) { // duplicate term, add to posting list // the container is set (unique, sorted) ret.first->second.add(docID); } } line.erase(0, pos + 1); pos = line.find(" "); } if (line != "") { term = line; p.initPostingList(docID); ret = DictPostings.insert(pair<string, PostingList>(term, p)); if (!ret.second) { // duplicate term, add to posting list // the container is set (unique, sorted) ret.first->second.add(docID); }; } } } else { cout << "cannot open file collection.txt" << endl; return 1; } // output fstream outf(outfile.c_str(), ios::out); for (it = DictPostings.begin(); it != DictPostings.end(); ++it) outf << left << setw(10) << it->first << it->second << '\n'; return 0; }
Java
UTF-8
6,205
2.296875
2
[]
no_license
import java.awt.Graphics2D; import java.awt.image.BufferedImage; import static java.awt.image.BufferedImage.TYPE_INT_ARGB; import static java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import static java.lang.Math.PI; import static java.lang.Math.abs; import static java.lang.Math.acos; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.floor; import static java.lang.Math.log; import static java.lang.Math.tan; import static java.lang.Math.exp; import static java.lang.Math.pow; import static java.lang.Math.sin; import static java.lang.Math.sqrt; import static java.lang.Thread.sleep; import javax.swing.ImageIcon; import javax.swing.JLabel; class Newton_gen extends Formula{ double []pr; double []pi; double bailin; double ar,ai; double rhoa,phia; double []rhop; double []phip; int highestnonzero; int K; public Newton_gen(){ NPars=8; pr=new double[6]; pi=new double[6]; rhop=new double[6]; phip=new double[6]; } @Override public void SetParameters(double[]pR,double[]pI){ bailin=pR[0]; ar=pR[1]; ai=pI[1]; rhoa=sqrt(ar*ar+ai*ai); phia=atan2(ai,ar); highestnonzero=0; for(int i=0;i<6;i++){ pr[i]=pR[i+2]; pi[i]=pI[i+2]; rhop[i]=sqrt(pr[i]*pr[i]+pi[i]*pi[i]); phip[i]=atan2(pi[i],pr[i]); if(rhop[i]!=0) highestnonzero=i; } } @Override public void SetStartingPoint(double x,double y){ zr[0]=x; zi[0]=y; //zrprev=ziprev=0; Niters=0; sig=fcon; } @Override public void Evolve(){ double rhoz=sqrt(zr[Niters]*zr[Niters]+zi[Niters]*zi[Niters]); double phiz=atan2(zi[Niters],zr[Niters]); double NumR,NumI; NumR=NumI=0; double DeNumR,DeNumI; DeNumR=DeNumI=0; for(int i=0;i<=highestnonzero;i++){ NumR+=rhop[i]*pow(rhoz,i)*cos(phip[i]+i*phiz); NumI+=rhop[i]*pow(rhoz,i)*sin(phip[i]+i*phiz); if(i>0){ DeNumR+=i*rhop[i]*pow(rhoz,i-1)*cos(phip[i]+(i-1)*phiz); DeNumI+=i*rhop[i]*pow(rhoz,i-1)*sin(phip[i]+(i-1)*phiz); } } double rhonum=sqrt(NumR*NumR+NumI*NumI); double phinum=atan2(NumI,NumR); double rhodenum=sqrt(DeNumR*DeNumR+DeNumI*DeNumI); double phidenum=atan2(DeNumI,DeNumR); double tx=zr[Niters]-rhoa*rhonum*cos(phia+phinum-phidenum)/rhodenum; double ty=zi[Niters]-rhoa*rhonum*sin(phia+phinum-phidenum)/rhodenum; zr[Niters+1]=tx; zi[Niters+1]=sig*ty; sig*=falt; Niters++; } @Override public boolean CheckExit(){ if(Niters==0) return true; return ((zr[Niters]-zr[Niters-1])*(zr[Niters]-zr[Niters-1])+(zi[Niters]-zi[Niters-1])*(zi[Niters]-zi[Niters-1])>bailin*bailin && Niters<maxiters); } @Override public double FinalSmoothingNorm(){ if(Niters<2) return Niters; double rho=sqrt((zr[Niters]-zr[Niters-1])*(zr[Niters]-zr[Niters-1])+(zi[Niters]-zi[Niters-1])*(zi[Niters]-zi[Niters-1])); double rhoprev=sqrt((zr[Niters-2]-zr[Niters-1])*(zr[Niters-2]-zr[Niters-1])+(zi[Niters-2]-zi[Niters-1])*(zi[Niters-2]-zi[Niters-1])); return Niters-1+log(1+log(bailin/rhoprev)/log(rho/rhoprev))/log(2); // return Niters-1+frac; } @Override public double GetRadiusForOrbit(){ return 1./bailin; } } class Rot_Newton_gen extends Formula{ double []pr; double []pi; double bailin; double ar,ai; double RotAngle; double ARA; double RotI,RotR; double rhoa,phia; double []rhop; double []phip; int sumrot; int mulrot; int highestnonzero; int K; public Rot_Newton_gen(){ NPars=12; pr=new double[8]; pi=new double[8]; rhop=new double[8]; phip=new double[8]; } @Override public void SetParameters(double[]pR,double[]pI){ bailin=pR[0]; ar=pR[1]; ai=pI[1]; rhoa=sqrt(ar*ar+ai*ai); phia=atan2(ai,ar); highestnonzero=0; for(int i=0;i<8;i++){ pr[i]=pR[i+2]; pi[i]=pI[i+2]; rhop[i]=sqrt(pr[i]*pr[i]+pi[i]*pi[i]); phip[i]=atan2(pi[i],pr[i]); if(rhop[i]!=0) highestnonzero=i; } RotAngle=pR[10]*PI; sumrot=(int)pR[11]; mulrot=1; if(sumrot==2) mulrot=2; if(sumrot>1) sumrot=1; } @Override public void SetStartingPoint(double x,double y){ zr[0]=x; zi[0]=y; //zrprev=ziprev=0; ARA=RotAngle; Niters=0; sig=fcon; } @Override public void Evolve(){ if(Niters>0){ ARA=mulrot*ARA+sumrot*RotAngle; } RotR=cos(ARA); RotI=sin(ARA); double zrlast=RotR*zr[Niters]-RotI*zi[Niters]; double zilast=RotR*zi[Niters]+RotI*zr[Niters]; double rhoz=sqrt(zrlast*zrlast+zilast*zilast); double phiz=atan2(zilast,zrlast); double NumR,NumI; NumR=NumI=0; double DeNumR,DeNumI; DeNumR=DeNumI=0; for(int i=0;i<=highestnonzero;i++){ NumR+=rhop[i]*pow(rhoz,i)*cos(phip[i]+i*phiz); NumI+=rhop[i]*pow(rhoz,i)*sin(phip[i]+i*phiz); if(i>0){ DeNumR+=i*rhop[i]*pow(rhoz,i-1)*cos(phip[i]+(i-1)*phiz); DeNumI+=i*rhop[i]*pow(rhoz,i-1)*sin(phip[i]+(i-1)*phiz); } } double rhonum=sqrt(NumR*NumR+NumI*NumI); double phinum=atan2(NumI,NumR); double rhodenum=sqrt(DeNumR*DeNumR+DeNumI*DeNumI); double phidenum=atan2(DeNumI,DeNumR); double tx=zr[Niters]-rhoa*rhonum*cos(phia+phinum-phidenum)/rhodenum; double ty=sig*(zi[Niters]-rhoa*rhonum*sin(phia+phinum-phidenum)/rhodenum); zr[Niters+1]=RotR*tx+RotI*ty; zi[Niters+1]=RotR*ty-RotI*tx; sig*=falt; Niters++; } @Override public boolean CheckExit(){ if(Niters==0) return true; return ((zr[Niters]-zr[Niters-1])*(zr[Niters]-zr[Niters-1])+(zi[Niters]-zi[Niters-1])*(zi[Niters]-zi[Niters-1])>bailin*bailin && Niters<maxiters); } @Override public double FinalSmoothingNorm(){ if(Niters<2) return Niters; double rho=sqrt((zr[Niters]-zr[Niters-1])*(zr[Niters]-zr[Niters-1])+(zi[Niters]-zi[Niters-1])*(zi[Niters]-zi[Niters-1])); double rhoprev=sqrt((zr[Niters-2]-zr[Niters-1])*(zr[Niters-2]-zr[Niters-1])+(zi[Niters-2]-zi[Niters-1])*(zi[Niters-2]-zi[Niters-1])); return Niters-1+log(1+log(bailin/rhoprev)/log(rho/rhoprev))/log(2); // return Niters-1+frac; } @Override public double GetRadiusForOrbit(){ return 1./bailin; } }
Shell
UTF-8
2,599
3.84375
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # Copyright 2019 Cloudera, 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. basedir="$(dirname "$0")" CONF_FILE="configs.properties" if [ ! -f ${CONF_FILE} ]; then echo "${CONF_FILE} is missing in current directory!" exit 1 fi SERVICE=`cat ${CONF_FILE} | grep service | cut -d "=" -f 2` SECRET=`cat ${CONF_FILE} | grep secret | cut -d "=" -f 2` NAMESPACE=`cat ${CONF_FILE} | grep namespace | cut -d "=" -f 2` delete_resources() { kubectl delete -f server.yaml kubectl delete -n ${NAMESPACE} secret ${SECRET} kubectl delete -n ${NAMESPACE} certificatesigningrequest.certificates.k8s.io ${SERVICE}.${NAMESPACE} rm -rf server.yaml return 0 } create_resources() { KEY_DIR=$1 # Generate keys into a temporary directory. ${basedir}/generate-signed-ca.sh "${KEY_DIR}" # Create the yunikorn namespace. echo "Creating namespace ${NAMESPACE}" kubectl create namespace ${NAMESPACE} &> /dev/null # Create the TLS secret for the generated keys. kubectl create secret generic ${SECRET} \ --from-file=key.pem=${KEY_DIR}/server-key.pem \ --from-file=cert.pem=${KEY_DIR}/server-cert.pem \ --namespace=${NAMESPACE} # Replace the certificate in the template with a valid CA parsed from kube-config ca_pem_b64=$(kubectl config view --raw --flatten -o json | jq -r '.clusters[] | select(.name == "'$(kubectl config current-context)'") | .cluster."certificate-authority-data"') sed -e 's@${CA_PEM_B64}@'"$ca_pem_b64"'@g' <"${basedir}/server.yaml.template" > server.yaml kubectl create -f server.yaml echo "The webhook server has been deployed and configured!" return 0 } usage() { echo "usage: ${0} [OPTION]" echo " create" echo " Create admission controller and other related resources" echo " delete " echo " Delete all resources previously created" } if [ $# -eq 1 ] && [ $1 == "delete" ]; then delete_resources exit $? elif [ $# -eq 1 ] && [ $1 == "create" ]; then KEY_DIR="$(mktemp -d)" create_resources ${KEY_DIR} rm -rf "$keydir" exit $? else usage exit 1 fi
JavaScript
UTF-8
103
3.140625
3
[]
no_license
let numbers = [1,2,3,4,5,6,]; let doubled = numbers.map((number) => number * 2); console.log(doubled);
Java
UTF-8
13,493
2.46875
2
[ "Apache-2.0" ]
permissive
/** */ package housebuilderV2.util; import housebuilderV2.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see housebuilderV2.HousebuilderV2Package * @generated */ public class HousebuilderV2Switch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static HousebuilderV2Package modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public HousebuilderV2Switch() { if (modelPackage == null) { modelPackage = HousebuilderV2Package.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case HousebuilderV2Package.HOUSE: { House house = (House)theEObject; T result = caseHouse(house); if (result == null) result = caseNamed(house); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.NAMED: { Named named = (Named)theEObject; T result = caseNamed(named); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.FLOOR: { Floor floor = (Floor)theEObject; T result = caseFloor(floor); if (result == null) result = caseNamed(floor); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.SPACE: { Space space = (Space)theEObject; T result = caseSpace(space); if (result == null) result = caseNamed(space); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.ROOM: { Room room = (Room)theEObject; T result = caseRoom(room); if (result == null) result = caseSpace(room); if (result == null) result = caseNamed(room); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.PASSAGE: { Passage passage = (Passage)theEObject; T result = casePassage(passage); if (result == null) result = caseDoor(passage); if (result == null) result = caseNamed(passage); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.CONTROLLER: { Controller controller = (Controller)theEObject; T result = caseController(controller); if (result == null) result = caseNamed(controller); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.ACTUATOR: { Actuator actuator = (Actuator)theEObject; T result = caseActuator(actuator); if (result == null) result = caseNamed(actuator); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.SENSOR: { Sensor sensor = (Sensor)theEObject; T result = caseSensor(sensor); if (result == null) result = caseNamed(sensor); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.DEVICE: { Device device = (Device)theEObject; T result = caseDevice(device); if (result == null) result = caseNamed(device); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.WINDOW: { Window window = (Window)theEObject; T result = caseWindow(window); if (result == null) result = caseNamed(window); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.EXTERNAL_SPACE: { ExternalSpace externalSpace = (ExternalSpace)theEObject; T result = caseExternalSpace(externalSpace); if (result == null) result = caseSpace(externalSpace); if (result == null) result = caseNamed(externalSpace); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.DOOR: { Door door = (Door)theEObject; T result = caseDoor(door); if (result == null) result = caseNamed(door); if (result == null) result = defaultCase(theEObject); return result; } case HousebuilderV2Package.ENTRANCE: { Entrance entrance = (Entrance)theEObject; T result = caseEntrance(entrance); if (result == null) result = caseDoor(entrance); if (result == null) result = caseNamed(entrance); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>House</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>House</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseHouse(House object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Named</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Named</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNamed(Named object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Floor</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Floor</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFloor(Floor object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Space</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Space</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSpace(Space object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Room</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Room</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseRoom(Room object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Passage</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Passage</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T casePassage(Passage object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Controller</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Controller</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseController(Controller object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Actuator</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Actuator</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseActuator(Actuator object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Sensor</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Sensor</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseSensor(Sensor object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Device</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Device</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDevice(Device object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Window</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Window</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseWindow(Window object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>External Space</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>External Space</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseExternalSpace(ExternalSpace object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Door</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Door</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseDoor(Door object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Entrance</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Entrance</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseEntrance(Entrance object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //HousebuilderV2Switch
Java
UTF-8
984
2.40625
2
[]
no_license
package com.trojanmd.domain; import javax.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; @Entity public class Membership { @Id @GeneratedValue private Long id; @Temporal(TemporalType.DATE) private Date beginTime; @Temporal(TemporalType.DATE) private Date endTime; @OneToOne(mappedBy = "membership") private User user; public Membership(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getBeginTime() { return beginTime; } public void setBeginTime(Date beginTime) { this.beginTime = beginTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
PHP
UTF-8
2,033
2.921875
3
[ "MIT" ]
permissive
<?php /** * Fuel is a fast, lightweight, community driven PHP 5.4+ framework. * * @package Fuel * @version 1.8.2 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2019 Fuel Development Team * @copyright 2008 - 2009 Kohana Team * @link https://fuelphp.com */ namespace Fuel\Core; class Database_MySQLi_Result extends \Database_Result { /** * Sets the total number of rows and stores the result locally. * * @param mixed $result query result * @param string $sql SQL query * @param mixed $as_object object */ public function __construct($result, $sql, $as_object) { parent::__construct($result, $sql, $as_object); // Find the number of rows in the result $this->_total_rows = $result->num_rows; } /** * Result destruction cleans up all open result sets. * * @return void */ public function __destruct() { if ($this->_result instanceof \MySQLi_Result) { $this->_result->free(); } } /** * Get a cached database result from the current result iterator. * * $cachable = serialize($result->cached()); * * @return Database_PDO_Cached */ public function cached() { return new \Database_MySQLi_Cached($this->_result, $this->_query, $this->_as_object); } /************************** * Iterable methods *************************/ /** * Implements [Iterator::next], returns the next row. * * @return mixed */ public function next() { // Convert the result into an array, as PDOStatement::rowCount is not reliable if ($this->_as_object === false) { $this->_row = $this->_result->fetch_array(MYSQLI_ASSOC); } elseif (is_string($this->_as_object)) { $this->_row = $this->_result->fetch_object($this->_as_object); } else { $this->_row = $this->_result->fetch_object(); } // sanitize the data if needed if ($this->_sanitization_enabled) { $this->_row = \Security::clean($result, null, 'security.output_filter'); } return $this->_row; } }
C++
UTF-8
1,928
2.625
3
[]
no_license
#include "thFont.h" #include "thWindow.h" thFont::thFont( thWindow & a_Parent) : m_Parent( a_Parent) { } thFont::~thFont() { if ( m_sFont) { BOOL fResult = DeleteObject( m_sFont); if ( TRUE != fResult) { MSG_ERROR( TEXT( "DeleteObject failed with error = 0x%X"), GetLastError()); } } } void thFont::set() { // delete current font (if exist) if ( m_sFont) { BOOL fResult = DeleteObject( m_sFont); if ( TRUE != fResult) { MSG_ERROR( TEXT( "DeleteObject failed with error = 0x%X"), GetLastError()); } else { m_sFont = NULL; } } if ( NULL == m_sFont) { // Create Default Font m_sFont = CreateFontIndirect( &this->m_sLogicalFont); if ( m_sFont) { // set new font SendMessage( m_Parent.GetHandle(), WM_SETFONT, reinterpret_cast< WPARAM>( m_sFont), static_cast< LPARAM>( TRUE)); } else { MSG_ERROR( TEXT( "CreateFontIndirect failed with error = 0x%X"), GetLastError()); } } else { MSG_ERROR( TEXT( "Failed to set new font!")); } } void thFont::SetName( const thString & a_fontName) { SecureZeroMemory( this->m_sLogicalFont.lfFaceName, LF_FACESIZE); _tcscpy_s( this->m_sLogicalFont.lfFaceName, LF_FACESIZE, a_fontName.c_str()); this->set(); } // set size in point void thFont::SetSize( uint32_t a_newsize) { HDC hDevContext = GetDC(NULL); // Calcuate font size to point format this->m_sLogicalFont.lfHeight = -MulDiv(a_newsize, GetDeviceCaps(hDevContext, LOGPIXELSY), 72); // If you want constant font size in pixels for all DPI then you should use this: // nHeight = MulDiv(PointSize, 96, GetDeviceCaps(hDC, LOGPIXELSY)); // 96 is current dpi ReleaseDC(NULL, hDevContext); this->set(); }
C
GB18030
1,671
3.8125
4
[]
no_license
#include <stdio.h> #include "../../../Algorithms/01_abstract/Status.h" //**01_abstract**// #include "../../../Algorithms/06_tree_binaryTree/07 ChildSiblingTree/ChildSiblingTree.c" //**06 Ͷ**// /* Funcԭ */ void Algo_6_71_1(CSTree T, int i); void Algo_6_71_2(CSTree T, int i); int main(int argc, char *argv[]) { CSTree T; FILE *fp; printf("УABE^F^^CG^^D^^^...\n"); InitTree_CS(&T); fp = fopen("Data/Algo_6_71.txt", "r"); CreateTree_CS(fp, &T); fclose(fp); printf("\n"); printf("TΪ\n"); Print_CS(T); printf("\n"); printf(" 1ӡ\n"); Algo_6_71_1(T, 0); printf("\n"); printf(" 2ӡ\n"); Algo_6_71_2(T, 0); printf("\n"); return 0; } /* 6.71ӡ */ /* 1ֱʹõݹ */ void Algo_6_71_1(CSTree T, int i) //iʼΪ0 { int j; if (T) { for (j = 1; j <= 2 * i; j++) { printf(" "); } printf("%c\n", T->data); Algo_6_71_1(T->firstchild, i + 1); Algo_6_71_1(T->nextsibling, i); //˴Ϊi } } /* 2ѭʹõݹ */ void Algo_6_71_2(CSTree T, int i) { int j; CSTree p; if (T) { for (j = 1; j <= 2 * i; j++) { printf(" "); } printf("%c\n", T->data); for (p = T->firstchild; p; p = p->nextsibling) { Algo_6_71_2(p, i + 1); } } }
Markdown
UTF-8
3,630
3.5
4
[]
no_license
## ConcurrentHashMap ## Fork/Join 框架 Fork/Join框架是Java 7提供的一个用于并发执行任务的框架。 Fork/Joing框架可以把一个大任务分割成若干个小任务,最终汇总每一个小人物结果得到大人物结果 ### 1.工作窃取算法 工作窃取算法是指某个线程从其他队列里窃取任务来进行。 将任务分割成若干个子任务,将这些子任务分别放到不同的队列里,并为每个队列创建一个单独的线程来执行队列里的任务。 这个线程每次都从队首获取任务执行。 如果某个子任务队列,其线程执行完了这个队列里的所有任务,它就会去其他线程的队列里窃取一个任务来执行,从这个队列的尾部获取任务执行。 **优点**:充分利用线程进行并行计算,减少了线程间的计算。 **缺点**:在某些情况下还是存在竞争,比如双端队列种只有一个任务时,该算法会消耗更多的系统资源。 ### 2.Fork/Join框架的设计 1. 分割任务。 2. 执行任务并合并结果 Fork/Join使用两个类来完成以上两件事。 1. ForkJoinTask:Fork/Join任务提供了在任务种执行fork()和join()操作的机制,通常情况下只需要继承它的子类来创建响应的Fork/Join任务。 * RecursiveAction:用于没有返回结果的任务 * RecursiveTask:用于有返回结果的任务 2. ForkJoinPool:ForkJoinTask需要通过ForkJoinPool来执行。 任务分割出的子任务会添加到当前工作线程锁维护的双端队列中,进入队列的头部,当一个线程的队列里没有任务时,将会从其他线程的队列的尾部获取一个任务 ### 3.使用Fork/Join框架 **案例:使用Fork/Join框架计算1+2+3+4** ```java public class Demo { public static void main(String[] args) { ForkJoinPool forkJoinPool = new ForkJoinPool(); AddCountTask task = new AddCountTask(1,4); ForkJoinTask<Integer> submit = forkJoinPool.submit(task); try { System.out.println(submit.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } class AddCountTask extends RecursiveTask<Integer>{ private static final int THRESHOLD = 2;//最小任务数 private int start;//任务开始 private int end;//任务结束 public AddCountTask(int start, int end) { this.start = start; this.end = end; } @Override protected Integer compute() { int sum = 0; //判断当前任务是否小于最小阈值 boolean canCompute = (end-start) <= THRESHOLD; //如果任务已经最小了,开始计算任务 if(canCompute){ for (int i = start; i <=end ; i++) { sum += i ; } }else {//如果任务大于阈值,分裂成两个任务计算 int middle = (start+end)/2; //分成两个子任务 AddCountTask left = new AddCountTask(start,middle); AddCountTask right = new AddCountTask(middle + 1, end); //执行任务 left.fork(); right.fork(); //合并结果 sum = left.join()+right.join(); } return sum; } } ``` ### Fork/Join框架的异常处理 ### 5.Fork/Join框架的实现原理 ForkJoinPool由ForkJoinTask数组和ForkJoinWorkerThread数组组成。 ForkJoinTask数组负责将存放程序提交给ForkJoinPool任务,而ForkJoinWorkerThread负责执行这些任务
Python
UTF-8
1,246
3.21875
3
[]
no_license
import timeit from random import randint, shuffle import matplotlib.pyplot as plt def geraLista(tam): lista = list(range(1, tam + 1)) shuffle(lista) return lista def desenhaGrafico(x,lista1,xl = "Entradas", yl = "Y",name="out", label1 = "Lista 1", label2 = "Lista 2"): fig = plt.figure(figsize=(10, 8)) ax = fig.add_subplot(111) ax.plot(x, lista1, label = label1) ax.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure) plt.ylabel(yl) plt.xlabel(xl) plt.savefig(name) def sort(lista): radix(lista) def radix(lista): base = 1 maxim = max(lista) while maxim/base > 0: v = len(lista) + 1 aux = [0] * v for i in lista: aux[i] += 1 y = 0 for i in range(v): for j in range(aux[i]): lista[y] = i y += 1 base *= 10 quant = [100000,200000,400000,500000,1000000,2000000] graf_tempo = [] for i in range(len(quant)): print(quant[i]) lista = geraLista(quant[i]) graf_tempo.append(timeit.timeit("sort({})".format(lista),setup="from __main__ import sort",number=1)) desenhaGrafico(quant,graf_tempo,"Tamanho", "Tempo", "saida_time", label1 = "Lista")
Python
UTF-8
5,239
2.9375
3
[]
no_license
from selenium import webdriver from selenium.webdriver.chrome.options import Options from time import sleep import csv from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import ElementClickInterceptedException class Tag():#用于保存计数好的标签 '''标签类''' def __init__(self,dic = {}): self.dic = dic #完整标签字典,用于分类统计用 self.dic0 = {'其他':0} #不完整标签字典,用于简化汇总用 def reset(self): '''用于再次将数据整理''' '''标签数小于等于2的归类为其他''' for key,value in self.dic.items(): if value <= 2: self.dic0['其他'] += value else: self.dic0[key] = value class Data():#数据类,爬取相关内容并保存 def __init__(self,url,browser): self.url = url self.browser = browser self.cbox = [] #用户创建歌单 self.sbox = [] #用户收藏歌单 self.tags = Tag() #用户歌单的标签及数据 def write_data_csv(self,filename,lists): '''名称写入csv文件,方便用户查看''' with open(filename+'.csv','w',encoding = 'utf-8-sig',newline = '') as f: i = 1; writer = csv.writer(f) writer.writerow([str(filename)]) for ment in lists: writer.writerow([str(i),ment.get_attribute('title')]) i+= 1; f.close() def write_data_txt(self,filename,lists): '''名称写入txt文件,方便后续处理''' with open(filename+'.txt','w',encoding = 'utf-8') as f: for ments in lists: f.write(ments.get_attribute('title')+'\n') def getin_pages(self): #进入网页爬取信息 '''数据部分''' id0 ='g_iframe' per = 10 #用于向下滚动页面加载 '''操作部分''' #模拟访问操作 self.browser.get(self.url) self.browser.switch_to.frame(id0)#进入需要访问的内页 #模拟鼠标向下滚动加载 for i in range(per): self.browser.execute_script('window.scrollTo(0,document.body.scrollHeight)') sleep(2)#每个页面两秒时间加载 def get_cbox(self): '''获取用户创建的歌单并写入文件''' self.cbox = self.browser.find_elements_by_css_selector('#cBox li a[class = "tit f-thide s-fc0"]') filename = '用户创建的歌单列表' self.write_data_csv(filename,self.cbox) self.write_data_txt(filename,self.cbox) def get_sbox(self): '''获取用户收藏的歌单并写入文件''' self.sbox = self.browser.find_elements_by_css_selector('#sBox li a[class = "tit f-thide s-fc0"]') filename = '用户收藏的歌单列表' self.write_data_csv(filename,self.sbox) self.write_data_txt(filename,self.sbox) def get_moreinfo(self): '''获取与歌单更详细的信息内容''' id0 ='g_iframe' #i = 0 s_news = []#收藏歌单的子页面的url for li in self.sbox:#需要另保存在一个列表里,因为会存在过时问题 newurl = str(li.get_attribute('href'))#这是歌单的网址 s_news.append(newurl) for li in s_news: self.browser.get(li) self.browser.switch_to.frame(id0) self.get_tags() self.get_desc() #i+=1 def get_tags(self): '''获取用户创建和收藏歌单的标签''' with open("tag.txt","a",encoding = 'utf-8') as f: try: lis = self.browser.find_elements_by_css_selector('.u-tag i') except NoSuchElementException: pass else: for li in lis: text = li.text.strip('\n')#删掉换行符 #self.tags.append(text) if text in self.tags.dic: self.tags.dic[text] += 1 else: self.tags.dic[text] = 1 f.write(li.text+'\n') def get_desc(self): '''获取用户创建和收藏歌单的简介''' with open('desc.txt','a',encoding = 'utf-8') as f: #判断内容是否需要展开 try: check = self.browser.find_element_by_css_selector('#album-desc-spread') except NoSuchElementException: pass else: self.browser.execute_script('window.scrollTo(0,document.body.scrollHeight)') #browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')#防止按钮覆盖问题 if check.text.endswith('展开'): check.click() #sleep(2) #判断是否有简介信息 try: des = self.browser.find_element_by_css_selector('#album-desc-more') except NoSuchElementException: pass else: f.write(des.text+'\n\n') def get_infor(): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') url = input('请输入用户的网易云音乐主页网址:') browser = webdriver.Chrome(options = chrome_options)#使用谷歌浏览器 data = Data(url,browser) data.getin_pages() data.get_cbox() data.get_sbox() data.get_moreinfo() print('over') browser.close() return data def main(): chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') url = input('请输入用户的网易云音乐主页网址:') browser = webdriver.Chrome(options = chrome_options)#使用谷歌浏览器 data = Data(url,browser) data.getin_pages() data.get_cbox() data.get_sbox() data.get_moreinfo() print('over') for key,values in data.tags.dic.items(): print(str(key)+":"+str(values)) browser.close() if __name__ == '__main__': '''不弹出页面进行网页爬虫''' main()
Java
UTF-8
778
1.875
2
[]
no_license
package com.ayc.service.app.dao.mapper; import com.ayc.framework.dao.IBaseMapper; import com.ayc.service.app.entity.QuestionEntity; import com.ayc.service.app.entity.QuestionEntityWithBLOBs; import java.util.List; public interface QuestionEntityMapper extends IBaseMapper { int deleteByPrimaryKey(Integer id); int insert(QuestionEntityWithBLOBs record); int insertSelective(QuestionEntityWithBLOBs record); QuestionEntityWithBLOBs selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(QuestionEntityWithBLOBs record); int updateByPrimaryKeyWithBLOBs(QuestionEntityWithBLOBs record); int updateByPrimaryKey(QuestionEntity record); /** * 获取问答列表 * @return */ List<QuestionEntity> listQuestions(); }
Java
UTF-8
113
1.90625
2
[]
no_license
package homework.Unit2.Task3.interfaces; public interface CanErase extends OfficeSupplies { void erase(); }
Java
UTF-8
1,688
3.625
4
[]
no_license
package Offer; /**复杂链表的额复制 * 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) */ public class ReplicationOfComplexLinkedList { public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } public RandomListNode Clone(RandomListNode pHead) { if (pHead == null) return null; RandomListNode head1 = pHead; while (head1 != null) { RandomListNode next = head1.next; head1.next = new RandomListNode(head1.label); head1.next.next = next; head1 = head1.next.next; } RandomListNode head2 = pHead; while (head2 != null) { if (head2.random == null) head2.next.random = null; else head2.next.random = head2.random.next; head2 = head2.next.next; } RandomListNode head3 = pHead; RandomListNode node = head3.next; RandomListNode res = node; while (head3 != null) { head3.next = head3.next.next; head3 = head3.next; if (head3 == null) node.next = null; else { node.next = head3.next; node = node.next; } } return res; } }
PHP
UTF-8
3,721
2.796875
3
[]
no_license
<?php class RadnikController extends AdminController { private $viewDir = 'privatno' . DIRECTORY_SEPARATOR . 'radnik' . DIRECTORY_SEPARATOR; public function index() { $radnici= Radnik::ucitajSve(); foreach($radnici as $radnik){ if(strlen($radnik->lozinka)>20){ $radnik->lozinka= substr($radnik->lozinka,0,20) . '...'; } if(strlen($radnik->komentar)===0){ $radnik->komentar= 'Nema komentar'; } if(strlen($radnik->komentar)>20){ $radnik->komentar=substr($radnik->komentar,0,20) . '...'; } } $this->view->render($this->viewDir . 'index',[ 'radnici'=>$radnici ]); } public function novo() { if ($_SERVER['REQUEST_METHOD']==='GET'){ $radnik=new stdClass(); $radnik->ime=''; $radnik->prezime=''; $radnik->email='@sdfgroup.com'; $radnik->lozinka=''; $radnik->komentar=''; $radnik->radnomjesto=''; $this->novoView('Unesite tražene podatke',$radnik); return; } // radi se o POST i moram kontrolirati prije unosa u bazu // kontroler mora kontrolirat vrijednosti prije nego se ode u bazu $radnik=(object)$_POST; //kontrole jel dobro ukucano if(!$this->kontrolaIme($radnik,'novoView')){return;}; if(!$this->kontrolaPrezime($radnik,'novoView')){return;}; Radnik::dodajNovi($_POST); // unese i prebaci me na popis radnika $this->index(); //unese i ostavi te s svim podacima na trenutnoj stranici //$this->novoView('radnik unesen, nastavite s unosom novih podataka',$_POST); } public function promjena() { if ($_SERVER['REQUEST_METHOD']==='GET'){ //print_r(Radnik::ucitaj($_GET['id'])); $this->promjenaView('Promjenite željene podatke', Radnik::ucitaj($_GET['id'])); return; } $radnik=(object)$_POST; //kontrole jel dobro ukucano if(!$this->kontrolaIme($radnik,'promjenaView')){return;}; if(!$this->kontrolaPrezime($radnik,'promjenaView')){return;}; Radnik::promjena($_POST); $this->index(); } public function brisanje() { //kontrola dali je id došao Radnik::brisanje($_GET['id']); $this->index(); } private function novoView($poruka,$radnik) { $this->view->render($this->viewDir . 'novo',[ 'poruka' => $poruka, 'radnik' => $radnik ]); } private function promjenaView($poruka,$radnik) { $this->view->render($this->viewDir . 'promjena',[ 'poruka' => $poruka, 'radnik' => $radnik ]); } //kontrole jel dobro ukucano vidi još gore if ima private function kontrolaIme($radnik,$view) { if(strlen(trim($radnik->ime))===0){ $this->$view('Obavezno unos imena', $radnik); return false; } if(strlen(trim($radnik->ime))>20){ $this->$view('Duzina imena prevelika', $radnik); return false; } // na kraju uvijek vrati true return true; } private function kontrolaPrezime($radnik,$view) { if(strlen(trim($radnik->prezime))===0){ $this->$view('Obavezno unos prezimena', $radnik); return false; } if(strlen(trim($radnik->prezime))>20){ $this->$view('Duzina prezimena prevelika', $radnik); return false; } // na kraju uvijek vrati true return true; } }
Java
UTF-8
364
2.71875
3
[]
no_license
/** * Creates a new instance of a menu object, then uses said object, menu, to * run method select * * @author Geovany Felix * @since February 2021 */ public class AddressBookApplication { /** * * @param args collection of Strings */ public static void main(String args[]){ Menu menu = new Menu(); menu.select(); } }
C
UTF-8
5,288
2.875
3
[ "MIT" ]
permissive
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/types.h> #include<sys/wait.h> #include"Config.h" #include"Tool.h" int argc; char** argv; const char* tip = "HelloShell"; int pipeNum; int shouldExit = 0; // 程序初始化 void Init(){ argc = 0; argv = calloc(ARGV_MAXIMUM_LENGTH, sizeof(char*)); for( int i = 0 ; i < ARGV_MAXIMUM_LENGTH ; i++ ){ argv[i] = calloc(ARG_MAXIMUM_SIZE, sizeof(char) ); } pipeNum = 0; } // 程序退出前执行 void Clean(){ pipeNum = 0; for( int i = 0 ; i < ARGV_MAXIMUM_LENGTH ; i++ ){ if(argv[i] != NULL) free(argv[i]); argv[i] = NULL; } free(argv); argv = NULL; } // 每次输入前的初始化 void InitBeforeInput(){ argc = 0; pipeNum = 0; } // 输出提示语 void OutputTip(){ // 输出提示语 char pwd[1024]; getcwd(pwd, sizeof(pwd)); sprintf(pwd, "%s/%s$ ", tip, pwd); fputs(pwd, stdout); } // 检查管道数目 void CheckPipeNum(){ for( int i = 0 ; i < argc ; i++ ){ if( strcmp(argv[i], "|") == 0 ){ pipeNum++; } } } int CheckIsSpecialCommand(char* file, char** argv){ // 判断是否为特殊命令 if( strcmp(file,"cd") == 0 ){ chdir(argv[1]); return 0; }else if( strcmp(file, "exit") == 0 ){ shouldExit = 1; return 0; } return -1; } void HandleNonPipe( char* file, char** argv ){ if(CheckIsSpecialCommand(file, argv) == 0) return; pid_t pid = fork(); if( pid < 0 ){ fprintf(stderr, "Error to fork!\n"); }else if( pid == 0 ){ execvp(file, argv); printf("Error on %s\n", file); exit(0); }else{ waitpid(pid, NULL, 0); } return; } void HandlePipe( int* argcs, char*** argvs, int* pfd, int curProcessNum, int processNum ){ if( curProcessNum == -1 ) return; int pfd_next[2]; pipe(pfd_next); pid_t firstProcess = fork(); if( firstProcess < 0 ){ }else if( firstProcess == 0 ){ close(pfd[0]); if( curProcessNum != processNum -1 ) dup2(pfd[1],1); else close(pfd[1]); close(pfd_next[1]); if( curProcessNum != 0 ) dup2(pfd_next[0],0); else close(pfd_next[0]); execvp(argvs[curProcessNum][0], argvs[curProcessNum]); }else{ HandlePipe(argcs, argvs, pfd_next, curProcessNum-1, processNum); } } void HandleWithPipe(int argc, char** argv){ // 进程数是管道符数量加一 int processNum = pipeNum + 1; // 为每个线程的参数作准备 int* argcs = calloc(processNum, sizeof(int)); for( int i = 0 ; i < processNum ; i++ ){ argcs[i] = 0; } char*** argvs = calloc(processNum, sizeof(char*)); for( int i = 0 ; i < processNum ; i++ ){ argvs[i] = calloc(ARGV_MAXIMUM_LENGTH, sizeof(char*)); for( int j = 0 ; j < ARGV_MAXIMUM_LENGTH ; j++ ){ argvs[i][j] = calloc(ARG_MAXIMUM_SIZE, sizeof(char)); } } // 分割每个进程的参数 for( int i = 0, j = 0 ; i < processNum ; i++ ){ while( j < argc && strcmp(argv[j],"|") != 0 ){ strcpy( argvs[i][argcs[i]], argv[j]); argcs[i]++; j++; } argvs[i][argcs[i]] = NULL; j++; } pid_t pid = fork(); if( pid < 0 ){ }else if( pid == 0 ){ int pfd[2]; pipe(pfd); HandlePipe(argcs, argvs, pfd, processNum - 1, processNum); exit(0); }else{ waitpid(pid, NULL, 0); } // @TODO: 防止内存泄露 free(argcs); argcs = NULL; for( int i = 0 ; i < processNum ; i++ ){ free(argvs[i]); argvs[i] = NULL; } free(argvs); argvs = NULL; } int main(){ Init(); char input[ARG_MAXIMUM_SIZE]; while( !shouldExit ){ // 判断是否结束 InitBeforeInput(); // 进行初始化 OutputTip(); // 输出提示语 fgets(input, ARG_MAXIMUM_SIZE, stdin); // 输入 input[strlen(input)-1] = '\0'; argc = Split(argv, input, " "); // 切割字符串 if( argc != 0 ){ char* temp = argv[argc]; argv[argc] = NULL; CheckPipeNum(); // 检查管道数目 if( pipeNum > 0 ){ // 如果超过一个管道的情况 HandleWithPipe(argc, argv); }else{ HandleNonPipe( argv[0], argv ); } argv[argc] = temp; } } Clean(); return 0; } // void HandlePipe( int* argcs, char*** argvs, int processNum ){ // printf("HandlePipe\n"); // int pfd[2]; // pipe(pfd); // for( int i = 0 ; i < processNum ; i+=2 ){ // pid_t pidA = fork(); // if( pidA < 0 ){ // }else if( pidA == 0 ){ // dup2( pfd[1], 1 ); // if( i == 0 ) close(pfd[0]); // else dup2(pfd[0], 0); // execvp( argvs[i][0], argvs[i] ); // }else if( i < processNum ){ // pid_t pidB = fork(); // if( pidB < 0 ){ // }else if( pidB == 0 ){ // dup2(pfd[0], 0); // if( (i+1) == processNum - 1 ) close(pfd[1]); // else dup2(pfd[1],1); // execvp(argvs[i+1][0], argvs[i+1]); // }else{ // // pipe(pfd); // } // } // } // } // void HandlePipe_( int* argcs, char*** argvs, int processNum ){ // printf("HandlePipe\n"); // int pfd[2]; // pipe(pfd); // pid_t firstProcess = fork(); // if( firstProcess < 0 ){ // }else if( firstProcess == 0 ){ // dup2(pfd[1],1); // close(pfd[0]); // execvp(argvs[0][0], argvs[0]); // }else{ // for( int i = 1 ; i < processNum ; i++ ){ // pid_t nextProcess = fork(); // if( nextProcess < 0 ){ // }else if( nextProcess == 0 ){ // dup2(pfd[0],0); // if( i == processNum - 1 ) close(pfd[1]); // else dup2(pfd[1],1); // execvp(argvs[i][0], argvs[i]); // }else{ // } // } // } // }
Java
UTF-8
809
1.898438
2
[]
no_license
package com.hy.crm.entity; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; /** * <p> * * </p> * * @author mq * @since 2020-04-03 */ public class Users_roles implements Serializable { private static final long serialVersionUID = 1L; @TableId private String u_id; @TableId private String r_id; public String getU_id() { return u_id; } public void setU_id(String u_id) { this.u_id = u_id; } public String getR_id() { return r_id; } public void setR_id(String r_id) { this.r_id = r_id; } @Override public String toString() { return "Users_roles{" + "u_id='" + u_id + '\'' + ", r_id='" + r_id + '\'' + '}'; } }
PHP
UTF-8
5,414
2.671875
3
[ "MIT" ]
permissive
<?php namespace MLS\Capsule; use Illuminate\Support\Collection; class Normalizer { /** * The Model instance * * @var MLS\Capsule\Model */ protected $model; /** * The options array * * @var array */ protected $options; /** * The root of the entity * * @var array|string */ protected $root; /** * The collection root * * @var string */ protected $collection_root; /** * The attribute to assign * * @var string */ protected $attribute_to_assign; /** * Create a new Normalizer instance * * @param MLS\Capsule\Model $model * @param array $options * @return void */ public function __construct(Model $model, array $options = []) { $this->model = $model; $this->options = $options; } /** * Normalize a single model * * @param array $attributes * @return MLS\Capsule\Model */ public function model(array $attributes) { if($this->hasSubclasses()) { return $this->normalizeSubclass($attributes); } return $this->normalizeModel($attributes); } /** * Normalize a collection of models * * @param array $attributes * @return Illuminate\Support\Collection */ public function collection(array $attributes) { if($this->hasSubclasses()) { return $this->normalizeSubclassCollection($attributes); } return $this->normalizeCollection($attributes); } /** * Get the root of the entity * * @return array|string */ private function root() { if($this->root) { return $this->root; } if(isset($this->options['root'])) { return $this->root = $this->options['root']; } return $this->root = $this->model->serializableOptions()['root']; } /** * Get the collection root of the entity * * @return string */ private function collectionRoot() { if($this->collection_root) { return $this->collection_root; } if(isset($options['collection_root'])) { return $this->collection_root = $options['collection_root']; } return $this->collection_root = $this->model->serializableOptions()['collection_root']; } /** * Normalize a subclass * * @param array $attributes * @return MLS\Capsule\Model */ private function normalizeSubclass(array $attributes) { reset($attributes); $key = key($attributes); return $this->createNewModelInstance($key, $attributes[$key]); } /** * Normalize a single model * * @param array $attributes * @return MLS\Capsule\Model */ private function normalizeModel(array $attributes) { return $this->createNewModelInstance($this->model->base()->singular(), $attributes[(string) $this->root()]); } /** * Normalize a collection * * @param array $attributes * @return Illuminate\Support\Collection */ private function normalizeCollection(array $attributes) { $collection = new Collection; $type = (string) $this->collectionRoot(); $root = (string) $this->root(); if ($this->isAssociativeArray($attributes[$type][$root])) { $collection[] = $this->createNewModelInstance($root, $attributes[$type][$root]); } else { foreach($attributes[$type][$root] as $entity) { if($this->attributeToAssign()) { $collection[] = $this->createNewModelInstance($root, [$this->attributeToAssign() => $entity]); } else { $collection[] = $this->createNewModelInstance($root, $entity); } } } return $collection; } /** * Normalize a subclass collection * * @param array $attributes * @return Illuminate\Support\Collection */ private function normalizeSubclassCollection($attributes) { $collection = new Collection; foreach($attributes[(string)$this->collectionRoot()] as $key => $value) { if($this->isAssociativeArray($value)) { $collection[] = $this->createNewModelInstance($key, $value); } else { foreach($value as $attributes) { $collection[] = $this->createNewModelInstance($key, $attributes); } } } return $collection; } /** * Create a new model * * @param string $name * @param array $attributes * @return MLS\Capsule\Model */ private function createNewModelInstance($name, array $attributes) { $class = ucfirst($name); $class = "MLS\Capsule\\$class"; $attributes = Helper::toSnakeCase($attributes); return new $class($this->model->connection(), $attributes); } /** * Check to see if the entity has subclasses * * @return bool */ private function hasSubclasses() { return is_array($this->root()); } /** * Check to see if the array is associative * * @param array $array * @return bool */ private function isAssociativeArray($array) { return (bool) count(array_filter(array_keys($array), 'is_string')); } /** * Return the attribute to assign * * @return string */ private function attributeToAssign() { if($this->attribute_to_assign) { return $this->attribute_to_assign; } if(isset($this->model->serializableOptions()['attribute_to_assign'])) { return $this->model->serializableOptions()['attribute_to_assign']; } } }
Swift
UTF-8
1,373
3.453125
3
[ "Apache-2.0" ]
permissive
class Solution { // 674. Longest Continuous Increasing Subsequence // Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing. // A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1]. // Example 1: // Input: nums = [1,3,5,4,7] // Output: 3 // Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3. // Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. // Example 2: // Input: nums = [2,2,2,2,2] // Output: 1 // Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly // increasing. // Constraints: // 1 <= nums.length <= 10^4 // -10^9 <= nums[i] <= 10^9 func findLengthOfLCIS(_ nums: [Int]) -> Int { guard nums.count > 1 else { return nums.count } var index = 1 var res = 1 for i in 0..<nums.count - 1{ if nums[i + 1] > nums[i] { index += 1 } else { index = 1 } res = max(index, res) } return res } }
Python
UTF-8
695
2.5625
3
[]
no_license
""" Created on 2019/3/11 16:33 @author: zhouweixin @note: """ import os from pdfminer.pdfparser import PDFParser, PDFDocument path = r'D:\助研\成程老师\20190220\pdf' files = os.listdir(path) files = [file for file in files if file.endswith('.pdf')] for file in files: print(file) with open(os.path.join(path, file), 'rb') as f: # 创建解析器 parser = PDFParser(f) # 创建文档 doc = PDFDocument() # 链接解析器和文档 parser.set_document(doc) doc.set_parser(parser) doc.initialize() if doc.is_extractable: print('支持txt转换') else: print('不失支持')
C
UTF-8
5,995
2.765625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> int flag_pipe = 0; #define buffer_size 1000 char* get_command(char *command){ int n = strlen(command); int index = -1; for(int i=n-1; i>=0; i--){ if(command[i] == '/'){ index = i; break; } } char *desired_command = (char*)(malloc(sizeof(char)*n)); strcpy(desired_command,command+index+1); // printf("%s", desired_command); return desired_command; } char* add_space(char *without_space){ int input_len = strlen(without_space); char *with_space = (char*)(malloc(sizeof(char)*input_len*3)); for(int i=0,j=0; i<input_len; i++,j++){ with_space[j] = without_space[i]; if (without_space[i] == '|'){ with_space[j++] = ' '; with_space[j++] = '|'; with_space[j] = ' '; } else if (without_space[i] == '<'){ with_space[j++] = ' '; with_space[j++] = '<'; with_space[j] = ' '; } else if (without_space[i] == '1' && without_space[i+1] == '>'){ with_space[j++] = ' '; with_space[j++] = '1'; with_space[j++] = '>'; with_space[j] = ' '; i++; } else if (without_space[i] == '2' && without_space[i+1] == '>' && without_space[i+2] != '&'){ with_space[j++] = ' '; with_space[j++] = '2'; with_space[j++] = '>'; with_space[j] = ' '; i++; } else if (without_space[i] == '>' && without_space[i+1] == '>'){ with_space[j++] = ' '; with_space[j++] = '>'; with_space[j++] = '>'; with_space[j] = ' '; i++; } else if (without_space[i] == '>' && without_space[i+1] != '&'){ with_space[j++] = ' '; with_space[j++] = '>'; with_space[j] = ' '; } } free(without_space); return with_space; } void remove_backslash_n(char *command_token){ int len = strlen(command_token); if(command_token[len-1] == '\n'){ command_token[len-1] = '\0'; } } void redirect_stdout_to_file(char* file){ close(1); creat(file, 0666); } void redirect_stderr_to_file(char* file){ close(2); creat(file, 0666); } void redirect_append_to_file(char *file){ close(1); open(file, O_WRONLY | O_CREAT | O_APPEND); } void redirect_stderr_to_stdout(char *file){ close(2); dup(1); } void read_from_file(char *file){ close(0); open(file, O_RDONLY); } int normal_exec(char *piping_commands[]){ // pid = fork(); piping_commands[0] = get_command(piping_commands[0]); int first_redirect_index = 0; for(int i=0; i<100 && piping_commands[i]!=NULL; i++){ // printf("<%s>\n",piping_commands[i]); if(strcmp(piping_commands[i],"exit") == 0){ // printf("exiting\n"); exit(0); } if(strcmp(piping_commands[i],">") == 0 || strcmp(piping_commands[i],"1>") == 0){ char* file = piping_commands[i+1]; redirect_stdout_to_file(file); if (first_redirect_index == 0) { first_redirect_index = i; } } if(strcmp(piping_commands[i],">>") == 0){ char* file = piping_commands[i+1]; redirect_append_to_file(file); if (first_redirect_index == 0) { first_redirect_index = i; } } if(strcmp(piping_commands[i],"2>") == 0){ char* file = piping_commands[i+1]; redirect_stderr_to_file(file); if (first_redirect_index == 0) { first_redirect_index = i; } } if(strcmp(piping_commands[i],"2>&1") == 0){ char* file = piping_commands[i+1]; redirect_stderr_to_stdout(file); if (first_redirect_index == 0) { first_redirect_index = i; } } if(strcmp(piping_commands[i],"<") == 0){ char* file = piping_commands[i+1]; read_from_file(file); if (first_redirect_index == 0) { first_redirect_index = i; } } } if (first_redirect_index != 0) { piping_commands[first_redirect_index] = NULL; } execvp(piping_commands[0], piping_commands); } void rec_execute_pipe(char *piping_commands[][100]){ if (piping_commands[1][0] == NULL){ normal_exec(piping_commands[0]); return; } if (piping_commands[2][0] == NULL) { int fd2[2]; pipe(fd2); pid_t pid2 = fork(); if (pid2 == 0) { // char *param[2] = {"/usr/bin/wc", NULL}; close(fd2[0]); close(1); dup(fd2[1]); close(fd2[1]); // execvp(piping_commands[0][0], piping_commands[0]); normal_exec(piping_commands[0]); } else { // char *param[2] = {"/bin/cat", NULL}; close(fd2[1]); close(0); dup(fd2[0]); close(fd2[0]); // execvp(piping_commands[1][0], piping_commands[1]); normal_exec(piping_commands[1]); } return; } int fd1[2]; pipe(fd1); pid_t pid1 = fork(); if (pid1 == 0) { close(fd1[0]); close(1); dup(fd1[1]); close(fd1[1]); execvp(get_command(piping_commands[0][0]), piping_commands[0]); } else { close(fd1[1]); close(0); dup(fd1[0]); close(fd1[0]); rec_execute_pipe((char * (*)[100])piping_commands[1]); } } int get_input(char *piping_commands[][100]) { int read_size; int arg_count = 0; int pipe_count = 0; char *args[100]; char *input = (char*)malloc(sizeof(char*)*buffer_size); read_size = read(0, input, buffer_size); remove_backslash_n(input); input = add_space(input); // printf("%s",input); // exit(0); char *command_token = strtok(input, " "); while (command_token != NULL) { // printf("<%s>\n", command_token); args[arg_count] = command_token; command_token = strtok(NULL, " "); arg_count++; } for (int i = 0; i < arg_count; i++) { // printf("<%s>\n", args[i]); int pipe_args = 0; while (i < arg_count && strcmp(args[i],"|")) { piping_commands[pipe_count][pipe_args] = args[i]; pipe_args++; i++; } pipe_count++; } return pipe_count; } int main(){ while(1){ write(1, "$ ", 2); pid_t pid = fork(); if(pid == 0){ char *piping_commands[100][100]; int pipe_count = get_input(piping_commands); // printf("%s\n", piping_commands[0][0]); if(strcmp(piping_commands[0][0], "exit") == 0){ exit(1); } rec_execute_pipe(piping_commands); } else if(pid > 0){ int status; wait(&status); if (status != 0){ break; } } } }
PHP
UTF-8
607
2.5625
3
[ "MIT" ]
permissive
<?php require_once dirname(__DIR__).'/vendor/autoload.php'; /** * This autoloader is only added to help load classes from the Rave namespace. * It is not required if you installed the Rave package in your project using composer. * It is used only for this example. */ // spl_autoload_register(function($class) { // if (preg_match("/^Rave\\\(.+)$/", $class, $matches)) { // $raveDir = dirname(__DIR__).'/src/Rave'; // $file = realpath("{$raveDir}/{$matches[1]}.php"); // if ($file && is_file($file)) { // require_once $file; // } // } // }); use Rave\Rave; $rave = Rave::init()->run();
C++
UTF-8
3,999
2.609375
3
[]
no_license
#include "StdAfx.h" #include "xtGlutView.h" //xtGlutView::xtGlutView(void) //{ //} xtGlutView * xtGlutView::m_Window = NULL; xtGlutView::xtGlutView(const char *title, int width, int height) : m_Width(width), m_Height(height) { int argc = 1; char *argv[] = {"hello"}; glutInit(&argc,argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA); glutInitWindowSize(m_Width, m_Height); glutInitWindowPosition(100, 100); m_WindowId = glutCreateWindow(title); m_Window = this; // register callbacks glutDisplayFunc(display__); glutKeyboardFunc(keyboard__); glutSpecialFunc(special__); glutMouseFunc(mouse__); glutMotionFunc(motion__); glutPassiveMotionFunc(passivemotion__); glutReshapeFunc(reshape__); glutVisibilityFunc(visibility__); //glutMouseWheelFunc(mouseWheel__); // create menu this->m_NumDrawMode = 0; this->m_MenuID = glutCreateMenu(processmenu__); glutAttachMenu(GLUT_RIGHT_BUTTON); } xtGlutView::~xtGlutView(void) { glutDestroyWindow(m_WindowId); glutDestroyMenu(m_MenuID); } void xtGlutView::clear_draw_modes() { for ( unsigned int i=0; i<this->m_NumDrawMode; ++i ) { glutRemoveMenuItem(1); } this->m_NumDrawMode = 0; this->m_DrawModelNames.clear(); } unsigned int xtGlutView::add_draw_mode(const std::string& _s) { // insert in popup menu glutAddMenuEntry(_s.c_str(), m_NumDrawMode); ++m_NumDrawMode; m_DrawModelNames.push_back(_s); return m_NumDrawMode-1; } void xtGlutView::set_draw_mode(int _id) { this->m_DrawMode = _id; glutPostRedisplay(); } xtGlutView *xtGlutView::Get_Window() { return m_Window; } void xtGlutView::keyboard(int key, int x, int y) { switch (key) { case 27: { exit(0); break; } case GLUT_KEY_F12: { if (!m_Fullscreen) { m_BakLeft = glutGet(GLUT_WINDOW_X); m_BakTop = glutGet(GLUT_WINDOW_Y); mBakWidth = glutGet(GLUT_WINDOW_WIDTH); mBakHeight = glutGet(GLUT_WINDOW_HEIGHT); glutFullScreen(); m_Fullscreen = true; } else { glutReshapeWindow(mBakWidth, mBakHeight); glutPositionWindow(m_BakLeft, m_BakTop); m_Fullscreen = false; } break; } } } void xtGlutView::display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (m_DrawMode < m_DrawModelNames.size()) draw(m_DrawModelNames[m_DrawMode]); else draw(""); glutSwapBuffers(); } //======================================================================= // Cheat the compiler //void xtGlutView::display(void) {} void xtGlutView::idle(void) {} //void xtGlutView::keyboard(int key, int x, int y) {} void xtGlutView::motion(int x, int y) {} void xtGlutView::mouse(int button, int state, int x, int y) {} void xtGlutView::passivemotion(int x, int y) {} void xtGlutView::reshape(int w, int h) {} void xtGlutView::visibility(int visible) {} void xtGlutView::processmenu(int i) { set_draw_mode(i); } void xtGlutView::mouseWheel(int button, int dir, int x, int y) {} //======================================================================= void xtGlutView::display__(void) { Get_Window()->display(); } void xtGlutView::idle__(void) { Get_Window()->idle(); } void xtGlutView::keyboard__(unsigned char key, int x, int y) { Get_Window()->keyboard(key, x, y); } void xtGlutView::motion__(int x, int y) { Get_Window()->motion(x, y); } void xtGlutView::mouse__(int button, int state, int x, int y) { Get_Window()->mouse(button, state, x, y); } void xtGlutView::passivemotion__(int x, int y) { Get_Window()->passivemotion(x, y); } void xtGlutView::reshape__(int w, int h) { Get_Window()->reshape(w, h); } void xtGlutView::special__(int key, int x, int y) { Get_Window()->keyboard(key, x, y); } void xtGlutView::visibility__(int visible) { Get_Window()->visibility(visible); } void xtGlutView::processmenu__(int i) { Get_Window()->processmenu(i); } void xtGlutView::mouseWheel__(int button, int dir, int x, int y) { Get_Window()->mouseWheel(button, dir, x, y); }
Swift
UTF-8
531
2.5625
3
[]
no_license
public class StdCodeEmitterSymbolRenderer : CodeEmitterSymbolRenderer { public func render(_ symbol:CodeEmitterSymbol) -> String { switch(symbol) { case .ScopeOpen : return "{" case .ScopeClose : return "}" case .Comma : return "," case .FunctionResult : return "->" case .Space : return " " case .Newline : return "\n" case .Colon : return ":" case .Literal(let string) : return string } } }
C
UTF-8
229
3.15625
3
[]
no_license
printf("Hello World"); int a = 5; int b = 10; if (a > b && b & 2 == 2 || a & 3 == 3) { printf("true"); int i; for(i = 0; i < 10; i++) { if(a > i) printf("i = %d", i); } } else { printf("false"); }
Java
UTF-8
1,061
2.28125
2
[ "Apache-2.0" ]
permissive
package de.davelee.personalman.api; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; import lombok.Getter; import lombok.Setter; /** * This class is part of the PersonalMan REST API. It represents a request for an absence containing company and * username of the person requesting the absence as well as the start date, end date and category of the requested * absence. * @author Dave Lee */ @Builder @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class AbsenceRequest { // Which company the person making the absence request works for private String company; // The username of the person making the absence request private String username; // The start date of the absence in the format dd-mm-yyyy private String startDate; // The end date of the absence in the format dd-mm-yyyy private String endDate; // The category of the absence private String category; // The token of the user to verify that they are logged in private String token; }
Rust
UTF-8
1,190
4.21875
4
[]
no_license
trait Animal { // static method signature; 'self' refers to the implementor type fn new(name: &'static str) -> Self; // instance methods, only signatures fn name(&self) -> &'static str; fn noise(&self) -> &'static str; // a trait can provide default method definitions fn talk(&self) { // these definitions can access other methods declared in the same trait println!("{} says {}", self.name(), self.noise()); } } struct Dog { name: &'static str} impl Dog { fn wag_tail(&self) { println!("{} wags tail", self.name); } } // implement the animal trait for dog impl Animal for Dog { // replace self with the implementor type: dog fn new(name: &'static str) -> Dog { Dog { name: name } } fn name(&self) -> &'static str { self.name } fn noise(&self) -> &'static str { "woof!" } // default trait methods can be overridden fn talk(&self) { // traits methods can access the implementor methods self.wag_tail(); println!("{} says {}", self.name, self.noise()); } } fn main() { let buck: Dog = Animal::new("Buck"); buck.talk(); }
C++
WINDOWS-1250
1,672
2.921875
3
[]
no_license
/* ___________________________________________ | IDrawable.cpp - implementacja interfejsu. | | SCI - August 2012. | |___________________________________________| */ #include "IDrawable.h" #include "../Drawable/CDrawableManager.h" namespace rendering { namespace drawable { //Konstruktor domylny IDrawable::IDrawable() : m_visible (true), m_layer_vector_index (-1), //na wszelki wypadek wstawiamy -1, aby warstwa nie bya ustawiona m_layer_index (-1) //na wszelki wypadek wstawiamy -1, aby warstwa nie bya ustawiona { } //Konstruktor kopiujcy IDrawable::IDrawable(const IDrawable& IDrawableCopy) : m_visible (IDrawableCopy.m_visible), m_layer_vector_index (IDrawableCopy.m_layer_vector_index), m_layer_index (IDrawableCopy.m_layer_index) { } //Wirtualny destruktor IDrawable::~IDrawable() { if (m_layer_vector_index >= 0) //jeli w kontenerze, n awarstwach s jakie obiekty gDrawableManager.UnregisterDrawable(this); //wyrejestrowujemy je } //Metoda zwraca flag, czy obiekt jest widoczny const bool IDrawable::GetVisible() const { return m_visible; } //Metoda ustawia flage, czy obiekt jest widoczny const void IDrawable::SetVisible(bool visible) { m_visible = visible; } //Metoda zwraca indeks warstwy, na ktrej ma by renderowany obiekt const int IDrawable::GetLayerIndex() const { return m_layer_index; } //Metoda ustawia indeks warstwy, na ktrej ma by renderowany obiekt const void IDrawable::SetLayerIndex(int layer_index) { m_layer_index = layer_index; } }//namespace drawable }//namespace rendering
Java
UTF-8
2,322
3.765625
4
[ "MIT" ]
permissive
/** @author Zhifan Li <a href="mailto:zhifan.li@ucalgary.ca">zhifan.li@ucalgary.ca</a> @version 1.0 @since 1.0 */ //This class is for exercise5_2 in ENSF409 assignment 2. public class JavaStrings { /** * * @param first first string to be passed to this method * @param second second string to be passed to this method * @return the length of the trimmed, concatenated String */ public int addTogether(String first,String second) { String firstTrimmed=first.trim(); String secondTrimmed=second.trim(); String finalString=firstTrimmed+secondTrimmed; return finalString.length(); } /** * * @param firstName first name of client * @param lastName last name of client * @param petName name of pet * @param year year of birth of the pet * @return an identifier as a String */ public String idProcessing(String firstName, String lastName, String petName, int year) { firstName=firstName.trim(); lastName=lastName.trim(); petName=petName.trim(); String id=String.valueOf(firstName.charAt(0))+String.valueOf(lastName.charAt(0)); id+=String.valueOf(petName.charAt(0))+String.valueOf(year); return id; } /** * * @param originalString original String going to be encrypted * @return secret String */ public String secretCode(String originalString) { originalString=originalString.trim(); String stringTemp=originalString.replace('a','z'); stringTemp=stringTemp.replace('e','z'); stringTemp= stringTemp.replace('i','z'); stringTemp= stringTemp.replace('o','z'); stringTemp= stringTemp.replace('u','z'); stringTemp= stringTemp.replace('A','z'); stringTemp= stringTemp.replace('E','z'); stringTemp= stringTemp.replace('I','z'); stringTemp= stringTemp.replace('O','z'); stringTemp= stringTemp.replace('U','z'); stringTemp=stringTemp.toLowerCase(); String secretString= stringTemp.substring(0,3); return secretString; } /** * * @param args Ignored command line argument */ public static void main(String[] args) { JavaStrings test=new JavaStrings(); int addTogether=test.addTogether(" hey ", " hello "); String id=test.idProcessing("Zhifan", "Li", "Mika", 2017); String encrypted=test.secretCode("AEIAto"); System.out.println(addTogether); System.out.println(id); System.out.println(encrypted); } }//End of class declaration.
C#
UTF-8
668
2.828125
3
[]
no_license
using System.IO; using System.Text; namespace YandeDowner { public static class FileHelper { public static void processPath(string path) { if (!Directory.Exists(@path)) { Directory.CreateDirectory(@path); } } public static string getVoidFileName(string fileName) { StringBuilder rBuilder = new StringBuilder(fileName); foreach (char rInvalidChar in Path.GetInvalidFileNameChars()) { rBuilder.Replace(rInvalidChar.ToString(), string.Empty); } return rBuilder.ToString(); } } }
SQL
UTF-8
363
2.578125
3
[]
no_license
# remove_anonymous_users DELETE FROM mysql.user WHERE User=''; # remove_remote_root DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1'); # remove_test_database DROP DATABASE IF EXISTS test; # remove privileges on test database DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'; # reload privileges FLUSH PRIVILEGES;
Java
UTF-8
622
2.515625
3
[]
no_license
package com.exadel.kaliada.core.services; import java.util.Map; /** * Class to load news from https://news.harvard.edu/gazette/ and parse them * @author akaliada */ public interface HarvardNewsParser { /** * load and parse all news from the main web-site * @return Map of pairs news Id and news link */ Map<String, String> getAllNews(); /** * load and parse single news by link * @param link - link to single news * @return Map with pairs components of news page (tag, image, title, text) and their values */ Map<String, String> parseSingleNews(String link); }
C#
UTF-8
734
2.59375
3
[]
no_license
using MongoDB.Driver; using System; namespace Mongo { public class MongoRepository<T> { private readonly IMongoConnectionSettings _settings; public MongoRepository(IMongoConnectionSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } _settings = settings; } public void Insert(T document) { //var mongoClient = new MongoClient(_settings.ConnectionString); //var db = mongoClient.GetDatabase(_settings.DatabaseName); //var coll = db.GetCollection<T>(_settings.CollectionName); //coll.InsertOne(document); } } }
C++
UTF-8
1,869
2.890625
3
[ "CC0-1.0" ]
permissive
#include "../advent/advent25.h" #include "../utils/int_range.h" #include <numeric> namespace { using utils::int_range; using ValType = int64_t; constexpr ValType MOD = 20201227; constexpr ValType CARD_SUBJECT_NUMBER = 7; constexpr ValType DOOR_SUBJECT_NUMBER = 7; constexpr ValType INITIAL_CRYPTO_VALUE = 1; ValType update_crypto_value(ValType value, ValType subject_number) { const ValType intermediate = value * subject_number; const ValType result = intermediate % MOD; return result; } ValType encrypt(ValType subject_number, ValType loop_size) { const int_range range(loop_size); return std::accumulate(begin(range), end(range), INITIAL_CRYPTO_VALUE, [subject_number](ValType prev, ValType) { return update_crypto_value(prev, subject_number); }); } ValType get_loop_size(ValType subject_number, ValType public_key) { ValType crypto_value = INITIAL_CRYPTO_VALUE; ValType trial_loop_size = 0; while (true) { if (crypto_value == public_key) return trial_loop_size; ++trial_loop_size; crypto_value = update_crypto_value(crypto_value, subject_number); } } ValType get_encryption_key(ValType my_public, ValType other_public, ValType my_subject_number) { const ValType my_loop_size = get_loop_size(my_subject_number, my_public); return encrypt(other_public, my_loop_size); } ValType solve_p1(ValType card_key, ValType door_key) { const auto result = get_encryption_key(card_key, door_key, CARD_SUBJECT_NUMBER); assert(result == get_encryption_key(door_key, card_key, DOOR_SUBJECT_NUMBER)); return result; } } ResultType day_twentyfive_testcase_a() { return solve_p1(5764801, 17807724); } ResultType advent_twentyfive_p1() { return solve_p1(1327981, 2822615); } ResultType advent_twentyfive_p2() { return "MERRY CHRISTMAS!"; }
PHP
UTF-8
799
2.515625
3
[]
no_license
<?php use Illuminate\Database\Seeder; class UsersQuestionsAnswersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { \DB::table('answers')->delete(); \DB::table('questions')->delete(); \DB::table('users')->delete(); factory(App\User::class,3)->create()->each(function($u){ $u->questions() ->saveMany(factory(App\Question::class, rand(3,10))->make() ) ->each(function($q){ $q->answers()->saveMany(factory(App\Answer::class,rand(1,5))->make()); });//a question may have more than one answers. }); } } //factory(App\Question,3)->create(); cant call like that bcz each user may have one or more questions
JavaScript
UTF-8
1,382
2.984375
3
[]
no_license
/* Draw basic demo chart */ function drawChart1() { var div = createDiv({ id: 'chart1', style: 'height: 400px; width: 400px;' }); var data = [{ x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], type: 'bar' }]; Plotly.newPlot('chart1', data); } function drawChart2() { getJSON('services.json', function(data) { console.log(data); var x1 = []; var y1 = []; var y2 = []; var y3 = []; var cnt = 0; for (var name in data) { cnt++; if (cnt>10) { break; } x1.push(name); y1.push(data[name]['ახალი'] || 0); y2.push(data[name]['დასრულებული'] || 0); y3.push(data[name]['მიმდინარე'] || 0); } var trace1 = { x: x1, y: y1, type: 'bar', name: 'ახალი', marker: { color: 'pink' } }; var trace2 = { x: x1, y: y2, type: "bar", name: 'მიმდინარე', marker: { color: 'lightblue' } }; var trace3 = { x: x1, y: y3, type: "bar", name: 'დასრულებული', marker: { color: 'red' } }; var div = createDiv({ id: 'chart2', style: 'height: 800px; width: 100%;' }); Plotly.newPlot(div, [trace1, trace2, trace3]); }); } function init() { drawChart1(); drawChart2(); drawChart3(); drawChart4(); } window.onload = init;
Python
UTF-8
184
3.328125
3
[]
no_license
#Reversing month and date import re str="June 10 1994, June 11 1994, June 12 1994, June 13 1994" regex=r"([a-zA-Z]+) (\d+) (\d+)" print(re.sub(regex,r"\3\\2\\1",str)) #End of file
Ruby
UTF-8
222
3.546875
4
[]
no_license
# As per other languages, scope in preserved inside methods beer_description = "A crisp, summer ale with hints of coffee." def describer # Ruby complains (scope is inside the string) print beer_description end describer
Python
UTF-8
2,973
2.953125
3
[]
no_license
import pandas as pd import networkx as nx import numpy as np from scipy.spatial import Delaunay import math semiMajorAxis = 6378137.0 #赤道半径 flattening = 1/298.257223563 # 扁平率 e_2 = flattening * (2 - flattening) degree = math.pi / 180 def distance_latlon(p, q): x1, y1, x2, y2 = p[0], p[1], q[0], q[1] coslat = math.cos((y1 + y2) / 2 * degree) w2 = 1 / (1 - e_2 * (1 - coslat * coslat)) dx = (x1 - x2) * coslat dy = (y1 - y2) * w2 * (1 - e_2) return math.sqrt((dx * dx + dy * dy) * w2) * semiMajorAxis * degree def create_edges(nodes, nodes_index, G): edges = {} tri = Delaunay(list(nodes.values())) for t in tri.simplices: t = np.sort(t) t_edge1 = (t[0], t[1]) t_edge2 = (t[1], t[2]) t_edge3 = (t[0], t[2]) if t_edge1 not in edges: d = nx.shortest_path_length(G, nodes_index[t_edge1[0]], nodes_index[t_edge1[1]], weight='weight') edges[t_edge1] = d edges[(t_edge1[1], t_edge1[0])] = d if t_edge2 not in edges: d = nx.shortest_path_length(G, nodes_index[t_edge2[0]], nodes_index[t_edge2[1]], weight='weight') edges[t_edge2] = d edges[(t_edge2[1], t_edge2[0])] = d if t_edge3 not in edges: d = nx.shortest_path_length(G, nodes_index[t_edge3[0]], nodes_index[t_edge3[1]], weight='weight') edges[t_edge3] = d edges[(t_edge3[1], t_edge3[0])] = d return edges if __name__ == '__main__': base_dir="../data/kawagoe_example" df_node = pd.read_csv(f"{base_dir}/node.csv") df_edge_all = pd.read_csv(f"{base_dir}/edge_all.csv") G = nx.from_pandas_edgelist(df_edge_all, 'source', 'target', 'weight') out, out_path = {}, {} for i in df_node["id"].values: for j in df_node["id"].values: if i == j: out[(i, j)] = 0 out_path[(i, j)] = None else: out[(i, j)] = nx.shortest_path_length(G, source=i, target=j, weight='weight') path=[] for p in nx.shortest_path(G, source=i, target=j, weight='weight'): if p in df_node["id"].values: path.append(p) out_path[(i, j)] = path df_out = pd.DataFrame(out.keys(), columns=["from", "to"]) df_out["length"] = out.values() df_out["path"] = out_path.values() df_out.to_csv(f"{base_dir}/distance_matrix.csv", index=False) nodes ,nodes_index={}, {} count=0 for v in df_node.values: nodes_index[count] = v[0] nodes[count]=(v[3], v[4]) count +=1 # ノード間のドローネもうをedgeにする edges = create_edges(nodes, nodes_index, G) out_e =[] count=0 for e in edges: out_e.append([count, nodes_index[e[0]], nodes_index[e[1]], edges[e]]) count += 1 df_edge = pd.DataFrame(out_e, columns=["edge_id","source", "target", "weight"]) df_edge.to_csv(f"{base_dir}/edge.csv", index=False)
PHP
UTF-8
4,851
2.734375
3
[ "MIT" ]
permissive
<?php require_once('../md5rand.php'); $atword = ""; function punctuate($line) { $reps = array( " " => " ", " " => " ", " ." => ".", " ," => ",", " '" => "'", " !" => "!", " ?" => "?", " :" => ":", "- " => "-", " _" => "", '>_ ' => '>', " a a" => " an a", " a e" => " an e", " a o" => " an o", " a u" => " an u", " a i" => " an i", " a A" => " an A", " a E" => " an E", " a O" => " an O", " a U" => " an U", " a I" => " an I", " A A" => " An A", " A E" => " An E", " A O" => " An O", " A U" => " An U", " A I" => " An I", " a the" => " the", " the the " => " the ", " The The " => " The ", "?." => "?", " )" => ")", "( " => "(", " +" => "-", "+ " => "-", "+-" => "+ ", "<br/> " => "<br/>" ); $lowercases = array( " A " => " a ", " An " => " an ", " By " => " by ", " In " => " in ", " Of " => " of ", " On " => " on ", " Or " => " or ", " To " => " to ", " And " => " and ", " The " => " the " ); foreach ($reps as $search => $replace) $line = str_replace($search, $replace, $line); $line = ltrim($line); foreach ($lowercases as $search => $replace) $line = str_replace($search, $replace, $line); $sentences = explode(". ", $line); foreach ($sentences as &$sentence) $sentence = ucfirst($sentence); $line = implode(". ", $sentences); $sentences = explode("? ", $line); foreach ($sentences as &$sentence) $sentence = ucfirst($sentence); $line = implode("? ", $sentences); $sentences = explode("! ", $line); foreach ($sentences as &$sentence) $sentence = ucfirst($sentence); $line = implode("! ", $sentences); return $line; } function Title($r=null) { if ($r === null) $r = new MD5Rand(); return punctuate(" " . randomline($r, "title", False, False)); } function Cast($r=null) { if ($r === null) $r = new MD5Rand(); return punctuate(" " . randomline($r, "cast", False, False)); } function Rating($r=null) { if ($r === null) $r = new MD5Rand(); return punctuate(" " . randomline($r, "rating", False, False)) . ", " . ($r->range(80)+80) . " mins"; } function Tagline($r=null) { if ($r === null) $r = new MD5Rand(); return punctuate(" " . randomline($r, "basemovie", False, False)); } function randomline($r, $filename, $plural, $cap) { global $atword; $capitalise = False; $file_flags = FILE_IGNORE_NEW_LINES + FILE_SKIP_EMPTY_LINES; if (file_exists("vocabulary/" . $filename . '.txt')) $lines = file("vocabulary/" . $filename . '.txt', $file_flags); else { return "No such file: " . "vocabulary/" . $filename . '.txt'; } if (substr($lines[0], 0, 1) == "#") { # comment, remove first line of $lines array_shift($lines); } if ($lines[0] == "&") { # set capital and remove first line of $lines $capitalise = True; array_shift($lines); } # pick a random line $line = $r->choice($lines); $story = ""; $words = explode(" ", $line); foreach ($words as $word) { if ($word == "@") { $word = $atword; $atword = ""; } elseif (strpos($word, "@") !== False) { $atword = substr($word, 1); $word = ""; } $pos = strpos($word, "|"); if ($pos !== False) { if (!$plural) $word = substr($word, 0, $pos); else $word = substr($word, $pos + 1); } $pos = strpos($word, "$"); if ($pos !== False) { if ($pos == 0) $chance = 10; else $chance = substr($word, 0, $pos) + 0; if ($chance > $r->next_float()*10) #$story .= "(1 " . substr($word, $pos + 1) . ")"; $story .= randomline($r, substr($word, $pos + 1), False, $capitalise); } elseif (strpos($word, "*") === 0) #$story .= "(2 " . substr($word, 1) . ")"; $story .= randomline($r, substr($word, 1), True, $capitalise); else { #if ($capitalise) #{ # echo "<!--pow!-->"; # $word = ucfirst($word); #} $story .= $word . " "; } } if ($capitalise) $story = ucwords($story); return $story; } ?>
Python
UTF-8
972
4.15625
4
[]
no_license
def frequentChr(word): """frequentChr: accept a string as input and returns the most frquently occured element as dictionary""" #Verifying that the input is type string try: #To ensure that the parameter is a string not an array if (type(word) in [list,set,dict]): return f"Note!: {word} is {type(word)}, please input a string" new = {} #iterating through the input for i in word: #Updating the dictionary (new). if (i in new): new[i] += 1 else: new[i] = 1 #Geting the element(s) with the highest frquency maxValue = max(new.values()) arr = [] for i,j in new.items(): if j == maxValue: arr.append({i:j}) #returning a list of elements(s) return arr #Raising a warning when input is not string except: return f"Note! : {word} is {type(word)}, please enter a string"
Markdown
UTF-8
2,930
2.90625
3
[]
no_license
``` body{ -moz-user-select:none; /*火狐*/ -webkit-user-select:none; /*webkit浏览器*/ -ms-user-select:none; /*IE10*/ -khtml-user-select:none; /*早期浏览器*/ user-select:none; } ``` ``` 判断浏览器 第一种,只区分浏览器,不考虑版本 function myBrowser(){ var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var isOpera = userAgent.indexOf("Opera") > -1; if (isOpera) { return "Opera" }; //判断是否Opera浏览器 if (userAgent.indexOf("Firefox") > -1) { return "FF"; } //判断是否Firefox浏览器 if (userAgent.indexOf("Chrome") > -1){ return "Chrome"; } if (userAgent.indexOf("Safari") > -1) { return "Safari"; } //判断是否Safari浏览器 if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) { return "IE"; }; //判断是否IE浏览器 } //以下是调用上面的函数 var mb = myBrowser(); if ("IE" == mb) { alert("我是 IE"); } if ("FF" == mb) { alert("我是 Firefox"); } if ("Chrome" == mb) { alert("我是 Chrome"); } if ("Opera" == mb) { alert("我是 Opera"); } if ("Safari" == mb) { alert("我是 Safari"); } 第二种,区分浏览器,并考虑IE5.5 6 7 8 function myBrowser(){ var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器 var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器 var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器 var isSafari = userAgent.indexOf("Safari") > -1; //判断是否Safari浏览器 if (isIE) { var IE5 = IE55 = IE6 = IE7 = IE8 = false; var reIE = new RegExp("MSIE (\\d+\\.\\d+);"); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp["$1"]); IE55 = fIEVersion == 5.5; IE6 = fIEVersion == 6.0; IE7 = fIEVersion == 7.0; IE8 = fIEVersion == 8.0; if (IE55) { return "IE55"; } if (IE6) { return "IE6"; } if (IE7) { return "IE7"; } if (IE8) { return "IE8"; } }//isIE end if (isFF) { return "FF"; } if (isOpera) { return "Opera"; } }//myBrowser() end //以下是调用上面的函数 if (myBrowser() == "FF") { alert("我是 Firefox"); } if (myBrowser() == "Opera") { alert("我是 Opera"); } if (myBrowser() == "Safari") { alert("我是 Safari"); } if (myBrowser() == "IE55") { alert("我是 IE5.5"); } if (myBrowser() == "IE6") { alert("我是 IE6"); } if (myBrowser() == "IE7") { alert("我是 IE7"); } if (myBrowser() == "IE8") { alert("我是 IE8"); } ```
Markdown
UTF-8
870
2.53125
3
[]
no_license
# bash Based on the default bashrc from Ubuntu 20.04. ## Clock On the right top of the terminal display clock using [`tput`][tldp-bash]. In addition to date and time, it also displays: * current git branch, * status (with return code) of the last command. ## Pure-like prompt A custom prompt inspired by [pure][pure-git]that displays the following: * current working directory * current git branch (if any) * whether git is dirty or not (denoted with a `+`) ## References * [Colours and Cursor Movement With `tput`][tldp-bash] on The Linux Documentation Project * [Bash/Prompt customization][archwiki-bash] on ArchWiki * [Pure][pure-git]: Pretty, minimal and fast ZSH prompt [archwiki-bash]: https://wiki.archlinux.org/title/Bash/Prompt_customization [tldp-bash]: https://tldp.org/HOWTO/Bash-Prompt-HOWTO/x405.html [pure-git]: https://github.com/sindresorhus/pure
SQL
UTF-8
3,026
2.5625
3
[]
no_license
-- GENRES insert into HBDEMO_GENRE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('fa55b59e-a193-a9f2-9737-e548d9884d0e', 1, '2020-07-04 13:28:30', 'admin', '2020-07-04 13:28:30', null, null, null, 'Fantasy'); insert into HBDEMO_GENRE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('fc67c0bc-6430-bba3-c7bb-e2587e270b19', 1, '2020-07-04 13:28:17', 'admin', '2020-07-04 13:28:17', null, null, null, 'Drama'); insert into HBDEMO_GENRE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('c266d418-39a0-b66b-74c0-b3a896e2ca2a', 1, '2020-07-04 13:28:08', 'admin', '2020-07-04 13:28:08', null, null, null, 'Comedy'); insert into HBDEMO_GENRE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('7fd34139-17d9-7eaf-6011-453012c1bf78', 1, '2020-07-04 13:27:53', 'admin', '2020-07-04 13:27:53', null, null, null, 'Horror'); insert into HBDEMO_GENRE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('5d293b4e-182d-d1d4-da99-72bd90797de8', 1, '2020-07-04 13:27:44', 'admin', '2020-07-04 13:27:44', null, null, null, 'Musical'); -- DIRECTOR insert into HBDEMO_DIRECTOR (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, FIRST_NAME, LAST_NAME, AGE, GROWTH, BIRTH_DATE) values ('fad796bd-26f7-7f17-23b9-308544ececb9', 1, '2020-07-04 13:45:06', 'admin', '2020-07-04 13:45:06', null, null, null, 'Damien', 'Chazelle', 35, 177, 1985-01-19); insert into HBDEMO_DIRECTOR (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, FIRST_NAME, LAST_NAME, AGE, GROWTH, BIRTH_DATE) values ('fad796bd-26f7-7f17-23b9-308544ececb9', 1, '2020-07-04 13:45:06', 'admin', '2020-07-04 13:45:06', null, null, null, 'Damien', 'Chazelle', 35, 177, 1985-01-19); -- COUNTRY insert into HBDEMO_COUNTRY (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME) values ('7bdace73-1a0b-870e-6f97-be08bb485ca5', 1, '2020-07-04 13:47:42', 'admin', '2020-07-04 13:47:42', null, null, null, 'USA'); -- MOVIE insert into HBDEMO_MOVIE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME, YEAR_, BUDGET, TIME_, DIRECTOR_ID, COUNTRY_ID) values ('66d55b63-5e4d-2e65-5917-8c2284ceaf34', 1, '2020-07-04 13:51:44', 'admin', '2020-07-04 13:51:44', null, null, null, 'The Shawshank Redemption', '1994', 25000000.00, 142, 'e9ac3fdf-7f9e-12e8-68e6-fddb91b847d0', '7bdace73-1a0b-870e-6f97-be08bb485ca5'); insert into HBDEMO_MOVIE (ID, VERSION, CREATE_TS, CREATED_BY, UPDATE_TS, UPDATED_BY, DELETE_TS, DELETED_BY, NAME, YEAR_, BUDGET, TIME_, DIRECTOR_ID, COUNTRY_ID) values ('84fb1ea0-4f31-fd21-db44-9854d960fc9b', 1, '2020-07-04 13:52:45', 'admin', '2020-07-04 13:52:45', null, null, null, 'La La Land', '2016', 30000000.00, 128, 'fad796bd-26f7-7f17-23b9-308544ececb9', '7bdace73-1a0b-870e-6f97-be08bb485ca5');
Java
ISO-8859-1
5,614
3.09375
3
[]
no_license
package speakit.io.record; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * Representa un registro. Un objeto serializable y comparable. Para extender * Record es necesario sobreescribir el metodo getKey y getFields. * * Incluye un campo de hash que sirve para detectar datos corruptos al momento de deserializarlo. Si esto sucede se arroja una excepcin. */ public abstract class Record<KEYTYPE extends Field> implements Comparable<Record<KEYTYPE>> { /** * @return el campo que har de clave. El campo devuelto no se serializar a * menos que haya sido incluido en la lista de getFields(). */ public abstract KEYTYPE getKey(); /** * @return el arreglo de campos que se quiere sean serializables. Si el * campo clave tambien se quiere serializar se debe incluir en esta * lista. */ protected abstract Field[] getFields(); /** * Serializa el registro escribindolo en un stream de salida. * * @param stream * Stream de salida. * @return Cantidad de bytes escrito. * @throws RecordSerializationException */ public long serialize(OutputStream stream) throws RecordSerializationException { long byteCount = 0; byte hash = 0; try { for (Field field : this.getFields()) { byte[] serialize = field.serialize(); stream.write(serialize); byteCount += serialize.length; //modifica el hash actual con los datos de la serializacin del campo hash = calculateHash(hash,serialize); } //graba el hash al final stream.write(new byte[]{hash}); } catch (IOException e) { throw new RecordSerializationException(); } return byteCount; } public static byte calculateHash(byte hash,byte[] serialize) { for (int i = 0; i < serialize.length; i++) { hash += calculateHash(serialize[i]); } return hash; } public static byte calculateHash(int source) { return (byte) (((source+1) * 379) >> 2); } /** * Serializa el registro y devuelve la serializacin en varias partes de * tamao partSize, tantas como necesite. * * @param partSize * tamao de cada parte expresado en bytes. Debe ser >0 * @return * @throws IOException * @throws RecordSerializationException */ public List<byte[]> serializeInParts(int partSize) throws RecordSerializationException, IOException { if (!(partSize > 0)) { throw new IllegalArgumentException("PartSize debe ser > 0."); } List<byte[]> parts = new ArrayList<byte[]>(); ByteArrayInputStream stream = new ByteArrayInputStream(this.serialize()); while (stream.available() > 0) { byte[] serializationPart = new byte[partSize]; stream.read(serializationPart, 0, partSize); parts.add(serializationPart); } return parts; } /** * Deserializa el registro a partir de un array de partes de serializacion. * Primero concatena los bytes de todas las partes y despues delega la * deserializacin al metodo deserialize * * @param serializationParts * @throws IOException */ public void deserializeFromParts(List<byte[]> serializationParts) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); for (byte[] bytes : serializationParts) { stream.write(bytes); } this.deserialize(stream.toByteArray()); } /** * Deserializa el registro a partir de un stream de entrada. * * @param stream * Stream de entrada. * @return Cantidad de bytes leido. * @throws RecordSerializationException */ public long deserialize(InputStream stream) throws RecordSerializationException { long byteCount = 0; byte calculatedHash = 0; byte deserializedHash=0; try { for (Field field : this.getFields()) { byteCount += field.deserialize(stream); //agrega al hash actual el hash del campo calculatedHash = calculateHash(calculatedHash,field.serialize()); } //carga el hash serializado deserializedHash=(byte) stream.read(); } catch (IOException e) { throw new RecordSerializationException(e); } if(deserializedHash!=calculatedHash){ throw new RecordSerializationCorruptDataException("Record",deserializedHash,calculatedHash); } return byteCount; } /** * Compara un registro con otro. */ @Override public int compareTo(Record<KEYTYPE> o) { return this.getKey().compareTo(o.getKey()); } /** * Compara la clave de un registro con un campo. */ public int compareToKey(KEYTYPE key) { return this.getKey().compareTo(key); } public final byte[] serialize() throws IOException, RecordSerializationException { ByteArrayOutputStream out = new ByteArrayOutputStream(); this.serialize(out); return out.toByteArray(); } public final void deserialize(byte[] data) throws IOException, RecordSerializationException { ByteArrayInputStream in = new ByteArrayInputStream(data); this.deserialize(in); } @Override public String toString() { String stringRepresention = this.getStringRepresentation(); int i = 0; if (stringRepresention.length() == 0) { String res = ""; for (Field field : this.getFields()) { res += (i != 0 ? "," : "") + field.toString(); i++; } res += ""; return res; } else { return stringRepresention; } } protected String getStringRepresentation(){ return ""; } }
Python
UTF-8
9,100
2.75
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 13:54:54 2020 @author: fatcatcat """ import numpy as np from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, UpSampling2D, ZeroPadding2D,Input,BatchNormalization, Dropout from tensorflow.keras.models import Sequential,Model from tensorflow.keras import initializers import cv2 #from keras.models import Sequential,Model from tensorflow.keras.optimizers import SGD, Adam from keras.utils import np_utils import matplotlib.pyplot as plt import os import tensorflow as tf from tensorflow.keras.callbacks import TensorBoard f1 = 'D:/building/new_train' f2 = 'D:/building/new_label' f3 = 'D:/building/new_test' f4 = 'D:/building/new_test_label' print("-----開始讀取數據-----") #讀取四個不同的照片資料夾 def get_imlist(path): #此函式讀取特定資料夾下的tif格式影象,返回圖片所在路徑的列表 return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')] imagePath1 = get_imlist(f1) #r""是防止字串轉譯 imagePath2 = get_imlist(f2) #r""是防止字串轉譯 imagePath3 = get_imlist(f3) #r""是防止字串轉譯 imagePath4 = get_imlist(f4) #r""是防止字串轉譯 #資料夾裡面的照片個數 train_N = len(imagePath1) trainL_N = len(imagePath2) test_N = len(imagePath3) testL_N = len(imagePath4) #建立四個空陣列 train_data = np.empty((train_N,256,256,3)) train_labels = np.empty((trainL_N,256,256,1)) test_data = np.empty((test_N,256,256,3)) test_labels = np.empty((testL_N,256,256,1)) #將照片轉換成numpy 並儲存進陣列(圖片來源,照片個數,要儲存的陣列),順便縮小成256*256 #也要將label 照片轉成rgb 跟input 一樣 def loadIMG(imagePath , number, Array): while number > 0: img = cv2.imread(imagePath[number-1]) img = cv2.resize(img,(256,256),interpolation=cv2.INTER_AREA) img_ndarray=np.asarray(img,dtype='float64') Array[number-1] = img_ndarray number = number - 1 def loadIMG_gray(imagePath , number, Array): while number > 0: img = cv2.imread(imagePath[number-1],0) img = cv2.resize(img,(256,256),interpolation=cv2.INTER_AREA) img_ndarray=np.asarray(img,dtype='float64') Array[number-1] = img_ndarray.reshape(256,256,1) number = number - 1 loadIMG(imagePath1,train_N,train_data) loadIMG_gray(imagePath2,trainL_N,train_labels) loadIMG(imagePath3,test_N,test_data) loadIMG_gray(imagePath4,testL_N,test_labels) #檢查是否有匯入 print ("train_data.shape:",train_data.shape) print(type(train_data)) print ("train_labels.shape:",train_labels.shape) print(type(train_labels)) print ("test_data.shape:",test_data.shape) print(type(test_data)) print ("test_labels.shape:",test_labels.shape) print(type(test_labels)) #正規化到[0,1]之間 train_data = train_data/255 train_labels = train_labels/255 test_data = test_data/255 test_labels = test_labels/255 #開始建立模型 print('-----開始建立模型------') def train_model(): global history initializer = tf.keras.initializers.he_normal(seed = None) input_img= Input(shape=(256, 256, 3)) # Encoder 使用卷積層,激活函數用 relu,輸入的維度就是上面定義的 input_img #大小 = 256*256 x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(input_img) x = BatchNormalization()(x) x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = MaxPooling2D((2, 2), padding='same')(x) #大小 = 128*128 x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = MaxPooling2D((2, 2), padding='same')(x) #大小 = 64*64 x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = MaxPooling2D((2, 2), padding='same')(x) #大小 = 32*32 x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) encoded = MaxPooling2D((2, 2), padding='same', name='encoder')(x) #大小 = 16*16 為編碼器設置了一個名稱,以便能夠訪問它 # Decoder 的過程與 Encoder 正好相反,需要跟 Encoder 的神經網絡層做相對應,相對應的激活函數也是一樣,但這邊在解碼中最後一層使用的激活函數是 sigmoid x = UpSampling2D((2, 2))(encoded) #大小32*32 x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(128, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = UpSampling2D((2, 2))(x) #大小64*64 x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(64, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = UpSampling2D((2, 2))(x) #大小128*128 x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(32, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = UpSampling2D((2, 2))(x) #大小256*256 x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) x = Conv2D(16, (3, 3), activation='relu', padding='same',kernel_initializer=initializer)(x) x = BatchNormalization()(x) decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x) # 用 Model 來搭建模型,輸入為圖片,輸出是解碼的結果 autoencoder = Model(input_img, decoded) print(autoencoder.summary()) # 編譯模型,optimizer 使用 adam,loss 使用 categorical_crossentropy autoencoder.compile(optimizer='adam', loss=tf.keras.losses.MeanSquaredError(),metrics=[tf.keras.metrics.MeanSquaredError()]) history = autoencoder.fit(train_data, train_labels, epochs=200, batch_size=16, shuffle=True, validation_data=(test_data, test_labels)) autoencoder.save('segnet2_outputgray.h5') print('-----開始訓練模型----') train_model() print('-----訓練完成-------') #將訓練過程損失可視化 plt.plot(history.history['mean_squared_error']) plt.plot(history.history['val_mean_squared_error']) plt.title('Segnet_outputgray_model2 accuracy') plt.ylabel('error') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Segnet_outputgray_Model2 loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Test'], loc='upper left') plt.show() # 這邊嘗試 batch = 20 + batch normalization
Swift
UTF-8
984
2.578125
3
[]
no_license
import Foundation import Glibc let group = DispatchGroup() let checkIsMainThread: () -> Void = { if Thread.isMainThread { print("Thread #\(gettid()) isMainThread") } else { print("Thread #\(gettid()) NOT MainThread") } } let defaultQueue = DispatchQueue.global() defaultQueue.async(group: group, execute: checkIsMainThread) let userInteractiveQueue = DispatchQueue.global(qos: .userInteractive) userInteractiveQueue.async(group: group, execute: checkIsMainThread) let userInitiatedQueue = DispatchQueue.global(qos: .userInitiated) userInitiatedQueue.async(group: group, execute: checkIsMainThread) let utilityQueue = DispatchQueue.global(qos: .utility) utilityQueue.async(group: group, execute: checkIsMainThread) let backgroundQueue = DispatchQueue.global(qos: .background) backgroundQueue.async(group: group, execute: checkIsMainThread) let mainQueue = DispatchQueue.main mainQueue.async(group: group, execute: checkIsMainThread) checkIsMainThread() group.wait()
TypeScript
UTF-8
557
2.71875
3
[]
no_license
import {Component, Directive, Host, SkipSelf,Injector} from '@angular/core'; import {Service} from './service'; @Component({ selector : 'child', template : '<h1> have a look @ ur console </h1>', providers : [Service] }) export class Child { //SkipSelf decorator will restrict the provider lookup to parent->grandparent->ancestor parent constructor(@SkipSelf() pSvc: Service, svc: Service,injector:Injector) { console.log('instance of ', pSvc.someProp); console.log('instance of', svc.someProp); injector.get() ; } }
C++
UTF-8
1,375
3.765625
4
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //Time Complexity O(n) //Space Complexity O(log n) (if balanced) otherwise O(n) class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(!root) return false; sum -= root->val; //subtract from sum and try to reach zero if((!root->left) && (!root->right)) return sum == 0; //if both children are null check if the sum is equal to 0 //recursion call return hasPathSum(root->left, sum) || hasPathSum(root->right, sum); } }; //example tree using this code // 5 // / \ // 3 7 // / \ \ // 1 4 8 //sum = 20 //now here is what sum would print if there was a cout statement after sum -= root->val; //sum = 15 //sum = 12 //sum = 11 (after this, it checks if sum == 0 because 1's left and right child nodes are null) //sum = 8 (at this point it went back and ran hasPathSum(root->right, sum) to satisfy the return statement) //also at that point it will return as well (false) //sum = 8 (now it has gotten all the way back to the first node and is running the right side) //sum = 0 (reaches end and will return true) and entire statement will be true since it is F || T = T
Markdown
UTF-8
4,288
2.90625
3
[]
no_license
Features -------- * Timeline, layer, tracks, clips We provide a high level API with video edition semantics, anyone familiar with video editing should be able to quickly figure out how to use GES, as opposed to lower level concepts such as "source" and "composition". * Integrated mixing Doing video and audio mixing in GES is as straightforward as adding video elements in different layers and manipulating their alpha property. We also provide nice commodities such as automatic rescaling, which means you don't have to worry about the sizes of your videos being different, we will make it look "just right" anyway. * Transitions In previous versions of GES, you had to set transitions yourself, and figure out how to set their priorities etc, which was not really intuitive. Now you can just set "auto-transitions" to true on either the timeline or individual layers, and we will take care of adding, removing and updating them when elements overlap on the same layer. We support crossfades and all kinds of standard transitions, such as screen swipe. * Keyframes Keyframes are "control points", allowing you to change the value of any controllable property of any gstreamer element smoothly over time (think "red component" in an RGB manipulation element for instance) We exposed the GstController API. We made the choice to expose it as is as the API really maps what we wanted to offer, in consequence the naming of the API feels a little lower level but it's very functionnal. We just wrap it so that we can offer saving and loading of the control points. * High level interfaces to audio volume, video alpha and geometry. In GES, video sources all share the common properties of alpha, size and position. As I mentioned earlier, we will rescale the incoming videos automatically when mixing them, but you still have the choice to change their size manually, as well as their position on the screen. Nice bonus is that you can also change them dynamically thanks to keyframes ! Their audio counterparts share a "volume" property, animatable as well. Current state ------------- * Tested Testing is of course obvious to a lot of us, and from its inception GES was unit tested. Development is usually test-driven, so GES in and of itself is pretty well tested with a good coverage. However, real life scenarios are very difficult to test with unit testing, and that's why we needed a "integration" test suite. Basically we use all sorts of input / output formats in all sorts of basic scenarios (transition, mixing, effects, etc...) and validate the result, to make sure what we ask from gstreamer is correctly supported. When it's not, we fix it upstream. * Fully introspected. GES offers a very high level API, so it's extremely important to us that it can be used from higher level languages. Not much to say here as the introspection guys diserve all the praise for this, apart from the fact that we are "introspection-friendly". Use cases --------- * High level simple mixing. As soon as you want to mix two video sources together, you should seriously consider using GES, as it will abstract a lot of the complexity for you, and will do that fairly well, with zero performance cost. * Server for online edition. This one is very interesting ! Basically, due to our design it will be very easy to deploy a server side edition service, as it is only a matter of setting the audio and video sinks (outputs) to network sinks, and connect to them in the client. Future possibilities -------------------- * Collaborative editing. Extending asset management to multi-user use cases. Need for quite a lot of code though, or to find a decent library that does that. * Speed control. We had a google summer of code targeted at this feature this summer, however this proved to be a little challenging for a newcomer to finalize. Good progress has been made though, and we would be able to finish that quickly for a "fixed speed" first step. In my spare time I also had fun with porting slowmovideo's code to gstreamer and make it a plugin, which means we can simulate high fps slow motion for certain types of input streams. Demo ---- Gonna make it now.
TypeScript
UTF-8
4,511
2.609375
3
[ "LicenseRef-scancode-generic-cla", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project. */ import { promises as fs, createWriteStream, existsSync, mkdirSync } from 'fs' import path from 'path' import { error, info, traceFile } from '@essex/tasklogger' import archiver from 'archiver' import chalk from 'chalk' import glob from 'glob' import ProgressBar from 'progress' // eslint-disable-next-line @typescript-eslint/no-var-requires const format = require('human-format') export interface ZipCommandOptions { baseDir: string } export async function zip( destination: string, sources: string[], { baseDir }: ZipCommandOptions, ): Promise<number> { const outputDir = path.dirname(destination) if (!existsSync(outputDir)) { info('creating output folder', outputDir) mkdirSync(outputDir, { recursive: true }) } const fileEntries = await getFileEntries(sources, baseDir) info( `archiving ${chalk.green(destination)} from base dir ${chalk.blueBright( baseDir, )} and sources ${sources.map(s => chalk.blueBright(s)).join(', ')}`, ) info(`including ${fileEntries.length} files`) if (process.env.ESSEX_DEBUG) { fileEntries.forEach(e => traceFile(e, 'zip')) } await archive(destination, fileEntries, baseDir) return 0 } async function getFileEntries( sources: string[], baseDir: string, ): Promise<string[]> { const result: string[] = [] for (const source of sources) { const sourcePath = path.join(baseDir, source) const foundFiles = source.indexOf('*') >= 0 ? // handle globs await getGlobSource(sourcePath) : // handle files await getSourceFiles(sourcePath) const isIncluded = await Promise.all(foundFiles.map(isZippable)) const filteredFiles = foundFiles.filter((_t, i) => isIncluded[i]) if (process.env.ESSEX_DEBUG) { filteredFiles.forEach(f => traceFile(f, `expand ${source}`)) } result.push(...filteredFiles) } return result.map(file => path.relative(baseDir, file)) } function getGlobSource(source: string): Promise<string[]> { if (process.env.ESSEX_DEBUG) { info('handle source glob: ' + source) } return new Promise<string[]>((resolve, reject) => { glob(source, { dot: true }, (err, files) => { if (err) { error('glob error', error) reject(err) } else { resolve(files) } }) }) } async function getSourceFiles(source: string): Promise<string[]> { if (process.env.ESSEX_DEBUG) { info('handle source file: ' + source) } const stats = await fs.stat(source) if (stats.isDirectory()) { return await walkDir(source) } else if (stats.isFile()) { return [source] } else { console.warn(`${source} is not a file or directory. Unable to compress.`) return [] } } async function walkDir(directory: string): Promise<string[]> { const directoryStack = [directory] let allFiles: string[] = [] while (directoryStack.length) { const currentDirectoryPath: string = directoryStack.pop() as string const directoryFiles = await fs.readdir(currentDirectoryPath) for (const file of directoryFiles) { const filePath = path.join(currentDirectoryPath, file) const stats = await fs.stat(filePath) if (stats.isFile()) { allFiles = [...allFiles, filePath] } else if (stats.isDirectory()) { directoryStack.push(filePath) } else { console.warn( `${filePath} is not a file or directory. Skipping compression`, ) } } } return allFiles } async function archive( destination: string, fileEntries: string[], cwd: string, ): Promise<void> { const bar = new ProgressBar(':percent :bar', { total: fileEntries.length, width: 80, complete: '=', incomplete: '-', }) return new Promise(async (resolve, reject) => { const output = createWriteStream(destination) const archive = archiver('zip') output.on('close', () => { console.log( `archive complete - ${chalk.green(destination)} ${chalk.grey( format(archive.pointer(), { scale: 'binary', unit: 'B', }), )}`, ) resolve() }) archive.on('entry', () => { bar.tick() }) archive.on('warning', reject) archive.on('error', reject) archive.pipe(output) for (const entry of fileEntries) { const entryPath = path.join(cwd, entry) archive.file(entryPath, { name: entry, }) } info('finalizing archive') archive.finalize() }) } async function isZippable(file: string): Promise<boolean> { const stat = await fs.stat(file) return !stat.isSymbolicLink() && !stat.isDirectory() && stat.isFile() }
C++
ISO-8859-1
4,061
2.6875
3
[]
no_license
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ * * * Started by ngel on january of 2016 * * This is free software released into the public domain. * * angel.rodriguez@esne.edu * * * \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "MainMenu.hpp" #include "GameScene.hpp" #include "SimpleAudioEngine.h" using namespace cocos2d; namespace mainGame { bool Main::init() { // Se intenta inicializar la clase base y, si falla, se retorna con error: if (!Scene::init()) { return false; } //se coge la musica del juego CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("music.mp3"); //se inicia la musica CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("music.mp3", true); // Se crea una capa y se aade a la escena auto layer = Layer::create(); this->addChild(layer); // Se toma el tamao visible del display para colocar los elementos grficos // usando posiciones relativas (en lugar de absolutas): visibleSize = Director::getInstance()->getVisibleSize(); //se establece el fondo background = Sprite::create("BG.png"); background->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); layer->addChild(background, 1); //se crean los botones createButtons(layer); //se crea la label donde se printara la ayuda y se oculta labelHelp = Label::createWithTTF("Coge todos los bebes con la cesta, evista los monstruos. Muevete con las felchas de direccion", "fonts/pixelart.ttf", 40); labelHelp->setDimensions(visibleSize.width, visibleSize.height / 2); addChild(labelHelp, 5); labelHelp->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 1.5)); labelHelp->setOpacity(0); return true; } void Main::createButtons(Layer * layer) { // Se crean los sprites: buttonPlay = Sprite::create(); buttonHelp = Sprite::create(); buttonClose = Sprite::create(); // Se coloca el punto de anclaje (el que se tiene en cuenta para establecer la posicin) // para facilitar la maquetacin: buttonPlay->setAnchorPoint(Vec2(0.5f, 0.5f)); buttonHelp->setAnchorPoint(Vec2(1.f, 0.f)); buttonClose->setAnchorPoint(Vec2(0.5f, 0.5f)); //se crean los items del menu menu_item1 = MenuItemImage::create("play.png", "play.png", CC_CALLBACK_1(Main::LoadGame, this)); menu_item2 = MenuItemImage::create("help.png", "help.png", CC_CALLBACK_1(Main::LoadHelp, this)); menu_item3 = MenuItemImage::create("exit.png", "exit.png", CC_CALLBACK_1(Main::CloseHelp, this)); //se establecen sus posiciones dentro de el menu_item1->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); menu_item2->setPosition(Vec2(visibleSize.width * 0.9, visibleSize.height * 0.9)); menu_item3->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 1.5)); //se crea el menu y se establce su posicion y se aade a la escena menu = Menu::create(menu_item1, menu_item2, menu_item3, NULL); menu->setPosition(0., 0.f); layer->addChild(menu, 10); //se oculta el boton para salir de la ayuda menu_item3->setVisible(false); } // Carga el juego al darle a play void Main::LoadGame(Ref * pSender) { auto myScene = game::GameScene::create(); Director::getInstance()->replaceScene(myScene); } //Permite abrir la ayuda void Main::LoadHelp(Ref * pSender) { labelHelp->setOpacity(255); menu_item1->setVisible(false); menu_item2->setVisible(false); menu_item3->setVisible(true); } //Permite cerrar la ayuda void Main::CloseHelp(Ref * pSender) { labelHelp->setOpacity(0); menu_item1->setVisible(true); menu_item2->setVisible(true); menu_item3->setVisible(false); } }
SQL
UTF-8
2,107
3.015625
3
[]
no_license
-- Alimentos INSERT INTO PRODUCT (ID,PRODUCT_ID,PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(1, 1, 'Arroz', 'Arroz Parboilizado', 3.50); INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(2, 2, 'Feijão', 'Feijao Sitio Cercado', 4.10); -- Eletrodomésticos INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(3, 3, 'Aspirador de pó', 'Aspirador Vertical Philco Turbo - 309', 193.50); INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(4, 4, 'Batedeira', 'Batedeira Stand Mixer', 3.599); INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(5, 5, 'Liquidificador', 'Liquidificador Phillips Walita', 149.00); -- Móveis INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(6, 6, 'Sofá', 'Sofá 3 Lugares Retratil Kennedy', 2.500); INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(7, 7, 'Mesa', 'Mesa de Jantar com 4 cadeiras Tabaco-Perola Rossini', 510.00); INSERT INTO PRODUCT (ID,PRODUCT_ID, PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_COST) VALUES(8, 8, 'Estante', 'Estante Multiuso 5 Divisórias', 420.00); --Insert categories INSERT INTO CATEGORY (ID, CATEGORY_ID, CATEGORY_NAME) VALUES(1, 1, 'Alimentos'); INSERT INTO CATEGORY (ID, CATEGORY_ID, CATEGORY_NAME) VALUES(2, 2, 'Eletrodomésticos'); INSERT INTO CATEGORY (ID, CATEGORY_ID, CATEGORY_NAME) VALUES(3, 3, 'Móveis'); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES(1, 1); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES(1, 2); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 2, 3); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 2, 4); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 2, 5); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 3, 6); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 3, 7); INSERT INTO PRODUCT_CATEGORY ( CATEGORY_ID, PRODUCT_ID) VALUES( 3, 8);
Swift
UTF-8
5,546
3
3
[]
no_license
// // CountryDataHelper.swift // Country // // Created by Mario Kovacevic on 09/05/16. // Copyright © 2016 Brommko, LLC. All rights reserved. // import Foundation import SQLite class CountryDataHelper: DataHelperProtocol { static let TABLE_NAME = "country" static let id = Expression<Int>("id") static let name = Expression<String?>("name") static let capital = Expression<String?>("capital") static let region = Expression<String?>("region") static let table = Table(TABLE_NAME) typealias T = CountryModel /** Example of how you can create a table in database. */ static func createTable() throws { do { try SQLiteDataStore.sharedInstance.DB!.run(table.create { t in t.column(id, primaryKey: .Autoincrement) t.column(name) t.column(capital) t.column(region) }) } catch { print("Error!") } } /** Example of how you can insert one country in database. */ static func insert(item: T) -> Bool { do { let rowid = try SQLiteDataStore.sharedInstance.DB!.run(table.insert(name <- item.name, capital <- item.capital, region <- item.region)) if rowid > 0 { print("inserted id: \(rowid)") return true } else { return false } } catch { print("insertion failed: \(error)") return false } } /** Example of how you can update one country in database using 'name' parameter to find which one to update. */ static func update(item: T) -> Bool { do { if (item.name != nil) { let query = table.filter(name == item.name!) let rowid = try SQLiteDataStore.sharedInstance.DB!.run(query.update(capital <- item.capital, region <- item.region)) if rowid > 0 { print("updated id: \(rowid)") return true } else { return false } } print("inserted id: \(rowid)") return false } catch { print("insertion failed: \(error)") return false } } /** Example of how you can delete one country from database. */ static func delete (item: T) -> Bool { do { if let countryId = item.id { let query = table.filter(id == countryId) let rowid = try SQLiteDataStore.sharedInstance.DB!.run(query.delete()) if rowid > 0 { print("delete id: \(rowid)") return true } else { return false } } else { return false } } catch { print("delete failed: \(error)") return false } } /** Example of how you can find just one country using countru id. */ static func find(countryId: Int) -> T? { let query = table.filter(id == countryId) var results: T? if let item = SQLiteDataStore.sharedInstance.DB!.pluck(query) { results = self.populateObject(item) } return results } /** Example of how you can fatch all countries from database. */ static func findAll() -> [T]? { var retArray = [T]() do { for item in try SQLiteDataStore.sharedInstance.DB!.prepare(table) { retArray.append(self.populateObject(item)!) } } catch { print("Error!") } return retArray } /** Example of how countries are find in database using region parameter. */ static func findAllForRegion(reg:Navigation) -> [T]? { let query = table.filter(region == reg.rawValue) var retArray = [T]() do { for item in try SQLiteDataStore.sharedInstance.DB!.prepare(query) { retArray.append(self.populateObject(item)!) } } catch { print("Error!") } return retArray } /** Using the transaction and savepoint functions, we can run a series of statements in a transaction. If a single statement fails or the block throws an error, the changes will be rolled back. */ static func importCountries(countries:[T]?, onCompletion: () -> Void){ if countries != nil { do { try SQLiteDataStore.sharedInstance.DB!.transaction { txn in for country in countries! { if self.update(country) != true { self.insert(country) } } } } catch { print("Error!") } } onCompletion() } /** If you change your model, this is the only place for populating it. */ static func populateObject(item:Row) -> T? { let country: CountryModel = CountryModel() country.id = item[id] if item[name] != nil { country.name = item[name] } if item[capital] != nil { country.capital = item[capital] } if item[region] != nil { country.region = item[region] } return country } }
Markdown
UTF-8
5,531
2.53125
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "OpenSSL" ]
permissive
--- title: Third party tools headerTitle: Third party tools linkTitle: Third party tools description: Interactive third party clients that you can use with YugabyteDB. headcontent: Use popular third party clients with YugabyteDB. image: /images/section_icons/troubleshoot/troubleshoot.png menu: v2.16: identifier: tools parent: reference weight: 2900 type: indexpage --- Because YugabyteDB is compatible with PostgreSQL and Cassandra, you can use third-party clients to connect to your YugabyteDB clusters. ### YugabyteDB prerequisites To use these tools with YugabyteDB, you should have a cluster up and running, and you will need to know the connection parameters required by the client to connect to your cluster. To create a local cluster, follow the steps in [Quick start](../quick-start/). To create a cluster in YugabyteDB Managed, follow the steps in [Create a cluster](../yugabyte-cloud/cloud-quickstart/). In addition, do the following: - [Download the cluster certificate](../yugabyte-cloud/cloud-secure-clusters/cloud-authentication/#download-your-cluster-certificate); YugabyteDB requires the use of TLS - [Add your computer to the cluster IP allow list](../yugabyte-cloud/cloud-secure-clusters/add-connections/#assign-an-ip-allow-list-to-a-cluster); this allows your computer to access the cluster #### Connection parameters To connect, follow the client's configuration steps, and use the following values: | Setting | Local installation | YugabyteDB Managed | | :--- | :--- | :--- | | Hostname | `localhost` | The cluster hostname as displayed on the cluster **Settings** tab | | Port | `5433` (YSQL) `9042` (YCQL) | `5433` (YSQL) `9042` (YCQL) | | Database | Database name (`yugabyte` is the default) | Database name (`yugabyte` is the default) | | Username | `yugabyte` or `cassandra` | Database username (`admin` is the default) | | Password | `yugabyte` or `cassandra`<br>Leave blank if [authentication is not enabled](../secure/enable-authentication/) | Database user password | YugabyteDB Managed requires TLS. Use the root.ca certificate you downloaded for connections to YugabyteDB Managed clusters. ## Tools <div class="row"> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="pgadmin/"> <div class="head"> <img class="icon" src="/images/develop/tools/pgadmin-icon.png" aria-hidden="true" /> <div class="title">pgAdmin</div> </div> <div class="body"> Management tool for PostgreSQL. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="superset/"> <div class="head"> <img class="icon" src="/images/develop/tools/superset/superset-icon.png" aria-hidden="true" /> <div class="title">Apache Superset</div> </div> <div class="body"> Open-source data exploration and visualization tool. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="arctype/"> <div class="head"> <img class="icon" src="/images/develop/tools/arctype/arctype-icon.png" aria-hidden="true" /> <div class="title">Arctype</div> </div> <div class="body"> SQL client and database management tool. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="dbeaver-ysql/"> <div class="head"> <img class="icon" src="/images/develop/tools/dbeaver-icon.png" aria-hidden="true" /> <div class="title">DBeaver</div> </div> <div class="body"> Eclipse-based, multi-platform database tool. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="tableplus/"> <div class="head"> <img class="icon" src="/images/section_icons/develop/tools/tableplus.png" aria-hidden="true" /> <div class="title">TablePlus</div> </div> <div class="body"> Unified developer console for querying databases. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="dbschema/"> <div class="head"> <img class="icon" src="/images/develop/tools/dbschema/dbschema-icon.png" aria-hidden="true" /> <div class="title">DbSchema</div> </div> <div class="body"> Visual database tool for reverse-engineering schemas, editing ER diagrams, browsing data, and more. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="sql-workbench/"> <div class="head"> <img class="icon" src="/images/develop/tools/sql-workbench.png" aria-hidden="true" /> <div class="title">SQL Workbench/J</div> </div> <div class="body"> Unified developer console for querying YugabyteDB and displaying results. </div> </a> </div> <div class="col-12 col-md-6 col-lg-12 col-xl-6"> <a class="section-link icon-offset" href="visualstudioworkbench"> <div class="head"> <img class="icon" src="/images/section_icons/develop/tools/cassandraworkbench.png" aria-hidden="true" /> <div class="title">Cassandra Workbench</div> </div> <div class="body"> Visual Studio Code extension for querying Apache Cassandra databases. </div> </a> </div> </div>
Java
UTF-8
6,460
2.53125
3
[]
no_license
import jade.core.AID; import jade.core.Agent; import jade.core.behaviours.Behaviour; import jade.core.behaviours.CyclicBehaviour; import jade.domain.DFService; import jade.domain.FIPAAgentManagement.DFAgentDescription; import jade.domain.FIPAAgentManagement.ServiceDescription; import jade.domain.FIPAException; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NavigatorAgent extends Agent { @Override protected void setup() { System.out.println("Hello! The navigator agent " + getAID().getName() + " is ready."); DFAgentDescription dfd = new DFAgentDescription(); dfd.setName(getAID()); ServiceDescription sd = new ServiceDescription(); sd.setType(WumpusWorldAgent.Constants.NAVIGATOR_AGENT_TYPE); sd.setName(WumpusWorldAgent.Constants.NAVIGATOR_SERVICE_DESCRIPTION); dfd.addServices(sd); try { DFService.register(this, dfd); } catch (FIPAException fe) { fe.printStackTrace(); } addBehaviour(new LocationRequestsServer()); } @Override protected void takeDown() { try { DFService.deregister(this); } catch (FIPAException fe) { fe.printStackTrace(); } System.out.println("The navigator agent " + getAID().getName() + " terminating."); } private class LocationRequestsServer extends CyclicBehaviour { int time = 0; @Override public void action() { MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.INFORM); ACLMessage msg = myAgent.receive(mt); if (msg != null) { if (parseSpeleologistMessageRequest(msg.getContent())){ ACLMessage reply = msg.createReply(); reply.setPerformative(ACLMessage.REQUEST); reply.setContent(WumpusWorldAgent.Constants.INFORMATION_PROPOSAL_NAVIGATOR); System.out.println("NavigatorAgent: " + WumpusWorldAgent.Constants.INFORMATION_PROPOSAL_NAVIGATOR); myAgent.send(reply); } else if (parseSpeleologistMessageProposal(msg.getContent())) { ACLMessage reply = msg.createReply(); reply.setPerformative(ACLMessage.PROPOSE); String advice = getAdvice(msg.getContent()); reply.setContent(advice); System.out.println("NavigatorAgent: " + advice); myAgent.send(reply); } else System.out.println("NavigatorAgent: Wrong message!"); } else { block(); } } private boolean parseSpeleologistMessageRequest(String instruction) { String regex = "\\bHelp\\b"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(instruction); if (matcher.find()) { String res = matcher.group(); return res.length() > 0; } return false; } private boolean parseSpeleologistMessageProposal(String instruction) { String regex = "\\bPosition\\b"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(instruction); if (matcher.find()) { String res = matcher.group(); return res.length() > 0; } return false; } private String getAdvice(String content){ boolean stench = false; boolean breeze = false; boolean glitter = false; boolean scream = false; String advicedAction = ""; for (Map.Entry<Integer, String> entry : STATES.entrySet()) { String value = entry.getValue(); Pattern pattern = Pattern.compile("\\b" + value + "\\b", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); if (matcher.find()) { switch (value){ case "Stench": stench = true; case "Breeze": breeze = true; case "Glitter": glitter = true; case "Scream": scream = true; } } } switch (time){ case 0: advicedAction = WumpusWorldAgent.Constants.MESSAGE_RIGHT; time++; break; case 1: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 2: advicedAction = WumpusWorldAgent.Constants.MESSAGE_LEFT; time++; break; case 3: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 4: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 5: advicedAction = WumpusWorldAgent.Constants.MESSAGE_GRAB; time++; break; case 6: advicedAction = WumpusWorldAgent.Constants.MESSAGE_LEFT; time++; break; case 7: advicedAction = WumpusWorldAgent.Constants.MESSAGE_SHOOT; time++; break; case 8: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 9: advicedAction = WumpusWorldAgent.Constants.MESSAGE_LEFT; time++; break; case 10: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 11: advicedAction = WumpusWorldAgent.Constants.MESSAGE_FORWARD; time++; break; case 12: advicedAction = WumpusWorldAgent.Constants.MESSAGE_CLIMB; time++; break; } int rand = 1 + (int) (Math.random() * 3); switch (rand) { case 1: return WumpusWorldAgent.Constants.ACTION_PROPOSAL1 + advicedAction; case 2: return WumpusWorldAgent.Constants.ACTION_PROPOSAL2 + advicedAction; case 3: return WumpusWorldAgent.Constants.ACTION_PROPOSAL3 + advicedAction; default: return ""; } } final Map<Integer, String> STATES = new LinkedHashMap<Integer, String>() {{ put(1, "Stench"); put(2, "Breeze"); put(3, "Glitter"); put(4, "Scream"); }}; } }
Go
UTF-8
5,524
2.71875
3
[]
no_license
package adapter import ( "bytes" "net/url" "goadminapi/context" "goadminapi/modules/auth" "goadminapi/modules/config" "goadminapi/modules/db" "goadminapi/modules/menu" "goadminapi/plugins" "goadminapi/plugins/admin/models" "goadminapi/template" "goadminapi/template/types" ) // WebFrameWork 功能都設定在框架中(使用/adapter/gin/gin.go框架) type WebFrameWork interface { // 回傳使用的web框架名稱 Name() string // 將插件插入框架引擎中 Use(app interface{}, plugins []plugins.Plugin) error // 添加html到框架中 Content(ctx interface{}, fn types.GetPanelFn, fn2 context.NodeProcessor, navButtons ...types.Button) // 從給定的上下文中取得用戶模型 User(ctx interface{}) (models.UserModel, bool) // 將路由(路徑)及處理程式加入框架 AddHandler(method, path string, handlers context.Handlers) DisableLog() Static(prefix, path string) Run() error // Helper functions // ================================ SetApp(app interface{}) error SetConnection(db.Connection) GetConnection() db.Connection SetContext(ctx interface{}) WebFrameWork GetCookie() (string, error) Path() string Method() string FormParam() url.Values IsPjax() bool Redirect() SetContentType() Write(body []byte) CookieKey() string HTMLContentType() string } // BaseAdapter 是db.Connection(interface) type BaseAdapter struct { db db.Connection } // SetConnection 將參數(conn)設置至BaseAdapter.db func (base *BaseAdapter) SetConnection(conn db.Connection) { base.db = conn } // GetConnection 回傳BaseAdapter.db func (base *BaseAdapter) GetConnection() db.Connection { return base.db } // CookieKey return "session" func (base *BaseAdapter) CookieKey() string { return "session" } // HTMLContentType return "text/html; charset=utf-8" func (base *BaseAdapter) HTMLContentType() string { return "text/html; charset=utf-8" } // GetUse 首先將參數(app)轉換成gin.Engine(/gin-gonic/gin套件)型態設置至Gin.app // 接著對參數(plugin []plugins.Plugin)執行迴圈,設置Context(struct)並增加handlers、處理url及寫入header // -------wf參數是Gin(struct)------------ func (base *BaseAdapter) GetUse(app interface{}, plugin []plugins.Plugin, wf WebFrameWork) error { // 將參數轉換成gin.Engine(/gin-gonic/gin套件)型態設置至Gin.app if err := wf.SetApp(app); err != nil { return err } // plugin is interface for _, plug := range plugin { // 回傳Base.App.Handlers(map[Path]Handlers),path(struct)裡包含URL、method for path, handlers := range plug.GetHandler() { // 設置Context(struct)並增加handlers、處理url及寫入header wf.AddHandler(path.Method, path.URL, handlers) } } return nil } // GetUser 透過參數取得cookie後,利用cookie取得用戶角色、權限以及可用menu,最後將UserModel.Conn = nil後回傳UserModel // -------wf參數是Gin(struct)------------ func (base *BaseAdapter) GetUser(ctx interface{}, wf WebFrameWork) (models.UserModel, bool) { // SetContext將參數(ctx)轉換成gin.Context(gin-gonic/gin套件)類別Gin.ctx(struct) // 取得cookie cookie, err := wf.SetContext(ctx).GetCookie() if err != nil { return models.UserModel{}, false } // wf.GetConnection()回傳BaseAdapter.db(interface) // 透過cookie、conn可以得到角色、權限以及可使用菜單 user, exist := auth.GetCurUser(cookie, wf.GetConnection()) // 設置UserModel.Conn = nil後回傳UserModel return user.ReleaseConn(), exist } // GetContent 利用cookie驗證使用者,取得role、permission、menu,接著檢查權限,執行模板並導入HTML // -------wf參數是Gin(struct)------------ func (base *BaseAdapter) GetContent(ctx interface{}, getPanelFn types.GetPanelFn, wf WebFrameWork, navButtons types.Buttons, fn context.NodeProcessor) { var ( // 將參數(ctx)轉換成gin.Context(gin-gonic/gin套件)類別Gin.ctx(struct) // -------wf參數是Gin(struct)------------ newBase = wf.SetContext(ctx) // 取得session裡設置的cookie cookie, hasError = newBase.GetCookie() ) if hasError != nil || cookie == "" { newBase.Redirect() return } // wf.GetConnection()回傳BaseAdapter.db(interface) // 透過參數sesKey(cookie)取得id並利用id取得該user的role、permission以及可用menu,最後回傳UserModel(struct) user, authSuccess := auth.GetCurUser(cookie, wf.GetConnection()) if !authSuccess { newBase.Redirect() return } var ( panel types.Panel err error ) // CheckPermissions檢查用戶權限(在modules\auth\middleware.go) if !auth.CheckPermissions(user, newBase.Path(), newBase.Method(), newBase.FormParam()) { panel = template.WarningPanel("no permission", template.NoPermission403Page) } else { panel, err = getPanelFn(ctx) if err != nil { panel = template.WarningPanel(err.Error()) } } fn(panel.Callbacks...) tmpl, tmplName := template.Default().GetTemplate(newBase.IsPjax()) buf := new(bytes.Buffer) hasError = tmpl.ExecuteTemplate(buf, tmplName, types.NewPage(types.NewPageParam{ User: user, Menu: menu.GetGlobalMenu(user, wf.GetConnection()).SetActiveClass(config.URLRemovePrefix(newBase.Path())), Panel: panel.GetContent(config.IsProductionEnvironment()), Assets: template.GetComponentAssetImportHTML(), Buttons: navButtons.CheckPermission(user), TmplHeadHTML: template.Default().GetHeadHTML(), TmplFootJS: template.Default().GetFootJS(), })) newBase.SetContentType() newBase.Write(buf.Bytes()) }
Markdown
UTF-8
19,025
3.015625
3
[]
no_license
--- title: "Data Organization with Excel 1 on ITaP Computers" author: "Pete E. Pascuzzi" date: "September 5, 2019" output: html_document: keep_md: yes toc: yes --- # Setup For Purdue University students, **you cannot save fies to the lab computer!** However, your ITaP home directory should be mapped as the `W:` drive. Remember to drag your work to your home directory before you log out! ![](images/Capture00_0.png) *** **Important! Make Windows 10 show file name extensions by doing the following** 1. Left-click on an empty area of the Desktop. 2. Enter `Ctrl + n` to open a File Explorer Window. 3. Select the `View` tab at the top of the window. 4. Check the box next to `File name extensions`. ![](images/Capture00_4.png) *** This will make it much easier for you to identify the correct files for the workshop. **File extensions are an important part of a file name!** Locate the Excel01 folder for the workshop on the `lab (R:`) drive on the lab computers, `This PC > lab (R:) > PascuzziPE > Excel01` . ![](images/Capture00_1.png) *** ![](images/Capture00_2.png) *** ![](images/Capture00_3.png) *** Drag the Excel01 folder to your desktop. Open the file `Excel01.html` with Chrome or Firefox. # Introduction Excel is a widely used tool for data science and data sharing. However, Excel has very few rules--you can (dis)organize your data in nearly any way that you want. In addition, Excel files are generally NOT protected from accidental data entry or deletion, so data corruption is a common problem. Many researchers and students share their data as Excel files, and it is often very difficult for others to understand or analyze the data because Excel does not encourage good data organization practices. An Excel worksheet is inherently a rectangular data format with data arranged in rows and columns. Generally, each row corresponds to an observational unit such as sample, student or gene, and each column corresponds to a variable such as nitrogen content, class rank or expression level. Excel worksheets often become more complex because researchers use them to summarize or analyze their data. The consequence is that this rectangular data format can break down as researchers include subtables to perform calculations or add rows or columns that contain summary results derived from groups of samples or variables. An Excel worksheet that includes such information is no longer strictly a data set, but a data analysis document. The purpose of this workshop, and the follow up Data Organization with Excel02, is to show you how to use some of the features in Excel that can minimize data organization problems. In addition, there is a brief overview on rectangular data formats. ThThese concepts and skills will help you to organize your data and protect it from corruption, making your data to easier to share with other (even if this other is only your future self). Need more convincing? Read this perspective on data sharing written by a professional statistician, [How to share data with a statistician](https://github.com/jtleek/datasharing). # Learning Objectives * Recognize wide, long and tidy formats for rectangular data sets. * Learn how to import and export data with Excel to minimize data corruption. * Learn how to use Data Filtering in Excel to subset your data sets. * Learn how to use Data Validation in Excel to minimize data entry errors and to help you clean your data. * Learn how to make an Excel Pivot Table to summarize your data and as tool to aid data cleaning. # Rectangular Data In rectanglur data formats, samples or other observational units are arranged in rows and the variables that are collected for these samples are arranged in columns. ![](images/RectData.png) There are many data sets that are not amenable to rectangular format, but it is unlikely that you would try to analyze such data with Excel. Almost any table can be considered a rectangular data set, but some tables can be a data visualization because they are meant to be read by a person and not a computer, e.g. a menu is a type of table. Within rectangular data sets, there are two common formats, **wide** and **long**. A third format named **tidy** is emerging with the increasing use of data science in all fields. **Tidy** data is essentially a rigorous form of the **long** format that incorporates additional best practices in data management [Wickham, 2014](https://www.jstatsoft.org/article/view/v059i10). ## Wide Data In **wide** data sets, similar variables are organized into separate columns, but there is information stored in the column name that can be considered a variable. In the example below, taken from bacterial growth assays in tomato leaves, there are four columns with `cfu` (colony forming units) in the column name, but there is also information in the column name that indicates that the `cfu` was measured on different days. There is nothing inherently wrong with wide format, and Excel often requires this format for analysis or visualization. In fact, wide format applies to data matrices which are very common in computational data analysis. However, wide format is often not amenable to statistical analysis with software other than Excel. ![](images/Wide.png) ## Long Data In **long** format, similar variables are gathered into a single column that can be aggregated or grouped on additional variables. The wide format for the bacterial growth assays can be easily (relatively speaking) converted to long format by gathering the values in the `cfu` columns into a single column named `cfu` and introducting a new column named `day` with values derived from the original column names. ![](images/Long.png) ## Tidy Data Finally, **tidy** data sets are motivated by the imperative to make your data as transparent as possible. Each variable should be as simple and unambiguous as possible. In the example, there is only one ambiguous variable, and that is `day`. Relatively speaking, the variable is easy to interpret, but there is valuable information missing, i.e. *what exact day of the past several centuries are we talking about?* For some data sets, this might not be critical, but for an experiment in plant pathology, the environmental can have huge effects on the results. Thus, it is critical to know the exact date. ![](images/Tidy.png) There is still one problem with this data set in that the `day` format is month-day-year. It is generally recommended that may you use year-month-day. However, Excel does not allow year-month-day format in English (Unitd States), a ridiculous decision on the part of Microsoft! # Opening Text Files. Excel is notorious for corrupting data because of the assumptions that are made about your data type. The General import method in Excel will often convert specific textual data to dates. In addition, Excel will strip leading zeroes from numbers used as identifiers. See this [thread](https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-mso_windows8-mso_2013_release/microsoft-excel-corrupts-data-in-csv-files/8337e85c-b1f5-4e99-9ca4-1ab51ae2984e?auth=1) on the Microsoft forum about related issues. You can avoid these issues if you use the Excel Text Import Wizard, although the process is still imperfect. 1. Make sure that you have the workshop folder on your desktop. 2. Locate the files **exampleGradeBookCSV.csv** and **exampleGradeBookTAB.txt**. 3. Double-click on the **exampleGradeBookCSV.csv** file. Excel should start and open the file. 4. Look in the first column of the file labelled `student`. Confirm that this is comprised of three letters and a number. This is intended to be an anonymous student identifier. 5. Examine rows 33 and 43. What happened to the student identifier? The original data was JUN2 and MAR1. ![](images/Capture01.png) 6. Excel has converted the text values to date format because it matched a date pattern that Excel recognizes, even though none of the other values in this column were converted! 7. We can try to fix this problem. Highlight cell A33. Go to the Number section of the Menu. There is a drop-down window which should display Custom. Select Text from this drop-down. Did it fix the problem? No, we now have a number rather than `JUN2`, the original text value. In fact, if you did not save the original text file, the original data is likely lost! ![](images/Capture02.png) 8. We are done with this file. **Close** Excel and do not save the file. 9. Locate the file **exampleGradeBookTAB.txt**. Double-click on it. It should open with NotePad or WordPad not Excel. Note that the data is not corrupted in this file! Close NotePad/WordPad because we will open this file with Excel. 10. Locate Excel on your lab computer, and open it. In the bottom left of the window, click on `Open Other Workbooks`. ![](images/Capture03.png) 11. Click on `Browse` and navigate to the folder for this workshop. ![](images/Capture03a.png) 12. At the bottom right of this window is a drop down that displays `All Excel Files`. Change this to `All Files`. You should now see all files in the workshop folder. ![](images/Capture04.png) 13. Select **exampleGradeBookTAB.txt**. The Text Import Wizard should open. 14. In Step 1, confirm that file type is set to `Delimited`, and check the `My data has headers` box. Hit `Next`. ![](images/Capture05.png) 15. Note that the first few lines of the file begin with hash signs, `#`. These lines are metadata (data about data) for this data set. It is always a good idea to include metadata at the beginning of a file, marking it with a specific character or flag. 16. In Step 2, confirm that the `Delimiter` is set to `Tab` and the `Text qualifier` is set to `{none}`. Change these settings to see how it alters the `Data preview`. Restore the correct settings and enter `Next`. ![](images/Capture06.png) 17. In Step 3, change the `Column data format` to Text for the columns labelled `student`, `class` and `letter.grade`. Click `Finish`. ![](images/Capture07.png) 18. Examine rows 36 and 46 (these were rows 33 and 43 in the csv file, but the metadata has shifted their position). The student identifiers should now be correct because we did not **allow** Excel to guess at the data in this column. ![](images/Capture08.png) # Data Filtering Data Filtering is a useful Excel feature that is unfamiliar to a surprising number of people. This workshop includes Filtering primarily to help you clean your data. A simple Google search of "Excel Filtering" will produce at least dozens of useful guides or videos on additional tips for filtering. 1. Select the `Data` tab at the top of the Excel window. 2. Highlight row 4 in the data and click on the `Filter` icon. Small arrows triangles for drop down windows should appear for each column. ![](images/Capture09.png) 3. Go to the drop down for the column `class`. In the bottom of the window, you will see the values for this column. What is wrong here? We will fix these data entry errors later. ![](images/Capture10.png) 4. Go to the drop down for the column `letter.grade`. Uncheck `Select all` and select A only. Excel should display only the four students that received an A in the class. Note that you can filter on more than one column to obtain very specific subsets of your data. Try it by selecting only "Sophomores" from the `class` drop down. ![](images/Capture11.png) 5. We will use `Data filtering` again in the next workshop. Reset all columns to `Select all` before proceeding to the next section. # Data Validation Data Validation is an Excel feature that can help you to clean your data, i.e. make sure that all entries are valid and consistent. Data Validation is also an excellent tool to help insure that data is entered correctly in the first place. For example, what if you six undergraduate assistant helping you to collect data on bird observations? You need to collect date, time, environment, species and behavior for each observation. Date, time and species would probably be consistent between the students. But, can you imagine the different ways that each student could enter environment and behavior? With Data Validation, you can pre-populate the Excel columns with valid values, e.g. for behavior, you could specify flying, perching, eating, singing and bathing. The exercise will show how to clean the grades data with Data Validation. 1. The "class" column appeared to have some typos. These would be pretty easy to find and fix manually with this small file, but what if you had thousands of entries? Fortunately, there is a better way. 2. In cells L4 through L8, enter the values "valid.class", "Freshman", "Sophomore", "Junior", and "Senior". This small list will be used by Data Validation. ![](images/Capture12.png) 3. Highlight the data in the class column by selecting cell B5. Hold down `Control` and `Shift` and hit the `Down Arrow`. All data in column B should now be highlighted. ![](images/Capture13.png) 4. In the `Data` tab, find the `Data Validation` icon. It may or may not be labelled depending on the size of your window. The menu icon that you want is shown as two rectangles, one with a check and one with a red circle/slash. Click on the icon and select `Data Validation` from the drop down. ![](images/Capture14.png) 5. In the `Allow` window, select `List`. 6. In the `Source` box, click on the small spreadsheet icon at the right. Select cells L5 through L8 and click on the spreadsheet icon again. ![](images/Capture15.png) 7. Click on `OK` in the `Data Validation` window. Nothing seems to change in the `class` column, but data validation is now enabled for this column. 8. Make sure that all data in the `class` column is still highlighted. Go to `Data Validation` again and select `Circle invalid data`. ![](images/Capture16.png) 9. Scroll down, and you should see the invalid entries in the `class` column. You can fix these by selecting the bad cells and choosing the valid values from the drop down. ![](images/Capture17.png) 10. Data validation is an excellent way to check and existing data set, but you can also use it to control data entry as well. What strategies could you use on the other columns? Explore the ways that you can use Data Validation with numbers. # Pivot Tables Pivot Tables and Charts are a powerful tool to help you explore and summarize your Excel data. Unfortunately, the interface for this tool is not very intuitive, and there are significant changes between Excel versions. This is a very simple protocol to get you started. There are numerous tutorials and videos on the web. In addition, there will be more on Pivot Tables in **Data Organization with Excel 2**. 1. Before proceeding, let's save the file as an actual Excel Workbook. Go to the `File` tab, select `Save As` from the menu on the left. Select the folder for the workshop. 2. The `Save As` window should open. In the `Save as type` drop-down, select `Excel Workbook`. Change the file name by removing the TAB and click `Save`. 3. Select all data in your Excel workbook by selecting cell A4. Hold down `Ctrl` and `Shift`. Hit the `right arrow`, then the `down arrow`. Cells A4 through J104 should now be highlighted. ![](images/Capture18.png) 4. Go to the `Insert` tab and select `Pivot Table`. ![](images/Capture19.png) The `Pivot Table` window should open. Confirm that the data range `$A$4:$J$104` is showing and that the Pivot Table will be placed in a New Worksheet. Click OK. ![](images/Capture20.png) 5. You should now be in a new worksheet. At the right, there should be a section labelled `Pivot Table Fields`. Each column from the data set should appear in the top window. ![](images/Capture21.png) 6. Drag `class` to the `ROWS` window. The possible values for class should now appear in your Pivot Table on the left, but there is no more information yet. ![](images/Capture21a.png) 7. Drag `class` to the `VALUES` window. A column labelled `Count of class` should now appear. ![](images/Capture22.png) 8. Click on the `Count of class` in the `VALUES` window. Select `Value Field Settings`. ![](images/Capture23.png) 8. In the `Summarize value field by` window, `Count` should be selected. This is the only valid selection for this data. ![](images/Capture24.png) 9. Click on the `Show Value As` tab. In the drop-down, `No Calculation` should be selected. Try choosing `% of Grand Total`. ![](images/Capture25.png) 10. Let's cross tabulate class with letter.grade. Drag `letter.grade` to the `COLUMNS` window on the right. You should now have a column for each letter grade and a row for each class. ![](images/Capture26.png) Use Pivot Tables to summarize additional data from the grade book. For example, make a Pivot Table that shows `class` in rows and the `Average` of the three tests in columns. Which class did best on the first test? Which class did best on the last test? We will use Pivot Tables again in the next workshop. # Exercise In the workshop directory, there is a file named **flights_ex.xlsx**. This file contains 10000 records from a larger data set for airline flights **originating in New York City** in 2013. The column names are fairly easy to understand, but you will only need a few for this exercise. 1. There are five data entry errors in the data set, three in one column and two in a second column. Locate and correct these errors using the techinques from the workshop. Hint, it will be difficult to use Data Validation because you do not have enough information, but Filtering and Pivot Tables will be helpful. Identifying the errors will require critical thinking. 2. Answer the following questions using Pivot Tables, a. Which carrier had the most flights? b. Which carrier had the longest Average flight? c. Which carrier and origin airport had the longest Average delay? # Useful Information [Excel Functions](https://support.office.com/en-us/article/Excel-functions-alphabetical-b3944572-255d-4efb-bb96-c6d90033e188). An alphabetical list of available functions for Excel with some information on how to use them. [Excel Cheatsheet](http://www.collegedegreesearch.net/excel-cheats/) - Not comprehensive but a nice cheatsheet for common tasks. [Disadvantages of Spreadsheets](https://www.denizon.com/spreadsheets/top-10-disadvantages-of-spreadsheets/) - There are likely dozens of documents like this. Simply put, spreadsheets must used with caution. They should never be used as the sole format for your datasets!
C++
UTF-8
1,413
2.875
3
[ "MIT" ]
permissive
#include<cstdio> #include<string.h> #include<vector> #include<stack> #include<algorithm> using namespace std; #define MAXN 1000000 struct BinTree{ vector<int> C; BinTree(){ C = vector<int>(MAXN,0);} int lowbit(int x){ return x&-x; } int sum(int x){ int ret = 0; while(x > 0){ ret += C[x]; x -= lowbit(x); } return ret; } void add(int x, int d){ while(x <= MAXN){ C[x] += d; x += lowbit(x); } } int find(int x, int l ,int r){ if(l==r) return l; int mid = (l+r)/2; if(sum(mid) < x) return find(x, mid+1, r); else return find(x, l, mid); } }; BinTree tree; int main() { int N,t; char s[12]; stack<int> num; scanf("%d",&N); while(N--){ scanf("%s",s); if(s[1]=='o'){ if(num.empty()) printf("Invalid\n"); else { printf("%d\n",num.top()); tree.add(num.top(),-1); num.pop(); } } else if(s[1]=='u'){ scanf("%d",&t); num.push(t); tree.add(t,1); } else if(s[1]=='e'){ if(num.empty()) printf("Invalid\n"); else{ t = (num.size()+1)/2; printf("%d\n",tree.find(t, 1, MAXN-1)); } } } return 0; }
Java
UTF-8
413
2.25
2
[]
no_license
package ood.ocp; import java.util.function.Predicate; public class ReportITPDF implements ReportImp { private final ReportIT reportIT; public ReportITPDF(Store store) { this.reportIT = new ReportIT(store); } public String generate(Predicate<Employer> filter) { String output = reportIT.generate(filter); output += "Compile file to PDF"; return output; } }
C++
UTF-8
1,862
3.828125
4
[]
no_license
/* * merge sort */ class MergeSort{ public: int min(int x, int y) { return x < y ? x : y; } void mergeSort(int arr[], int len) { int* back = arr; int* tmp = new int[len]; //外层循环是决定内层循环每次合并元素的个数,直到<len //依次为:1->2->4->8->16->--- for (int step = 1; step < len; step += step) { //内层循环是完成一次合并 //下一次循环的开始是上一次的结尾,所以start=start+step+step for (int start = 0; start < len; start += step + step) { //取最小值:设10个元素,一次循环为0-2-4,4-6-8,8-10-10 int low = start, mid = min(low + step, len), high = min(mid + step, len); int k = low; int start1 = low, end1 = mid; int start2 = mid, end2 = high; while (start1 < end1 && start2 < end2) tmp[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; while (start1 < end1) tmp[k++] = arr[start1++]; while (start2 < end2) tmp[k++] = arr[start2++]; } swap(tmp, arr); } //跳出外层循环后arr就是排好序的,但是我们必须把结果放到arr(back)中 //因为上边tmp和arr不断交换,到底谁指向arr需要判断 //如果back!=arr那么需要把arr的值赋值给back,然后把arr赋给tmp if (back != arr) { //arr == tmp; for (int i = 0; i < len; i++) { back[i] = arr[i]; } tmp = arr; } delete[] tmp; } };
PHP
UTF-8
724
3.046875
3
[]
no_license
<?php require __DIR__.'/vendor/autoload.php'; class obj implements Serializable { private $data; public function __construct() { $this->data = "Mes données privées"; } public function serialize() { return serialize($this->data); } public function unserialize($data) { $this->data = unserialize($data); } public function getData() { return $this->data; } } $filePath = __DIR__ ; $colors = new Cli\Colors(); $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($filePath), RecursiveIteratorIterator::SELF_FIRST); foreach($files as $name => $file){ echo $colors->getColoredString($name, "black", "green") . "\n"; } ?>
JavaScript
UTF-8
4,887
3.640625
4
[]
no_license
/** * Created by mshoc on 10/10/2017. */ /** * An object that implements a simple publisher / subscriber interface. */ export class Publisher { constructor() { this.topics = {}; } /** * Subscribe to a topic. * @param topic * @param callback */ subscribe(topic, callback) { // If only 1 argument is provided the topic is *. if(arguments.length === 1) { callback = topic; topic = "*"; } // Sanity check. if(typeof callback !== "function") { throw new TypeError("Callback must be a function."); } if(!this.topics[topic]) { this.topics[topic] = []; } this.topics[topic].push(callback); } /** * Unsubscribe from a topic. * @param topic * @param callback * @returns {*} */ unsubscribe(topic, callback) { // If only 1 argument is provided the topic is *. if(arguments.length === 1) { callback = topic; topic = "*"; } if(this.topics[topic]) { let i = this.topics[topic].indexOf(callback); if(i !== -1) { this.topics[topic].splice(i, 1); return callback; } } } /** * Returns true if the callback is subscribed to the topic. * @param topic * @param callback * @returns {boolean} */ isSubscribed(topic, callback) { // If only 1 argument is provided the topic is *. if(arguments.length === 1) { callback = topic; topic = "*"; } return this.topics[topic] ? this.topics[topic].indexOf(callback) !== -1 : false; } /** * Clears a topic of all subscribers. * @param topic */ clear(topic) { if(this.topics[topic]) { this.topics[topic] = []; } } /** * Publishes a topic with the given arguments. * @param topic * @param args */ publish(topic, ...args) { if(topic === "*") { throw new Error("You cannot publish the global topic *."); } if(this.topics[topic]) { for(let i = 0, l = this.topics[topic].length; i < l; i++) { if(this.topics[topic][i](...args) === false) { break; } } } if(this.topics["*"]) { for(let i = 0, l = this.topics["*"].length; i < l; i++) { if(this.topics["*"][i](topic, ...args) === false) { break; } } } } } /** * An observable object. Can add and remove callbacks and fire events. */ export class Observable { constructor(...args) { this.args = args; this.callbacks = []; } add(callback) { // Sanity check. if(typeof callback !== "function") { throw new TypeError("Callback must be a function."); } this.callbacks.push(callback); } remove(callback) { let i = this.indexOf(callback); if(i !== -1) { this.callbacks.splice(i, 1); return callback; } } has(callback) { return this.indexOf(callback) !== -1; } indexOf(callback) { return this.callbacks.indexOf(callback); } clear() { this.callbacks = []; } fire(...args) { if(this.args) { args = this.args.concat(args); } for(let i = 0, l = this.callbacks.length; i < l; i++) { this.callbacks[i](...args); } } } /** * Returns a function that sets a flag if it is called once. * * Expected usage. * * let flag = flagCallback(); * * pubsub.publish("someTopic", flag); * * if(flag.wasCalled()) { * // Do something * } * * @return {fn} */ export function flagCallback() { let fn = function() { fn.flag = true; }; fn.flag = false; fn.wasCalled = function() { return fn.flag; }; return fn; } /** * Creates a function that register any function passed to it to a list of actions. You can then call fn.fire(...args) * to fire all register callbacks of that function. The expected usage of this function is to create parameters for * other callback function. * * Example usage. * * let before = thenCallback(), * after = thenCallback(); * * pubsub.publish("someTopic", before, after); * * before.fire(); * // do something. * after.fire(); * * @return {fn} */ export function thenCallback() { let fn = function(callback) { fn.actions.push(callback); }; fn.actions = []; fn.fire = function(...args) { for(let i = 0, l = fn.actions.length; i < l; i++) { fn.action[i](...args); } }; return fn; }
Python
UTF-8
22,248
3.640625
4
[]
no_license
#Functions related to statistics applied on the data. import numpy as np import healpy as hp from progress.bar import Bar from tqdm.notebook import tqdm from scipy.special import legendre from itertools import product #Dot product function (normalized) def dot_product(X,Y): normx = np.linalg.norm(X) normy = np.linalg.norm(Y) if normx == 0 or normy == 0: return 0 else: return np.multiply(X/normx, Y/normy).sum() #Correlation function def correlation(X,Y): ''' Correlation function. Assumes the input x and y are two numpy matrices of identical shape. The formula is corr = COV(x,y)/(STD(x)*STD(y)) = COV(x,y)/sqrt(VAR(x)*VAR(y)) Note that COV(x,y) = E(x.*y) - E(x)E(y), where .* is pointwise multiplication between the two matrices. ''' cov = np.multiply(X,Y).mean() - X.mean()*Y.mean() if X.std()==0 or Y.std()==0: return 0 else: return cov/(X.std()*Y.std()) #Algorithm dividing into subarrays two matrices and computing a function that takes submatrices as arguments. def sub_apply(a, b, func, subarr_size = 10, filter_zeros=True): ''' Algorithm: Takes two matrices of size NxN. Then it divides each matrix into submatrices of size 'subarr_size' x 'subarr_size', and computes the given function on submatrices from one matrix and the other element-wise (elements being the submatrices). From this an array of scalar values is obtained. The mean and std are computed and returned. Parameters : ---------------------- a: First matrix of size (N,N) b: Second matrix of size (N,N) func: function that will be applied on subarrays. subarr_size: The wanted size of the subarrays. Must be a multiple of N. filter_zeros: If true, removes all correlation values that are exactly equal to 0 from the array. ''' if a.shape != b.shape: #We want same dimensions for both matrices raise Exception('The matrices are of different shape.') return 0 if a.shape[0] != a.shape[1]: #We want square matrices raise Exception('The matrices are not squares. They have shape: {}'.format(a.shape)) return 0 N,_ = a.shape vals = [] if N % subarr_size != 0: #We want the size of the subarray to be a multiple of the size of the whole array return 0 step = subarr_size #This is solely to express understanding of how subarray size translates to algorithm. for i in range(0,N,step): for j in range(0,N,step): vals.append(func(a[i:i+step, j:j+step],b[i:i+step, j:j+step])) if filter_zeros: vals = list(filter(lambda x: x!=0, vals)) #Remove all 0 values. return np.mean(vals), np.std(vals) #Same as sub_apply, except we also compute function between "not-element-wise" submatrices. def cross_sub_apply(arr_fixed, arr_iter, func, subarr_size=10, filter_zeros=True, weights=False): ''' Similar in concept to sub_apply. The difference is that instead of applying the function subarray-wise only, that is, first subarray of array #1 taken with first subarray of array #2, second with second, etc... we have that the first subarray of arr_fixed is taken with all of the subarrays of arr_iter, and we average over these values to get our first scalar value. We repeat for the second subarray of fixed_arr,the third, etc... and this way we get (N/subarr_size)^2 scalar values. We then return the mean and std of these values. Parameters: -------------- arr_fixed: The array that is fixed. arr_iter: The array over which we iterate. func: The function applied on the subarrays. subarr_size: If subarray size is N^2, then subarr_size is N. weights: If true, we compute a weighted average on values gotten from a single iteration. The weights are given by 1/(1+distance). ''' if arr_fixed.shape != arr_iter.shape: #We want same dimensions for both matrices raise Exception('The matrices are of different shape.') if arr_fixed.shape[0] != arr_fixed.shape[1]: #We want square matrices raise Exception('The matrices are not squares. They have shape: {}'.format(a.shape)) N,_ = arr_fixed.shape vals = [] if N % subarr_size != 0: #We want the size of the subarray to be a multiple of the size of the whole array raise Exception('The subarray size must be a multiple of the array size') step = subarr_size #This is solely to express understanding of how subarray size translates to algorithm. for i in range(0,N,step): for j in range(0,N,step): subvals = [] distance = [] for n in range(0,N,step): for m in range(0,N,step): subvals.append(func(arr_fixed[i:i+step, j:j+step], arr_iter[n:n+step, m:m+step])) distance.append(max([abs(n-i)/step, abs(m-j)/step])) if filter_zeros: subvals = np.array(subvals) distance = np.array(distance)[subvals!=0] subvals = subvals[subvals!=0] if len(subvals)!=0: if weights: subvals_avg = np.average(subvals, weights=1/(1+np.array(distance))) else: subvals_avg = np.mean(subvals) vals.append(subvals_avg) return np.mean(vals), np.std(vals) #Applies dot product function above on elements lying on radius def circular_product(X,Y, filter_zeros=True): ''' Algorithm: We pick an element at position i,j from both matrices X,Y. We pick the boundary elements of a square of size 2*theta+1 (basically, the side of the square is a distance theta from the point i,j) centered at i,j from both X and Y. We compute the normalized dot product between the two boundaries gotten from X and Y. we then increase theta and repeat the latter action. This gives us a set of subvalues associated with position i,j. We average those subvalues, giving us a single value associated with position i,j. We then repeat for each position in the matrix. Finally, we have a total of NxN values. We return the mean and std. Note that boundary conditions are not circular. They are flattening. That is, we return 0 when going in negative indices, and we return N-1 when going over the array size. (For keen observers, we see that the function actually returns N instead of N-1 when slice=True. This is because when slicing numpy array like X[a:b], a <= index < b. Parameters: ------------- X: The first matrix of size NxN. Y: The second matrix of size NxN. filter_zeros: If true, we remove the 0's from the sub_value array. (array containing values for fixed position, changing theta) ''' if X.shape != Y.shape: raise Exception('The matrices are of different shape.') return 0 if X.shape[0] != X.shape[1]: raise Exception('The matrices are not squares. They have shape: {}'.format(a.shape)) return 0 N,_ = X.shape def b(index, slice=False): if index<=0: return 0 if slice: if index>N: return N else : return index else: if index>=N : return N-1 else : return index vals = [] for i in range(N): for j in range(N): subvals = [] for theta in range(1,N): upper_border = X[b(i-theta), b(j-theta, True) : b(j+theta, True)] lower_border = X[b(i+theta), b(j-theta, True) : b(j+theta, True)] left_border = X[b(i-theta, True) : b(i+theta, True), b(j-theta)] right_border = X[b(i-theta, True) : b(i+theta, True), b(j+theta)] X_circle = np.concatenate((upper_border, lower_border, left_border, right_border), axis=0) upper_border = Y[b(i-theta), b(j-theta, True) : b(j+theta, True)] lower_border = Y[b(i+theta), b(j-theta, True) : b(j+theta, True)] left_border = Y[b(i-theta, True) : b(i+theta, True), b(j-theta)] right_border = Y[b(i-theta, True) : b(i+theta, True), b(j+theta)] Y_circle = np.concatenate((upper_border, lower_border, left_border, right_border), axis=0) subvals.append(dot_product(X_circle, Y_circle)) if filter_zeros: subvals = list(filter(lambda x: x!=0, subvals)) if subvals: vals.append(np.mean(subvals)) return np.mean(vals), np.std(subvals) #Computes arr[i,j] - <arr_i,j> where arr_i,j is a subarray of size kxk centered at i,j. i.e., localized centering. def filter_arr(arr, k): ''' Takes an array of size NxM, and for each point in the array, it centers it locally. i.e., removes the mean from the point. Conditions are as follows: -We pick a radius of k for all points except for border stripes of size k. For the latter case its a bit different. -Boundary conditions are not cyclic. Parameters: --------------- arr : The array we wish to apply a function on locally. k : The radius of the subarrays. i.e. if k=1, we look at 3x3 sub-arrays, k=2 means 4x4, etc... ''' N,M = arr.shape final_arr = np.empty([N,M]) #Center of array for i in range(k,N-k): for j in range(k, M-k): final_arr[i,j] = arr[i,j] - arr[i-k:i+k+1, j-k:j+k+1].mean() #Four sides, excluding corners #Vertical lefmost stripe for i in range(k,N-k): for j in range(0, k): final_arr[i,j] = arr[i,j] - arr[i-k:i+k+1, 0:k].mean() #Vertical rightmost stripe for i in range(k,N-k): for j in range(M-k, M): final_arr[i,j] = arr[i,j] - arr[i-k:i+k+1, M-k:M].mean() #Horizontal uppermost stripe for i in range(0,k): for j in range(k, M-k): final_arr[i,j] = arr[i,j] - arr[0:k, j-k:j+k+1].mean() #Horizontal lowermost stripe for i in range(N-k,N): for j in range(k, M-k): final_arr[i,j] = arr[i,j] - arr[N-k:N, j-k:j+k+1].mean() #Upper-left corner for i in range(0,k): for j in range(0,k): final_arr[i,j] = arr[i,j] - arr[0:k, 0:k].mean() #Upper-right corner for i in range(0,k): for j in range(M-k,M): final_arr[i,j] = arr[i,j] - arr[0:k, M-k:M].mean() #Lower-left corner for i in range(N-k, N): for j in range(0,k): final_arr[i,j] = arr[i,j] - arr[N-k:N, 0:k].mean() #Lower-right corner for i in range(N-k, N): for j in range(M-k,M): final_arr[i,j] = arr[i,j] - arr[N-k:N, M-k:M].mean() return final_arr def get_circle(mat, center_point, radius, full=False): ''' Used to retrieve points on an approximated circle on a 2d array (matrix). Center point is an index and radius is in term of indices. Parameters: ------------ mat: A numpy matrix of size (N,M) center_point: The center of the circle, given as an index tuple (i,j) radius: radius of approximated circle ''' if full: f = lambda x:x else: f = abs j, i = np.meshgrid(range(mat.shape[1]), range(mat.shape[0])) return mat[f((i-center_point[0])**2 + (j-center_point[1])**2 - radius**2) < radius] def get_circle_coord(x, y, center_point, radius, full=True): ''' Used to retrieve all points of an x-y grid found on the boudary of a circle. Parameters: ------------ x: x coordinate y: y coordinate center_point: The center of the circle, given in same units as x,y coordinates radius: radius of circle in units of x,y coordinates full: If false, returns only coordinates on the boundary. ''' if full: mask = (x-center_point[0])**2 + (y-center_point[1])**2 <= radius**2 else: epsilon=radius mask = abs((x-center_point[0])**2 + (y-center_point[1])**2 - radius**2) < epsilon return x[mask], y[mask] def w(iter_map, circle_map, theta): ''' Two point correlation function approximated. parameters: ------------ iter_map: map from which we draw the scalar values at each index. circle_map: map from which we draw the circle values centered at index of scalar value of iter_map. theta: radius of circle drawn / distance of two point correlation function. returns w(theta) and the error on w(theta). The error comes from the variance of the dot product over position in the sky. Hence, for a fixed theta, it quantifies how much variation there is over the sky for the "circular" dot product. ''' if iter_map.shape != circle_map.shape: raise Exception('matrices are of different shape.') it = (get_circle(circle_map, index, theta).mean() for index in product(range(circle_map.shape[0]), range(circle_map.shape[1]))) arr = np.fromiter(it, dtype=np.float).reshape(iter_map.shape) res = iter_map*arr return res.mean(), res.std()/np.sqrt(res.size) def coord2hp(ra, dec, nside, nest=False, lonlat=True, remove_zeros=True, galactic=True): ''' Transformation from a set of ra, dec coordinates in degrees to an overdensity field in healpix format. Parameters: ----------------- ra: ra coordinates as numpy array dec: dec coordinates as numpy array nside: nside parameter of healpix map nest: Ordering of healpix map. If true, nested, else, ring. lonlat: Degrees or radians, and latitude vs co-latitude. See healpy documentation for specifics. remove_zeros: If true, pixels holding 0 count will hold the value of hp.UNSEEN. Useful to exclude 0's from further calculations. galactic: If true, transforms the map to galactic coordinates. Else it returns it in equatorial coordinates. ''' arr = hp.ang2pix(nside,ra,dec,nest=nest,lonlat=lonlat) count_arr = np.histogram(arr, bins=hp.nside2npix(nside), range=[0,hp.nside2npix(nside)])[0].astype('float') if count_arr.mean()==0: raise Exception('Empty set of coordinates.') mean = count_arr[count_arr!=0].mean() count_arr[count_arr==0] = hp.UNSEEN if galactic: count_arr = change_coord(count_arr, ['C', 'G']) count_arr[count_arr!=hp.UNSEEN] = count_arr[count_arr!=hp.UNSEEN]/mean - 1 return count_arr def field2healpix(ra, dec, nside, prog=True): ''' Converts a density field to a healpix map. Assumes density field is in degrees, and has coordinates system ra (x-axis) and dec (y-axis). Parameters: -------------- nside: resolution of wanted healpix map ra: ra coordinates forming the field dec: dec coordinates forming the field ''' resol = np.degrees(hp.nside2resol(nside, arcmin=False)) radius = resol/2 N = len(ra) index = np.arange(hp.nside2npix(nside)) theta, phi = hp.pix2ang(nside, index, nest=False, lonlat=True) if prog: it = (((ra-cp[0])**2 + (dec-cp[1])**2 <= radius**2).sum() for cp in tqdm(zip(theta,phi), total=len(theta))) else: it = (((ra-cp[0])**2 + (dec-cp[1])**2 <= radius**2).sum() for cp in zip(theta,phi)) return np.fromiter(it, dtype=np.float) def C(theta, C_l): ''' Two point correlation function defined by its fourier transform (basically) for some fixed theta Parameters: ------------- theta: separation angle. C_l: array of C_l values computed with anafast. ''' it = ( ((2*l+1)/4*np.pi) * legendre(l)(np.cos(theta)) for l in range(len(C_l)) ) return np.dot(C_l, np.fromiter(it, dtype=np.float)) def change_coord(m, coord): """ Change coordinates of a HEALPIX map Parameters ---------- m : map or array of maps map(s) to be rotated coord : sequence of two character First character is the coordinate system of m, second character is the coordinate system of the output map. As in HEALPIX, allowed coordinate systems are 'G' (galactic), 'E' (ecliptic) or 'C' (equatorial) Example ------- The following rotate m from galactic to equatorial coordinates. Notice that m can contain both temperature and polarization. >>>> change_coord(m, ['G', 'C']) """ # Basic HEALPix parameters npix = m.shape[-1] nside = hp.npix2nside(npix) ang = hp.pix2ang(nside, np.arange(npix)) # Select the coordinate transformation rot = hp.Rotator(coord=reversed(coord)) # Convert the coordinates new_ang = rot(*ang) new_pix = hp.ang2pix(nside, *new_ang) return m[..., new_pix] #CORRELATION FUNCTION #The database-independent two-point correlation function. def compute_corr_v1(map1, map2, theta, nest=False): ''' version 1 of w(theta). This version gets the whole list of possible m(r1)m(r2) using the ring method to then compute <m(r1)m(r2)>. It is very explicit and thus slow. On the other hand, it is clear what the function does. The function is symmetric and linear. (experimentally tested, and it is also logical) Parameters: ------------ map1: first healpix map map2: second healpix map theta: distance |r1-r2| in radians nest: ordering of the healpix maps ''' if hp.get_nside(map1)!=hp.get_nside(map2): raise Exception('Maps are of two different resolutions.') #set healpix maps parameters nside = hp.get_nside(map1) npix = hp.nside2npix(nside) #Get the vectors associated with pixels X,Y,Z = hp.pix2vec(nside, np.arange(npix), nest=False) #Function used to retrieve mean of circle with center vec and radius theta in map2 def get_circle(vec): dr = 10*hp.nside2resol(nside) disk1 = hp.query_disc(nside, vec, theta+dr, nest=nest) disk2 = hp.query_disc(nside, vec, theta, nest=nest) index = np.setdiff1d(disk1,disk2, assume_unique=True) circle = map2[index].astype(np.float) return circle[circle!=hp.UNSEEN] #Function used to retrieve scalar at vector position x,y,z in map1 def get_scalar(x,y,z): scalar = map1[hp.vec2pix(nside, x, y, z, nest=nest)] if scalar == hp.UNSEEN: return 0 else: return scalar vals = [] for x,y,z in tqdm(zip(X,Y,Z), total=X.size): vals.extend(get_scalar(x,y,z)*get_circle([x,y,z])) ans = np.array(vals) return ans[ans!=0].mean(), ans[ans!=0].std() #Function used to store the index ring matrices in the CorrelatonFunctionDB file. def make_ring_matrices(nside, thetas, nest=False, save=True): for theta in tqdm(thetas, position=0): npix = hp.nside2npix(nside) dr = 2*hp.nside2resol(nside) R = np.radians(theta) X,Y,Z = hp.pix2vec(nside, np.arange(npix), nest=nest) l=0 #We look for the smallest size of the indices first. This is to avoid indices mismatch between rows. for x,y,z in tqdm(zip(X,Y,Z),total=npix,position=1): disk1_size = hp.query_disc(nside, [x,y,z], R+dr, nest=nest).size disk2_size = hp.query_disc(nside, [x,y,z], R, nest=nest).size if (disk1_size-disk2_size)>l: l=(disk1_size-disk2_size) #We initialize our matrix of indices. A = np.empty((npix,l), np.int) #We loop over all pixels in the map, and retrieve the indices of the values #on the circle centered on that pixel and of radius theta. #We thus fill up a matrix of indices, where each row is the indices of the values on that circle. for x,y,z,i in tqdm(zip(X,Y,Z,range(npix)),total=npix, position=2): disk1 = hp.query_disc(nside, [x,y,z], R+dr, nest=nest) disk2 = hp.query_disc(nside, [x,y,z], R, nest=nest) idx = np.setdiff1d(disk1,disk2, assume_unique=True) if idx.size<l: #pad with nan values up to size l num = l-idx.size idx = np.append(idx, [npix]*num) A[i,:] = idx if save: full_path = '/Users/williiamlaplante/Research/SynchrotronMaps/data/CorrelationFunctionDB/' if nest: n = '_nest' else: n = '_ring' np.save(full_path + str(nside) + '_' + str(theta) + n + '.npy', A) return #Function used to compute the correlation function values beteen two maps. It assumes the index array is in the DB. def compute_corr_v2(m1,m2, theta, nest=False): if hp.get_nside(m1)!=hp.get_nside(m2): raise Exception('Maps are of different resolution.') if theta==0: return (m1*m2).mean(), (m1*m2).std() nside = hp.get_nside(m1) full_path = '/Users/williiamlaplante/Research/SynchrotronMaps/data/CorrelationFunctionDB/' if nest: n = '_nest' else: n = '_ring' try: theta_list = list(str(theta)) while len(theta_list)<6: theta_list.append('0') A = np.load(full_path + str(nside) + '_' + ''.join(theta_list)[:6] + n + '.npy') except FileNotFoundError: raise Exception('There is no index matrix for this theta and resolution, you must create one first.') return arr1 = np.append(m1, hp.UNSEEN)[A] arr1[arr1==hp.UNSEEN] = np.nan m2[m2==hp.UNSEEN] = np.nan arr1 = arr1*m2.reshape(-1,1) return np.nanmean(arr1, dtype=np.float), np.nanstd(arr1, dtype=np.float)
Ruby
UTF-8
2,924
2.546875
3
[ "Apache-2.0" ]
permissive
# Copyright 2018 Google LLC # # 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. require 'google/apis/drive_v3' require 'securerandom' class TeamDriveSnippets def initialize(service) @service = service end def drive_service @service end def create_team_drive # [START drive_create_team_drive] team_drive_metadata = { name: 'Project Resources' } request_id = SecureRandom.uuid team_drive = drive_service.create_teamdrive(request_id, team_drive_metadata, fields: 'id') puts "Team Drive Id: #{team_drive.id}" # [END drive_create_team_drive] team_drive.id end def recover_team_drives(real_user) # [START drive_recover_team_drives] # Find all Team Drives without an organizer and add one. # Note: This example does not capture all cases. Team Drives # that have an empty group as the sole organizer, or an # organizer outside the organization are not captured. A # more exhaustive approach would evaluate each Team Drive # and the associated permissions and groups to ensure an active # organizer is assigned. new_organizer_permission = { type: 'user', role: 'organizer', email_address: 'user@example.com' } # [START_EXCLUDE silent] new_organizer_permission[:email_address] = real_user # [END_EXCLUDE] team_drives = drive_service.fetch_all(items: :team_drives) do |page_token| drive_service.list_teamdrives( q: 'organizerCount = 0', fields: 'nextPageToken, teamDrives(id, name)', use_domain_admin_access: true, page_token: page_token ) end for team_drive in team_drives puts "Found Team Drive without organizer: #{team_drive.name} #{team_drive.id}" permission = drive_service.create_permission(team_drive.id, new_organizer_permission, use_domain_admin_access: true, supports_team_drives: true, fields: 'id') puts "Added organizer permission: {permission.id}" end # [END drive_recover_team_drives] return team_drives.to_a end end
Python
UTF-8
358
3.3125
3
[]
no_license
shopping_items = [ ("ziemniak", 2.5, 0.51), ("cebula", 3, 1.60), ("ser", 0.8, 15.50) ] def get_index_1_tuple_element(given_tuple): return given_tuple[1] sorted_items = sorted(shopping_items, key=get_index_1_tuple_element) print(sorted_items) sorted_items = sorted(shopping_items, key=lambda given_tuple: given_tuple[1]) print(sorted_items)
Markdown
UTF-8
2,533
2.734375
3
[]
no_license
HOW IT'S WIRED -------------- 1. Nearly all requests go through a Sails API Controller ( `api/controllers` ) even if the controller is not tied to a model. Requests pass first through `config/router.js` where the controller is assigned to the route. <br> 2. Blueprint routes are attached to `api/v2` and every Blueprint needs to go through a policy by the time we get to production OR BE TURNED OFF. The Blueprint route security actually ends up also controlling the Angular UI apps. The UI-Router block uses `resolves` before pages are called. If those resolves fail, then the page isn't loaded. For example, trying to load an admin Blueprint resource by a non-admin will fail causing the page to not be shown. Exactly what we want. <br> 3. The EJS template engine is used. The UI is served from `views/ui`. There are 2 files in there: `uilayout.ejs` which has 99% of code needed, and `uiapp.ejs` which is really just the ui-view in a bootstrap container. CSS and JS dependencies are loaded through EJS includes from `views/partials`. <br> 4. Nearly all URLs go through `policies/authDecorator.js` which add local vars for the EJS engine to use to see if the user is authenticated, admin, etc. The templates use this to keep HTML from even getting into the client browser that shouldn't be seen such as admin menus. PASSWORD RESET FLOW ------------------- 1. Request goes to `auth/reset?email=someone@test.com`. 2. A token is generated inside `reset.js` inside waterlock-local-auth. The ResetToken model has a before and after create method that does the actual emailing. I don't think I would have done it this way, since it ties the reset method very tightly to the emailing. For example, what if you wanted to do an SMS method? 3. An email is sent with a link to `GET /auth/reset?token=xyzed`. This GET is handled in `lib/controllers/actions/reset.js` and it checks the token, then if the token is cool, and a redirect is set in `config/waterlock.js` a redirect happens to whatever URL is in there. It should be a page to deal with letting the user enter a new password. `res.session.resetToken` is set to the same token. 4. A policy should be run to check the session token that gates access to a password rest page. USER VALIDATION FLOW -------------------- Create the user, get the auth and create a token then add it to the auth and the token creation will send an email. An HTTP `GET` to `/auth/validate` will invoke the validation process. This is done by clicking the link from the email
Shell
UTF-8
363
2.828125
3
[ "MIT" ]
permissive
#!/bin/bash #Using script from http://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_cloudwatch_logs.html # Install awslogs and the jq JSON parser yum install -y awslogs jq aws-cli # ECS config ${ecs_config} { echo "ECS_CLUSTER=${cluster_name}" echo 'ECS_AVAILABLE_LOGGING_DRIVERS=${ecs_logging}' } >> /etc/ecs/ecs.config start ecs echo "Done"
TypeScript
UTF-8
1,727
2.640625
3
[ "MIT" ]
permissive
import * as commander from 'commander'; import { generate } from '../generate'; export class AppGen { private program: commander.CommanderStatic; private package: any; constructor() { this.program = commander; this.package = require('../../package.json'); } public initialize() { this.program .version(this.package.version) .option("-t, --template <dir>", "folder from which to fetch the template(s)", "./template") .option("-w, --target <dir>", "folder in which to write the generated code file(s)", "./") .option("-s, --schema <file>", "JSON file to read (base) schema from", "models/schema.json") .option("-o, --overlay <file>", "JSON file to read, defining additions to the schema.data.__schema.types (especially metadata)") .option("-d, --default-meta <file>", "ES6 template file defining the metadata structure and default values (used for each type, in the absence of any other sources)") .option("-k, --default-meta-key <key>", "key of the metadata structure node in the above file") .option("-e, --eval-exclude-files", " a regex to match any filenames to be excluded from eval (e.g. to exclude defaultMeta)") .option("-b, --debug", "output extra debugging") .parse(process.argv); const options = this.program.opts(); if (options.debug) console.log(options); // if (typeof this.program.target !== 'string') throw new Error(`No target folder specified`); generate( this.program.template, this.program.target, this.program.schema, this.program.overlay, this.program.defaultMeta, this.program.defaultMetaKey ); process.exit(); } } let app = new AppGen(); app.initialize();
TypeScript
UTF-8
5,462
2.625
3
[]
no_license
import { Point } from "../../utils/Point"; import { getRules } from "../../facade"; import { Container } from "pixi.js"; import { DragProcessController } from "./DragProcessController"; export interface CustomDragEvent<T> { target: T; cursor: Point; } export interface DragEventNodeControllable { activateAwaitDrag(): void; activateDrag(): void; deactivateDrag(): void; deactivateAwaitDrag(): void; } export interface DragController<T> { start(node: DragEventNodeControllable, event: CustomDragEvent<T>): void; drag(node: DragEventNodeControllable, event: CustomDragEvent<T>): void; end(node: DragEventNodeControllable, event: CustomDragEvent<T>): void; post(node: DragEventNodeControllable, event: CustomDragEvent<T>): void | Promise<void>; } export interface DragNode<Target> extends DragEventNodeControllable { install ( dragController: DragController<Target> ): void; } export interface DragValidator<Target, State> { validate( event: CustomDragEvent<Target>, state: State ): boolean; } export interface DragContext<State> { isPure: boolean; state: State; dragProcessController: DragProcessController; } export interface DragRuleState<S> { defaultState?(): S; } export interface DragUtils { isPure: boolean; dragProcessController: DragProcessController; } export interface DragRule<Target, State> extends DragRuleState<Partial<State>>, WithEvents<Target, State, any>{ start?: (event: CustomDragEvent<Target>, state: State, utils: DragUtils) => Partial<State> drag?: (event: CustomDragEvent<Target>, state: State, utils: DragUtils) => Partial<State> end?: (event: CustomDragEvent<Target>, state: State, utils: DragUtils) => Partial<State> post?: (event: CustomDragEvent<Target>, state: State, utils: DragUtils) => void | Promise<void> postAbort?: (event: CustomDragEvent<Target>, state: State, utils: DragUtils) => void } /* */ export type WithDefaultState = { defaultState?: () => any; } type DefaultState<Instance extends WithDefaultState> = NonNullable<Instance["defaultState"]> export type ToStore<T extends DragRuleState<any>> = ReturnType<NonNullable<T["defaultState"]>>; type UnionKeys<T> = T extends object ? keyof T : never; type UnionPick<T, PikedKey extends UnionKeys<T>> = T extends { [K in PikedKey]: any } ? T[PikedKey] : never; type UnionMerge<T extends object> = { [K in UnionKeys<T>]: UnionPick<T, K> } type ExcludeActions<T> = T extends WithState<any> ? T : never; type Rules = ReturnType<typeof getRules>[number]; type Functions = ExcludeActions<Rules>; type GetState = ToStore<Functions>; type CommonState = UnionMerge<Functions>; // type RuleAll = ReturnType<typeof getRules>[number]; // type RuleState = ToStore<RuleAll>; export type DragGlobalState = UnionMerge<GetState> export interface PhaseElement<T, S, R> { (event: Readonly<CustomDragEvent<T>>, state: Readonly<S>, utils: DragUtils): R; } export interface WithState<S> { defaultState: () => Partial<S>; } export type WithEvents<T, S, E> = { toDragEndEvent?: PhaseElement<T, S, E>; } export type WithDragEndEvent<T, S, E> = { toDragEndEvent: PhaseElement<T, S, E>; } export interface ActionLifeCycle<T, S> extends PhaseElement<T, S, void>{ } export interface FunctionLifeCycle<T, S> extends PhaseElement<T, S, Partial<S>>{ } export interface StartActionLifeCycle<T, S> { start: ActionLifeCycle<T, S>; } export interface DragActionLifeCycle<T, S> { drag: ActionLifeCycle<T, S>; } export interface EndActionLifeCycle<T, S> { end: ActionLifeCycle<T, S>; } export interface StartFunctionLifeCycle<T, S> { start: FunctionLifeCycle<T, S>; } export interface DragFunctionLifeCycle<T, S> { drag: FunctionLifeCycle<T, S>; } export interface EndFunctionLifeCycle<T, S> { end: FunctionLifeCycle<T, S>; } export interface PostActionLifeCycle<T, S> { post: PhaseElement<T, S, void>; } export interface PostAsyncActionLifeCycle<T, S> { post: PhaseElement<T, S, Promise<void>>; } export interface PostAbortActionLifeCycle<T, S> { postAbort: PhaseElement<T, S, void>; } export interface ActionOnlyLifeCycle<T, S> { start?: ActionLifeCycle<T, S>; drag?: ActionLifeCycle<T, S>; end?: ActionLifeCycle<T, S>; } export interface FunctionOnlyLifeCycle<T, S> { start?: FunctionLifeCycle<T, S>; drag?: FunctionLifeCycle<T, S>; end?: FunctionLifeCycle<T, S>; } interface BState { b: number; } interface CState { c: string; } type State = BState & CState; class Rule {} class ARule implements StartActionLifeCycle<Container, State>{ start: ActionLifeCycle<Container, State> = () => { }; } class BRule implements StartFunctionLifeCycle<Container, BState>{ defaultState(){ return { b: 5 }; } start: FunctionLifeCycle<Container, BState> = () => { return { b: 6 } }; } class CRule implements StartFunctionLifeCycle<Container, CState>, DragFunctionLifeCycle<Container, CState>{ defaultState(){ return { c: `5` }; } start: FunctionLifeCycle<Container, CState> = () => { return { c: `` } } drag: FunctionLifeCycle<Container, CState> = () => { return { c: `` } } } const rules = () => [ new ARule(), new BRule(), new CRule(), ]; type TExcludeActions<T> = T extends WithState<any> ? T : never; type TRules = ReturnType<typeof rules>[number]; type TFunctions = TExcludeActions<TRules>; type TGetState = ToStore<TFunctions>; type TCommonState = UnionMerge<TGetState>;
Markdown
UTF-8
612
2.953125
3
[]
no_license
# Concurrent Adder This Golang package provides a function to generate a sum of an integer array (with each value transformed first) and send it through a channel (to allow for concurrency). The number of transformations and channels is variable. This is the rough equivalent of a set of `MapReduce` functions, with the `map` being a function reference as an argument and the `reduce` being the sum of the result of the function applied to the value. This is a terrible thing and I was inspired by [@CtrlShiftGo](https://github.com/ctrlshiftgo) and [@GalaxyVintage](https://github.com/galaxyvintage) to do it.
Java
UTF-8
3,825
2.46875
2
[]
no_license
package org.usfirst.frc.team5422.commands; import org.usfirst.frc.team5422.controller.StrongholdRobot; import org.usfirst.frc.team5422.defense.ChivalDeFrise; import org.usfirst.frc.team5422.defense.DefenseTypeInterface; import org.usfirst.frc.team5422.defense.DrawBridge; import org.usfirst.frc.team5422.defense.LowBar; import org.usfirst.frc.team5422.defense.Moat; import org.usfirst.frc.team5422.defense.PortCullis; import org.usfirst.frc.team5422.defense.Ramparts; import org.usfirst.frc.team5422.defense.RockWall; import org.usfirst.frc.team5422.defense.RoughTerrain; import org.usfirst.frc.team5422.defense.SallyPort; import org.usfirst.frc.team5422.utils.StrongholdConstants.defenseTypeOptions; import org.usfirst.frc.team5422.utils.StrongholdConstants.shootOptions; import edu.wpi.first.wpilibj.command.Command; /** *@author Suren */ public class DefenseCommand extends Command { protected defenseTypeOptions defenseTypeSelected = defenseTypeOptions.LOW_BAR; protected int defensePositionSelected = -1; protected shootOptions shootOptionSelected = shootOptions.HIGH_CENTER; DefenseTypeInterface defense; public DefenseCommand() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { System.out.println("Initializing DefenseCommand through AutonomousCommandGroup."); defenseTypeSelected = StrongholdRobot.defenseTypeSelected;//(defenseTypeOptions) DSIO.defenseChooser.getSelected(); defensePositionSelected = StrongholdRobot.defensePositionSelected;//(defensePositionOptions) DSIO.defensePositionChooser.getSelected(); shootOptionSelected = StrongholdRobot.shootOptionSelected;//(shootOptions) DSIO.shootChooser.getSelected(); switch(defenseTypeSelected) { case CHIVAL_DE_FRISE: defense = new ChivalDeFrise(defenseTypeSelected, defensePositionSelected); ; break; case LOW_BAR: defense = new LowBar(defenseTypeSelected, defensePositionSelected); break; case MOAT: defense = new Moat(defenseTypeSelected, defensePositionSelected); break; case PORTCULLIS: defense = new PortCullis(defenseTypeSelected, defensePositionSelected); ; break; case RAMPARTS: defense = new Ramparts(defenseTypeSelected, defensePositionSelected); break; case ROCK_WALL: defense = new RockWall(defenseTypeSelected, defensePositionSelected); break; case ROUGH_TERRAIN: defense = new RoughTerrain(defenseTypeSelected, defensePositionSelected); break; case SALLYPORT: defense = new SallyPort(defenseTypeSelected, defensePositionSelected); break; case DRAWBRIDGE: defense = new DrawBridge(defenseTypeSelected, defensePositionSelected); break; case NONE: defense = null; break; default: defense = null; break; } System.out.println("Completed Initialization of DefenseCommand through AutonomousCommandGroup."); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Java
UTF-8
345
2.109375
2
[ "Apache-2.0" ]
permissive
package zx.soft.sample.data.jpa.utils; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class Object2Json { public static String toJsonWithoutPretty(Object object) { try { return new ObjectMapper().writeValueAsString(object); } catch (IOException e) { throw new RuntimeException(e); } } }
Markdown
UTF-8
4,279
2.953125
3
[]
no_license
--- title: The Next Few Months for Kingdom Code intro: As life begins to find a bit more rhythm, I want to share with you our thinking for Kingdom Code over the next few months… type: article tags: date: 2020-04-20 canonical: https://kingdomcode.org.uk/blog/2020/the-next-few-months/ --- **A month into lockdown and we're beginning to stablise - there is more of an understanding of how our lives work now.** We don't need to worry about panic buying toilet paper, our churches are beginning to get their heads around that live-streaming thing, and this is good! As I've been catching up with people it has become apparent that there are two tribes of people at the moment – those with more time, and those with less time. I think that for the Kingdom Code community we’re mostly in the ‘less-time’ camp. Even if you haven’t suddenly had to start up a home-school, your skillset has just become a very valuable commodity! Our work, our relationships, our churches have all moved to tech in the last three weeks. It was suggested that the church is now involved in its biggest experiment with technology ever! And, as a community we’re getting stuck in supporting the local church to do this. A couple of weeks ago many Christian technologists around the world gave up more of their evenings and weekends to participate in the [Covid-19 Global Church Hackathon](https://www.covidhack.com/), and some amazing projects were kicked off to serve our church and our world. Some of the things that came out of this week are amazing, and I really want to encourage this. I want to encourage you as part of the Kingdom Code community to use your skills to serve the church well, to help it to flourish in this time. But with this encouragement to get stuck in, I also want to care for our community too. There are a lot of demands on our time at the moment, and there is a time to go all-hands-on-deck, to make time and energy sacrifices to get things working. But that is not a long term thing! God’s people need to be looked after, protected, and encouraged to rest _well_ in this time. If your days are anything like mine, you start the work day looking at a screen, talking through a camera, and we are ending our day in a similar way as we share time with friends and family. A lot of meetup groups are going online at the moment, I see the value in this, but I don’t think that Kingdom Code doesn’t need to add to this. Actually - I want to lead us in doing the reverse, let’s not add to the demands to spend more time in front of the screen, but instead use this time to encourage rest, sabbath, offline time. In our Leeds community we had the pattern of gathering on the last Monday of the month, in London we gathered on the first Monday. I've put those dates in my diary now as an evening of digital quiet. We're not going to go completely quiet, the Kingdom Code blog will still remain active. Over the next few months we'll be working on some book recommendations, stories of encouragement, etc. If you are wanting to meet together, on Thursday 30th April, [Faithtech](https://faithtech.com), are [hosting a big call](https://www.eventbrite.com/e/faithtech-global-community-meetup-online-tickets-102822386526), to meet Christian in the tech from all over the world, to talk, and to pray together. As things begin to change, we'll review and change what we're doing to match. At the top of this post I suggested that there were two tribes of people. If you’re in the camp that has more time than normal, let me encourage you to invest in your relationship with God, maybe buy a copy of [From the Garden to the City](https://www.amazon.co.uk/Garden-City-Dyer-John/dp/0825426685/) and read it, talk to your church leader to see how you can serve in this time, log into the [Kingdom Builders Slack](http://kingdombuilders.io/) and ask around for projects, there is lots to do at the moment. But… if you’re in the tribe that has less time than you would like, let me encourage you to rest. Make time at the end of the day. Go for a walk, listen to a bible reading ([I’ve been enjoying the Psalms of Ascent](https://jamesdoc.com/blog/2020/psalm-130/)), take time to pray. Don’t feel guilty about not working on that side project right now!
Java
UTF-8
770
2.359375
2
[]
no_license
package com.example.job; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by eric on 2018/3/8. */ public class ThirdJob implements Job { private static final Logger logger = LoggerFactory.getLogger(ThirdJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { logger.info("ThirdJob->JobName: " + context.getJobDetail().getKey().getName() + " ->JobGroup:" + context.getJobDetail().getKey().getGroup() + " ->Execute Time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); } }
Java
UTF-8
299
1.578125
2
[]
no_license
package top.fan2wan.common.api.config; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @description: config for feign * @author: FantTao * @date: 2020-02-14 12:11 */ @EnableFeignClients(basePackages = {"top.fan2wan.*.feign"}) public abstract class AbstractFeignConfig { }
SQL
UTF-8
6,291
4.5
4
[]
no_license
USE austin_housing; -- Average price of homes sold for each quarter in years 2018-2020 SELECT * FROM (SELECT latest_saledate_year AS Year, DATEPART(quarter, latest_saledate) AS Quarter, AVG(latestPrice) AS AvgHomePrice FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND latest_saledate_year <> 2021 GROUP BY latest_saledate_year, DATEPART(quarter,latest_saledate) ) avg_price PIVOT (AVG(AvgHomePrice) FOR Year IN ([2018],[2019],[2020])) pivot_years -- year over year differences 2018-2020 SELECT latest_saledate_year AS Year, FORMAT(SUM(CAST(latestPrice AS BIGINT)),'C') AS Total, FORMAT(LAG(SUM(CAST(latestPrice AS BIGINT))) OVER(ORDER BY latest_saledate_year),'C') AS PreviousYear, FORMAT(SUM(CAST(latestPrice AS BIGINT)) - LAG(SUM(CAST(latestPrice AS BIGINT))) OVER( ORDER BY latest_saledate_year ),'C') AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND YEAR(latest_saledate) BETWEEN '2018' AND '2020' GROUP BY latest_saledate_year; -- avg home price year over year SELECT latest_saledate_year AS Year, FORMAT(AVG(CAST(latestPrice AS BIGINT)),'C') AS Total, FORMAT(LAG(AVG(CAST(latestPrice AS BIGINT))) OVER(ORDER BY latest_saledate_year),'C') AS PreviousYear, FORMAT(AVG(CAST(latestPrice AS BIGINT)) - LAG(AVG(CAST(latestPrice AS BIGINT))) OVER( ORDER BY latest_saledate_year ),'C') AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND YEAR(latest_saledate) BETWEEN '2018' AND '2020' GROUP BY latest_saledate_year; -- year over year difference for number of homes sold SELECT latest_saledate_year AS Year, COUNT(*) AS HomesSold, LAG(COUNT(*)) OVER ( ORDER BY latest_saledate_year ) AS PreviousYear, COUNT(*) - LAG(COUNT(*)) OVER ( ORDER BY latest_saledate_year ) AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND YEAR(latest_saledate) BETWEEN '2018' AND '2020' GROUP BY latest_saledate_year; -- % growth year over year 2018-2020 ;WITH cte AS ( SELECT latest_saledate_year AS Year, SUM(CAST(latestPrice AS FLOAT)) AS Total, LAG(SUM(CAST(latestPrice AS FLOAT))) OVER ( ORDER BY latest_saledate_year ) AS PreviousYear, SUM(CAST(latestPrice AS FLOAT)) - LAG(SUM(CAST(latestPrice AS FLOAT))) OVER ( ORDER BY latest_saledate_year ) AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND YEAR(latest_saledate) BETWEEN '2018' AND '2020' GROUP BY latest_saledate_year ) SELECT Year, FORMAT(Total,'C') TotalSales, FORMAT(YOY_Difference,'C') YOYDifference, FORMAT(100.0*(YOY_Difference/PreviousYear),'N') AS PercentageChange FROM cte; ---- total home sales for all months from 2018 to 2020 WITH cte AS ( SELECT latest_saledate_year AS Year, MONTH(latest_saledate) AS MonthSold, SUM(latestPrice) AS Total, LAG(SUM(latestPrice)) OVER( partition by latest_saledate_year ORDER BY MONTH(latest_saledate)) AS PreviousYear, SUM(latestPrice) - LAG(SUM(latestPrice)) OVER(partition by latest_saledate_year ORDER BY latest_saledate_year) AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND latest_saledate_year <> '2021' GROUP BY latest_saledate_year, MONTH(latest_saledate) ) SELECT Year, DATENAME(month, DATEADD(MONTH, MonthSold, -1)) Month, FORMAT(Total,'C') Total_Sales, FORMAT(PreviousYear,'C') AS Previous_Month, FORMAT(YOY_Difference,'C') MoM_Difference, FORMAT(100*(CAST(YOY_Difference AS FLOAT)/CAST(PreviousYear AS FLOAT)),'N') AS Percentage_Change FROM cte ORDER BY Year; -- avg price (monthly) SELECT latest_saledate_year AS Year, MONTH(latest_saledate) AS MonthSold, AVG(latestPrice) AS Average FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND latest_saledate_year <> '2021' GROUP BY latest_saledate_year, MONTH(latest_saledate) ORDER BY Year, MonthSold; -- jan only -- total home sales for all months from 2018 to 2021 WITH cte AS ( SELECT latest_saledate_year AS Year, MONTH(latest_saledate) AS MonthSold, SUM(latestPrice) AS Total, LAG(SUM(latestPrice)) OVER(ORDER BY latest_saledate_year) AS PreviousYear, SUM(latestPrice) - LAG(SUM(latestPrice)) OVER(ORDER BY latest_saledate_year) AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND MONTH(latest_saledate) = 1 GROUP BY latest_saledate_year, MONTH(latest_saledate) ) SELECT Year, DATENAME(month, DATEADD(MONTH, MonthSold, -1)) Month, FORMAT(Total,'C') Total_Sales_Jan, FORMAT(PreviousYear,'C') AS Previous_Jan, FORMAT(YOY_Difference,'C') YOY_Difference_Jan, FORMAT(100*(CAST(YOY_Difference AS FLOAT)/CAST(PreviousYear AS FLOAT)),'N') AS Percentage_Change_Jan FROM cte ORDER BY Year; ---- AVG home price by month and year SELECT * FROM (SELECT latest_saledate_year AS Year, MONTH(latest_saledate) AS MonthSold, AVG(latestPrice) AS AvgHomePrice FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND latest_saledate_year <> 2021 GROUP BY latest_saledate_year, MONTH(latest_saledate) ) avg_price PIVOT(AVG(AvgHomePrice) FOR Year IN ([2018],[2019],[2020])) byyear; -- total sold and avg cost of home in jan SELECT latest_saledate_year AS Year, DATENAME(month,latest_saledate) AS Month, AVG(latestPrice) AS AvgHomePrice, COUNT(*) AS Total_Sold FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND MONTH(latest_saledate) = 01 GROUP BY latest_saledate_year, DATENAME(month,latest_saledate); -- number of houses sold year over year for jan WITH cte AS ( SELECT DISTINCT latest_saledate_year AS Year, DATENAME(month,latest_saledate) AS Month, COUNT(*) AS Total_Sold, LAG(COUNT(*)) OVER (ORDER BY latest_saledate_year) AS PreviousYear, COUNT(*) - LAG(COUNT(*)) OVER (ORDER BY latest_saledate_year) AS YOY_Difference FROM austin_housing WHERE latest_saledate_year IS NOT NULL AND MONTH(latest_saledate) = 01 GROUP BY latest_saledate_year, DATENAME(month,latest_saledate)) SELECT Year, Month, Total_Sold, YOY_Difference YOY_Difference, FORMAT(100*(CAST(YOY_Difference AS FLOAT)/CAST(PreviousYear AS FLOAT)),'N') AS Percentage_Change FROM cte;
C++
UTF-8
3,938
3.21875
3
[]
no_license
#pragma once #include <vector> #include <thread> #include <future> //packaged_task #include <queue> #include <functional> //bind #include <mutex> #include <condition_variable> #include <type_traits> //invoke_result class thread_pool { public: thread_pool(size_t thread_count); ~thread_pool(); //since std::thread objects are not copiable, it doesn't make sense for a thread_pool // to be copiable. thread_pool(const thread_pool &) = delete; thread_pool &operator=(const thread_pool &) = delete; //F must be Callable, and invoking F with ...Args must be well-formed. template <typename F, typename ...Args> auto execute(F, Args&&...); private: //_task_container_base and _task_container exist simply as a wrapper around a // MoveConstructible - but not CopyConstructible - Callable object. Since an // std::function requires a given Callable to be CopyConstructible, we cannot // construct one from a lambda function that captures a non-CopyConstructible // object (such as the packaged_task declared in execute) - because a lambda // capturing a non-CopyConstructible object is not CopyConstructible. //_task_container_base exists only to serve as an abstract base for _task_container. class _task_container_base { public: virtual ~_task_container_base() {}; virtual void operator()() = 0; }; //_task_container takes a typename F, which must be Callable and MoveConstructible. // Furthermore, F must be callable with no arguments; it can, for example, be a // bind object with no placeholders. // F may or may not be CopyConstructible. template <typename F> class _task_container : public _task_container_base { public: //here, std::forward is needed because we need the construction of _f *not* to // bind an lvalue reference - it is not a guarantee that an object of type F is // CopyConstructible, only that it is MoveConstructible. _task_container(F &&func) : _f(std::forward<F>(func)) {} void operator()() override { _f(); } private: F _f; }; //returns a unique_ptr to a _task_container that wraps around a given function // for details on _task_container_base and _task_container, see above // This exists so that _Func may be inferred from f. template <typename _Func> static std::unique_ptr<_task_container_base> allocate_task_container(_Func &&f) { //in the construction of the _task_container, f must be std::forward'ed because // it may not be CopyConstructible - the only requirement for an instantiation // of a _task_container is that the parameter is of a MoveConstructible type. return std::unique_ptr<_task_container_base>( new _task_container<_Func>(std::forward<_Func>(f)) ); } std::vector<std::thread> _threads; std::queue<std::unique_ptr<_task_container_base>> _tasks; std::mutex _task_mutex; std::condition_variable _task_cv; bool _stop_threads = false; }; template <typename F, typename ...Args> auto thread_pool::execute(F function, Args &&...args) { std::unique_lock<std::mutex> queue_lock(_task_mutex, std::defer_lock); std::packaged_task<std::invoke_result_t<F, Args...>()> task_pkg( std::bind(function, args...) ); std::future<std::invoke_result_t<F, Args...>> future = task_pkg.get_future(); queue_lock.lock(); //this lambda move-captures the packaged_task declared above. Since the packaged_task // type is not CopyConstructible, the function is not CopyConstructible either - // hence the need for a _task_container to wrap around it. _tasks.emplace( allocate_task_container([task(std::move(task_pkg))]() mutable { task(); }) ); queue_lock.unlock(); _task_cv.notify_one(); return std::move(future); }
Java
UTF-8
7,046
2.25
2
[]
no_license
package guiChange; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import articles.Article; import articles.Dish; import articles.Drink; import buyers.Buyer; import employees.Supplier; import enumeration.EnumStatus; import loadFiles.LoadF; import net.miginfocom.swing.MigLayout; import order.Order; import restaurants.Restaurants; import user.Users; public class BuyerOrderChange extends JFrame { private static final long serialVersionUID = 1L; private JLabel lblnewArticle = new JLabel("Izaberite novi artikal"); private JComboBox<String> cbArticle = new JComboBox<String>(); private JButton btnAdd = new JButton("Dodaj"); private JLabel lblArticle = new JLabel("Poruceni artikal"); private JTextField txtArticle = new JTextField(20); private JLabel lblRest = new JLabel("Restoran"); private JTextField txtRest = new JTextField(20); private JLabel lblDate = new JLabel("Datum"); private JTextField txtDate = new JTextField(20); private JLabel lblBuyer = new JLabel("Kupac"); private JTextField txtBuyer = new JTextField(20); private JLabel lblSupplier = new JLabel("Dostavljac"); private JTextField txtSupplier = new JTextField(20); private JLabel lblStatus = new JLabel("Status"); private JComboBox<EnumStatus> cbStatus = new JComboBox<EnumStatus>(EnumStatus.values()); private JLabel lblPrice = new JLabel("Cena"); private JTextField txtPrice = new JTextField(20); private JButton btnOK = new JButton("OK"); private JButton btnCancel = new JButton("Cancel"); private static ArrayList<Article> orderedArticle = new ArrayList<Article>(); private LoadF entities; private Order order; private Users user; public BuyerOrderChange(LoadF entities, Order order, Users user) { this.entities = entities; this.order = order; this.user = user; //orderedArticle.removeAll(orderedArticle); setTitle("Izmena porudzbine"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLocationRelativeTo(null); setIconImage(Toolkit.getDefaultToolkit().getImage("src/projectImages/hamburger.png")); setResizable(false); initGui(); initActions(); enableFields(); pack(); } private void initGui() { MigLayout layout = new MigLayout("wrap 2"); setLayout(layout); String suString = "prazno"; if(this.order.getSupplier() != null) suString = this.order.getSupplier().getUsername(); if(this.order != null) { txtArticle.setText(this.order.forWrite()); txtRest.setText(this.order.getRest().getRestName()); txtDate.setText(this.order.getDate().toString()); txtBuyer.setText(this.order.getBuyer().getUsername()); txtSupplier.setText(suString); cbStatus.setSelectedItem(this.order.getStatus()); txtPrice.setText(String.valueOf(this.order.getPrice())); } for(Order o: entities.getOrder()) { if(o.getOrderedDish() == order.getOrderedDish()) { orderedArticle.addAll(o.getOrderedDish()); orderedArticle.removeAll(orderedArticle); } } String restString = txtRest.getText().trim(); Restaurants rest = entities.rName(restString); for(Dish s: entities.getDish()) { if(s.getRestaurantName().getRestName().equals(rest.getRestName())) { cbArticle.addItem(s.getArticleName()); } } for(Drink dr: entities.getDrink()) { if(dr.getRestaurantName().getRestName().equals(rest.getRestName())) { cbArticle.addItem(dr.getArticleName()); } } add(lblnewArticle); add(cbArticle, "split 2"); add(btnAdd); add(lblArticle); add(txtArticle); add(lblRest); add(txtRest); add(lblDate); add(txtDate); add(lblBuyer); add(txtBuyer); add(lblSupplier); add(txtSupplier); add(lblStatus); add(cbStatus); add(lblPrice); add(txtPrice); add(new JLabel()); add(btnOK, "split 2"); add(btnCancel); } private double getSum() { double startPrice = 0; for(Article a: orderedArticle) { startPrice += a.getPrice() + 200; } txtPrice.setText(String.valueOf(startPrice)); return startPrice; } private void enableFields() { txtRest.setEditable(false); txtDate.setEditable(false); txtBuyer.setEditable(false); txtSupplier.setEditable(false); cbStatus.setEnabled(false); txtPrice.setEditable(false); } private boolean validation() { boolean ok = true; String message = "Greska u unosu:\n"; if(txtArticle.getText().trim().equals("")) { ok = false; message += "- Artikal ne sme biti prazno polje:\n"; }else if(txtRest.getText().trim().equals("")) { ok = false; message += "- Restoran ne sme biti prazno polje:\n"; }else if(txtDate.getText().trim().equals("")) { ok = false; message += "- Datum ne sme biti prazno polje:\n"; } try { Double.parseDouble(txtPrice.getText().trim()); }catch(NumberFormatException e) { ok = false; message += "- Cena mora biti broj"; } if(ok == false) { JOptionPane.showMessageDialog(null, message, "Greska", JOptionPane.WARNING_MESSAGE); } return ok; } private void initActions() { btnAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Article ar = entities.gArticle(cbArticle.getSelectedItem().toString()); orderedArticle.add(ar); getSum(); } }); btnOK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(validation() == true) { String restString = txtRest.getText().trim(); Restaurants rest = entities.rName(restString); String dateString = txtDate.getText().trim(); SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); Date date = null; try { date = (Date)format.parse(dateString); } catch (ParseException e1) { e1.printStackTrace(); } Buyer buyer = entities.bName(txtBuyer.getText().trim()); Supplier supplier = entities.sName(txtSupplier.getText().trim()); EnumStatus status = (EnumStatus)cbStatus.getSelectedItem(); String priceString = txtPrice.getText().trim(); double price = Double.parseDouble(priceString); if(order != null) { order.setOrderedDish(orderedArticle); order.setRest(rest); order.setDate(date); order.setBuyer(buyer); order.setSupplier(supplier); order.setStatus(status); order.setPrice(price); } entities.writeOrders(); BuyerOrderChange.this.dispose(); BuyerOrderChange.this.setVisible(false); } } }); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { BuyerOrderChange.this.dispose(); BuyerOrderChange.this.setVisible(false); } }); } }
Python
UTF-8
1,398
4.46875
4
[]
no_license
class person: def __init__(self, name): self.name = name # 只有实例化的时候才确定的值,这个值只在实例上存在,在class类中没有这个变量。 print('{}来到人间~!'.format(name)) def eat(self): print('{}寻找可以吃的东西'.format(self.name)) def __run(self): print('{}岁的{}像野马一样狂奔'.format(self.age, self.name)) print('跑累了之后') self.eat() def __del__(self): print('尘归尘,土归土~!') age = 10 # 类变量,实例里也有age,但实例里改动不会影响模板。创建实例后,在模板里改动不会影响实例。 __age = 15 # 私有变量,外面直接person.__age访问不到,实例p.__age也访问不到。必须通过类里的函数间接访问。 @classmethod # 加了这个的函数就是class函数,只属于class,不属于某个实例。 def make_love(cls): print('很舒服~!') def show(self): # 为了显示私有变量 print(person.__age) def show_method(self): # 为了显示私有函数 self.__run() # print(person.__age) 私有变量访问不到。 p = person('辜鸿铭') # print(p.__age) 私有变量不论是用person.__age和实例化的p.__age都访问不到。必须由内置函数来间接访问。 p.show() p.show_method()
Java
UTF-8
4,183
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package action.quanlytaikhoan; import actionform.quanlytaikhoan.QLTaiKhoanForm; import com.sun.javafx.scene.control.skin.VirtualFlow; import entity.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import managesessionbean.ManageSessionBean; import org.apache.struts.actions.DispatchAction; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForward; /** * * @author HaiHamHo */ public class TaiKhoanAction extends DispatchAction { /* forward name="success" path="" */ private final static String SUCCESS = "success"; private final ManageSessionBean msb = new ManageSessionBean(); public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { List<QLTaiKhoanForm> listtk = new ArrayList<>(); for (Tbltaikhoan tk : msb.tbltaikhoanFacade.findAll()) { SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy"); String ngaysinh = sf.format(tk.getNgaysinh()); Tblphanquyen quyen = msb.tblphanquyenFacade.find(tk.getMaquyen()); listtk.add(new QLTaiKhoanForm(tk.getTentaikhoan(), quyen.getQuyen(), tk.getMatkhau(), tk.getHoten(), tk.getCmnd(), tk.getDiachi(), ngaysinh)); } request.setAttribute("listquyen", msb.tblphanquyenFacade.findAll()); request.setAttribute("list", listtk); return mapping.findForward(SUCCESS); } public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { QLTaiKhoanForm myform = (QLTaiKhoanForm) form; Tbltaikhoan tk = new Tbltaikhoan(); tk.setTentaikhoan(myform.getTentaikhoan()); tk.setMaquyen(myform.getMaquyen()); tk.setMatkhau(myform.getMatkhau()); tk.setHoten(myform.getHoten()); SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy"); Date ngaysinh = sf.parse(myform.getNgaysinh()); tk.setNgaysinh(ngaysinh); tk.setCmnd(myform.getCmnd()); tk.setDiachi(myform.getDiachi()); msb.tbltaikhoanFacade.create(tk); return list(mapping, form, request, response); } public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { QLTaiKhoanForm myform = (QLTaiKhoanForm) form; Tbltaikhoan tk = new Tbltaikhoan(); tk.setTentaikhoan(myform.getTentaikhoan()); tk.setMaquyen(myform.getMaquyen()); tk.setMatkhau(myform.getMatkhau()); tk.setHoten(myform.getHoten()); SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy"); Date ngaysinh = sf.parse(myform.getNgaysinh()); tk.setNgaysinh(ngaysinh); tk.setCmnd(myform.getCmnd()); tk.setDiachi(myform.getDiachi()); msb.tbltaikhoanFacade.edit(tk); return list(mapping, form, request, response); } public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String taikhoan = request.getParameter("tentaikhoan"); Tbltaikhoan tk = msb.tbltaikhoanFacade.find(taikhoan); msb.tbltaikhoanFacade.remove(tk); return list(mapping, form, request, response); } }
PHP
UTF-8
822
2.921875
3
[]
no_license
<?php declare(strict_types=1); namespace backend\components\book\blocks; class Test implements GuestBlockInterface { private $testId; private $header; private $description; public function __construct(int $testId, string $header = '', string $description = '') { $this->testId = $testId; $this->header = $header; $this->description = $description; } public function getTestId(): int { return $this->testId; } public function isEmpty(): bool { return empty($this->testId); } /** * @return string */ public function getHeader(): string { return $this->header; } /** * @return string */ public function getDescription(): string { return $this->description; } }
Java
UTF-8
1,048
2.171875
2
[]
no_license
package frances.emart.com.emartidentityservice.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import frances.emart.com.emartidentityservice.models.EmartUser; import frances.emart.com.emartidentityservice.repositories.EmartUserRepository; import frances.emart.com.emartidentityservice.viewmodel.EmartUserDetails; @Service("EmartUserDetailService") public class EmartUserDetailService implements UserDetailsService { @Autowired private EmartUserRepository userRepository; @Override public EmartUserDetails loadUserByUsername(String username) throws UsernameNotFoundException { EmartUser user = userRepository.findByUsernameOrEmail(username, username). orElseThrow(() -> new UsernameNotFoundException("not found : " + username)); return EmartUserDetails.create(user); } }
C++
UTF-8
1,383
3.265625
3
[]
no_license
#ifndef EMPLOYEES_H #define EMPLOYEES_H #include<iostream> #include<string> #include<vector> #include<cstdlib> using namespace std; class Employee { public: Employee(string JobTitle, char FirstInitial, string LastName, int EmployeeID, int GrossPay); ~Employee(){}; ostream& operator <<(ostream &os); string GetJobTtile(); string GetName(); string GetContactInfo(); int GetEmployeeID(); int GetGrossPay(); void shift_to_root( ); //Precondition: size() > 0. //Postcondition: The "current node" is now the root of the tree. void shift_up( ); //Precondition: has_parent( ) returns true. //Postcondition: The "current node" has been shifted up to the parent of //the old current node. void shift_left( ); //Precondition: has_left_child( ) returns true. //Postcondition: The "current node" been shifted down to the left child //of the original current node. void shift_right( ); //Precondition: has_left_child( ) returns true. //Postcondition: The "current node" been shifted down to the left child //of the original current node. private: string EmployeeTitle; string EmployeeName; int EmployeeID; vector<string> Employees; char eFirstInitial; string eLastName; int eSalary; }; #endif
Java
UTF-8
3,169
2.90625
3
[]
no_license
package hu.schonherz.homework.daoimpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import hu.schonherz.homework.connection.ConnectionHandler; import hu.schonherz.homework.dao.OrderDao; import hu.schonherz.homework.records.Order; public class OrderDaoImpl implements OrderDao { private Connection con; //create connection public OrderDaoImpl() { try { con = ConnectionHandler.getConnection(); } catch (SQLException e) { System.out.println("Could not establish connection"); e.printStackTrace(); } } public List<Order> getAllOrders() { //SQL statement in a String; will be executed as a query String sql = "SELECT user_id, product_id FROM public.\"Order\""; List<Order> orders = new ArrayList<>(); //create statement in try-with block (auto resource management) try (Statement stmt = con.createStatement()) { //execute query in result set in try-with block try (ResultSet rs = stmt.executeQuery(sql);) { while (rs.next()) { //add actual order to the orders list orders.add(new Order(rs.getInt("user_id"), rs.getInt("product_id"))); } } } catch (SQLException e) { //handling SQLException in catch e.printStackTrace(); } return orders; } public List<Order> getAllOrdersOfUser(int userId) { String sql = "SELECT * FROM public.\"Order\" WHERE user_id = ?;"; List<Order> orders = new ArrayList<>(); try (PreparedStatement stmt = con.prepareStatement(sql)) { stmt.setInt(1, userId); try (ResultSet rs = stmt.executeQuery()) { while(rs.next()) { orders.add(new Order(rs.getInt("user_id"), rs.getInt("product_id"))); } } } catch (SQLException e) { e.printStackTrace(); } return orders; } public void addOrder(Order order) { //SQL statement in a String; will be executed as a prepared statement //question marks are placeholders String sql = "INSERT INTO public.\"Order\" (user_id, product_id) VALUES (?, ?) ;"; try (PreparedStatement stmt = con.prepareStatement(sql)) { //fill the placeholders with valid data stmt.setInt(1, order.getUserId()); stmt.setInt(2, order.getProductId()); //execute the completed statement stmt.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void deleteAllOrderOfUser(Order order) { //it will delete all the orders which have the given user id String sql = "DELETE FROM public.\"Order\" WHERE user_id = ?;"; try (PreparedStatement stmt = con.prepareStatement(sql)) { stmt.setInt(1, order.getUserId()); stmt.execute(); } catch (SQLException e) { e.printStackTrace(); } } public void deleteOrder(Order order) { //it will delete all the orders wich has the given user id (!)and(!) product id String sql = "DELETE FROM public.\"Order\" WHERE user_id = ? AND product_id = ?;"; try (PreparedStatement stmt = con.prepareStatement(sql)) { stmt.setInt(1, order.getUserId()); stmt.setInt(2, order.getProductId()); stmt.execute(); } catch (SQLException e) { e.printStackTrace(); } } }
Python
UTF-8
5,507
3.875
4
[]
no_license
# 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. # В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета # для конкретных значений необходимо запускать скрипт с параметрами. # import sys # vyrabotka, stavka, bonus = sys.argv[1:] # print("Зарплата всего: ", float(vyrabotka) * float(stavka) + float(bonus)) # 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше # предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать # генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. # Результат: [12, 44, 4, 10, 78, 123]. # s = [5, 10, 6, 2, 11, 15, 3] # res_list = [x for i, x in enumerate(s) if s[i] > s[i-1] and i > 0] # print(res_list) # 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. # Подсказка: использовать функцию range() и генератор. # print(list(i for i in range(20, 241) if i % 20 == 0 or i % 21 ==0)) # 4. Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив # чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения # задания обязательно использовать генератор. # Пример исходного списка: [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11]. # Результат: [23, 1, 3, 10, 4, 11] # src_list = [2, 2, 2, 7, 23, 1, 44, 44, 3, 2, 10, 7, 4, 11] # print(list(x for x in src_list if src_list.count(x) == 1)) # 5. Реализовать формирование списка, используя функцию range() и возможности генератора. В список должны войти # четные числа от 100 до 1000 (включая границы). Необходимо получить результат вычисления произведения всех # элементов списка. # Подсказка: использовать функцию reduce(). # from functools import reduce # print(reduce(lambda x, y: x * y, [x for x in range(100, 1001, 2)])) # 6. Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. Обратите внимание, что создаваемый цикл # не должен быть бесконечным. Необходимо предусмотреть условие его завершения. # Например, в первом задании выводим целые числа, начиная с 3, а при достижении числа 10 завершаем цикл. # Во втором также необходимо предусмотреть условие, при котором повторение элементов списка будет прекращено. # from itertools import count, cycle # # а) # for i in count(start=3, step=1): # print(i) # if i == 10: # break # б) # sec = [3, 2, 1] # i = 0 # for s4et in cycle(sec): # print(s4et) # i += 1 / (len(sec)) # if i >= 4: # break # 7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение. При вызове # функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: for el in fact(n). # Функция отвечает за получение факториала числа, а в цикле необходимо выводить только первые n чисел, начиная # с 1! и до n!. # Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24. # from math import factorial as fact # from itertools import count # # def generator(): # for i in count(1, 1): # yield fact(i) # # x, n = 1, int(input('Введите целое число: ')) # # for el in generator(): # print(f'Факториал {x} = {el}') # if x == n: # break # x += 1
Markdown
UTF-8
1,732
2.828125
3
[ "MIT" ]
permissive
# go-bunyan Bunyan logger written in Golang. See https://github.com/trentm/node-bunyan for in depth documentation. This package attempts to implement the original node.js library as closely as possible using golang. ## TODO * Implement `rotating-file` stream * Write tests * Publish to go registry ### Simple usage ```golang import ( "os" "github.com/bhoriuchi/go-bunyan/bunyan" ) func main() { config := bunyan.Config{ Name: "app", Stream: os.Stdout, Level: bunyan.LogLevelDebug } if log, err := bunyan.CreateLogger(config); err == nil { log.Info("Hello %s!", "World") } } ``` ### Multi-stream usage ```golang import ( "os" "github.com/bhoriuchi/go-bunyan/bunyan" ) func main() { staticFields := make(map[string]interface{}) staticFields["foo"] = "bar" type Employee struct { Name string Id int Address string Salary int Country string O []*Order Z []string } e := &Employee{ Name: "Naveen", Id: 565, Address: "Coimbatore", Salary: 90000, Country: "India", O: orders, Z: z, } config := bunyan.Config{ Name: "app", Streams: []bunyan.Stream{ { Name: "app-info", Level: bunyan.LogLevelInfo, Stream: os.Stdout, }, { Name: "app-errors", Level: bunyan.LogLevelError, Path: "/path/to/logs/app-errors.log" }, }, StaticFields: staticFields, DefaultKey:"message", } if log, err := bunyan.CreateLogger(config); err == nil { log.Info("default key and struct log",e) } } ```
Python
UTF-8
2,489
2.703125
3
[]
no_license
import base64 import re import os import datetime import random import string from subprocess import Popen, PIPE inputFileName = 'inputFile.txt' outputFileName = 'outputFile' oracleFileName = 'oracle.txt' seed = datetime.datetime.now() random.seed() def execute( argIn ): arguments = ['./base64'] for args in argIn: arguments.append(args) ps = Popen(arguments, stdout=PIPE, stderr=PIPE) result = ps.communicate() return result def reportError(section, error): print("Error") log = open('log.txt', 'a') log.write("Error in: " + section + " Output: " + error+"\n\n\n\n") def generateCharacter(): bits = '' for bit in range(8): bits += random.sample({'0','1'}, 1)[0] return chr(int(bits, 2)) def generateRandomFile(): #number of characters charCount = random.sample(xrange(100000), 1)[0] toReturn = "" for c in range(charCount): toReturn += generateCharacter() #return string return toReturn; def getResults(inputs): results = execute( inputs ) if results[1] != "": reportError("Execute: ", results[1]+" ".join(inputs)) return results[0] def reciprocal(): inputFile = open(inputFileName, 'w') outputFile = open(outputFileName, 'w') toEncode = generateRandomFile() inputFile.write(toEncode) inputFile.close() results = getResults( [inputFileName] ) outputFile.write(results) outputFile.close() results = getResults(['-d', outputFileName]) if toEncode != results: reportError("Reciprocal", "Original is different from Encoded/decoded") def oracle(): inputFile = open(inputFileName, 'w') codedString = generateRandomFile() inputFile.write(codedString) inputFile.close() resultsCore = getResults( [inputFileName, '-w 0'] ) resultsOracle = base64.b64encode(codedString) for i in range(len(resultsCore)): if resultsCore[i] != resultsOracle[i]: reportError("Oracle", "Strings do not match at position: %d received: " + resultsCore[i] + " Expected: " +resultsOracle[i]) def ignoreOption(): inputFile = open(inputFileName, 'w') toDecode = generateRandomFile() inputFile.write(toDecode) inputFile.close() getResults(['-i', inputFileName]) getResults(['--help']) getResults(['--version']) testFile = open('testFile.txt', 'w') while True: print("Reciprocal") reciprocal() print("Oracle") oracle() print("IgnoreOption") ignoreOption()
Shell
UTF-8
1,346
3.21875
3
[]
no_license
#!/bin/bash # 明星运营周报表邮件 source $ETL_HOME/common/db_util.sh function execute() { start_date=`date +'%Y-%m-%d' -d "$the_day 7 day ago"` end_date=`date +'%Y-%m-%d' -d "$the_day 1 day ago"` date_range=`date +'%Y%m%d' -d "$start_date"`"-"`date +'%Y%m%d' -d "$end_date"` debug "Date range: $date_range" if [[ -n "$sub_emails" ]]; then # 设置数据库连接 set_db ${SDK_NDW[@]} "" "" "--column-names" echo "SELECT id, date_range '日期范围', title '标题', start_time '开始时间', end_time '结束时间', click_count '点击次数', click_user '点击人数', comment_count '评论次数', comment_user '评论人数', share_count '分享次数', share_user '分享人数' FROM stat_interact WHERE date_range='$date_range'; " | exec_sql > $data_path/interact_mail.tmp # windows默认编码为gbk iconv -f utf-8 -t gbk -c $data_path/interact_mail.tmp -o $data_path/互动运营周报表.xls # 发送 $SHELL_HOME/common/mail_sender.py "$sub_emails" "互动运营周报表" "数据请查看附件" $data_path/互动运营周报表.xls else warn "There is no email subscribers" fi } execute "$@"
Java
UTF-8
1,149
2.296875
2
[]
no_license
package net.rc.lab.springboot.entities; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.transaction.Transactional; import javax.validation.ConstraintViolationException; @ContextConfiguration(locations = { "classpath:test-db-context.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class RoleVoTest extends AbstractVoTest<RoleVo> { @Override public Class<RoleVo> getEntityClass() { return RoleVo.class; } @Override protected RoleVo newInstance() { return new RoleVo(); } @Test @Transactional public void testCreateVoSuccess() { RoleVo instance = newInstance(); instance.setName("testRole"); save(instance); assertNotNull(instance.getRoleId()); } @Test(expected = ConstraintViolationException.class) @Transactional public void testCreateVoFail() { RoleVo instance = newInstance(); save(instance); fail("Exception is expected."); } }