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
Java
UTF-8
3,408
1.953125
2
[ "Apache-2.0" ]
permissive
package cherry.gallery.db.gen.query; import static com.querydsl.core.types.PathMetadataFactory.*; import com.querydsl.core.types.dsl.*; import com.querydsl.core.types.PathMetadata; import javax.annotation.Generated; import com.querydsl.core.types.Path; import com.querydsl.sql.ColumnMetadata; import java.sql.Types; /** * QAsyncProcessFileResultDetail is a Querydsl query type for BAsyncProcessFileResultDetail */ @Generated("com.querydsl.sql.codegen.MetaDataSerializer") public class QAsyncProcessFileResultDetail extends com.querydsl.sql.RelationalPathBase<BAsyncProcessFileResultDetail> { private static final long serialVersionUID = 6577436; public static final QAsyncProcessFileResultDetail asyncProcessFileResultDetail = new QAsyncProcessFileResultDetail("ASYNC_PROCESS_FILE_RESULT_DETAIL"); public final NumberPath<Long> asyncId = createNumber("asyncId", Long.class); public final DateTimePath<java.time.LocalDateTime> createdAt = createDateTime("createdAt", java.time.LocalDateTime.class); public final StringPath description = createString("description"); public final NumberPath<Long> id = createNumber("id", Long.class); public final NumberPath<Integer> lockVersion = createNumber("lockVersion", Integer.class); public final NumberPath<Long> recordNumber = createNumber("recordNumber", Long.class); public final DateTimePath<java.time.LocalDateTime> updatedAt = createDateTime("updatedAt", java.time.LocalDateTime.class); public final com.querydsl.sql.PrimaryKey<BAsyncProcessFileResultDetail> asyncProcessFileResultDetailPkc = createPrimaryKey(id); public QAsyncProcessFileResultDetail(String variable) { super(BAsyncProcessFileResultDetail.class, forVariable(variable), "PUBLIC", "ASYNC_PROCESS_FILE_RESULT_DETAIL"); addMetadata(); } public QAsyncProcessFileResultDetail(String variable, String schema, String table) { super(BAsyncProcessFileResultDetail.class, forVariable(variable), schema, table); addMetadata(); } public QAsyncProcessFileResultDetail(Path<? extends BAsyncProcessFileResultDetail> path) { super(path.getType(), path.getMetadata(), "PUBLIC", "ASYNC_PROCESS_FILE_RESULT_DETAIL"); addMetadata(); } public QAsyncProcessFileResultDetail(PathMetadata metadata) { super(BAsyncProcessFileResultDetail.class, metadata, "PUBLIC", "ASYNC_PROCESS_FILE_RESULT_DETAIL"); addMetadata(); } public void addMetadata() { addMetadata(asyncId, ColumnMetadata.named("ASYNC_ID").withIndex(2).ofType(Types.BIGINT).withSize(19).notNull()); addMetadata(createdAt, ColumnMetadata.named("CREATED_AT").withIndex(6).ofType(Types.TIMESTAMP).withSize(23).withDigits(10).notNull()); addMetadata(description, ColumnMetadata.named("DESCRIPTION").withIndex(4).ofType(Types.VARCHAR).withSize(100)); addMetadata(id, ColumnMetadata.named("ID").withIndex(1).ofType(Types.BIGINT).withSize(19).notNull()); addMetadata(lockVersion, ColumnMetadata.named("LOCK_VERSION").withIndex(7).ofType(Types.INTEGER).withSize(10).notNull()); addMetadata(recordNumber, ColumnMetadata.named("RECORD_NUMBER").withIndex(3).ofType(Types.BIGINT).withSize(19).notNull()); addMetadata(updatedAt, ColumnMetadata.named("UPDATED_AT").withIndex(5).ofType(Types.TIMESTAMP).withSize(23).withDigits(10).notNull()); } }
Python
UTF-8
4,365
2.96875
3
[]
no_license
import queue class Graph: def __init__(self,nV): self.nV=nV self.adjMatrix=[[0 for i in range(nV)] for j in range(nV)] def dfsHelper(self,sv,visited): print(sv) visited[sv]=True for i in range(self.nV): if (self.adjMatrix[sv][i]>0 and visited[i] is False): self.dfsHelper(i,visited) def DFS(self): visited=[False for i in range(self.nV)] self.dfsHelper(0,visited) def BFS(self): q=queue.Queue() q.put(0) visited=[False for i in range(self.nV)] visited[0]=True while not q.empty(): u=q.get() print(u) for i in range(self.nV): if (self.adjMatrix[u][i]>0 and visited[i] is False): q.put(i) visited[i]=True def Get_path_dfs_helper(self,visited,v1,v2): if v1==v2: return [v2] visited[v1]=True for i in range(self.nV): if (self.adjMatrix[v1][i]>0 and visited[i] is False): ans=self.Get_path_dfs_helper(visited,i,v2) if ans is not None: ans.append(v1) return ans return None def Get_path_dfs(self,v1,v2): visited=[False for i in range(self.nV)] return self.Get_path_dfs_helper(visited,v1,v2) def __IsConnected(self,sv,visited): q=queue.Queue() q.put(sv) c=2 c2=self.nV visited[sv]=True while not q.empty(): u=q.get() for i in range(self.nV): if (self.adjMatrix[u][i]==1 and visited[i] is False): q.put(i) visited[i]=True c=c+1 for boolV in visited: print(visited[boolV]) #if not boolV: # return False #return True #if c==c2: # return True def IsConnected(self,sv): visited=[False for i in range(self.nV)] return self.__IsConnected(sv,visited) def __Has_path_bfs(self,v1,v2,visited): if v1==v2: return True q=queue.Queue() q.put(v1) visited[v1]=True while not q.empty(): u=q.get() for i in range(self.nV): if (self.adjMatrix[u][i]==1 and visited[i] is False): if i==v2: return True q.put(i) visited[i]=True return False def Has_path_bfs(self,v1,v2): visited=[False for i in range(self.nV)] return self.__Has_path_bfs(v1,v2,visited) def __getPath_bfs(self,sv,ev,visited): q=queue.Queue() mapp={} q.put(sv) visited[sv]=True while not q.empty(): u=q.get() for i in range(self.nV): if (self.adjMatrix[u][i]==1 and visited[i] is False): mapp[i]=u q.put(i) visited[i]=True if i==ev: ans=[] ans.append(ev) value=mapp[ev] while value !=sv: ans.append(value) value=mapp[value] ans.append(value) return ans def getpath_bfs(self,sv,ev): visited=[False for i in range(self.nV)] return self.__getPath_bfs(sv,ev,visited) def connected(self): visited=[False for i in range(self.nV)] self.DFS() for boolv in visited: print(visited[boolv]) #if not boolv: # return False #return True def addEdge(self,v1,v2): self.adjMatrix[v1][v2]=1 self.adjMatrix[v2][v1]=1 def remEdge(self,v1,v2): if self.containsEdge is False: return self.adjMatrix[v1][v2]=0 self.adjMatrix[v2][v1]=0 def conatinsEdge(self,v1,v2): return True if self.adjMatrix[v1][v2] >0 else False def __str__(self): return str(self.adjMatrix) ##################################################################################################### def dfs(self,sv,visited): visited[sv]=True for i in range(self.nV): if (self.adjMatrix[sv][i]==1 and visited[i] is False): self.dfs(i,visited) visited[i]=True def connected(self): visited=[False for i in range(self.nV)] self.dfs(0,visited) for boolV in visited: if not boolV: return False return True ###################################################################################################### def __connectedComponent(self,visited,smallOutput,sv): visited[sv]=True smallOutput.append(sv) for i in range(self.nV): if(self.adjMatrix[sv][i]==True and visited[i] is False): self.__connectedComponent(visited,smallOutput,i) def connectedComponent(self): visited=[False for i in range(self.nV)] ans=[] for i in range(len(visited)): if not visited[i]: smallOutput=list() self.__connectedComponent(visited,smallOutput,i) ans.append(smallOutput) return ans g=Graph(5) g.addEdge(0,1) g.addEdge(0,2) g.addEdge(1,3) g.addEdge(2,4) g.addEdge(1,4) #g.addEdge(2,4) #g.DFS() print(g.Get_path_dfs(1,3)) #print(g.getpath_bfs(1,3)) #print(g.connected())
Markdown
UTF-8
26,731
2.921875
3
[]
no_license
# Pang Yong Hock and Another v PKS Contracts Services Pte Ltd **Case Number** :CA 103/ **Decision Date** :19 April 2004 **Tribunal/Court** :Court of Appeal **Coram** :Chao Hick Tin JA; Tay Yong Kwang J; Yong Pung How CJ **Counsel Name(s)** :Gregory Vijayendran and Linda Wee (Wong Partnership) for appellants; Hee Theng Fong and Yu Siew Fun (Hee Theng Fong and Co) for respondent **Parties** :Pang Yong Hock; Lee Kim Swee — PKS Contracts Services Pte Ltd _Companies_ – _Oppression_ – _Derivative action_ – _Shareholders owning 50% of company's shares wanting to commence proceedings in name and on behalf of company_ – _Whether appropriate to grant leave under s 216A of Companies Act_ – _Legislative intention behind s 216A Companies Act (Cap 50, 1994 Rev Ed)_ 19 April 2004 **Tay Yong Kwang J:** 1       This appeal arose out of Originating Summons No 1597 of 2002 which was an application by the appellants, Pang Yong Hock (“Pang”) and Lee Kim Swee (“Lee”), under s 216A of the Companies Act (Cap 50, 1994 Rev Ed) for leave to commence proceedings in the name of the respondent (“the company”) against two of its directors, Koh Hwee Meng (“Koh”) and his wife, Tan Sok Khin (“Tan”), for alleged breaches of their duties as directors of the company. The originating summons was heard by Choo Han Teck J who delivered an oral judgment dismissing it. We dismissed the appeal by Pang and Lee for the reasons that follow. **The factual background** 2       The company was registered in Singapore in August 1996. It is involved in the business of building construction, specialising in interior decoration, repair and redecoration, as well as additions and alteration works. The shareholders and their respective shareholdings are as follows: (a) Pang 22% (b) Lee 28% (c) Koh 20% (d) Tan 30%. Each of the two factions therefore holds 50% of the shares of the company. 3       The four shareholders are also directors of the company. However, there is no deadlock at the board of directors’ level as there is a fifth director, Lim Chong Huat, the husband of Tan’s niece, whose allegiance is naturally with the Koh-Tan faction. 4       The Pang-Lee faction alleged that in March 2002, Pang stumbled upon a series of payment records documenting payments made to various parties including the company’s subsidiary, PK Summit Pte Ltd (“PK Summit”). Pang and Lee alleged that they were not aware of such payments. Pang and Koh are directors of PK Summit. Until March 2003, Koh also held 77.5% of the shares of PK Summit. Pang and Lee therefore began to suspect that Koh and Tan were abusing their powers as directors of the company although they did not have evidence of any wrongdoing. 5       Pang questioned Koh and Tan about the said payments and asked that he be allowed to inspect the company’s documents but was denied this request. Koh, purporting to act on behalf of the company, then terminated Pang’s employment as Project Controller of the company. Subsequently, Pang was also removed as a signatory for the company’s bank account. Pang and Lee alleged that all this was done in bad faith to prevent Pang from making further inquiries into the company’s affairs. 6       In August 2002, Pang and Lee obtained an order of court pursuant to ss 199(3) and 396(2) of the Companies Act to inspect the accounting and other records of the company and of PK Summit. The court authorised the appointment of Mr Chee Yoh Chuang, an auditor, to act on behalf of Pang to inspect the said records. After his inspection, Mr Chee prepared a report on the nature of the transactions undertaken by the company and by PK Summit and the completeness of the records supporting those transactions. 7       On 7 October 2002, Pang and Lee gave 14 days’ notice to the directors of the company, as required by s 216A(3)(a) of the Companies Act, to bring an action against Koh and Tan in respect of payments made by the company to PK Summit and of transactions concerning other companies. On 24 October 2002, a reminder was sent to the directors. However, the company did not convene a directors’ meeting to discuss the same. On 6 November 2002, Pang and Lee commenced their originating summons, the subject of this appeal. **The decision of the trial judge** 8       On 27 January and 27 February 2003, Choo J made preliminary orders appointing Mr Chan Ket Teck of PricewaterhouseCoopers as a special accountant to perform an independent review of the accounting records of the company on terms of reference subsequently agreed between the parties. The special accountant prepared a report on 14 April 2003. 9       On 2 September 2003, Choo J dismissed the originating summons. He found the special accountant’s report to be sufficiently detailed and that it indicated there were strong _prima facie_ grounds for a fuller inquiry but not necessarily against Koh and Tan only. 10     The paper trail showed that contracts were signed with PK Summit, a shell company with no employees, and the work under those contracts was carried out by the company’s own employees. Pang alleged a sum of $385,086.90 was paid by the company to PK Summit without any value having been given by PK Summit. The report referred to unusual transactions between the company and AA Pyrodor Development Pte Ltd (“AAP”), an entity in which the company and Koh are shareholders. The special accountant was of the view that the margin earned by AAP in the works carried out under a sub-contract from the company was unusually low. There were also payments made to two suppliers of labour where the description in the invoices lacked the details necessary to enable the special accountant to determine the reasonableness of the amounts paid. Further, there were payments made to relatives of the directors and to Tan which were not fully accounted for. 11     Choo J opined, having perused the detailed disputes concerning the various payments and the alleged breaches of directors’ duties on the part of Pang, Lee, Koh and Tan, that the allegations and counter-allegations could not be satisfactorily proved or disproved by affidavit evidence alone. He accepted from the report that there were aspects of the conduct of the company that required a more thorough inquiry but was of the view that that was only evidence that a fuller inquiry was required. The parties before us referred to this ground compendiously as the “affidavit evidence reason”. 12     The judge next dealt with what was termed the “counter-suits reason”. He held that granting leave to Pang and Lee to sue in the name of the company was not the best solution as the court would also have to grant leave to Koh and Tan to pursue their counter-allegations against them. Although Koh and Tan had not made an application under s 216A of the Companies Act, the court would only be burdened with a late application by them. The judge was of the view that “the prospect of two sets of directors each suing and counter-suing in the name of the company is inappropriate, if not farcical”. 13     Pang was at the material times also a director and shareholder of PK Summit. In view of Pang’s and Lee’s positions in the company and Pang’s position in PK Summit, there was a duty on their part to inquire, if not investigate fully, all reasonable suspicions of impropriety by other directors as soon as they arose. The judge felt that Pang and Lee were slack in picking up the matters they were complaining about and he took into account their “sudden burst of allegations” in his overall assessment on whether their application ought to be granted. The parties referred to this ground as the “delay reason”. 14     Finally, the judge held that winding up the company was a much more sensible and desirable solution since the company was not doing well and “the inability of the two factions to co-exist itself portends no future for this partnership in a company’s clothing”. A professional liquidator would be able to investigate the company’s affairs and take the appropriate action after studying the special accountant’s report and the affidavits filed in the originating summons. This was the “winding up reason”. **The appeal** 15     The thrust of the appellants’ case was that Choo J erred in concluding that Pang and Lee failed to satisfy the requirements of s 216A of the Companies Act. Subsections (2) and (3) of that section provide: (2) Subject to subsection (3), a complainant may apply to the Court for leave to bring an action in the name and on behalf of the company or intervene in an action to which the company is a party for the purpose of prosecuting, defending or discontinuing the action on behalf of the company. (3) No action may be brought and no intervention in an action may be made under subsection (2) unless the Court is satisfied that — (a) the complainant has given 14 days’ notice to the directors of the company of his intention to apply to the Court under subsection (2) if the directors of the company do not bring, diligently prosecute or defend or discontinue the action; (b) the complainant is acting in good faith; and (c) it appears to be prima facie in the interests of the company that the action be brought, prosecuted, defended or discontinued. It was not in dispute that sub-s (3)(a) was complied with. The contentions centred on the conditions specified by sub-ss (3)(b) and (3)(c). 16     In _Teo Gek Luang v Ng Ai Tiong_ <span class="citation">[1999] 1 SLR 434</span>, a director holding 25% of the issued and paid-up capital of a company applied under s 216A of the Companies Act for leave to commence a representative action, in the name and on behalf of the company, against its managing director to recover a sum of money allegedly withdrawn unlawfully by him. Lai Kew Chai J held that the plaintiff’s delay in making the application, the less than happy circumstances under which she left the employ of the company, and her personal disputes with the managing director, were not sufficient to evidence bad faith on her part. The judge adopted the approach stated by the Ontario Court of Appeal in _Richardson Greenshields of Canada Ltd v Kalmacoff_ (1995) 123 DLR (4th) 628 that before granting leave, the court should be satisfied that there was a reasonable basis for the complaint and that the action sought to be instituted was a legitimate or arguable one. He also held that the court at the leave stage was not called upon to adjudicate on the disputes of facts and inferences but was to rely merely on affidavit evidence. As he concluded that there was “some substance in her complaint”, Lai J granted the plaintiff leave to commence the action for a reduced amount subject to certain terms. 17     _Agus Irawan v Toh Teck Chye_ <span class="citation">[2002] 2 SLR 198</span> involved a director of a company applying for leave under s 216A of the Companies Act to commence an action against two other directors of the company for alleged breach of fiduciary duties. Choo Han Teck JC (as he then was) dismissed the application. In responding to an application to file a further affidavit and to have the plaintiff there cross-examined, the judge said (at [6]): I do not see any need to expand or broaden the case at this stage. At this stage the court need not and ought not be drawn into an adjudication on the disputed facts. This is what a prima facie legitimate or arguable case is all about. Leave to cross-examine in such situations ought to be sparingly granted. I need only consider the grounds and points of challenge raised by the defendants to see if they are sufficient in themselves to destroy the credibility of the plaintiff’s propounded case without a full scale hearing to determine who was truthful and who was not. Agreeing with the approach taken by Lai J in the earlier case of _Teo Gek Luang v Ng Ai Tiong_ , Choo JC went on to say (at [8]) that the terms “legitimate” and “arguable” must be given their common and natural meaning, which was that the claim must have a reasonable semblance of merit, “not that it is bound to succeed or likely to succeed, but that if proved the company will stand to gain substantially in money or money’s worth”. 18     Addressing the company’s argument that the burden was on the plaintiff to prove that he acted in good faith, Choo JC said (at [9]): If at all, the burden would be on the opponent to show that the applicant did not act in good faith; for I am entitled, am I not, to assume that every party who comes to court with a reasonable and legitimate claim is acting in good faith – until proven otherwise. ... It would appear, in my view, that this requirement overlaps in no small way with the requirement that the claim must be in the interests of the company. Beyond that, whether malice or vindictiveness of the applicant ought to be taken into account must be left to the touch and feel of the court in each individual case ... This decision proceeded on appeal (Civil Appeal No 30 of 2002) and was dismissed by the Court of Appeal on 13 September 2002 with no written grounds of decision rendered. 19     In our opinion, the approach taken in the two cases above is generally beyond reproach. It is consonant with the legislative intention of providing a procedure for the protection of genuinely aggrieved minority interests and for doing justice to a company while ensuring that the company’s directors are not unduly hampered in their management decisions by loud but unreasonable dissidents attempting to drive the corporate vehicle from the back seat. 20     The best way of demonstrating good faith is to show a legitimate claim which the directors are unreasonably reluctant to pursue with the appropriate vigour or at all. Naturally, the parties opposing a s 216A application will seek to show that the application is motivated by an ulterior purpose, such as dislike, ill-feeling or other personal reasons, rather than by the applicant’s concern for the company. Hostility between the factions involved is bound to be present in most of such applications. It is therefore generally insufficient evidence of lack of good faith on the part of the applicant. However, if the opposing parties are able to show that the applicant is so motivated by vendetta, perceived or real, that his judgment will be clouded by purely personal considerations, that may be sufficient for the court to find a lack of good faith on his part. An applicant’s good faith would also be in doubt if he appears set on damaging or destroying the company out of sheer spite or worse, for the benefit of a competitor. It will also raise the question whether the intended action is going to be in the interests of the company at all. To this extent, there is an interplay of the requirements in s 216A(3)(b) and (c). 21     Having established that an applicant is acting in good faith and that a claim appears genuine, the court must nevertheless weigh all the circumstances and decide whether the claim ought to be pursued. Whether the company stands “to gain substantially in money or in money’s worth” ( _per_ Choo JC in _Agus Irawan_ ) relates more to the issue of whether it is in the interests of the company to pursue the claim rather than whether the claim is meritorious or not. A $100 claim may be meritorious but it may not be expedient to commence an action for it. The company may have genuine commercial considerations for not wanting to pursue certain claims. Perhaps it does not want to damage a good, long-term, profitable relationship. It could also be that it does not wish to generate bad publicity for itself because of some important negotiations which are underway. 22     In considering the requirement in s 216A(3)(c), the court should also consider whether there is another adequate remedy available, such as the winding up of the company ( _Barrett v Duckett_ [1995] 1 BCLC 243). We shall return to this case later when we consider the arguments on the “winding up reason”. 23     On the facts of the present appeal, Choo J appears to have been satisfied that there was no lack of good faith on the part of the applicants, Pang and Lee. We were not persuaded that the judge applied the wrong test or standard of proof in determining whether it was _prima facie_ in the interests of the company that the derivative action be brought against Koh and Tan. While the judge did not refer to his earlier decision in _Agus Irawan_ in his grounds of judgment, it was clear that he was acutely conscious of the principles he had to apply in coming to the conclusion that he did. He did not attempt to determine conclusively the disputed facts. He was correct in concluding that the allegations and counter-allegations from the two factions could not be determined on affidavit evidence alone. No legitimate or arguable case had been made out by Pang and Lee against Koh and Tan. If there was such a case made out by the special accountant’s report, it was against all the four shareholder-directors. 24     Following from the above, if leave had been granted to Pang and Lee to pursue an action against Koh and Tan, it would only be natural that leave should be granted to Koh and Tan as well to pursue their allegations against Pang and Lee, if they in turn made an application under s 216A. Of course, Koh and Tan, with the concurrence of the fifth director, may not even need to make such an application before commencing action, as they would be in a position to pass board resolutions. At any rate, the prospect of the company suing each faction with the respective suits being driven by the opposing faction was a real possibility. 25     The “delay reason” did not feature prominently in the judge’s consideration. This reason was overshadowed by what the judge termed the “more substantial matters that operate against the plaintiffs’ application”. Those matters were the fact that the company was not performing well and the deadlock that the factions were in. It followed that liquidation of the company would be a much more sensible and desirable solution. We agree with Choo J. 26     We now return to the decision in _Barrett v Duckett_. The facts of that case were somewhat unique in that “the circumstances in which the action [was] brought and pursued include[d] a bitter matrimonial dispute between the plaintiff’s daughter and the primary defendant” ( _per_ Peter Gibson LJ at 245, who delivered the first judgment in the English Court of Appeal). The plaintiff in that case, Mrs Barrett, was a 50% shareholder in Nightingale Travel Ltd. The primary defendant, her former sonin-law, was the other 50% shareholder and the sole director of the company. He was also one of two shareholders in Nightingale Coaches Ltd. His present wife was a director of the second company. 27     On 13 November 1992, the primary defendant petitioned for the compulsory winding up of the first company on the ground that it was insolvent and on the “just and equitable” ground because of the deadlock position that the company was in. On 11 March 1993, Mrs Barrett commenced proceedings on behalf of the first company and/or herself alleging, among other things, that the primary defendant and his present wife had diverted business from the first company to the second company. On 9 June 1993, the defendants applied to strike out Mrs Barrett’s action or to stay it until after the hearing of the winding up petition. They did so on the basis that an alternative remedy to the derivative action existed and that Mrs Barrett was an inappropriate person to conduct such litigation on behalf of the first company. The judge at first instance dismissed the application to strike out the action but directed that the action be set down to be heard with the winding up petition. 28     The arguments in the Court of Appeal centred on the applicability of the following proposition of law as stated by Peter Gibson LJ at 250: The shareholder will be allowed to sue on behalf of the company if he is bringing the action bona fide for the benefit of the company for wrongs to the company for which no other remedy is available. Conversely if the action is brought for an ulterior purpose or if another adequate remedy is available, the court will not allow the derivative action to proceed. Peter Gibson LJ, with whom Russell LJ agreed, concluded that Mrs Barrett, upset at the matrimonial problems between her erstwhile son-in-law and her daughter, and indignant at the supplanting of her daughter by the present wife, was driven by personal rather than financial considerations in pursuing the action and was therefore not pursuing it _bona fide_ on behalf of the company. He repeated and agreed (at 256) with what Hoffmann LJ said in giving leave to appeal to the Court of Appeal: As a matter of common sense, it seems arguable that the parties should not be subjected to lengthy and costly proceedings exacerbated by family hostilities when an independent liquidator might decide that the action could be settled on reasonable terms. In the result, the Court of Appeal unanimously allowed the appeal and ordered that Mrs Barrett’s action be struck out. 29     The appellants before us sought to distinguish the above case on four points. Firstly, there was no pending winding up petition here up to the time Choo J pronounced his decision. It was only after the respondent’s Case had been filed on 2 January 2004, in which _Barrett v Duckett_ was cited for the first time, that Koh and Tan filed a winding up petition on 19 January 2004. In late February 2004, Koh and Tan applied for a provisional liquidator to be appointed but the High Court adjourned that application pending the present appeal. The company was therefore not in liquidation nor would it be imminently. 30     Secondly, the appellants argued, _Barrett v Duckett_ was an exceptional case on the facts. There was a matrimonial dispute and the two individual defendants there were legally aided persons. The litigation was ruinous to the plaintiff and also caused heavy costs to be incurred by the public purse. 31     The third argument was that the application in the English case was in substance a _locus standi_ issue taken out at an early stage of the proceedings. In the present case, considerable time and costs have been spent in court attendance and in the extensive investigation undertaken by the special accountant. 32     The fourth ground propounded by the appellants was that the true rationale in the English case was that the wrongdoers would no longer be in control. In the present case, the contested winding up petition could be dismissed and the alleged wrongdoers would continue to be in control. Alternatively, the rationale in that case was that it was more appropriate for the liquidator rather than the shareholders to take the decision whether to sue. In the present case, it was not a certainty that a liquidator would be appointed. 33     It is true that the winding up petition in _Barrett v Duckett_ preceded the derivative action whereas the petition here came about only after the hearing of the application for leave. However, we do not think that would make a crucial difference. In any event, Koh and Tan had, through their solicitors’ letter of 26 September 2002, proposed to Pang and Lee that both the company and PK Summit be wound up since there was an impasse in the management of both companies. It was after that letter that Pang and Lee served notice under s 216A(3)(a) on 7 October 2002. The winding up option was therefore not an afterthought. 34     Similarly, the unusual circumstances of the English case do not detract from the principle that a person wishing to sue in the name of the company should be doing so in good faith for the benefit of the company. 35     We now deal with the third and fourth contentions. The arguments whether Pang and Lee should be allowed to sue in the name of the company were canvassed at the very threshold stage of leave. The fact that the case became drawn out merely showed the depth of the problems between the two factions of shareholder-directors. The winding up petition in _Barrett v Duckett_ was advertised and was transferred from the Leicester County Court to the High Court in London but it had not been dealt with at the time of the hearing. The petition was going to be contested. In fact, one of the arguments put forward by counsel for Mrs Barrett was that it was not certain that the company in issue would be wound up and that possibility was acknowledged by the court there. If the winding up petition in the present case is dismissed on account of the opposition by Pang and Lee, they have only themselves to blame. 36     The English Court of Appeal also acknowledged that there was no certainty that the liquidator would sue. However, it held that the fact that a liquidator had a discretion in relation to the bringing of an action was no answer to the objection based on the availability of an alternative remedy. It also noted that although Mrs Barrett was not a minority shareholder but a person holding the same number of shares as the other shareholder, she could be treated as being under the same disability as a minority shareholder in that it would not have been possible for her to set the company in motion to bring the action. We respectfully agree with these observations. They are equally apt in the present case. 37     Koh and Tan, as contributories, have taken out a petition (Companies Winding Up Petition No 15 of 2004) on 19 January 2004 to wind up the company. They pleaded that it would be just and equitable to have the company wound up due to the inability of the two factions to co-exist and the resulting deadlock in the company. They also claimed that the company was unable to pay its debts when they fell due and had not filed its statutory accounts nor held the statutory meetings. It appears to us eminently sensible for the parties to bring to an end a business relationship which had unfortunately evolved into a very unproductive and acrimonious one over the years. 38     While an appellate court would be able to form its own conclusions on the affidavit evidence adduced below, we see no reason to disagree with Choo J’s views. We therefore dismissed the appeal with costs. _Appeal dismissed with costs._ Copyright © Government of Singapore. Source: [link](https://www.singaporelawwatch.sg/Portals/0/Docs/Judgments/[2004] SGCA 18.pdf)
Java
UTF-8
641
1.8125
2
[]
no_license
package edu.unlv.kilo.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.ManyToMany; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; @RooJavaBean @RooToString @RooJpaActiveRecord public class UserData { @ManyToMany(cascade = CascadeType.ALL) List<TransactionEntity> transactions = new ArrayList<TransactionEntity>(); @ManyToMany(cascade = CascadeType.ALL) List<ItemEntity> items = new ArrayList<ItemEntity>(); }
Java
UTF-8
2,733
3.6875
4
[]
no_license
package trees_graphs_4; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class BSTSequences_4_9 { public static void main(String[] args) { TreeNode root = new MinimalTree_4_2().binarySearchTreee(new int[]{1, 2, 3, 4}); System.out.println(printDim(new BSTSequences_4_9().allSequences(root))); } ArrayList<LinkedList<Integer>> allSequences(TreeNode root) { ArrayList<LinkedList<Integer>> result = new ArrayList<>(); if (root == null) { result.add(new LinkedList<>()); return result; } LinkedList<Integer> prefix = new LinkedList<>(); prefix.add(root.val); ArrayList<LinkedList<Integer>> leftSeq = allSequences(root.left); ArrayList<LinkedList<Integer>> rightSeq = allSequences(root.right); for (LinkedList<Integer> left : leftSeq) { for (LinkedList<Integer> right : rightSeq) { ArrayList<LinkedList<Integer>> weaved = new ArrayList<>(); weaveLists(left, right, weaved, prefix); result.addAll(weaved); } } return result; } private void weaveLists(LinkedList<Integer> first, LinkedList<Integer> second, ArrayList<LinkedList<Integer>> results, LinkedList<Integer> prefix) { /* One list is empty. Add remainder to [a cloned] prefix and store result. */ if (first.size() == 0 || second.size() == 0) { LinkedList<Integer> result = (LinkedList<Integer>) prefix.clone(); result.addAll(first); result.addAll(second); results.add(result); return; } /* Recurse with head of first added to the prefix. Removing the head will damage first, so we'll need to put it back where we found it afterwards. */ int headFirst = first.removeFirst(); prefix.addLast(headFirst); weaveLists(first, second, results, prefix); prefix.removeLast(); first.addFirst(headFirst); /* Do the same thing with second, damaging and then restoring the list.*/ int headSecond = second.removeFirst(); prefix.addLast(headSecond); weaveLists(first, second, results, prefix); prefix.removeLast(); second.addFirst(headSecond); } public static String printDim(ArrayList<LinkedList<Integer>> values) { StringBuilder builder = new StringBuilder(); for (List<Integer> value : values) { builder.append(Arrays.toString(value.toArray(new Integer[0]))); builder.append("\n"); } return builder.toString(); } }
C++
UTF-8
3,093
3.625
4
[]
no_license
/* * Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left justified and no extra space is inserted between words. For example, words: ["This", "is", "an", "example", "of", "text", "justification."] L: 16. Return the formatted lines as: [ "This is an", "example of text", "justification. " ] Note: Each word is guaranteed not to exceed L in length. Corner Cases: A line other than the last line might contain only one word. What should you do in this case? In this case, that line should be left-justified. */ class Solution { private: void _fullJustify(vector<string> &ret, vector<string> &words, int i, int L) { int n = words.size(); if (i >= n) return; int s = i; int cnt = words[s].size(); s++; while (s < n) { if (cnt + words[s].size() + s - i <= L) { cnt += words[s].size(); s++; } else { break; } } string ss; if (s == n) { //over for (int j = i; j < s; j++) { ss += words[j]; if (j == s - 1) { string space(L - cnt - (s - i - 1), ' '); ss += space; } else ss += ' '; } ret.push_back(ss); return; } if (s == i + 1) { ss += words[i]; string sps(L - cnt, ' '); ss += sps; ret.push_back(ss); } else { int spaceslot = s - i - 1; string spaces[spaceslot]; for (int j = 0; j < L - cnt; j++) { spaces[j % spaceslot] += ' '; } int wc = s - i; for (int j = i; j < s; j++) { ss += words[j]; if (j == s - 1) continue; else { ss += spaces[j - i]; } } ret.push_back(ss); } _fullJustify(ret, words, s, L); } public: vector<string> fullJustify(vector<string> &words, int L) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> ret; if (words.size() < 1 || words[0].size() < 1) { string s; if (L > 0) { string tmp(L, ' '); s = tmp; } ret.push_back(s); return ret; } _fullJustify(ret, words, 0, L); return ret; } };
Markdown
UTF-8
6,350
3.140625
3
[]
no_license
# Why & How To Host a Club In A Low-Connectivity Neighborhoods > Help the next billion people read, write, and participate on the web with hands-on activities suitable for a low-connectivity environment! You decided to help your community learn new digital skills but you’re in a place with low-connectivity or no connection at all, or maybe you do have a connection but not enough machines. You know you want to help your learners but the infrastructure is a challenge. This guide will show you how to set up a club with activities suited for low-connectivity and fully offline situations. With Mozilla Clubs, you can connect your community to a global initiative, using participatory practices and bringing peer-learning into your low-connectivity neighborhood. Mozilla Clubs add value to your community by: * Spreading digital skills that enable life changing opportunities such as new careers and personal growth. * Teaching how to participate in online civic initiatives and e-Government processes, thus making the needs and dreams of your region known to a larger audience. * Providing a peer learning environment, which is an effective way to strengthen your community and ensure participants get a lot out of their involvement. * Share activities and content that attendees can then bring back to their own contexts (whether in their school, workplace, community, etc.). * Share participatory processes and informal learning tools that can be used to create and adapt activities that are focused on your community interests. * Being a part of a global initiative and exchange stories and feedback across the world. Mozilla Clubs add motivation for your attendees by: * Learning new digital skills that enables better jobs and opportunities. * Learning how to leverage the web and its large audience to spread social initiatives and participate in online civic processes. * Understanding how the internet works. * Looking to meet new people, learn new skills, make connections. * Learning through informal methods, by sharing, become a mentor. * Being a part of a larger community and causing positive social impact in your area. * Helping to spread knowledge about how to build the web they want. * Empowering people to put their voice on the web. How and why you should start a Mozilla Club in your neighborhood As a Mozilla Club Captain in a low-connectivity neighborhood, you can: * Uplevel your own mentoring and leadership skills. * Create or adapt activities that are focused on the same things your community cares about. * Be a catalyst for change in your region. * Join a global network and connect with other Mozilla Club Captains to share best practices and contribute new/adapted content. ## Activity Ideas There are tons of great activities that encourage community building, both online and offline at teach.mozilla.org/activities. Here are a few suggestions to host Mozilla Club with limited connectivity: * Personal Presentation Icebreakers: Sit in a circle and... * Share your name & fun fact about you. * Why do you want to be a part of this Mozilla Club? * What challenges do you face when it comes to digital use and learning? * Post-It Note Q&A/Discussions: Provide a prompt and have participants write answers/feedback on a post-it note, then stick it to a wall. Facilitate discussion afterwards. * Prompt Ideas: * What is your #1 aspiration when it comes to learning about the web? * If you were to connect the web with something you are passionate about, what would it be? (Then discuss as a group how you can do this.) * Lo-Fi, No-Fi Activities: These are key in a limited or no connectivity environment! It encourages teamwork, provides opportunity for great discussion, and can surface opportunities to build a stronger sense of community within your group dynamic. These can be especially fun when hosting a larger event that includes outside community members. * [Studio.code.org](https://studio.code.org) offers many “unplugged” activities for those with no prior programming experience. * [Teach.mozilla.org](https://teach.mozilla.org) offers 19 activities in this lo-fi, no-fi teaching kit. * Group Hack/Remix Challenges: When you do have connectivity, give these a try. Whatever tool or challenge you decide to use, pair your participants into teams to work together to achieve a goal. Add a bit of playful competition between teams by adding time restrictions, small prizes, or bragging rights. If unable to use online tools, simple print out a copy of the site or page and have learners go through the steps as if they were following online. If they are able to afterwards, they can complete the activity at home, school or another place they can access a computer/internet. * [Thimble](https://thimble.mozilla.org) - [Interactive Postcard Remix](https://docs.google.com/document/d/1gzbC5Q_XeHeii66v_Z4py6QrqYin5j1ozNhdeKJ-Ssg/edit) * [Create a WebMaker Project](http://mozilla.github.io/webmaker-curriculum/MobileWeb/create-webmaker-project.html) * [X-Ray Goggles](https://goggles.mozilla.org/) - [Hack the News activity](http://mozilla.github.io/webmaker-curriculum/WebLiteracyBasics-I/session02-hackthenews.html) ## Resources Want even more ideas and tools for hosting a club in a low-connectivity environment? Here are a few resources to help you dig further. * [Teach Like Mozilla - Our Values](https://teach.mozilla.org/teach-like-mozilla/) * [Discourse Community Forum](https://discourse.webmaker.org/) * [Latest Thimble Developments in low-fi, no-fi environments](https://blog.webmaker.org/colour-palettes-code-folding-and-new-thimble-projects-oh-my) * [Teaching the web offline](https://blog.webmaker.org/lets-teach-the-web-offline) * [Coder Dojo Erode offline event](http://govindsr.blogspot.in/2015/04/experience-coderdojo-erode-inaugural.html) ## Contact Email Mozilla’s Club expert Amira Dhalla (amira@mozillafoundation.org) with any questions about Mozilla Clubs Tweet us anytime [@MozTeach](https://twitter.com/mozteach) or using [#teachtheweb or #MozillaClubs](https://twitter.com/search?src=typd&q=%23mozillaclubs) Is your Mozilla Club doing an awesome job of retaining and growing the community? [Share your story with us!](https://docs.google.com/a/mozillafoundation.org/forms/d/1bOXV1OiF2EKS5KprlnzfFpwaoVNwxLAwN_UEq6hGKqU/viewform)
C++
UTF-8
1,703
2.640625
3
[]
no_license
#include "Usart.h" // inicjalizacja wlasciwosci statycznych klasy Usart Scenario Usart::scenarios; uint8_t Usart::params[4]; uint8_t Usart::paramsToRecv; uint8_t Usart::commandWithArguments; char Usart::incomeChar; bool Usart::newCharReceived; // definicja wektora przerwan odbioru danych USART ISR(USART_RXC_vect) { Usart::incomeChar = UDR; Usart::newCharReceived = true; } Usart::Scenario::Scenario(void* &function, const uint8_t &paramsBits) : function(function), paramsBits(paramsBits) { } void Usart::init() { // wlaczenie transmisji, wlaczenie odbioru, wlaczenie przerwania odbioru UCSRB = (1<<TXEN) | (1<<RXEN) | (1<<RXCIE); //nastaw 8-bitowej ramki UCSRC = (1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0); // for 9600 baud at 1MHz UBRRL = 71; sei(); } void Usart::run() { while (true) { _delay_ms(USART_SLEEP_TIME); if (!newCharReceived) continue; char charRecv = incomeChar; newCharReceived = false; processChar(charRecv); } } void Usart::processChar(const char &charRecv) { if (commandWithArguments) { if (paramsToRecv > 0) { params[scenarios[commandWithArguments - 32].paramsBits - paramsToRecv] = charRecv; --paramsToRecv; } else { params[scenarios[commandWithArguments - 32].paramsBits - paramsToRecv] = charRecv; send(commandWithArguments); } } else { if (scenarios.paramsBits == 0) { ((void (*)())(scenarios[charRecv - 32].function))(); send(charRecv); } else { commandWithArguments = true; paramsToRecv = scenarios.paramsBits; } } } void Usart::send(char toSend) { while (!(UCSRA & (1<<UDRE))); UDR = toSend; } void Usart::pushFunction(const Scenario &scenario, uint8_t id) { scenarios[id - 32] = fun; }
C#
UTF-8
1,739
3.140625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
using System; using System.Collections.Generic; namespace IfInjector.Util { /// <summary> /// Thread safe dictionary wrapper. Users supply a synchronization lock to allow for course-grained locking. Course grained locking helps to prevent obscure deadlock issues. /// /// For performance, the dictionary supports [optional] unsynced read operations. /// </summary> internal class SafeDictionary<TKey,TValue> { private readonly object syncLock; private readonly Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>(); private Dictionary<TKey, TValue> unsyncDict = new Dictionary<TKey, TValue> (); public SafeDictionary(object syncLock) { this.syncLock = syncLock; } public void Add(TKey key, TValue value) { lock (syncLock) { dict.Add(key, value); unsyncDict = new Dictionary<TKey, TValue> (dict); } } public bool TryGetValue(TKey key, out TValue value) { lock (syncLock) { return dict.TryGetValue (key, out value); } } public bool UnsyncedTryGetValue(TKey key, out TValue value) { return unsyncDict.TryGetValue (key, out value); } public IEnumerable<KeyValuePair<TKey, TValue>> UnsyncedEnumerate() { return unsyncDict; } public bool ContainsKey(TKey key) { lock (syncLock) { return dict.ContainsKey(key); } } public IEnumerable<TValue> Values { get { lock (syncLock) { // use unsync since that is a copy on write object. return unsyncDict.Values; } } } public bool Remove(TKey key) { lock (syncLock) { bool res = dict.Remove (key); if (res) { unsyncDict = new Dictionary<TKey, TValue> (dict); } return res; } } } }
Python
UTF-8
273
3.09375
3
[]
no_license
lst = [4, 15, 6, 8, 10, 15] max_val = max(lst) c = [0] * (max_val + 1) for ele in lst: c[ele] += 1 for i in range(1, len(c)): c[i] += c[i - 1] res = [0] * len(lst) for i in range(len(lst) - 1, -1, -1): res[c[lst[i]]-1] = lst[i] c[lst[i]] -= 1 print(res)
Python
UTF-8
16,297
4.09375
4
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 函数 # Python内置了很多有用的函数,我们可以直接调用。 # 注意:调用函数的时候,如果传入的参数数量不对,会报TypeError的错误; # 如果传入的参数数量是对的,但参数类型不能被函数所接受,也会报TypeError的错误。 # https://docs.python.org/3/library/functions.html 含有内置函数名字。 # 调用函数需要根据函数定义,传入正确的参数。如果函数调用出错,一定要学会看错误信息,所以英文很重要! # 求绝对值的函数 import math from function_import import my_abs_import number_abs = abs(-3.1415927) print('number_abs 的绝对值是:', number_abs) # 求最大值的函数 number_max = max(82, 3, 7, 11, 5, 4, 23, 100, -100, 6, 8, 5) print('number_max 最大值是:', number_max) # python 内置的函数,还包括数据类型转换的函数。 # 注意:字符串样式的 float ,不能转换为 ini , 但是 float 和 int 可互转。 str_float = float('3.1415927') str_int = int('1415927') float_int = int(3.1415927) int_float = float(3) print('str_float 的数据类型是:', type(str_float), '值是:', str_float) print('str_ini 的数据类型是:', type(str_int), '值是:', str_int) print('float_int 的数据类型是:', type(float_int), '值是:', float_int) print('int_float 的数据类型是:', type(int_float), '值是:', int_float) # 理解函数 # 函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”。 understandFunction = abs # 变量 understandFunction 指向 abs 函数 understandFunction(-1) # 所以也可以通过 understandFunction 调用 abs 函数 # 定义函数 # 定义函数使用( def 函数名 左括号 参数 有括号 ) 语句。 # 注意:函数内部语句一旦执行到return,函数就完毕,并将结果返回,因此,函数内部通过条件判断和循环可以实现非常复杂的逻辑; # 如果没有return语句,函数执行完毕后也会返回结果,只是结果为None。return None可以简写为return; # 在Python命令行模式下定义函数时,Python会出现...的提示。函数定义结束后需要按两次回车重新回到>>>提示符下。 def my_abs(num): if num >= 0: return num else: return -num use_my_abs = my_abs(-918) print('use_my_abs 调用函数 my_abs 后为:', use_my_abs) # 函数的导入 # 千万注意: xxx.py 文件名最好是不要含有数组(严格按照 python 的命名规范进行命名)。 print('导入含有函数的文件,调用my_abs_import方法后结果为:', my_abs_import(-3.14)) # 空函数 # 定义空函数可以使用 pass 作为占位符,比如还没有想好怎么写函数的代码。先放一个 pass 让代码能运行起来。 # 注意:pass是语句什么都不做的, 。 def none_function(): pass # pass 作为占位符还可以使用在条件语句里面 name = 'zhangxiaolin' if name == 'zhangxiaolin': pass # 自定义函数引用时,参数个数不对,Python 解释器会抛出 TypeError ,但是参数类型不对,解释器无法帮我们检查, # 所以需要在定义参数时对参数类型进行检查 def my_abs_add_type_inspect(num): if not isinstance(num, (int, float)): raise TypeError('参数类型错误') if num >= 0: return num else: return -num # use_my_abs_type = my_abs_add_type_inspect('985') #这里参数类型是错误的应该报“参数类型错误” # print('use_my_abs_type 调用参数类型检查函数 my_abs_add_type_inspect 结果为为:', use_my_abs_type) # 函数怎么返回多个值 # 例如:从已知点( x , y )向 angle 度方向移动 step 的距离。 # 注意:从返回值可以看出,返回的是一个 tuple , # 在语法上元组可以省略小括号,而多个变量,可以同时接受一个元组,按位置个对应的值, # 所以Python的函数返回多值,其实返回的就是一个 tuple ,但写起来更方便。 def move(x, y, step, angle=0): new_x = x + step * math.cos(angle) new_y = y - step * math.sin(angle) return new_x, new_y new_long_let = move(1, 30, 100, 30) # 值为: (16.425144988758404, 128.8031624092862) print('从( 1, 30 )向 30 度方向移动 100后为:', new_long_let) # 实验,利用函数写一个一元二次方程的两个解, # ax²+bx+c=0 求 x 的值。 # 注意:返回值一定不要加小括号,元组默认不需要加小括号的 def solve_equation_one_two(a, b, c): if not isinstance(a, (int, float)): raise TypeError('a 参数类型错误') if not isinstance(b, (int, float)): raise TypeError('b 参数类型错误') if not isinstance(c, (int, float)): raise TypeError('c 参数类型错误') pow_b_two = int(math.pow(b, 2)) # b 平方 new_sqrt = abs(pow_b_two - 4*a*c) # 平方根 new_x1 = (-b + new_sqrt)/(2*a) # 第一个值 new_x2 = (-b - new_sqrt)/(2*a) # 第二个值 return new_x1, new_x2 equation_one_two = solve_equation_one_two(1, 2, 3) print('一元二次方程equation_one_two,解为:', equation_one_two) # 解为: (3.0, -5.0) # 函数的默认参数 # 自定义一个计算 x 平方的函数 def my_power(x): return x * x # 函数设置三次方和多次方运算时, # 注意算法,很重要、相当重要、非常重要 def solve_power_n(x, n): s = 1 while n > 0: n = n - 1 s = s * x return s my_solve_power_n = solve_power_n(5, 3) print('my_solve_power_n 的三次方的值为', my_solve_power_n) # 在 Python 的函数中,需要设置默认参数是,可以直接给参数设置默认值 # 这种参数的设置类似给 typesecipt 函数设置默认值 # 注意:必选参数在前,默认参数在后,否则 Python 的解释器会报错; # 当函数有多个参数时,把变化大的参数放前面,变化小的参数放后面。变化小的参数就可以作为默认参数。 def solve_power_base(x, n=2): s = 1 while n > 0: n = n - 1 s = s * x return s my_solve_power_solve_power_base = solve_power_base(5, 4) print('my_solve_power_solve_power_base 的4次方的值为', my_solve_power_solve_power_base) # 函数中按顺序提供参数和不按顺序提供参数的区别写法 def enroll(name, grade, age=6, city='成都'): print('姓名是:', name) print('年级是:', grade) print('年龄是:', age) print('城市是:', city) enroll('张小', '一年级') # 使用默认参数,添加姓名、班级 enroll('张小小', '二年级', 10) # 设置默认参数,添加姓名、班级、年龄 enroll('张小小小', '三年级', city='广元') # 不按顺序修改默认参数,添加姓名、班级、城市 # 当参数为 list 时,常见问题 # 注意:函数在定义时,默认参数 l 的值就被计算出来了,即 [], # 因为默认参数 l 也是一个变量,它指向对象 [], # 每次调用该函数,如果改变了 l 的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的 [] 了。 def param_list(l=[]): l.append('结束') return l print('param_list 使用默认参数时:', param_list()) # 结果=> ['结束'] print('param_list 添加参数时:', param_list([1, 2, 3])) # 结果=> [1, 2, 3, '结束'] print('param_list 再次使用默认参数时:', param_list()) # 结果=> ['结束', '结束'] print('param_list 第三次使用默认参数时:', param_list()) # 结果=> ['结束', '结束', '结束'] # 修改上面的 param_list 为正确方式 # 注意:在下面代码中,为什么设置参数为str、None这样的不变对象呢? # 因为不变对象一旦创建,对象内部的数据就不能修改,这样就减少了由于修改数据导致的错误; # 此外,由于对象不变,多任务环境下同时读取对象不需要加锁,同时读取这条数据一点问题都没有; # 我们在编写程序时,如果可以设计一个不变对象,那就尽量设计成不变对象。 def change_param_list(l=None): if l is None: l = [] l.append('再次结束') return l print('change_param_list 使用默认参数时:', change_param_list()) # ['再次结束'] print('change_param_list 添加参数时:', change_param_list([1, 2])) # [1, 2, '再次结束'] print('change_param_list 再次使用默认参数时:', change_param_list()) # ['再次结束'] print('change_param_list 第三次使用默认参数时:', change_param_list()) # ['再次结束'] # 可变参数 # 可变参数就是传入的参数个数是可变的,可以是 1 个、 2 个到任意个,还可以是 0 个。 # 注意这种可变参数一般都会涉及到在函数内部循环; # variable_list_square_sum 函数只能传入 list ; # variable_tuple_square_sum 函数只能传入 tuple 元组; # 可变参数允许你传入 0 个或任意个参数,这些可变参数在函数调用时自动组装为一个 tuple ; def variable_list_square_sum(numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print('variable_list_square_sum 里面 list 的平方和为:', variable_list_square_sum([1, 2, 3])) def variable_tuple_square_sum(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print('variable_tuple_square_sum 里面数据的平方和为:', variable_tuple_square_sum(4, 5, 6)) variable_square_sum1 = variable_tuple_square_sum(*(7, 8, 9)) variable_square_sum2 = variable_tuple_square_sum(*[7, 8, 9]) print('把 list 或者 tuple 作为可变参数计算平方和为:', variable_square_sum1, variable_square_sum2) # 关键字参数 # 关键字参数允许你传入 0 个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个 dict 。 # **age 表示关键字参数(表示一个 dict )。 age 只做表示,替代,不做展示。 def login(name, password, **other): print('name:', name, 'password:', password, 'other_age:', other) return name, password, other any_param = login('张小霖', '123456', city='乐山') print('传入任意参数后:', any_param) # 关键字参数的复杂调用 dict_param = {'other_name': '蒙娜丽莎', 'age': 18, 'grade': '一班'} complex_param = login('张小霖', '123456', **dict_param) print('传入复杂参数后:', complex_param) # 命名关键字参数(限制关键字参数) # 作用:限制关键字参数的名字,就可以用命名关键字参数。 # 用法:和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。 # 注意:命名关键字参数必须传入定义的参数名。如果没有传入参数名,调用也将报错(必须传入定义的参数,多传少传都报错); # restrict_param('孙子', 45, '山东北部(齐国乐安)', '军事')) # 由于没有传入定义的参数名,所以此行调用会报错。 def restrict_param(name, age, *, city, job): return name, age, city, job # print('关键字参数为:', restrict_param('孙子', 45, city='山东北部(齐国乐安)')) # 会报错 # print('关键字参数为:', restrict_param('孙子', 45, city='山东北部(齐国乐安)', job='军事', wife='未知')) # 会报错 print('restrict_param 命名关键字参数:', restrict_param( '孙子', 45, city='山东北部(齐国乐安)', job='军事')) # 正确 # 如果函数参数中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了; # 这个可变参数仅作为后面参数的定义,不作为key值传递 def restrict_param_add(name, age, *, city, job): print(name, age, city, job) restrict_param_add('带参数的 *args 含有 city , job :', '年龄99', city='四川广元', job='我想成为一个军事家') # print('restrict_param_add 中间含有命名关键字参数:', restrict_param_add( # '孙膑', '不详', city='山东省菏泽市甄城县北', job='军事')) # 参数组合 # 在 Python 中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数, # 这5种参数都可以组合使用,但是参数定义的顺序必须是: # 必选参数、 # 默认参数、 # 可变参数、 # 命名关键字参数和关键字参数。 def compose_param1(a, b=0, *c, **d): print('组合参数1:a=', a, 'b=', b, 'c=', c, 'd=', d) def compose_param2(a, b=0, *c, d, e, **f): print('组合参数2:a=', a, 'b=', b, 'c=', c, 'd=', d, 'e=', e, 'f=', f) compose_param1('我是 compose_param1 的,必选参数a', '默认值b', [ '可变参数list1', '可变参数list2'], param1='关键字参数1', param2='关键字参数2') compose_param2('我是 compose_param2 的,必选参数a', '我是默认值b', [ '可变参数c_list1', '可变参数c_list2'], d='命名关键字参数1', e='命名关键字参数2', f1="关键字f1", f2="关键字f2") # 递归函数 # 函数在内部调用本身,这个函数就是递归函数。 # 所有的递归函数都可以写成循环的方式,但循环的逻辑不如递归清晰。 # 优点:逻辑简单清晰。 # 缺点:是过深的调用会导致栈溢出, Python 标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出的问题。 # 注意:使用递归函数需要注意防止栈溢出。 # 知识:在计算机中,函数调用是通过栈( stack )这种数据结构实现的, # 每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧; # 由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出。 # n! = 1 x 2 x 3 x ... x n def recursion(n): if n == 1: return 1 return n * recursion(n - 1) print('等差数列(从 5-1 )的积为:', recursion(5)) # recursion(5) 的计算过程是: # ===> fact(5) # ===> 5 * fact(4) # ===> 5 * (4 * fact(3)) # ===> 5 * (4 * (3 * fact(2))) # ===> 5 * (4 * (3 * (2 * fact(1)))) # ===> 5 * (4 * (3 * (2 * 1))) # ===> 5 * (4 * (3 * 2)) # ===> 5 * (4 * 6) # ===> 5 * 24 # ===> 120 # print('测试栈溢出的情况:', recursion(1000)) # 尾递归函数 # 解决递归调用栈溢出的方法是通过尾递归优化, # 事实上尾递归和循环的效果是一样的,所以,把循环看成是一种特殊的尾递归函数也是可以的。 # 注意: recursion(n) 函数由于引入了 return n * fact(n - 1) 乘法表达式,所以不是尾递归; # 遗憾的是,大多数编程语言没有针对尾递归做优化,Python解释器也没有做优化,所以,即使把上面的 recursion_last(n) 函数改成尾递归方式,也会导致栈溢出。 def recursion_last(n): return recursion_last_self(n, 1) def recursion_last_self(num, product): if num == 1: return product print('我爱美女', num - 1, num * product) return recursion_last_self(num - 1, num * product) recursion_last(5) # print('尾递归函数 recursion_last(5) 计算结果为:', recursion_last(5)) # recursion(5) 的计算过程是: # ===> fact_iter(5, 1) # ===> fact_iter(4, 5) # ===> fact_iter(3, 20) # ===> fact_iter(2, 60) # ===> fact_iter(1, 120) # ===> 120 # print('尾递归函数 recursion_last(1000) 计算结果为:', recursion_last(1000)) # 递归实验汉诺塔的移动 def hanoi_tower(n, a, b, c): if n == 1: print('hanoi_tower', a, '-->', c) else: hanoi_tower(n-1, a, c, b) hanoi_tower(1, a, b, c) hanoi_tower(n-1, b, a, c) hanoi_tower(4, 'A', 'B', 'C')
Python
UTF-8
421
4.4375
4
[]
no_license
'''Elabore um programa que leia do teclado o sexo de uma pessoa. Se o sexo digitado for “M” ou “m” ou “F” ou “f”, escrever na tela “Sexo válido!”. Caso contrário, exibir “Sexo inválido!”. ''' #ENTRADA sexo = input("Digite o seu sexo(M para masculino e F para feminino ") #PROCESSAMENTO if sexo.upper() == 'M' or sexo.upper()=='F': print("Sexo válido ") else: print("Sexo inválido ")
Markdown
UTF-8
1,898
2.59375
3
[ "LicenseRef-scancode-bsd-atmel" ]
permissive
USB_HID_MOUSE EXAMPLE ===================== # Objectives ------------ This example aims to test the USB Device Port(UDP) and USB Human Interface Device class (HID). # Example Description --------------------- The demonstration program simulates a HID-compliant mouse. When the board running this program connected to a host (PC for example), with USB cable, the board appears as a USB mouse for the host. Then the host can play sound through host software. Press 'I'/'J'/'K'/'L' into the console to control the cursor on the host. # Test ------ ## Supported targets -------------------- * SAM9XX5-EK * SAM9X60-EK * SAM9X60-CURIOSITY * SAMA5D2-PTC-EK * SAMA5D2-XPLAINED * SAMA5D27-SOM1-EK * SAMA5D3-EK * SAMA5D3-XPLAINED * SAMA5D4-EK * SAMA5D4-XPLAINED * SAME70-XPLAINED * SAMV71-XPLAINED ## Setup -------- On the computer, open and configure a terminal application (e.g. HyperTerminal on Microsoft Windows) with these settings: - 115200 bauds - 8 bits of data - No parity - 1 stop bit - No flow control ## Start the application ------------------------ When connecting USB cable to host, the new "HID Mouse Device" appears in the hardware device list. Once the device is connected and configured, pressing the 'I J K L' key to move the cursor. In the terminal window, the following text should appear (values depend on the board and chip used): ``` -- USB Device HID Mouse Project xxx -- -- SAMxxxxx-xx -- Compiled: xxx xx xxxx xx:xx:xx -- -- Press I J K L to move cursor ``` Tested with IAR and GCC (sram and ddram configuration) In order to test this example, the process is the following: Step | Description | Expected Result | Result -----|-------------|-----------------|------- Press 'I' | Cursor move up | PASSED | PASSED Press 'J' | Cursor move to left | PASSED | PASSED Press 'K' | Cursor move down | PASSED | PASSED Press 'L' | Cursor move to right | PASSED | PASSED
PHP
UTF-8
204
2.765625
3
[]
no_license
<?php $array_keys = array('a', 'b', 'c'); $array_values = array('one', 'two', 'three'); print_r(array_combine($array_keys, $array_values)); /* kết quả: Array( [a] => one [b] => two 1 => three; )*/; ?>
Java
UTF-8
1,231
2.953125
3
[ "Apache-2.0" ]
permissive
/* * 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 Design.OOP.VendingMachine; import java.util.List; /** * * @author mankank */ public class Client { public static void main(String[] args) { VendingMachine system = VendingMachineFactory.getVendingMachine("A"); system.createProduct("Pepsi"); system.createProduct("Pepsi"); system.createProduct("Pepsi"); system.createProduct("Coke"); system.createProduct("Coke"); system.createProduct("Coke"); system.createProduct("Soda"); system.createProduct("Soda"); system.createProduct("Soda"); system.insertAmount(10); system.insertAmount(10); system.insertAmount(5); system.insertAmount(5); system.purchaseProduct("Coke"); system.getChange(); system.insertAmount(25); system.insertAmount(25); system.purchaseProduct("Pepsi"); List<Coin> c = system.getChange(); for (int i = 0; i < c.size(); i++) { System.out.print(c.get(i).cointype + " "); } } }
Markdown
UTF-8
2,261
2.671875
3
[]
no_license
# [Target #70 - Froggy](https://cssbattle.dev/play/70) ![](https://cssbattle.dev/targets/70.png) ```HTML <!-- Battle #13 - Clip/ #70 - Froggy --> <div class="l-i"></div> <div class="l-inner-i"></div> <div class="l-p"></div> <div class="r-i"></div> <div class="r-inner-i"></div> <div class="r-p"></div> <div class="l-nose"></div> <div class="r-nose"></div> <div class="head"></div> <style> body { background: #293462; display: flex; justify-content: center; align-items: center; } .l-i { width: 50px; height: 50px; border-radius: 50%; background: #FE5F55; position: absolute; top: 85px; left: 140px; } .l-inner-i { width: 30px; height: 30px; border-radius: 50%; background: #FFF1C1; position: absolute; top: 95px; left: 150px; z-index: 2; } .l-p { width: 10px; height: 10px; background: #293462; z-index: 2; border-radius: 50%; position: absolute; top: 105px; left: 160px; } .r-i { width: 50px; height: 50px; border-radius: 50%; background: #FE5F55; position: absolute; top: 85px; left: 210px; } .r-inner-i { width: 30px; height: 30px; border-radius: 50%; background: #FFF1C1; position: absolute; top: 95px; left: 220px; z-index: 2; } .r-p { width: 10px; height: 10px; background: #293462; z-index: 2; border-radius: 50%; position: absolute; top: 105px; left: 230px; } .l-nose { width: 10px; height: 10px; background: #293462; z-index: 2; border-radius: 50%; position: absolute; top: 160px; left: 185px; } .r-nose { width: 10px; height: 10px; background: #293462; z-index: 2; border-radius: 50%; position: absolute; top: 160px; left: 205px; } .mouth { background: #A64942; } .head { width: 150px; height: 100px; background: #A64942; position: absolute; top: 110px; left: 125px; border-radius: 90px; overflow: hidden; } .head::before { content: ''; width: 250px; height: 200px; background: #FE5F55; border-radius: 46%; position: absolute; top: -130px; left: -50; } </style> ```
TypeScript
UTF-8
425
3.046875
3
[]
no_license
/** * This class represents the end user reponse model */ export class APIResponeModel< T = Record<string, any> | boolean | string | null > { //#region properties public readonly success: boolean = false; public readonly data: T; public readonly message: string = ''; public readonly errors: string[] = []; //#endregion constructor(init: Partial<APIResponeModel<T>>) { Object.assign(this, init); } }
PHP
UTF-8
746
2.578125
3
[]
no_license
<?php use Flatness\Cache; use PHPUnit\Framework\TestCase; use Flatness\FileSystemInterface; // phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace class CacheTest extends TestCase { public function test() { $data = ['a' => 'b']; $fs = $this->createMock(FileSystemInterface::class); $fs->expects($this->exactly(1))->method('loadFile')->willReturn(json_encode($data)); $fs->expects($this->exactly(1))->method('saveFile'); $fs->expects($this->exactly(2))->method('existsFile')->willReturn(true); $fs->expects($this->exactly(1))->method('filemtime')->willReturn(time()); $cache = new Cache($fs, '/'); $cache->save('uri', $data); $cache->get('uri'); } }
Swift
UTF-8
956
2.875
3
[]
no_license
// // UIViewController.swift // Surfline // // Created by Ali Aljoubory on 12/12/2020. // import UIKit extension UIViewController { func presentAlert(title: String, message: String, actionTitle: String, actionStyle: UIAlertAction.Style) { let ac = UIAlertController(title: title, message: message, preferredStyle: .alert) ac.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: nil)) present(ac, animated: true) } func presentAlertWithHandlerToDismissView(title: String, message: String, actionTitle: String, actionStyle: UIAlertAction.Style, viewController: UIViewController) { let ac = UIAlertController(title: title, message: message, preferredStyle: .alert) ac.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: { (action) in viewController.dismiss(animated: true, completion: nil) })) present(ac, animated: true) } }
Markdown
UTF-8
27,307
2.625
3
[]
no_license
--- title: 'Tutorial: Crear una aplicación web de una sola página - Bing Web Search API' titleSuffix: Azure Cognitive Services description: Esta aplicación de una página muestra cómo se puede usar Bing Web Search API para recuperar, analizar y mostrar los resultados de la búsqueda pertinentes en una aplicación de una página. services: cognitive-services author: erhopf manager: cgronlun ms.service: cognitive-services ms.component: bing-web-search ms.topic: tutorial ms.date: 09/12/2018 ms.author: erhopf ms.openlocfilehash: 670f02cbd8e994664e7c4edd75940ff43f9616b6 ms.sourcegitcommit: f10653b10c2ad745f446b54a31664b7d9f9253fe ms.translationtype: HT ms.contentlocale: es-ES ms.lasthandoff: 09/18/2018 ms.locfileid: "46126486" --- # <a name="tutorial-create-a-single-page-app-using-the-bing-web-search-api"></a>Tutorial: Crear una aplicación de una sola página con Bing Web Search API Esta aplicación de una página muestra cómo recuperar, analizar y mostrar los resultados de la búsqueda desde Bing Web Search API. El tutorial usa código HTML y CSS reutilizable y se centra en el código de JavaScript. Los archivos HTML, CSS y JS están disponibles en [GitHub](https://github.com/Azure-Samples/cognitive-services-REST-api-samples/tree/master/Tutorials/Bing-Web-Search) con instrucciones de inicio rápido. Esta aplicación de ejemplo puede: > [!div class="checklist"] > * Llamar a Bing Web Search API con opciones de búsqueda > * Mostrar resultados de vídeo, imágenes, noticias y web > * Paginar resultados > * Administrar claves de suscripción > * errores Para usar esta aplicación, se requiere una [cuenta de Azure Cognitive Services](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account) con Bing Search API. Si no tiene una cuenta, puede usar la [evaluación gratuita](https://azure.microsoft.com/try/cognitive-services/?api=bing-web-search-api) para obtener una clave de suscripción. ## <a name="prerequisites"></a>Requisitos previos A continuación se detalla lo que necesitará para ejecutar la aplicación: * Node.js 8 o posterior * Una clave de suscripción ## <a name="get-the-source-code-and-install-dependencies"></a>Obtención del código fuente e instalación de dependencias El primer paso consiste en clonar el repositorio con el código fuente de la aplicación de ejemplo. ```console git clone https://github.com/Azure-Samples/cognitive-services-REST-api-samples.git ``` A continuación, ejecute `npm install`. Para este tutorial, Express.js es la única dependencia. ```console cd <path-to-repo>/cognitive-services-REST-api-samples/Tutorials/Bing-Web-Search npm install ``` ## <a name="app-components"></a>Componentes de la aplicación La aplicación de ejemplo que estamos compilando se compone de cuatro partes: * `bing-web-search.js`: nuestra aplicación Express.js. Controla la lógica de solicitud/respuesta y el enrutamiento. * `public/index.html`: el esqueleto de nuestra aplicación; define cómo se presentan los datos al usuario. * `public/css/styles.css`: define los estilos de página, como fuentes, colores y tamaño del texto. * `public/js/scripts.js`: contiene la lógica para realizar solicitudes a Bing Web Search API, administrar claves de suscripción, administrar y analizar respuestas y mostrar resultados. En este tutorial se centra en `scripts.js` y la lógica necesaria para llamar a Bing Web Search API y controlar la respuesta. ## <a name="html-form"></a>Formulario HTML El elemento `index.html` incluye un formulario que permite a los usuarios buscar y seleccionar las opciones de búsqueda. El atributo `onsubmit` se desencadena cuando se envía el formulario, con una llamada al método `bingWebSearch()` definido en `scripts.js`. Toma tres argumentos: * Consulta de búsqueda * Opciones seleccionadas * Subscription key ```html <form name="bing" onsubmit="return bingWebSearch(this.query.value, bingSearchOptions(this), getSubscriptionKey())"> ``` ## <a name="query-options"></a>Opciones de consulta El formulario HTML incluye opciones que se asignan a parámetros de consulta en [Bing Web Search API v7](https://docs.microsoft.com/rest/api/cognitiveservices/bing-web-api-v7-reference#query-parameters). En esta tabla se proporciona un desglose de cómo los usuarios pueden filtrar los resultados de la búsqueda mediante la aplicación de ejemplo: | Parámetro | DESCRIPCIÓN | |-----------|-------------| | `query` | Un campo de texto para escribir una cadena de consulta. | | `where` | Un menú desplegable para seleccionar el mercado (ubicación e idioma). | | `what` | Casillas para promover tipos de resultados específicos. Por ejemplo, la promoción de imágenes aumenta el orden de clasificación de las imágenes en los resultados de la búsqueda. | | `when` | Un menú desplegable que permite al usuario limitar los resultados de la búsqueda para hoy, esta semana o este mes. | | `safe` | Una casilla para habilitar la búsqueda segura de Bing, que filtra el contenido para adultos. | | `count` | Campo oculto. Número de resultados de búsqueda que se devolverán en cada solicitud. Cambie este valor para mostrar más o menos resultados por página. | | `offset` | Campo oculto. El desplazamiento del primer resultado de la búsqueda de la solicitud, que se usa para la paginación. Se restablece a `0` en cada nueva solicitud. | > [!NOTE] > Bing Web Search API proporciona parámetros de consulta adicionales para ayudar a refinar los resultados de la búsqueda. Este ejemplo usa solo algunos. Para obtener una lista completa de los parámetros disponibles, vea la [referencia de Bing Web Search API v7](https://docs.microsoft.com/rest/api/cognitiveservices/bing-web-api-v7-reference#query-parameters). La función `bingSearchOptions()` convierte estas opciones para que coincidan con el formato que requiere Bing Search API. ```javascript // Build query options from selections in the HTML form. function bingSearchOptions(form) { var options = []; // Where option. options.push("mkt=" + form.where.value); // SafeSearch option. options.push("SafeSearch=" + (form.safe.checked ? "strict" : "off")); // Freshness option. if (form.when.value.length) options.push("freshness=" + form.when.value); var what = []; for (var i = 0; i < form.what.length; i++) if (form.what[i].checked) what.push(form.what[i].value); // Promote option. if (what.length) { options.push("promote=" + what.join(",")); options.push("answerCount=9"); } // Count option. options.push("count=" + form.count.value); // Offset option. options.push("offset=" + form.offset.value); // Hardcoded text decoration option. options.push("textDecorations=true"); // Hardcoded text format option. options.push("textFormat=HTML"); return options.join("&"); } ``` `SafeSearch` se puede establecer en `strict`, `moderate` o `off`, con `moderate` como la configuración predeterminada para Bing Web Search. Este formulario usa una casilla que tiene dos estados. En este fragmento de código, la búsqueda segura se establece en `strict` o `off`; `moderate` no se usa. Si cualquiera de las casillas **Promover** está seleccionada, se agrega el parámetro `answerCount` a la consulta. `answerCount` es obligatorio cuando se usa el parámetro `promote`. En este fragmento de código, el valor se establece en `9` para devolver todos los tipos de resultados disponibles. > [!NOTE] > La promoción de un tipo de resultado no *garantiza* que se incluirá en los resultados de la búsqueda. En su lugar, la promoción aumenta la clasificación de esos tipos de resultados con respecto a su clasificación habitual. Para limitar las búsquedas a determinados tipos de resultados, use el parámetro de consulta `responseFilter` o llamar a un punto de conexión más concreto como Bing Image Search o Bing News Search. Los parámetros de consulta `textDecoration` y `textFormat` están codificados de forma rígida en el script para que el término de búsqueda aparezca en negrita en los resultados de la búsqueda. Estos parámetros no son necesarios. ## <a name="manage-subscription-keys"></a>Administrar claves de suscripción Para evitar tener que codificar de forma rígida la clave de suscripción de Bing Search API, esta aplicación de ejemplo usa el almacenamiento persistente del explorador para almacenar la clave de suscripción. Si no se almacena ninguna clave de suscripción, se solicita al usuario que escriba una. Si se rechaza la clave de suscripción mediante la API, se pedirá al usuario que vuelva a escribir una clave de suscripción. La función `getSubscriptionKey()` usa las funciones `storeValue` y `retrieveValue` para almacenar y recuperar la clave de suscripción de un usuario. Estas funciones usan el objeto `localStorage`, si se admite, o cookies. ```javascript // Cookie names for stored data. API_KEY_COOKIE = "bing-search-api-key"; CLIENT_ID_COOKIE = "bing-search-client-id"; BING_ENDPOINT = "https://api.cognitive.microsoft.com/bing/v7.0/search"; // See source code for storeValue and retrieveValue definitions. // Get stored subscription key, or prompt if it isn't found. function getSubscriptionKey() { var key = retrieveValue(API_KEY_COOKIE); while (key.length !== 32) { key = prompt("Enter Bing Search API subscription key:", "").trim(); } // Always set the cookie in order to update the expiration date. storeValue(API_KEY_COOKIE, key); return key; } ``` Como vimos anteriormente, cuando se envía el formulario, se activa `onsubmit`, con una llamada a `bingWebSearch`. Esta función se inicializa y envía la solicitud. Se llama a `getSubscriptionKey` en cada envío para autenticar la solicitud. ## <a name="call-bing-web-search"></a>Llamar a Bing Web Search Dada la consulta, la cadena de opciones y la clave de suscripción, la función `BingWebSearch` crea un objeto `XMLHttpRequest` para llamar al punto de conexión de Bing Web Search. ```javascript // Perform a search constructed from the query, options, and subscription key. function bingWebSearch(query, options, key) { window.scrollTo(0, 0); if (!query.trim().length) return false; showDiv("noresults", "Working. Please wait."); hideDivs("pole", "mainline", "sidebar", "_json", "_http", "paging1", "paging2", "error"); var request = new XMLHttpRequest(); var queryurl = BING_ENDPOINT + "?q=" + encodeURIComponent(query) + "&" + options; // Initialize the request. try { request.open("GET", queryurl); } catch (e) { renderErrorMessage("Bad request (invalid URL)\n" + queryurl); return false; } // Add request headers. request.setRequestHeader("Ocp-Apim-Subscription-Key", key); request.setRequestHeader("Accept", "application/json"); var clientid = retrieveValue(CLIENT_ID_COOKIE); if (clientid) request.setRequestHeader("X-MSEdge-ClientID", clientid); // Event handler for successful response. request.addEventListener("load", handleBingResponse); // Event handler for errors. request.addEventListener("error", function() { renderErrorMessage("Error completing request"); }); // Event handler for an aborted request. request.addEventListener("abort", function() { renderErrorMessage("Request aborted"); }); // Send the request. request.send(); return false; } ``` Después de una solicitud correcta, el controlador de eventos `load` se activa y llama a la función `handleBingResponse`. `handleBingResponse` analiza el objeto de resultado, muestra los resultados y contiene la lógica de error para las solicitudes con error. ```javascript function handleBingResponse() { hideDivs("noresults"); var json = this.responseText.trim(); var jsobj = {}; // Try to parse results object. try { if (json.length) jsobj = JSON.parse(json); } catch(e) { renderErrorMessage("Invalid JSON response"); return; } // Show raw JSON and the HTTP request. showDiv("json", preFormat(JSON.stringify(jsobj, null, 2))); showDiv("http", preFormat("GET " + this.responseURL + "\n\nStatus: " + this.status + " " + this.statusText + "\n" + this.getAllResponseHeaders())); // If the HTTP response is 200 OK, try to render the results. if (this.status === 200) { var clientid = this.getResponseHeader("X-MSEdge-ClientID"); if (clientid) retrieveValue(CLIENT_ID_COOKIE, clientid); if (json.length) { if (jsobj._type === "SearchResponse" && "rankingResponse" in jsobj) { renderSearchResults(jsobj); } else { renderErrorMessage("No search results in JSON response"); } } else { renderErrorMessage("Empty response (are you sending too many requests too quickly?)"); } } // Any other HTTP response is considered an error. else { // 401 is unauthorized; force a re-prompt for the user's subscription // key on the next request. if (this.status === 401) invalidateSubscriptionKey(); // Some error responses don't have a top-level errors object, if absent // create one. var errors = jsobj.errors || [jsobj]; var errmsg = []; // Display the HTTP status code. errmsg.push("HTTP Status " + this.status + " " + this.statusText + "\n"); // Add all fields from all error responses. for (var i = 0; i < errors.length; i++) { if (i) errmsg.push("\n"); for (var k in errors[i]) errmsg.push(k + ": " + errors[i][k]); } // Display Bing Trace ID if it isn't blocked by CORS. var traceid = this.getResponseHeader("BingAPIs-TraceId"); if (traceid) errmsg.push("\nTrace ID " + traceid); // Display the error message. renderErrorMessage(errmsg.join("\n")); } } ``` > [!IMPORTANT] > Una solicitud HTTP correcta *no* significa que la búsqueda en sí se realizó correctamente. Si se produce un error en la operación de búsqueda, Bing Web Search API devuelve un código de estado HTTP distinto de 200 e incluye información de error en la respuesta JSON. Si la solicitud tenía limitación de frecuencia, la API devuelve una respuesta vacía. Gran parte del código de las dos funciones anteriores está dedicado al control de errores. Pueden producirse errores en las siguientes fases: | Fase | Errores posibles | Controlado por | |-------|--------------------|------------| | Creación de un objeto de solicitud | Dirección URL no válida | Bloqueo `try` / `catch` | | Hacer la solicitud | Errores de red, conexiones anuladas | Controladores de eventos `error` y `abort` | | Realizar la búsqueda | Solicitud no válida, JSON no válido, límites de frecuencia | Pruebas en el controlador de eventos `load` | Los errores se controlan con una llamada a `renderErrorMessage()`. Si la respuesta pasa todas las pruebas de error, se llama a `renderSearchResults()` para mostrar los resultados de la búsqueda. ## <a name="display-search-results"></a>Mostrar los resultados de la búsqueda Existen [requisitos de uso y visualización](useanddisplayrequirements.md) para los resultados devueltos por Bing Web Search API. Puesto que una respuesta puede incluir varios tipos de resultados, no es suficiente iterar por la colección `WebPages` de alto nivel. En su lugar, la aplicación de ejemplo usa `RankingResponse` para ordenar los resultados según la especificación. > [!NOTE] > Si solo desea un único tipo de resultado, use el parámetro de consulta `responseFilter` o considere el uso de uno de los otros puntos de conexión de Bing Search, como Bing Image Search. Cada respuesta tiene un objeto `RankingResponse` que puede incluir hasta tres colecciones: `pole`, `mainline` y `sidebar`. `pole`, si está presente, es el resultado de búsqueda más apropiado y debe mostrarse de manera destacada. `mainline` contiene la mayoría de los resultados de la búsqueda y se muestra inmediatamente después de `pole`. `sidebar` incluye los resultados de la búsqueda auxiliares. Si es posible, estos resultados se deben mostrar en la barra lateral. Si los límites de la pantalla hacen que una barra lateral sea poco práctica, estos resultados deben aparecer después de los resultados de `mainline`. Cada `RankingResponse` incluye una matriz `RankingItem` que especifica cómo se deben ordenar los resultados. Nuestra aplicación de ejemplo usa los parámetros `answerType` y `resultIndex` para identificar el resultado. > [!NOTE] > Hay otras formas de identificar y clasificar los resultados. Para más información, vea [Uso de la clasificación para mostrar resultados](rank-results.md). Veamos el código: ```javascript // Render the search results from the JSON response. function renderSearchResults(results) { // If spelling was corrected, update the search field. if (results.queryContext.alteredQuery) document.forms.bing.query.value = results.queryContext.alteredQuery; // Add Prev / Next links with result count. var pagingLinks = renderPagingLinks(results); showDiv("paging1", pagingLinks); showDiv("paging2", pagingLinks); // Render the results for each section. for (section in {pole: 0, mainline: 0, sidebar: 0}) { if (results.rankingResponse[section]) showDiv(section, renderResultsItems(section, results)); } } ``` La función `renderResultsItems()` realiza una iteración por los elementos de cada colección `RankingResponse`, asigna cada resultado de la clasificación a un resultado de la búsqueda mediante los valores `answerType` y `resultIndex`, y llama a la función de representación adecuada para generar el HTML. Si `resultIndex` no se especifica para un elemento, `renderResultsItems()` realiza una iteración por todos los resultados de ese tipo y llama a la función de representación en cada elemento. El HTML resultante se inserta en el elemento `<div>` correspondiente de `index.html`. ```javascript // Render search results from the RankingResponse object per rank response and // use and display requirements. function renderResultsItems(section, results) { var items = results.rankingResponse[section].items; var html = []; for (var i = 0; i < items.length; i++) { var item = items[i]; // Collection name has lowercase first letter while answerType has uppercase // e.g. `WebPages` RankingResult type is in the `webPages` top-level collection. var type = item.answerType[0].toLowerCase() + item.answerType.slice(1); if (type in results && type in searchItemRenderers) { var render = searchItemRenderers[type]; // This ranking item refers to ONE result of the specified type. if ("resultIndex" in item) { html.push(render(results[type].value[item.resultIndex], section)); // This ranking item refers to ALL results of the specified type. } else { var len = results[type].value.length; for (var j = 0; j < len; j++) { html.push(render(results[type].value[j], section, j, len)); } } } } return html.join("\n\n"); } ``` ## <a name="review-renderer-functions"></a>Revisión de las funciones de representador En nuestra aplicación de ejemplo, el objeto `searchItemRenderers` incluye funciones que generan código HTML para cada tipo de resultado de la búsqueda. ```javascript // Render functions for each result type. searchItemRenderers = { webPages: function(item) { ... }, news: function(item) { ... }, images: function(item, section, index, count) { ... }, videos: function(item, section, index, count) { ... }, relatedSearches: function(item, section, index, count) { ... } } ``` > [!IMPORTANT] > La aplicación de ejemplo tiene representadores para páginas web, noticias, imágenes, vídeos y búsquedas relacionadas. La aplicación necesitará representadores para cualquier tipo de resultados que puede recibir, lo que podría incluir cálculos, sugerencias de ortografía, entidades, zonas horarias y definiciones. Algunas de las funciones de representación solo aceptan el parámetro `item`. Otros aceptan parámetros adicionales, que se pueden usar para representar elementos de forma diferente según el contexto. Un representador que no usa esta información no necesita aceptar estos parámetros. Los argumentos del contexto son: | Parámetro | DESCRIPCIÓN | |------------|-------------| | `section` | La sección de resultados (`pole`, `mainline`, o `sidebar`) en que aparece el elemento. | | `index`<br>`count` | Disponible cuando el elemento `RankingResponse` especifica que se deben mostrar todos los resultados de una colección determinada; en caso contrario, `undefined`. El índice del elemento en su colección y el número total de elementos de dicha colección. Puede usar esta información para numerar los resultados, generar HTML diferente para el primer o el último resultado y así sucesivamente. | En la aplicación de ejemplo, los representadores `images` y `relatedSearches` usan los argumentos de contexto para personalizar el HTML generado. Observemos más de cerca el representador `images`: ```javascript searchItemRenderers = { // Render image result with thumbnail. images: function(item, section, index, count) { var height = 60; var width = Math.round(height * item.thumbnail.width / item.thumbnail.height); var html = []; if (section === "sidebar") { if (index) html.push("<br>"); } else { if (!index) html.push("<p class='images'>"); } html.push("<a href='" + item.hostPageUrl + "'>"); var title = escape(item.name) + "\n" + getHost(item.hostPageDisplayUrl); html.push("<img src='"+ item.thumbnailUrl + "&h=" + height + "&w=" + width + "' height=" + height + " width=" + width + " title='" + title + "' alt='" + title + "'>"); html.push("</a>"); return html.join(""); }, // Other renderers are omitted from this sample... } ``` El representador de imágenes: * Calcula el tamaño de la miniatura de la imagen (el ancho varía, mientras que la altura se fija en 60 píxeles). * Inserta el código HTML que precede al resultado de la imagen en función del contexto. * Compila la etiqueta `<a>` HTML vinculada a la página que contiene la imagen. * Crea la etiqueta HTML `<img>` para mostrar la miniatura de la imagen. El representador de imágenes utiliza las variables `section` y `index` para mostrar los resultados de forma diferente en función del lugar en que aparezcan. Se inserta un salto de línea (etiqueta `<br>`) entre los resultados de la imagen de la barra lateral, con el fin de que la barra lateral muestre una columna de imágenes. En otras secciones, el primer resultado de la imagen `(index === 0)` va precedido por la etiqueta `<p>`. El tamaño de las miniaturas se usa tanto en la etiqueta `<img>` como en los campos `h` y `w` en la dirección URL de la miniatura. Los atributos `title` y `alt` (una descripción textual de la imagen) se construyen a partir de nombre de la imagen y el nombre de host de la dirección URL. Este es un ejemplo de cómo las imágenes se muestran en la aplicación de ejemplo: ![[Resultados de imágenes de Bing]](media/cognitive-services-bing-web-api/web-search-spa-images.png) ## <a name="persist-the-client-id"></a>Conservación del identificador de cliente Las respuestas de Bing Search API pueden incluir un encabezado `X-MSEdge-ClientID` que debe volver a enviarse a la API con cada solicitud sucesiva. Si su aplicación usa más de una instancia de Bing Search APIs, asegúrese de que se envía el mismo identificador de cliente con cada solicitud en los servicios. Proporcionar el encabezado `X-MSEdge-ClientID` permite a las API de Bing asociar las búsquedas de un usuario. En primer lugar, permite al motor de búsqueda de Bing aplicar un contexto pasado a las búsquedas, con el fin de encontrar los resultados que más satisfagan a la solicitud. Si un usuario ha buscado previamente términos relacionados con la navegación, por ejemplo, una búsqueda posterior de "nudos" podría devolver información acerca de los nudos que se usan en la navegación de forma preferente. En segundo lugar, Bing puede seleccionar aleatoriamente usuarios para disfrutar de nuevas características antes de que estén disponibles públicamente. Especificar el mismo identificador de cliente en todas las solicitudes garantiza que los usuarios elegidos para ver una característica siempre la verán. Sin el identificador de cliente, el usuario puede ver una característica aparecer y desaparecer, de forma aparentemente aleatoria, en los resultados de búsqueda. Las directivas de seguridad del explorador, como el uso compartido de recursos entre orígenes (CORS), pueden evitar que la aplicación de ejemplo acceda al encabezado `X-MSEdge-ClientID`. Esta limitación tiene lugar cuando la respuesta a la búsqueda tiene un origen distinto al de la página que la solicitó. En un entorno de producción, debería abordar esta directiva mediante el hospedaje de un script de lado servidor que realice la llamada API en el mismo dominio que la página web. Como el script tiene el mismo origen que la página web, el encabezado `X-MSEdge-ClientID` está disponible para JavaScript. > [!NOTE] > En una aplicación web de producción, debe realizar la solicitud del lado servidor de todos modos. En caso contrario, es preciso incluir la clave de suscripción de Bing Search API en la página web, donde está disponible para cualquiera que vea el origen. Se le facturará todo el uso bajo su clave de suscripción a API, incluso las solicitudes que realicen partes no autorizadas, por lo que es importante no exponer su clave. Para fines de desarrollo, puede realizar la solicitud a través de un proxy CORS. La respuesta de un proxy de este tipo tiene un encabezado `Access-Control-Expose-Headers` que agrega los encabezados de respuesta a listas blancas y hace que estén disponibles para JavaScript. Es fácil instalar un proxy CORS para permitir que nuestra aplicación de ejemplo acceda al encabezado de identificador de cliente. Ejecute este comando: ```console npm install -g cors-proxy-server ``` A continuación, cambie el punto de conexión de Bing Web Search de `script.js` a: ```javascript http://localhost:9090/https://api.cognitive.microsoft.com/bing/v7.0/search ``` Inicie el proxy CORS con este comando: ```console cors-proxy-server ``` Deje la ventana de comandos abierta mientras utiliza la aplicación de ejemplo; si cierra la ventana, el proxy se detiene. En la sección de encabezados HTTP ampliable debajo de los resultados de la búsqueda, el encabezado `X-MSEdge-ClientID` debe estar visible. Compruebe que sea el mismo para cada solicitud. ## <a name="next-steps"></a>Pasos siguientes > [!div class="nextstepaction"] > [Referencia de Bing Web Search API v7](//docs.microsoft.com/rest/api/cognitiveservices/bing-web-api-v7-reference)
Python
UTF-8
8,327
2.765625
3
[]
no_license
''' This module to "pretty print" the results ------------------------------------------------------------------------------- Coded by Md. Iftekhar Tanveer (itanveer@cs.rochester.edu) Rochester Human-Computer Interaction (ROCHCI) University of Rochester ------------------------------------------------------------------------------- ''' from argparse import ArgumentParser import scipy.io as sio import numpy as np import matplotlib.pyplot as plt import math def plotLcurve(args): LplotDat = [] for afile in args.Files: if afile.lower().endswith('.mat'): allDat = sio.loadmat(afile) LplotDat.append(np.concatenate((allDat['L0'],\ allDat['reconError'],\ allDat['Beta'],allDat['cost']),axis=1)) LplotDat = np.concatenate(LplotDat,axis=0) plt.scatter(LplotDat[:,0],LplotDat[:,1]) ax=plt.gca() LplotDat = np.concatenate(LplotDat,axis=0) plt.scatter(LplotDat[:,0],LplotDat[:,1]) ax=plt.gca() for idx in xrange(len(LplotDat)): ax.annotate('Beta='+str(LplotDat[idx,2])+'\n'+\ '{:0.2e}'.format(LplotDat[idx,3])\ ,(LplotDat[idx,0],LplotDat[idx,1]+\ np.mean(LplotDat[:,1])/2*np.random.rand())) plt.xlabel('L0 norm of alpha') plt.ylabel('Reconstruction Error') plt.show() def buildArg(): pars = ArgumentParser(description="Program to 'pretty print' the results.\ It can also plot L curve.") pars.add_argument('Files',nargs='+',help='List of the (.mat) files from\ which the results are to read') pars.add_argument('--pprint',nargs='+',\ choices=['D','M','K','Beta','reconError','cost','SNR','L0'],\ help='Print the specified parameters from the files in a pretty format') pars.add_argument('--hi',nargs='?',\ choices=['D','M','K','Beta','reconError','cost','SNR','L0'],\ help='Specify a parameter name.\ The program returns names of all the files that contain the highest\ value of this parameter') pars.add_argument('--lo',nargs='?',\ choices=['D','M','K','Beta','reconError','cost','SNR','L0'],\ help='Specify a parameter name.\ The program returns names of all the files that contain the lowest\ value of this parameter') pars.add_argument('--nhi',nargs='?',\ choices=['D','M','K','Beta','reconError','cost','SNR','L0'],\ help='Specify a parameter name.\ The program returns names of all the files that does not \ contain the highest\ value of this parameter') pars.add_argument('--nlo',nargs='?',\ choices=['D','M','K','Beta','reconError','cost','SNR','L0'],\ help='Specify a parameter name.\ The program returns names of all the files that does not\ contain the lowest\ values of this parameter') pars.add_argument('--Lcurve',action='store_true',help='Command to\ draw an L curve') pars.add_argument('--showresults',action='store_true',help='Command to\ plot the patterns (psi) and corresponding activation sequences (alpha).\ If multiple files are given, it chooses one with minimum L0*exp(cost).') return pars # def showresults(args): # import skelplot_mayavi as splt # for idx,afile in enumerate(args.Files): # if afile.lower().endswith('.mat'): # allData = sio.loadmat(afile) # L0 = allData['L0'] # cost = allData['cost'] # mult = L0*math.exp(cost) # if idx==0: # lowmult = mult # bestFile = afile # elif mult<lowmult: # lowmult = mult # bestFile = afile # allData = sio.loadmat(bestFile) # # Print nonzero component indices # sumAlpha = np.sum(allData['alpha_recon'],axis=0) # validIdx = np.nonzero(sumAlpha) # print 'Available nonzero components are:' # for ind in validIdx: # print ind, # print # component = input('which component do you want to see?') # mult = input('please enter a multiplier:') # psi = mult*allData['psi_comp'][:,:,component].dot(allData['princmp'].T)\ # +allData['xmean'] # splt.animateSkeleton(psi) # plt.clf() # plt.plot(allData['alpha_recon'][:,component]) # plt.xlabel('frame') # plt.ylabel('alpha') # plt.show() def showresults(args): import skelplot_mayavi as splt for idx,afile in enumerate(args.Files): if afile.lower().endswith('.mat'): allData = sio.loadmat(afile) L0 = allData['L0'] cost = allData['cost'] mult = L0*math.exp(cost) if idx==0: lowmult = mult bestFile = afile elif mult<lowmult: lowmult = mult bestFile = afile allData = sio.loadmat(bestFile) # Print nonzero component indices # sumAlpha = np.sum(allData['alpha_recon'],axis=0) # validIdx = np.nonzero(sumAlpha) # print 'Available nonzero components are:' # for ind in validIdx: # print ind, # print # component = input('which component do you want to see?') # mult = input('please enter a multiplier:') X,Y,Z = np.shape(allData['psi_recon']) for x in range (0,Z): psi = 4*allData['psi_recon'][:,:,x] splt.animateSkeleton(psi) # plt.clf() # plt.plot(allData['alpha_recon'][:,component]) # plt.xlabel('frame') # plt.ylabel('alpha') # plt.show() def printparams(args): filelen = max([len(afile) for afile in args.Files]) # Build Template template = '{0:'+str(filelen)+'} | ' for cnt,par in enumerate(args.pprint): template=template+'{'+str(cnt+1)+':'+str(max(len(par),5))+'} | ' template = template[:-3] # Print Header header=template.format(*(['FILENAME']+[item for item in args.pprint])) print header print '='*len(header) # Print the data for afile in args.Files: if afile.lower().endswith('.mat'): allData = sio.loadmat(afile) paramdat = ['{:0.2f}'.format(float(allData[par][0][0]))\ for par in args.pprint] print template.format(*([afile]+paramdat)) def filtfile(args): if args.hi or args.nhi: # Scan all the highest indices for idx,afile in enumerate(args.Files): if afile.lower().endswith('.mat'): curval = sio.loadmat(afile)[args.hi if \ args.hi else args.nhi][0][0] if idx == 0: hiIdx = [idx] curmax = curval else: if curval > curmax: hiIdx = [idx] curmax = curval elif curval == curmax: hiIdx = hiIdx + [idx] for idx,afile in enumerate(args.Files): if afile.lower().endswith('.mat'): if args.hi and idx in hiIdx: print afile elif args.nhi and not idx in hiIdx: print afile elif args.lo or args.nlo: # Scan all the lowest indices for idx,afile in enumerate(args.Files): if afile.lower().endswith('.mat'): curval = sio.loadmat(afile)[args.lo \ if args.lo else args.nlo][0][0] if idx == 0: loIdx = [idx] curlo = curval else: if curval < curlo: loIdx = [idx] curlo = curval elif curval == curlo: loIdx = loIdx + [idx] for idx,afile in enumerate(args.Files): if afile.lower().endswith('.mat'): if args.lo and idx in loIdx: print afile elif args.nlo and not idx in loIdx: print afile def main(): parser = buildArg() args = parser.parse_args() if not args.Files: return if args.pprint: printparams(args) if args.hi or args.lo or args.nhi or args.nlo: filtfile(args) if args.Lcurve: plotLcurve(args) if args.showresults: showresults(args) if __name__ == '__main__': main()
JavaScript
UTF-8
1,930
4.4375
4
[]
no_license
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ /**************************************************************************** * BRUTE FORCED ATTEMPT, but a good approach if the input linked list is not sorted */ const example = [1,1,2,3,3] var deleteDuplicates = function(head) { let linkedToArr = [] let currentHead = head // looping through the linked list to convert it into an array while(currentHead !== null){ linkedToArr.push(currentHead.value) currentHead = currentHead.next } let filteredArr = [... new Set(linkedToArr)].sort() // turn array into a linked list return filteredArr.reduceRight((next, value) => ({value, next}), null); } /** * EXAMPLE OF TURNING AN ARRAY INTO A LINKEDLIST IN JAVASCRIPT * { value: 3, next: { value: 1, next: { value: 2, next: [Object] } } } * */ function linkedList(arr){ return arr.reduceRight((next, value) => ({value, next}), null); } let exampleLinkedList = linkedList(example) // console.log(exampleLinkedList); /** * TESTING THE FUNCTION */ // console.log(deleteDuplicates(exampleLinkedList)) /******************************************************************************* * SECOND TRY */ var deleteDuplicates2 = function(head) { let current = head while(current && current.next){ // since the linked list is sorted, we can check if the current value is the same a the next value, // if they ar ethe same replace current.next oject with current.next.next if(current.val == current.next.val){ current.next = current.next.next } else { current = current.next } } return head } console.log(deleteDuplicates2(exampleLinkedList))
JavaScript
UTF-8
5,187
2.65625
3
[]
no_license
import axios from 'axios' import React, { useEffect, useState } from 'react' import './App.css' //Função de listar usuários na página inicial export default function List(){ let [usuarios, setUsuarios] = useState([]) let [showModal, setShowModal] = useState(false) let [showTransacao, setShowTransacao] = useState(false) let [usuarioSelecionado, setUsuarioSelecionado] = useState({}) let [pagamento, setPagamento] = useState('') let [selecionaCartao, setSelecionaCartao] = useState('') let [transacao, setTransacao] = useState('') let cards = [ // valid card { card_number: '1111111111111111', cvv: 789, expiry_date: '01/18', }, // invalid card { card_number: '4111111111111234', cvv: 123, expiry_date: '01/20', } ]; {/*Pegando dados dos usuários na API*/} useEffect(() =>{ axios.get('https://www.mocky.io/v2/5d531c4f2e0000620081ddce', { }).then((resp) => { setUsuarios(resp.data) }) }, []) let mostraModal = (u) => { setShowModal(true) setUsuarioSelecionado(u) } const resetForm = () => { setPagamento('') setSelecionaCartao('') setShowTransacao(false) } {/*Envio da transação*/} const enviar= (evt) => { evt.preventDefault(evt) resetForm() const dadosTransacao = { "card_number": cards[selecionaCartao].card_number, "cvv": cards[selecionaCartao]?.cvv, "expiry_date": cards[selecionaCartao]?.expiry_date, "destination_user_id": usuarioSelecionado.id, "value": pagamento } {axios.post("https://run.mocky.io/v3/533cd5d7-63d3-4488-bf8d-4bb8c751c989", { body: dadosTransacao }).then((resp)=> { // console.log(resp.data) if (resp.data.status === "Aprovada") { setTransacao("O pagamento foi concluído com sucesso!") } else { setTransacao("O pagamento NÂO foi concluído com sucesso!") } setShowTransacao(true) }) }} return ( <> <div> {/*Backdrop*/} <div className="backdrop" style={{display : (showModal ? 'block' : 'none')}} onClick={() => setShowModal(false)}> </div> <div className="backdrop" style={{display : (showTransacao ? 'block' : 'none')}} onClick={() => setShowTransacao(false)}> </div> {/*Modal de pagamento*/} <div className="modalPagamento" style={{display : (showModal ? 'block' : 'none')}}> <div className="titulo"> <div className="cabecalho"> Pagamento para <span style={{color:'yellow'}}>{usuarioSelecionado.name}</span> </div> </div> <form className="selectUsuario" onSubmit={enviar}> <input className="valorTransf" type={"number"} placeholder={"R$ 0,00"} value={pagamento} onChange={ e => setPagamento(e.target.value)}/> <select className="selecionaCartao" required value={selecionaCartao} onChange= {e => setSelecionaCartao(e.target.value)}> <option>Selecione um cartão</option> {cards.map((card, i) => { return ( <option key={'opcaoCartao' + i} value={i}>Cartão com final {card.card_number.substr(-4)} </option>) })} </select> <button className="botaoEnviar" onClick={()=> setShowModal(false)}>Pagar</button> </form> </div> {/*Modal de Resultado*/} <div className="modalResult" style={{display : (showTransacao ? 'block' : 'none')}}> <div className="titulo"> <span className="cabecalho">Recibo de pagamento</span> </div> <div> <span className="resultTransacao">{transacao}</span> </div> </div> {/*Lista de usuários*/} <ul style={{margin:'0', padding:'0'}}> {usuarios.map((u, index) => { return ( <li key={'user-'+ index}> <div className={'users'}> <img src={u.img}></img> <div className={'dados'}> <div id={'uname'}> {u.name} </div> <div className={'dadosUsuario'}> ID: {u.id} - Username: {u.username} </div> </div> </div> <button data-index={index} onClick={()=> mostraModal(u)}>Pagar</button> </li> ) })} </ul> </div> </> ) }
C#
UTF-8
1,369
3.390625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Task_1 { class Program { public static bool checkPrime(string name) { int cnt = 0; StreamReader sr = new StreamReader(name); string str = sr.ReadLine(); string[] arr = str.Split(' '); int x = int.Parse(arr[0]); int y = int.Parse(arr[1]); for(int i=2;i<=Math.Min(x,y);i++) { if (x % i == 0 && y % i == 0) cnt++; } if (cnt == 0) return true; else return false; } static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\qalqa\Documents\Visual Studio 2015\Projects\Final_KalkamanAlisher\Task 1\Task1files"); FileInfo[] file = dir.GetFiles(); for (int i = 0; i < file.Length; i++) { if (checkPrime(file[i].FullName)) Console.WriteLine(file[i].Name + ": " + "yes"); else Console.WriteLine(file[i].Name + ": " + "no"); } Console.ReadKey(); } } }
Java
UTF-8
723
2.140625
2
[ "MIT" ]
permissive
package com.rjs.mymovies.server.repos; import com.rjs.mymovies.server.model.User; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * <p/> * Created with IntelliJ IDEA.<br> * User: Randy Strobel<br> * Date: 2017-07-06<br> * Time: 12:58<br> */ public interface UserRepository extends BaseRepository<User>, JpaSpecificationExecutor<User> { User findByUsername(String username); User findByUsernameAndPassword(String username, String password); @Query("SELECT u.password FROM User u WHERE u.username = :username") String getPasswordByUsername(@Param("username") String username); }
PHP
UTF-8
1,435
2.546875
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php /** * Created by PhpStorm. * User: angelika * Date: 10.02.19 * Time: 12:20 */ namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\File; /** * @ORM\Entity * @ORM\Table(name="progress") * Class Progress * @package AppBundle\Entity */ class Progress { /** * @ORM\Id //первичный ключ * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") //автоинкремент */ private $id; /** * @ORM\Column(type="text", nullable=false) */ private $image; /** * @var File */ private $file; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set image * * @param string $image * * @return Progress */ public function setImage($image) { $this->image = $image; return $this; } /** * Get image * * @return string */ public function getImage() { return $this->image; } /** * Set file * * @param File $file * * @return Progress */ public function setFile($file) { $this->file = $file; return $this; } /** * Get file * * @return File */ public function getFile() { return $this->file; } }
Python
UTF-8
1,737
2.625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 ### Modules # custom import kerningMisc reload(kerningMisc) from kerningMisc import MARGIN_VER, MARGIN_COL from ..ui import userInterfaceValues reload(userInterfaceValues) from ..ui.userInterfaceValues import vanillaControlsSize # standard from vanilla import Group, TextBox, SquareButton, SquareButton ### Classes class FactorController(Group): def __init__(self, posSize, canvasScalingFactor, callback): super(FactorController, self).__init__(posSize) self.canvasScalingFactor = canvasScalingFactor self.callback = callback jumpingX = 0 self.caption = TextBox((jumpingX, 0, 30, vanillaControlsSize['TextBoxRegularHeight']), '{:.1f}'.format(self.canvasScalingFactor)) jumpingX += 30+MARGIN_COL self.upButton = SquareButton((jumpingX, 0, 16, 16), '+', sizeStyle='small', callback=self.upButtonCallback) jumpingX += 16+MARGIN_COL self.dwButton = SquareButton((jumpingX, 0, 16, 16), '-', sizeStyle='small', callback=self.dwButtonCallback) def getScalingFactor(self): return self.canvasScalingFactor def upButtonCallback(self, sender): self.canvasScalingFactor += .1 self.caption.set('{:.1f}'.format(self.canvasScalingFactor)) self.callback(self) def dwButtonCallback(self, sender): self.canvasScalingFactor -= .1 self.caption.set('{:.1f}'.format(self.canvasScalingFactor)) self.callback(self)
C#
UTF-8
1,969
3.578125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task1 { public abstract class Figure { public abstract void Draw(); } class Program { // Напишите заготовку для векторного графического редактора. // Полная версия редактора должна позволять создавать и выводить на экран // такие фигуры как: Линия, Окружность, Прямоугольник, Кольцо. // Заготовка, для упрощения, должна представлять собой консольное приложение с функционалом: //⦁ Создать фигуру выбранного типа по произвольным координатам. //⦁ Фигуры должны создаваться в общей коллекции(массиве) //⦁ Вывести фигуры на экран // (для каждой фигуры вывести на консоль её тип и значения параметров реализовать в методе Draw) // с использованием перегрузки метода Draw static void Main(string[] args) { try { Figure[] fig = new Figure[4]; fig[0] = new Rectangle(0, 1, 5, 4); fig[1] = new Round(0, 0, 4); fig[2] = new Line(1, 5, 4, 5); fig[3] = new Ring(10, 5, 2, 5); foreach (Figure figure in fig) { figure.Draw(); } } catch (Exception e) { Console.WriteLine("Ошибка: " + e.Message); } } } }
Java
UTF-8
207
2.390625
2
[]
no_license
public abstract class Processor implements Component{ @Override public String name() { return "Processor"; } public abstract float price() ; public abstract String speed(); }
JavaScript
UTF-8
279
3.453125
3
[]
no_license
function nextDay(year, month, day) { let date = new Date(year, month - 1, day); let tomorrow = new Date(year, month - 1, date.getDate() + 1); console.log( `${tomorrow.getFullYear()}-${tomorrow.getMonth() + 1}-${tomorrow.getDate()}` ); } nextDay(2016, 9, 30);
Markdown
UTF-8
839
2.515625
3
[]
no_license
# Myleholic (iOS) An iOS-App that let you know how far you've been on the move. ### Features: * Any location can be easily found * Routes are calculated based on previous travellings * Geographical distances are summed up cumulatively * Routes and places can be clearly seen on the map ## Dependencies * [RealmSwift](https://realm.io/docs/swift/latest/) – an alternative database to SQLite and Core Data * [Eureka](https://eurekacommunity.github.io/) – elegant iOS form builder in Swift * [SwiftIconFont](https://github.com/0x73/SwiftIconFont) – vector icon fonts for iOS ## Requirements * iOS 11.0+ * XCode 9+ * Swift 4 ## Examples <table> <tr> <th> <img src="Example/Media/example-filter-interval.gif"/> </th> <th> <img src="Example/Media/example-nested-journies.gif"/> </th> </tr> </table>
Markdown
UTF-8
1,227
2.734375
3
[]
no_license
# PEKING UNIVERSITY [程序设计与算法](https://www.coursera.org/specializations/biancheng-suanfa) 专项课程学习记录 > ![](https://github.com/GrizzlyHills/PROGRAMMING-AND-ALGORITHMS/blob/master/IMG/pku_logo.png?raw=true) ## 专项课程介绍 - 本专项课程旨在系统培养你的程序设计与编写能力。系列课程从计算机的基础知识讲起,无论你来自任何学科和行业背景,都能快速理解;同时我们又系统性地介绍了C程序设计,C++程序设计,算法基础,数据结构与算法相关的内容,各门课之间联系紧密,循序渐进,能够帮你奠定坚实的程序开发基础;课程全部配套在线编程测试,将有效地训练和提升你编写程序的实际动手能力。并通过结业实践项目为你提供应用程序设计解决复杂现实问题的锻炼,从而积累实际开发的经验。因此,我们希望本专项课程能够帮助你完成从仅了解基本的计算机知识到能够利用高质量的程序解决实际问题的转变。 ## 课程 1. 计算导论与C语言基础 2. C程序设计进阶 3. C++程序设计 4. 算法基础 5. 数据结构基础 6. 高级数据结构与算法 7. 程序开发项目实践
PHP
UTF-8
1,165
3.75
4
[]
no_license
<?php namespace App; /** * Permet de calculer le poids d'un nombre * * Class weightOfNumbers * @author Guillaume RICHARD <g.jf.richard@gmail.com> * @package App */ class weightOfNumbers { /** * weightOfNumbers constructor. */ public function __construct(){} /** * calculer le poids d'un nombre de 3 chiffres. * donne les valeurs résolvant le problème, à partir d'un tableau de donnée * * @param array $numbers * @return array */ public function weight(array $numbers) { $data = []; for ($i = 100; $i < 1000; $i++) { if (strpos($i, '0')) { continue; } [$centaine, $dizaine, $unite] = str_split($i); $weight = $numbers[$centaine] + $numbers[$dizaine] + $numbers[$unite]; if ($i === $weight) { $data[] = [ "poids à trouver" => $weight, "clé du tableau" => "$centaine + $dizaine + $unite", "poids des clés" => "$numbers[$centaine] + $numbers[$dizaine] + $numbers[$unite]" ]; } } return $data; } }
Java
UTF-8
674
3.359375
3
[]
no_license
/** * @Author: zl * @Date: 2019/5/23 11:20 * @Description 数组实现出栈入栈 */ public class Stack { private int a[]; private int size; Stack(int size){ a=new int[size]; } private void insert(int data){ a[size]=data; size++; } private void delete(){ if(size>0){ size--; } } public static void main(String[] args) { Stack stack=new Stack(10); stack.insert(1); stack.insert(2); stack.insert(2); stack.insert(3); stack.delete(); for(int i=0;i<stack.size;i++){ System.out.println(stack.a[i]); } } }
C
UTF-8
7,303
2.734375
3
[ "MIT" ]
permissive
/* * usb_helper.c * * Created: 12/27/2017 7:34:07 AM * Author: pvallone */ #include "usb_helper.h" void sam_display_bmp(int x1, int y1, char *bitmap, int page){ struct bitmap_t bmp; bmp.name = bitmap; int8_t header_buff[60]; unsigned int byte_read; volatile uint8_t lun = LUN_ID_USB; int position = 0; uint8_t padding = 0; bool flip = false; /* Mount drive */ memset(&fs, 0, sizeof(FATFS)); FRESULT res = f_mount(lun, &fs); if (FR_INVALID_DRIVE == res) { printf("Mount Failed!\n\r"); return; } printf("Loading \t%s\n\r", (char *)bitmap); res = f_open(&file_object,(char *)bitmap, FA_OPEN_EXISTING | FA_READ); if (res == FR_NOT_READY || res != FR_OK) { /* LUN not ready or LUN test error */ printf("File open failed!\n\r"); f_close(&file_object); return; } // Read the bmp header res = f_read(&file_object, header_buff, sizeof header_buff, &byte_read); if(res != FR_OK){ print_fs_result(res); return; } bmp.signiture = (header_buff[1] << 8) | header_buff[0]; if(bmp.signiture != 0x4D42){ printf("Invalid File. Not a Bitmap!\n\r"); return; // not a bmp } uint16_t height = (header_buff[25] << 24) | (header_buff[24] << 16) | (header_buff[23] << 8) | header_buff[22]; // will tell us if negative of positive memcpy(&bmp.offset, &header_buff[6], sizeof(bmp.offset)); memcpy(&bmp.height, &header_buff[22], sizeof(bmp.height)); memcpy(&bmp.width, &header_buff[18], sizeof(bmp.width)); memcpy(&bmp.offset, &header_buff[10], sizeof(bmp.offset)); memcpy(&bmp.numberOfPixels, &header_buff[28], sizeof(bmp.numberOfPixels)); memcpy(&bmp.compression, &header_buff[30], sizeof(bmp.compression)); memcpy(&bmp.imageSize, &header_buff[34], sizeof(bmp.imageSize)); bmp.rowSize = ((bmp.width * 3 + 3) & ~3); if(height > -1){ flip = false; position = f_size(&file_object) - bmp.rowSize;// calculate last row to start at (bottom-up) if height is positive } else { flip = true; position = bmp.offset; // read from top down } //print_bitmap_header(&bmp); if(tft_conf.orient == LANDSCAPE){ swap(uint32_t, bmp.width, bmp.height); } uint8_t val = (bmp.height / bmp.numberOfPixels) % 4; // swaps in Landscape if(val != 0){ padding = 4 - val; } sam_clearCs(); sam_setXY(x1, y1 + page,(bmp.width + x1) - 1, (bmp.height + y1 + page)-1); // printf("page: %d Calcs: x1: %d y1:%d x2: %ld y2:%ld\n", page, x1, y1 + page,(bmp.width + x1) - 1, (bmp.height + y1 + page)-1); res = f_lseek(&file_object, position); // start at position - set by if height is negative or positive uint8_t row_buff[bmp.rowSize]; // only read 1 row at a time for(uint32_t row = 0; row < (bmp.imageSize / bmp.rowSize); row++){ // read 1 row at a time res = f_read(&file_object, row_buff, sizeof row_buff, &byte_read); // read 1 row if(res != FR_OK){ print_fs_result(res); return; } if(flip){ position = position + bmp.rowSize; // calculate next position on disk to read }else{ position = position - bmp.rowSize; // calculate next position on disk to read } res = f_lseek(&file_object, position); // set next position if(res != FR_OK){ print_fs_result(res); return; } // read the buffer and send to TFT if(!flip){ for (uint16_t x = 0; x < (sizeof row_buff)-padding ; x += 3) { sam_writeData(((row_buff[x + 2] & 248) | row_buff[x + 1] >> 5), ((row_buff[x + 1] & 28) << 3 | row_buff[x] >> 3)); } } else { for (uint16_t x = (sizeof row_buff)-padding; x > 0 ; x -= 3) { sam_writeData(((row_buff[x + 2] & 248) | row_buff[x + 1] >> 5), ((row_buff[x + 1] & 28) << 3 | row_buff[x] >> 3)); } } } // end while sam_setCs(); sam_clrXY(); f_close(&file_object); print_bitmap_header(&bmp); } void sam_display_raw(int x1, int y1, int width, int height, char *bitmap, int page){ volatile uint8_t lun = LUN_ID_USB; unsigned int byte_read; /* Mount drive */ memset(&fs, 0, sizeof(FATFS)); FRESULT res = f_mount(lun, &fs); if (FR_INVALID_DRIVE == res) { printf("Mount Failed!\n\r"); return; } printf("Loading \t%s\n\r", (char *)bitmap); res = f_open(&file_object,(char *)bitmap, FA_OPEN_EXISTING | FA_READ); if (res == FR_NOT_READY || res != FR_OK) { /* LUN not ready or LUN test error */ printf("File open failed!\n\r"); f_close(&file_object); return; } if(tft_conf.orient == LANDSCAPE){ swap(uint32_t, width, height); } DWORD totalBytes = f_size(&file_object); sam_clearCs(); sam_setXY(x1, y1 + page,(width + x1) - 1, (height + y1 + page)-1); int bytesPerRow = totalBytes / height; uint8_t row_buff[bytesPerRow]; // only read 1 row at a time for(int row = 0; row < height; row++){ // read 1 row at a time res = f_read(&file_object, row_buff, sizeof row_buff, &byte_read); // read 1 row if(res != FR_OK){ print_fs_result(res); return; } res = f_lseek(&file_object, f_tell(&file_object)); // set next position if(res != FR_OK){ print_fs_result(res); return; } // read the buffer and send to TFT for (int x = 0; x < bytesPerRow ; x+=2) { sam_writeData(row_buff[x], row_buff[x + 1]); } } // end while sam_setCs(); sam_clrXY(); f_close(&file_object); } void print_fs_result(FRESULT res){ switch(res){ case FR_OK: /* (0) Succeeded */ printf("(0) Succeeded"); break; case FR_DISK_ERR: printf("(1) A hard error occurred in the low level disk I/O layer"); break; case FR_INT_ERR: printf("(2) Assertion failed"); break; case FR_NOT_READY: printf("(3) The physical drive cannot work"); break; case FR_NO_FILE: printf("(4) Could not find the file"); break; case FR_NO_PATH: printf("(5) Could not find the path"); break; case FR_INVALID_NAME: /* */ printf("(6) The path name format is invalid"); break; case FR_DENIED: printf("(7) Access denied due to prohibited access or directory full"); break; case FR_EXIST: printf("(8) Access denied due to prohibited access"); break; case FR_INVALID_OBJECT: printf("(9) The file/directory object is invalid"); break; case FR_WRITE_PROTECTED: printf("(10) The physical drive is write protected"); break; case FR_INVALID_DRIVE: printf("(11) The logical drive number is invalid"); break; case FR_NOT_ENABLED: printf("(12) The volume has no work area "); break; case FR_NO_FILESYSTEM: printf("(13) There is no valid FAT volume"); break; case FR_MKFS_ABORTED: printf("(14) The f_mkfs() aborted due to any parameter error"); break; case FR_TIMEOUT: printf("(15) Could not get a grant to access the volume within defined period"); break; case FR_LOCKED: printf("(16) The operation is rejected according to the file sharing policy"); break; case FR_NOT_ENOUGH_CORE: printf("(17) LFN working buffer could not be allocated"); break; case FR_TOO_MANY_OPEN_FILES: printf("(18) Number of open files > _FS_SHARE"); break; case FR_INVALID_PARAMETER: printf("(19) Given parameter is invalid"); break; default: printf("Unknown Error Code %d", res); break; } printf("\n\r"); }
Markdown
UTF-8
5,663
2.84375
3
[]
no_license
# Vefforritun 1, 2021: Verkefni 4, CSS #2 [Kynning í fyrirlestri](https://youtu.be/Nw7FkpJl-Xo). Setja skal upp viðmót fyrir Vefforritunarfréttir, fréttamiðil sem færir vefforriturum mikilvægar fréttir af faginu. Haldið verður áfram með verkefnið: * [Verkefni 5](https://github.com/vefforritun/vef1-2021-v5/) gerir vefinn skalanlegann og setur upp grid. * [Verkefni 6](https://github.com/vefforritun/vef1-2021-v6/) setur upp tæki og tól: Sass, Stylelint, og browser-sync. Verkefnið verður „refactorað“ til að nota þetta. ## Útlit Fyrirmynd að útliti er í `fyrirmynd/` möppu. Skjáskot er tekið í `1500px` breiðum Firefox vafra. ### HTML Gefið er grunn HTML þar sem búið er að velja merkingfræðileg element m.v. efnið. Vísað er í myndir innan úr efni, fyrir utan mynd sem á að vera bakvið auglýsingu og `clock.svg` sem skal birta við hliðina á dagstíma frétta. Gera má ráð fyrir að það **verði** að bæta við `class` attributes og auka elementum við lausn/sýnilausn til að geta náð fram útliti. ### Almennt Þar sem allt útlit skal útfæra í einni CSS skrá, skal huga að cascade og erfðum, þó er fullkomlega eðlilegt að endurtaka eigindi, en t.d. fyrir málsgreinar (`<p>`) þarf aðeins að taka fram einu sinni hvert margin þeirra er. Gefið er „reset“ þ.a. allt `margin` og `padding` frá vafra sé sett í `0`, einnig er `box-sizing: border-box` sett fyrir öll element. CSS skal vera án villna og **viðvarana** þegar keyrt í gegnum [CSS validator](https://jigsaw.w3.org/css-validator/). Allar síður skulu vera villulausar ef prófaðar með HTML validator. ### Gildi og stærðir * Heildar breidd efnis skal vera `1400px`, miðjað á skjánum * Grunnletur stærð skal vera `16px` þ.a. `1rem == 16px` * Allt bil í fyrirmynd er hálf, eitt, eða tvöfalt margfeldi af grunnletur stærð * Gildi fyrir liti eru gefin sem breytur settar í `:root` * Leturgerðir: * Fyrir meginmál: [Inter](https://fonts.google.com/specimen/Inter), Helvetica, Arial, sans-serif * Fyrir fyrirsagnir: [Playfair Display](https://fonts.google.com/specimen/Playfair+Display), Georgia, serif * Leturþyngdir (e. font weights): * Tengill í auglýsingu skal nota þyngd `700` * Aðalfyrirsögn skal nota þyngd `600` * Tenglar í flokkum skal nota þyngd `400` * Birting á dagstíma skal nota þyngd `300` * Almennt skal aðeins nota hlutfallslegar einingar í breiddir, nema nota þarf `px` gildi til að útfæra birtingu á dagstíma icon ### Takmarkanir Aðeins skal nota flexbox til að setja upp útlit, þ.e.a.s. **aðeins** `display: flex`. Ekki skal nota önnur gildi fyrir `display` eða `position` eigindi _nema_ til að setja upp texta yfir mynd í auglýsingu. Í sýnilausn er eftirfarandi notað: * `@font-face` til að færa inn leturgerðir og tengd eigindi til að eiga við leturgerðir * `src` * `font-display: swap` * `font-family` * `font-size` * `font-variation-settings` * `line-height` * `text-decoration` * CSS breytur, sjá gefnar breytur innan `:root` og `var()` fall * Flexbox eigindi, t.d. * `align-items` * `flex-direction` * `flex` * `justify-content` * `order` * Bakgrunnseigindi: * `background-color` * `background-image` * `background-position` * `background-repeat` * `background-size` * eða shorthand `background` * Box model eigindi * `margin` * `border` * `padding` * `width`, með hlutfallslegum einingum * `height`, til að fastsetja hæðir á myndum sem síðan nota `object-fit` * `max-width` Ekki þarf að huga að skalanleika (síðan þarf ekki að líta vel út í undir `1400px` skjá, athugið að þar sem hámarksbreidd er `1400px` mun efnið liggja alveg utan í vafraglugga í nákvæmlega `1400px`). ## Heimasvæði Setja skal síður upp á [heimasvæði ykkar hjá HÍ](https://uts.hi.is/node/155) undir möppu `.public_html/vefforritun/verkefni4` svo verkefnið verði aðgengilegt á `https://notendur.hi.is/<notendanafn>/vefforritun/verkefni4` þar sem `<notendnafn>` er notendanafnið þitt (t.d. `osk`). ## Mat * 15% – Snyrtilega uppsett og gilt CSS * 15% – Flexbox notað fyrir útlit og takmarkanir virtar * 30% – Nýjustu fréttir og mest lesið * 10% – Útlit fyrir auglýsingu * 30% – Flokkar, skipting og innihald ## Sett fyrir Verkefni sett fyrir í fyrirlestri mánudaginn 13. september 2021. ## Skil Skila skal í Canvas í seinasta lagi fyrir lok dags þriðjudaginn 21. september 2021. Skilaboð skulu innihalda: * slóð á verkefni * zip skjali með lausn Hver dagur eftir skil dregur verkefni niður um 10%, allt að 20% ef skilað fimmtudaginn 23. september 2021 en þá lokar fyrir skil. ## Einkunn Leyfilegt er að ræða, og vinna saman að verkefni en **skrifið ykkar eigin lausn**. Ef tvær eða fleiri lausnir eru mjög líkar þarf að færa rök fyrir því, annars munu allir hlutaðeigandi hugsanlega fá 0 fyrir verkefnið. Sett verða fyrir tíu minni verkefni þar sem átta bestu gilda 5% hvert, samtals 40% af lokaeinkunn. Sett verða fyrir tvö hópverkefni þar sem hvort um sig gildir 10%, samtals 20% af lokaeinkunn. ## Myndir Myndir frá [Unsplash](https://unsplash.com/): * [Max Duzij](https://unsplash.com/@max_duz) * [Emma Dau](https://unsplash.com/@daugirl) * [Mika Baumeister](https://unsplash.com/@mbaumi) * [Alex Kotliarskyi](https://unsplash.com/@frantic) * [Dzmitry Tselabionak](https://unsplash.com/@tsellobenok) * [LinkedIn Sales Solutions](https://unsplash.com/@linkedinsalesnavigator) * [Kyle Hanson](https://unsplash.com/@kyledarrenhanson) * [Mathew Schwartz](https://unsplash.com/@cadop) > Útgáfa 0.1
JavaScript
UTF-8
189
2.84375
3
[]
no_license
function vogalOuConsoante(letra){ var letra = letra.toLowerCase() if (letra== 'a'||letra== 'e'||letra== 'i'||letra== 'o'||letra== 'u'){ return "vogal"; }else { return"consoante"; } }
Python
UTF-8
727
4.15625
4
[]
no_license
#!/usr/bin/env python """ What is the sum of the digits of the number 2 ** 1000? """ def way_1(): # as we know, 2**1 = 0x10, 2**2 = 0x100, ... # so we can get the result of 2**1000 in binary without actually calculating. bin_sum = '1' + ''.join(['0']*1000) dec_sum = str(int(bin_sum, 2)) sum_of_digits = sum([int(i) for i in dec_sum]) print sum_of_digits def way_2(): # but Python calculates in Binary internally. # so just use 2 ** 1000. It's even faster! sum_in_str = str(2 ** 1000) sum_of_digits = sum([int(i) for i in sum_in_str]) print sum_of_digits import time t1 = time.time() way_1() t2 = time.time() print t2 - t1 t3 = time.time() way_2() t4 = time.time() print t4 - t3
Markdown
UTF-8
556
2.65625
3
[]
no_license
# Introduction In this project we will learn how to implement an APC Design Architecture (Application, Page, Control) in our Xamarin Forms application. # Getting Started The APC Architecture is based on the use of Styles which could be stored on the Application resources, Page resources or Control properties. We will group the styles by the functionality, so the best type is Explicit styles. If you want to learn more about Xamarin Forms styles: - [Xamarin forms styles](https://developer.xamarin.com/guides/xamarin-forms/user-interface/styles/)
JavaScript
UTF-8
5,766
2.953125
3
[]
no_license
let geometryInstance = null; let arMarker = null; //------------------基底クラス-------------------- class Geometry { constructor(){ } update(dt){ } createObject(){ } setMarkerObject(marker){ arMarker = marker; } static getInstance(objectName){ if(geometryInstance != null){ return geometryInstance; } if(objectName == 'rocket'){ geometryInstance = new Rocket(); }else if(objectName == 'earth'){ geometryInstance = new Earth(); }else{ geometryInstance = new Video(); } return geometryInstance; } } //------------------------------------------------- //-------------子クラス(Rocketクラス)------------ class Rocket extends Geometry{ createObject(){ var geo = new THREE.CubeGeometry(1, 1, 1); // cube ジオメトリ(サイズは 1x1x1) var mat = new THREE.MeshNormalMaterial({ // マテリアルの作成 transparent: true, // 透過 opacity: 0.8, // 不透明度 side: THREE.DoubleSide, // 内側も描く }); var rocketMesh; // json形式のモデルを読み込むローダ var loader = new THREE.JSONLoader(); // モデルを読み込む loader.load("./model/rocketX.json", function(geo, mat) { //mat = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture("./model/rocketX.png"), transparent: true, opacity: 0.5}); mat = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture("./model/rocketX.png")}); // メッシュ化 rocketMesh = new THREE.Mesh(geo, mat); // メッシュの名前(後でピッキングで使う) rocketMesh.name = "rocket"; // 初期サイズ(現物合わせ) rocketMesh.scale.set(2.0, 2.0, 2.0); // 初期位置(現物合わせ) rocketMesh.position.set(-2.0, 0.5, 0); // メッシュをマーカに追加 arMarker.add(rocketMesh); }); } } //------------------------------------------------- //-------------子クラス(Earthクラス)------------ class Earth extends Geometry{ createObject(){ this.meshEarth = new THREE.Mesh(); var loaderEarth = new THREE.TextureLoader(); var textureEarth = loaderEarth.load( './image/earth_tex.png'); var materialEarth = new THREE.MeshBasicMaterial({ map:textureEarth }); //var materialEarth = new THREE.MeshBasicMaterial({ map:textureEarth, transparent: true, opacity: 0.5}); var geometryEarth = new THREE.SphereGeometry(3.0,32.0,32.0); this.meshEarth = new THREE.Mesh( geometryEarth, materialEarth ); this.meshEarth.position.set(-2.0, 0.5, 0); arMarker.add(this.meshEarth); this.meshCloud = new THREE.Mesh(); var loaderCloud = new THREE.TextureLoader(); var textureCloud = loaderCloud.load( './image/cloud_tex.png'); var materialCloud = new THREE.MeshBasicMaterial({ map:textureCloud, transparent:true }); var geometryCloud = new THREE.SphereGeometry(3.1,32.0,32.0); this.meshCloud = new THREE.Mesh( geometryCloud, materialCloud ); this.meshCloud.position.set(-2.0, 0.5, 0); arMarker.add(this.meshCloud); this.meshMoon = new THREE.Mesh(); var loaderMoon = new THREE.TextureLoader(); var textureMoon = loaderMoon.load( './image/moon_tex.png'); var materialMoon = new THREE.MeshBasicMaterial({ map:textureMoon}); var geometryMoon = new THREE.SphereGeometry(1.0,32.0,32.0); var meshMoon = new THREE.Mesh( geometryMoon, materialMoon ); //this.sceneCenter = new THREE.Scene(); //this.sceneCenter.position.set(0, 0.5, 0); //this.sceneCenter.add(meshMoon); this.meshMoon.position.set(-2.0, 0, 2.0); //arMarker.add(this.sceneCenter); arMarker.add(this.meshMoon); } update(dt){ this.meshCloud.rotation.y += dt * 0.1; this.meshEarth.rotation.y += dt * 0.2; //this.sceneCenter.rotation.y += dt * 0.5; this.meshMoon.rotation.y += dt * 0.5; } } //------------------------------------------------- //-------------子クラス(Videoクラス)------------ class Video extends Geometry{ createObject(){ //video要素 this.video = document.createElement( 'video' ); this.video.loop = true; this.video.muted = true; this.video.src = './video/PexelsVideos.mp4'; this.video.setAttribute( 'muted', 'muted' ); this.video.play(); var videoImage = document.createElement('canvas'); videoImage.width = 1280; videoImage.height = 720; this.videoImageContext = videoImage.getContext('2d'); this.videoImageContext.fillStyle = '#000000'; this.videoImageContext.fillRect(0, 0, videoImage.width, videoImage.height); //生成したcanvasをtextureとしてTHREE.Textureオブジェクトを生成 this.videoTexture = new THREE.Texture(videoImage); this.videoTexture.minFilter = THREE.LinearFilter; this.videoTexture.magFilter = THREE.LinearFilter; //生成したvideo textureをmapに指定し、overdrawをtureにしてマテリアルを生成 var movieMaterial = new THREE.MeshBasicMaterial({map: this.videoTexture, overdraw: true, side:THREE.DoubleSide}); //var movieMaterial = new THREE.MeshBasicMaterial({color: 0xFF0000, transparent: true, opacity: 0.5}); var movieGeometry = new THREE.BoxGeometry(5.5,0.05,5.5); var movieScreen = new THREE.Mesh(movieGeometry, movieMaterial); movieScreen.name = "plane"; movieScreen.position.set(-2.0, 0.5, 0); arMarker.add(movieScreen); } update(dt){ if (this.video.readyState === this.video.HAVE_ENOUGH_DATA) { this.videoImageContext.drawImage(this.video, 0, 0); if (this.videoTexture) { this.videoTexture.needsUpdate = true; } } } } //-------------------------------------------------
Java
UTF-8
1,532
3.046875
3
[]
no_license
package app; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; public class Jmeter_WriteFile { /* The default encoding. */ private static final String DEFAULT_ENCODING = "UTF-8"; /* version. */ private static final String VERSION = "1.0.0.0"; private static final String COMMENT = "2018-02-02 13:39 胡义东 初始化"; public String getComment() { return COMMENT; } public String getVersion() { return VERSION; } public static void writeFile(String fileName, String content, String method) throws IOException { /* 写入文件类 */ File file = new File(fileName); /* 获取文件目录 */ File dir = file.getParentFile(); /* 如果目录不存在,创建目录 */ if (!dir.exists()) { dir.mkdirs(); } /* 如果文件不存在,创建文件 */ if (!file.exists()) { file.createNewFile(); } /* 定义默认方法为追加ture */ boolean methodB = true; /* 如果方法为"o",就为复写"overWrite" */ if (method.equals("o")) { methodB = false; } /* 新建缓存字符输出流 */ BufferedWriter writer = null; /* 将字符输出流的文件设为fileName,写入方法为methodB,编码设置为UTF-8 */ writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(fileName, methodB), DEFAULT_ENCODING)); /* 写入字符串加换行符 */ content = content + "\r\n"; /* 文件中写入字符串 */ writer.write(content); writer.close(); } }
JavaScript
UTF-8
430
2.625
3
[]
no_license
'use strict'; window.error = { showErrorMessage(msg) { let node = document.createElement(`div`); node.style = `z-index: 100; margin: 0 auto; text-align: center; background-color: red; color: white;`; node.style.position = `absolute`; node.style.left = 0; node.style.right = 0; node.style.fontSize = `30px`; node.textContent = msg; document.body.insertAdjacentElement(`afterbegin`, node); } };
PHP
UTF-8
3,529
2.53125
3
[]
no_license
<link rel="stylesheet" type="text/css" href="style.css"> <title>search</title> <form method="post" action=""> <div class="container"> <div class="input-group"> <label for="type"><b>type</b></label> <input type="text" placeholder="Enter type of the rooms" id="type" name="type" > <label for="price"><b>price</b></label> <input type="text" placeholder="Enter price" id="price" name="price" > <label for="location"><b>location</b></label> <input type="text" placeholder="Enter location" id="location" name="location" > <label for="stars"><b>stars</b></label> <input type="int" placeholder="Enter stars" id="stars" name="stars" > <label for="rating"><b>rating</b></label> <input type="int" placeholder="Enter stars" id="rating" name="rating" > <input name= "search" type= "submit" > </div> <!-- <p> <a href="memindex.php?logout='1'" style="color: red;">logout</a> </p> --> </form> <?php session_start(); if (isset($_post['search'])){ $db = mysqli_connect('localhost', 'root', '', 'booking'); $sql1 ="CREATE TABLE test (id int(11) ,type VARCHAR(255) ,facilities VARCHAR(255) ,image longblob ,hotelId varchar(255) , price int(11) ,status VARCHAR(255) ,count int(11) ,tt VARCHAR(50) ,location VARCHAR(10) ,stars int ,suspended int ,approved int ,rating int ,owner_id int );"; $result4=mysqli_query($db,$sql1); echo ("sup"); $rating = mysqli_real_escape_string($db, $_POST['rating']); $type = mysqli_real_escape_string($db, $_POST['type']); $price = mysqli_real_escape_string($db, $_POST['price']); $location = mysqli_real_escape_string($db, $_POST['location']); $stars = mysqli_real_escape_string($db, $_POST['stars']); $sqol="drop table test"; $result3=mysqli_query($db,$sqol); $sql1 ="INSERT INTO test (id,type,facilities,image,hotelId,price,status,count,tt,location,stars,suspended,approved,rating,owner_id) SELECT * FROM rooms INNER JOIN hotels ON hotels.name=rooms.hotelId; "; $result2=mysqli_query($db,$sql1); $sql2 = "ALTER TABLE test drop tt;"; $result1=mysqli_query($db,$sql2); if (!empty($rating)){ $query_select = mysqli_query($db,"delete from test where rating<>$rating or rating is null"); } if (!empty($location)){ $query_select = mysqli_query($db,"delete from test where location<>'$location'"); } if (!empty($stars)){ $query_select = mysqli_query($db,"delete from test where star<>'$star'"); } if (!empty($price)){ $query_select = mysqli_query($db,"delete from test where price<>'$price'"); } if (!empty($type)){ $query_select = mysqli_query($db,"delete from test where type<>'$type'"); } } ?> </body> </html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <table> <tr> <th>hotel name </th> <th> stars</th> <th>rating</th> <th>location</th> <th>facilities</th> <th>type</th> <th>price</th> <th>image</th> </tr> <?php $db = mysqli_connect('localhost', 'root', '', 'booking'); $select=mysqli_query($db,"select * FROM test "); while ($hotel = mysqli_fetch_assoc($select)) { echo( "<tr><td>". $hotel['hotelId']. "</td><td>" .$hotel['stars']. "</td><td>" .$hotel['rating']. "</td><td>" .$hotel['location']. "</td><td>" .$hotel['facilities']. "</td><td>" .$hotel['type']. "</td><td>" .$hotel['price']. "</td></tr>" ); } echo "</table>"; ?>
Ruby
UTF-8
301
3.015625
3
[]
no_license
class ETL def self.transform(hash) create_new_hash(hash) end class << self private def create_new_hash(hash) new_hash = Hash.new() hash.keys.map do |key| hash[key].map {|element| new_hash[element.downcase] = key } end new_hash end end end
C++
UTF-8
1,189
2.875
3
[]
no_license
// //Manager.cpp // #include "Manager.h"; #include "ObjectList.h"; #include "WorldManager.h"; #include "LogManager.h"; //Constructor df::Manager::Manager() {} //Deconstructor df::Manager::~Manager() {} // Set type identifier of Manager. void df::Manager::setType(std::string new_type) { m_type = new_type; } // Get type identifier of Manager. std::string df::Manager::getType() const { return m_type; } // Startup Manager. // Return 0 if ok, else negative number. int df::Manager::startUp() { m_is_started = true; if (m_is_started) return 0; return -1; } // Shutdown Manager. void df::Manager::shutDown() { m_is_started = false; } // Return status of is_started (true when startUp() was successful). bool df::Manager::isStarted() const{ return m_is_started; } // Send event to all interested Objects. // Return count of number of events sent. int df::Manager::onEvent(const Event *p_event) const { int count = 0; df::ObjectList allObjects = WM.getAllObjects(); df::ObjectListIterator li = df::ObjectListIterator::ObjectListIterator(&allObjects); while (!li.isDone()) { li.currentObject()->eventHandler(p_event); li.next(); count++; } return count; }
Java
UTF-8
10,421
2.015625
2
[]
no_license
package com.pentapus.pentapusdmh.Fragments.Encounter; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import com.androidessence.recyclerviewcursoradapter.RecyclerViewCursorAdapter; import com.androidessence.recyclerviewcursoradapter.RecyclerViewCursorViewHolder; import com.pentapus.pentapusdmh.AdapterNavigationCallback; import com.pentapus.pentapusdmh.DbClasses.DataBaseHandler; import com.pentapus.pentapusdmh.DbClasses.DbContentProvider; import com.pentapus.pentapusdmh.Fragments.EncounterPrep.EncounterFragment; import com.pentapus.pentapusdmh.R; import com.pentapus.pentapusdmh.HelperClasses.RippleForegroundListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Koni on 14/4/16. */ public class EncounterAdapter extends RecyclerViewCursorAdapter<EncounterAdapter.EncounterViewHolder> implements AdapterNavigationCallback { public static int selectedPos = -1; private AdapterNavigationCallback mAdapterCallback; List<String> itemsPendingRemoval; private Handler handler = new Handler(); // handler for running delayed runnables HashMap<String, Runnable> pendingRunnables = new HashMap<>(); private static final int PENDING_REMOVAL_TIMEOUT = 3000; Context mContext; /** * Constructor. * * @param context The Context the Adapter is displayed in. */ public EncounterAdapter(Context context, AdapterNavigationCallback callback) { super(context); this.mContext = context; this.mAdapterCallback = callback; itemsPendingRemoval = new ArrayList<>(); setHasStableIds(true); setupCursorAdapter(null, 0, R.layout.card_encounter, false); } /** * Returns the ViewHolder to use for this adapter. */ @Override public EncounterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new EncounterViewHolder(mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent), mAdapterCallback); } @Override public long getItemId(int position) { mCursorAdapter.getCursor().moveToPosition(position); return mCursorAdapter.getCursor().getInt(mCursorAdapter.getCursor().getColumnIndexOrThrow(DataBaseHandler.KEY_ROWID)); } /** * Moves the Cursor of the CursorAdapter to the appropriate position and binds the view for * that item. */ @Override public void onBindViewHolder(EncounterViewHolder holder, int position) { // Move cursor to this position mCursorAdapter.getCursor().moveToPosition(position); // Set the ViewHolder setViewHolder(holder); // Bind this view mCursorAdapter.bindView(null, mContext, mCursorAdapter.getCursor()); } public void pendingRemoval(final int position) { Cursor mCursor = mCursorAdapter.getCursor(); mCursor.moveToPosition(position); final String identifier = mCursor.getString(mCursor.getColumnIndexOrThrow(DataBaseHandler.KEY_ROWID)); if (!itemsPendingRemoval.contains(identifier)) { itemsPendingRemoval.add(identifier); // this will redraw row in "undo" state notifyItemChanged(position); // let's create, store and post a runnable to remove the item Runnable pendingRemovalRunnable = new Runnable() { @Override public void run() { remove(position, identifier); } }; handler.postDelayed(pendingRemovalRunnable, PENDING_REMOVAL_TIMEOUT); pendingRunnables.put(identifier, pendingRemovalRunnable); } } public boolean isPendingRemoval(int position) { Cursor mCursor = mCursorAdapter.getCursor(); mCursor.moveToPosition(position); return itemsPendingRemoval.contains(String.valueOf(mCursor.getString(mCursor.getColumnIndexOrThrow(DataBaseHandler.KEY_ROWID)))); } public void remove(int position, String identifier) { Cursor mCursor = mCursorAdapter.getCursor(); mCursor.moveToPosition(position); if (itemsPendingRemoval.contains(identifier)) { itemsPendingRemoval.remove(identifier); } int encounterId = mCursor.getInt(mCursor.getColumnIndexOrThrow(DataBaseHandler.KEY_ROWID)); Uri uri = Uri.parse(DbContentProvider.CONTENT_URI_ENCOUNTER + "/" + encounterId); if (position == 0) { notifyItemChanged(position); } else { notifyItemRemoved(position); } mContext.getContentResolver().delete(uri, null, null); ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard.hasPrimaryClip()) { ClipData.Item itemPaste = clipboard.getPrimaryClip().getItemAt(0); Uri pasteUri = itemPaste.getUri(); if (pasteUri == null) { pasteUri = Uri.parse(String.valueOf(itemPaste.getText())); } if (pasteUri != null) { if (pasteUri.equals(uri)) { Uri newUri = Uri.parse(""); ClipData clip = ClipData.newUri(mContext.getContentResolver(), "URI", newUri); clipboard.setPrimaryClip(clip); mAdapterCallback.onMenuRefresh(); } } } } public static void setSelectedPos(int selectedPos) { EncounterAdapter.selectedPos = selectedPos; } @Override public void onItemClick(int position) { mAdapterCallback.onItemClick(position); } @Override public void onItemLongCLick(int position) { mAdapterCallback.onItemLongCLick(position); } @Override public void onMenuRefresh() { } public Cursor getCursor() { return mCursorAdapter.getCursor(); } public class EncounterViewHolder extends RecyclerViewCursorViewHolder { public View view; protected TextView vName, vInfo, vInfoDeleted; protected CardView cardViewTracker; private RelativeLayout clicker; private AdapterNavigationCallback mAdapterCallback; private Button undoButton; private String identifier; private RippleForegroundListener rippleForegroundListener = new RippleForegroundListener(R.id.card_view_encounter); public EncounterViewHolder(View v, AdapterNavigationCallback adapterCallback) { super(v); this.mAdapterCallback = adapterCallback; vName = (TextView) v.findViewById(R.id.name_encounter); cardViewTracker = (CardView) v.findViewById(R.id.card_view_encounter); vInfo = (TextView) v.findViewById(R.id.info_encounter); clicker = (RelativeLayout) v.findViewById(R.id.clicker_encounter); undoButton = (Button) v.findViewById(R.id.undo_encounter); vInfoDeleted = (TextView) v.findViewById(R.id.deleted_encounter); clicker.setOnTouchListener(rippleForegroundListener); clicker.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { EncounterAdapter.selectedPos = getAdapterPosition(); int test = getAdapterPosition(); mAdapterCallback.onItemLongCLick(getAdapterPosition()); return true; } }); clicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAdapterCallback.onItemClick(getAdapterPosition()); } }); } @Override public void bindCursor(Cursor cursor) { vName.setText(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseHandler.KEY_NAME))); vInfo.setText(cursor.getString(cursor.getColumnIndexOrThrow(DataBaseHandler.KEY_INFO))); identifier = cursor.getString(cursor.getColumnIndexOrThrow(DataBaseHandler.KEY_ROWID)); itemView.setActivated(getAdapterPosition() == EncounterAdapter.selectedPos); if (itemsPendingRemoval.contains(String.valueOf(identifier))) { // we need to show the "undo" state of the row itemView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorAccent)); vName.setVisibility(View.GONE); vInfo.setVisibility(View.GONE); vInfoDeleted.setVisibility(View.VISIBLE); undoButton.setVisibility(View.VISIBLE); undoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // user wants to undo the removal, let's cancel the pending task Runnable pendingRemovalRunnable = pendingRunnables.get(String.valueOf(identifier)); pendingRunnables.remove(String.valueOf(identifier)); if (pendingRemovalRunnable != null) handler.removeCallbacks(pendingRemovalRunnable); itemsPendingRemoval.remove(String.valueOf(identifier)); // this will rebind the row in "normal" state notifyItemChanged(getAdapterPosition()); } }); } else { // we need to show the "normal" state itemView.setBackgroundColor(Color.WHITE); vName.setVisibility(View.VISIBLE); vInfo.setVisibility(View.VISIBLE); // viewHolder.titleTextView.setText(item); vInfoDeleted.setVisibility(View.GONE); undoButton.setVisibility(View.GONE); undoButton.setOnClickListener(null); } } } }
Markdown
UTF-8
1,758
3.53125
4
[ "MIT" ]
permissive
# Python 时间相关用法 ### 相关函数功能转换示意图 ![pic_1](../../Figure/python-datetime-convert-figure.png) ### 字符串转整数时间戳 ```python import time int(time.mktime(time.strptime('2013-10-10 23:40:00', "%Y-%m-%d %H:%M:%S"))) # 1381419600 ``` ### 整数时间戳转字符串 ```python import time time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(1557673200)) # '2019-05-12 23:00:00' ``` ### 某一时间的前后几天 ```python from datetime import datetime, timedelta datetime.now() + timedelta(days = 1) ``` ### 某一时间的前后几月 `timedelta`不支持月的单位,需要用`dateutil` ```python from datetime import datetime from dateutil.relativedelta import relativedelta datetime.now() + relativedelta(months = 1) ``` ### 毫秒级处理 #### 获得当前时间的毫秒时间戳 ```python import datetime datetime.datetime.now() # datetime.datetime(2019, 7, 8, 21, 14, 37, 897386) ``` #### 获得当前时间的毫秒字符串 ```python import datetime datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') ``` #### 根据毫秒时间戳(小数)将时间转换为毫秒字符串 ```python import datetime datetime.datetime.fromtimestamp(1538271871.226226).strftime('%Y-%m-%d %H:%M:%S.%f') # '2018-09-30 09:44:31.226226' ``` #### 将毫秒字符串转换为时间格式 ```python import datetime datetime.datetime.strptime('2018-09-30 09:44:31.226226','%Y-%m-%d %H:%M:%S.%f') # datetime.datetime(2018, 9, 30, 9, 44, 31, 226226) ``` ## datetime #### 当前与指定时间的差值 ```python from datetime import datetime time_gap = datetime.now() - datetime.strptime('2017-8-1 18:20:20', '%Y-%m-%d %H:%M:%S') str(time_gap) ``` datetime.fromtimestamp(now_time)
Markdown
UTF-8
1,636
3.03125
3
[]
no_license
# Analyzing and planning a new Rails app ------------------------------------------- Today we will be looking at how to go about planning and thinking through a Rails application. We will be talking about some of the things that need to be done before you start coding. ## Agenda 1. A quick digression about partial templates 2. User Stories 3. Planning 4. Modelling ## User Stories As a ... I want ... So that... - Who's the user? - What do they need to do? - Why do they need it? What is the goal they're trying to accomplish? ### EXAMPLES - As a customer, I want to search for restaurants - As a customer, I want to search for reviews - As a customer, I want to know what's nearby - As a customer, I want to filter by cuisine - As a customer, I want to see the menu - As a customer, I want to be able to make an account - As a customer, I want to be able to make a reservation - As an owner, I want to receive reservations - As an owner, I want to know how many reservations I have - As an owner, I want to know what people are searching for - ... ## Prioritize 1. NEED TO HAVE 2. NICE TO HAVE 3. HAPPY TO HAVE ## Planning - Make assumptions - Max Occupancy - All reservations have the same duration (1h) - Simplify! - Make mockups - Gather feedback - Usability - Maybe idea of user flow through the app - Visualize what the app will look like - Test prioritization (are important things important?) - Reveals missed user stories or flaws in assumptions ## Modelling - Pen and paper / Whiteboard - Quick and easily changed - Create models - Draw relationships - Repeat!
Java
UTF-8
512
2.09375
2
[]
no_license
package com.koreait.contact03.command; import org.apache.ibatis.session.SqlSession; import org.springframework.ui.Model; import com.koreait.contact03.dao.ContactDAO; public class SelectContactListCommand implements ContactCommand { @Override public void execute(SqlSession sqlSession, Model model) { // 파라미터처리 X // DAO호출 ContactDAO contactDAO = sqlSession.getMapper(ContactDAO.class); // model에 저장 model.addAttribute("list", contactDAO.selectContactList()); } }
C++
UTF-8
1,178
3.125
3
[]
no_license
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; vector<int> tmp_vec; queue<TreeNode*> my_queue; TreeNode* tmp_node; int level = 2; if(!root) return res; my_queue.push(root); my_queue.push(NULL); while(!my_queue.empty()){ while(my_queue.front()!=NULL){ tmp_node = my_queue.front(); tmp_vec.push_back(tmp_node->val); if(tmp_node->left) my_queue.push(tmp_node->left); if(tmp_node->right) my_queue.push(tmp_node->right); my_queue.pop(); } my_queue.pop(); if(!my_queue.empty()) my_queue.push(NULL); if(level%2==0) res.push_back(tmp_vec); else{ reverse(tmp_vec.begin(),tmp_vec.end()); res.push_back(tmp_vec); } tmp_vec.clear(); level++; } return res; } };
C++
UTF-8
4,413
2.75
3
[]
no_license
#include<iostream> #include<string.h> #include <fstream> #include <sys/time.h> //Deneme //1 /2 using namespace std; #define PENCERE 5 int pencere_ortalamasi_al (int * matris, int genislik, int indeks); int main (int argc, char **argv) { if (argc == 2) { struct timeval currentTime; double startTime,endTime,elapsedTime; // Tam olarak bir tane arguman aldığımızdan emin olduk char * girdi_dosya_adresi_orig = new char [128]; // girilen metnin orijimal halini tuttuk strcpy(girdi_dosya_adresi_orig, argv[1]); char girdi_dosya_adresi[128]; // girilen metni burada tuttuk (token işlemi yaparken değişecek) strcpy(girdi_dosya_adresi, girdi_dosya_adresi_orig); char cikti_dosya_adresi[128]; char * dosya_ismi = NULL; if (strstr(girdi_dosya_adresi, "/")){ // Girilen metinde "/" varmı diye bakıyoruz char *p = strtok(girdi_dosya_adresi, "/"); while (p) { if (strstr(p, ".txt")) { dosya_ismi = strtok(p, "."); } p = strtok(NULL, "/"); } }else if (strstr(girdi_dosya_adresi, ".txt")) { // Girilen metinde ".txt" var mı diye bakıyoruz dosya_ismi = strtok(girdi_dosya_adresi, "."); } if (dosya_ismi == NULL) { cout << "Verilen adresteki dosya tanımlanamadı."; return -1; }else { sprintf(cikti_dosya_adresi, "%s_filtered.txt", dosya_ismi); } strcpy(girdi_dosya_adresi, girdi_dosya_adresi_orig); delete [] girdi_dosya_adresi_orig; ifstream girdi_txt_dosyasi; girdi_txt_dosyasi.open(girdi_dosya_adresi); if (girdi_txt_dosyasi.is_open()) { int yukseklik; int genislik; girdi_txt_dosyasi >> yukseklik >> genislik; int * girdi_ana_dizi = new int [yukseklik * genislik]; int * cikti_ana_dizi = new int [yukseklik * genislik]; int piksel; int i = 0; while (girdi_txt_dosyasi >> piksel) { girdi_ana_dizi[i] = piksel; cikti_ana_dizi[i] = piksel; i++; } gettimeofday(&currentTime, NULL); //Seconds from the epoch time startTime=currentTime.tv_sec+(currentTime.tv_usec/1000000.0); int pf = PENCERE/2; // pencere farkı int ilk_piksel = pf * genislik + pf; int son_piksel = (yukseklik-pf) * genislik + (genislik - pf); for (i = ilk_piksel; i < son_piksel; i++) { cikti_ana_dizi[i] = pencere_ortalamasi_al(girdi_ana_dizi, genislik, i); } gettimeofday(&currentTime, NULL); //Seconds from the epoch time endTime=currentTime.tv_sec+(currentTime.tv_usec/1000000.0); ofstream cikti_txt_dosyasi; cikti_txt_dosyasi.open(cikti_dosya_adresi); if (cikti_txt_dosyasi.is_open()) { cikti_txt_dosyasi << yukseklik << " " << genislik << endl; for (i = 0; i < yukseklik * genislik; i++) { if (i>0 && i % genislik == 0) cikti_txt_dosyasi << endl; cikti_txt_dosyasi << cikti_ana_dizi[i] << " "; } cikti_txt_dosyasi.close(); } girdi_txt_dosyasi.close(); delete [] girdi_ana_dizi; delete [] cikti_ana_dizi; elapsedTime = (endTime-startTime) * 1000; cout << "Total Time Taken (milisaniye cinsinden): " << elapsedTime<< endl; }else { cout << "Verilen adresteki dosya açılamadı." << endl;; return -1; } }else { cout << "Tam olarak bir komut satiri parametresi girilmelidir." << endl; return -1; } } int pencere_ortalamasi_al (int * matris, int genislik, int indeks) { int i; int j; int pf = PENCERE / 2; // pencere farkı int toplam = 0; int komsu_sayisi = 0; int ilk_piksel = (indeks - pf) - (pf*genislik); for ( i = 0; i < PENCERE; i++) { int k = ilk_piksel + (i*genislik); toplam += matris[k] + matris[k+1] + matris[k+2] + matris[k+3] + matris[k+4]; komsu_sayisi+=5; } return toplam / komsu_sayisi; }
C#
UTF-8
878
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Matveev.Mtk.Core { public abstract class FaceFunction { public abstract double Evaluate(Face face); public double[] EvaluateGradient(Face face) { double[] result = new double[9]; this.EvaluateGradientTo(face, result); return result; } public virtual void EvaluateGradientTo(Face face, double[] dest) { if (face == null) throw new ArgumentNullException("face"); if (dest == null) throw new ArgumentNullException("dest"); if (dest.Length != 9) throw new ArgumentException("dest.Length != 9", "dest"); // TODO: Place linear approximation here. } } }
Java
UTF-8
190
1.976563
2
[]
no_license
package com.example.dason.simweather.api; /** * Created by dason on 2016/11/10 0010. */ public interface InformationTransmitter { public abstract void receive(String dataAsJson); }
TypeScript
UTF-8
4,078
3.296875
3
[ "MIT" ]
permissive
import { generateMockFunctionsFromYaml } from "." import { ObjectType, ObjectTypeMock, Resolver } from "./types" describe("generateMockFunctionsFromYaml", () => { it("handles strings", () => { const yaml = ` name: Michael Scott ` expect(generateMockFunctionsFromYaml(yaml).name()).toEqual("Michael Scott") }) it("handles numbers", () => { const yaml = ` age: 51 ` expect(generateMockFunctionsFromYaml(yaml).age()).toEqual(51) }) it("handles nested object types", () => { const yaml = ` User: friend: name: Dwight Schrute ` const User = <ObjectType>generateMockFunctionsFromYaml(yaml).User() const friend = <ObjectType>User.friend() expect(friend.name()).toEqual("Dwight Schrute") }) it("handles lists of objects", () => { const yaml = ` friends: - name: Michael Scott - name: Dwight Schrute ` const friends = <ObjectType[]>generateMockFunctionsFromYaml(yaml).friends() expect(friends.map(f => f.name())).toEqual([ "Michael Scott", "Dwight Schrute" ]) }) it("handles lists of scalars", () => { const yaml = ` numbers: - 10 - 20 - 30 ` const numbers = <ObjectType[]>generateMockFunctionsFromYaml(yaml).numbers() expect(numbers).toEqual([10, 20, 30]) }) it("throws an error generating resolvers with an invalid library", () => { const yaml = ` age: function(): invalidLibrary.function ` expect(() => generateMockFunctionsFromYaml(yaml)).toThrow( Error("invalidLibrary is not a compatible library.") ) }) it("throws an error generating resolvers with an invalid function", () => { const yaml = ` age: function(): faker.invalidFunction ` expect(() => generateMockFunctionsFromYaml(yaml)).toThrow( Error("faker.invalidFunction is not a valid function.") ) }) it("handles a faker function without arguments", () => { const yaml = ` age: function(): faker.random.number ` const resolvers = generateMockFunctionsFromYaml(yaml) expect(typeof resolvers.age()).toBe("number") }) it("handles a faker function with a scalar argument", () => { const yaml = ` age: function(): faker.random.number args: 10 ` const resolvers = generateMockFunctionsFromYaml(yaml) const age = resolvers.age() expect(age).toBeLessThanOrEqual(10) }) it("handles a faker function with a scalar argument provided in a list", () => { const yaml = ` age: function(): faker.random.number args: - 10 ` const resolvers = generateMockFunctionsFromYaml(yaml) const age = resolvers.age() expect(age).toBeLessThanOrEqual(10) }) it("handles a faker function with an object argument", () => { const yaml = ` age: function(): faker.random.number args: - min: 51 max: 53 ` const resolvers = generateMockFunctionsFromYaml(yaml) const age = resolvers.age() expect(age).toBeGreaterThanOrEqual(51) expect(age).toBeLessThanOrEqual(53) }) it("handles a faker function with an array argument", () => { const yaml = ` name: function(): faker.random.arrayElement args: - - Michael - Dwight ` const resolvers = generateMockFunctionsFromYaml(yaml) const name = resolvers.name() expect(["Michael", "Dwight"].includes(<string>name)).toBeTruthy() }) it("handles a casual generator that's not a function", () => { const yaml = ` bool: function(): casual.coin_flip ` const resolvers = generateMockFunctionsFromYaml(yaml) const bool = resolvers.bool() expect(typeof bool).toBe("boolean") }) it("handles a casual function", () => { const yaml = ` words: function(): casual.array_of_words args: 5 ` const resolvers = generateMockFunctionsFromYaml(yaml) const words = <string[]>resolvers.words() expect((<string[]>words).length).toBe(5) }) })
Java
UTF-8
1,797
2.71875
3
[]
no_license
/** * */ package com.chinarewards.qqgbvpn.main.impl; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * * @author dengrenwen * @since 0.1.0 */ public class ServerTimer { protected Logger log = LoggerFactory.getLogger(ServerTimer.class); Runnable task; ScheduledExecutorService timer; ScheduledFuture<?> future; long delay = 0; long period = 1000; public ServerTimer() { timer = Executors.newScheduledThreadPool(1); } public void start() { if (task != null) { future = timer.scheduleAtFixedRate(task, delay, period, TimeUnit.SECONDS); } } public void stop() { if (future != null && !future.isCancelled()) { future.cancel(true); timer.shutdown(); } } /** * 如果定时任务没有启动,就初始参数 如果定时任务已经启动,就更改参数并重启设定启动任务 * * @param delay * @param period * @param task 如果为null就不改变上次完成的任务 */ public void scheduleAtFixedInterval(long delay, long period, Runnable task) { boolean cancel = false; if(this.delay == delay && this.period == period && task == null){ return; } if (delay >= 0 && period >= 0) { this.delay = delay; this.period = period; } if (task != null) { this.task = task; } if (this.future != null && !this.future.isCancelled()) { this.future.cancel(true); cancel = true; } if (cancel){ this.future = timer.scheduleAtFixedRate(this.task, this.delay, this.period, TimeUnit.SECONDS); } } }
Markdown
UTF-8
12,023
2.890625
3
[]
no_license
# 一、 什么是javax.validation JSR303 是一套JavaBean参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们JavaBean的属性上面(面向注解编程的时代),就可以在需要校验的时候进行校验了,在SpringBoot中已经包含在starter-web中,再其他项目中可以引用依赖,并自行调整版本: ```xml <!--jsr 303--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <!-- hibernate validator--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.0.Final</version> </dependency> ``` ## 1.1、 注解说明 | 验证注解 | 验证的数据类型 | 说明 | | :------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | | @AssertFalse | Boolean,boolean | 验证注解的元素值是false | | @AssertTrue | Boolean,boolean | 验证注解的元素值是true | | @NotNull | 任意类型 | 验证注解的元素值不是null | | @Null | 任意类型 | 验证注解的元素值是null | | @Min(value=值) | BigDecimal,BigInteger, byte,short, int, long,等任何Number或CharSequence(存储的是数字)子类型 | 验证注解的元素值大于等于@Min指定的value值 | | @Max(value=值) | 和@Min要求一样 | 验证注解的元素值小于等于@Max指定的value值 | | @DecimalMin(value=值) | 和@Min要求一样 | 验证注解的元素值大于等于@ DecimalMin指定的value值 | | @DecimalMax(value=值) | 和@Min要求一样 | 验证注解的元素值小于等于@ DecimalMax指定的value值 | | @Digits(integer=整数位数, fraction=小数位数) | 和@Min要求一样 | 验证注解的元素值的整数位数和小数位数上限 | | @Size(min=下限, max=上限) | 字符串、Collection、Map、数组等 | 验证注解的元素值的在min和max(包含)指定区间之内,如字符长度、集合大小 | | @Past | java.util.Date,java.util.Calendar;Joda Time类库的日期类型 | 验证注解的元素值(日期类型)比当前时间早 | | @Future | 与@Past要求一样 | 验证注解的元素值(日期类型)比当前时间晚 | | @NotBlank | CharSequence子类型 | 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的首位空格 | | @Length(min=下限, max=上限) | CharSequence子类型 | 验证注解的元素值长度在min和max区间内 | | @NotEmpty | CharSequence子类型、Collection、Map、数组 | 验证注解的元素值不为null且不为空(字符串长度不为0、集合大小不为0) | | @Range(min=最小值, max=最大值) | BigDecimal,BigInteger,CharSequence, byte, short, int, long等原子类型和包装类型 | 验证注解的元素值在最小值和最大值之间 | | @Email(regexp=正则表达式,flag=标志的模式) | CharSequence子类型(如String) | 验证注解的元素值是Email,也可以通过regexp和flag指定自定义的email格式 | | @Pattern(regexp=正则表达式,flag=标志的模式) | String,任何CharSequence的子类型 | 验证注解的元素值与指定的正则表达式匹配 | | @Valid | 任何非原子类型 | 指定递归验证关联的对象如用户对象中有个地址对象属性,如果想在验证用户对象时一起验证地址对象的话,在地址对象上加@Valid注解即可级联验证 | 此处只列出Hibernate Validator提供的大部分验证约束注解,请参考hibernate validator官方文档了解其他验证约束注解和进行自定义的验证约束注解定义。 ## 1.2、 **实战演练** ### 1.2.1、 @Validated 声明要检查的参数 控制层: ```java /** * 走参数校验注解 * * @param userDTO * @return */ @PostMapping("/save/valid") public RspDTO save(@RequestBody @Validated UserDTO userDTO) { userService.save(userDTO); return RspDTO.success(); } ``` ### 1.2.2、 **对参数的字段进行注解标注** ```java import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Date; /** * @author LiJing * @ClassName: UserDTO * @Description: 用户传输对象 * @date 2019/7/30 13:55 */ @Data public class UserDTO implements Serializable { private static final long serialVersionUID = 1L; /*** 用户ID*/ @NotNull(message = "用户id不能为空") private Long userId; /** 用户名*/ @NotBlank(message = "用户名不能为空") @Length(max = 20, message = "用户名不能超过20个字符") @Pattern(regexp = "^[\\u4E00-\\u9FA5A-Za-z0-9\\*]*$", message = "用户昵称限制:最多20字符,包含文字、字母和数字") private String username; /** 手机号*/ @NotBlank(message = "手机号不能为空") @Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手机号格式有误") private String mobile; /**性别*/ private String sex; /** 邮箱*/ @NotBlank(message = "联系邮箱不能为空") @Email(message = "邮箱格式不对") private String email; /** 密码*/ private String password; /*** 创建时间 */ @Future(message = "时间必须是将来时间") private Date createTime; } ``` ### 1.2.3、 **在全局校验中增加校验异常** MethodArgumentNotValidException是springBoot中进行绑定参数校验时的异常,需要在springBoot中处理,其他需要 处理ConstraintViolationException异常进行处理. * 为了优雅一点,我们将参数异常,业务异常,统一做了一个全局异常,将控制层的异常包装到我们自定义的异常中 * 为了优雅一点,我们还做了一个统一的结构体,将请求的code,和msg,data一起统一封装到结构体中,增加了代码的复用性 ```java import com.boot.lea.mybot.dto.RspDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; /** * @author LiJing * @ClassName: GlobalExceptionHandler * @Description: 全局异常处理器 * @date 2019/7/30 13:57 */ @RestControllerAdvice public class GlobalExceptionHandler { private Logger logger = LoggerFactory.getLogger(getClass()); private static int DUPLICATE_KEY_CODE = 1001; private static int PARAM_FAIL_CODE = 1002; private static int VALIDATION_CODE = 1003; /** * 处理自定义异常 */ @ExceptionHandler(BizException.class) public RspDTO handleRRException(BizException e) { logger.error(e.getMessage(), e); return new RspDTO(e.getCode(), e.getMessage()); } /** * 方法参数校验 */ @ExceptionHandler(MethodArgumentNotValidException.class) public RspDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { logger.error(e.getMessage(), e); return new RspDTO(PARAM_FAIL_CODE, e.getBindingResult().getFieldError().getDefaultMessage()); } /** * ValidationException */ @ExceptionHandler(ValidationException.class) public RspDTO handleValidationException(ValidationException e) { logger.error(e.getMessage(), e); return new RspDTO(VALIDATION_CODE, e.getCause().getMessage()); } /** * ConstraintViolationException */ @ExceptionHandler(ConstraintViolationException.class) public RspDTO handleConstraintViolationException(ConstraintViolationException e) { logger.error(e.getMessage(), e); return new RspDTO(PARAM_FAIL_CODE, e.getMessage()); } @ExceptionHandler(NoHandlerFoundException.class) public RspDTO handlerNoFoundException(Exception e) { logger.error(e.getMessage(), e); return new RspDTO(404, "路径不存在,请检查路径是否正确"); } @ExceptionHandler(DuplicateKeyException.class) public RspDTO handleDuplicateKeyException(DuplicateKeyException e) { logger.error(e.getMessage(), e); return new RspDTO(DUPLICATE_KEY_CODE, "数据重复,请检查后提交"); } @ExceptionHandler(Exception.class) public RspDTO handleException(Exception e) { logger.error(e.getMessage(), e); return new RspDTO(500, "系统繁忙,请稍后再试"); } } ``` ## 1.3、 **自定义参数注解** ### 1.3.1、 比如我们来个 自定义身份证校验 注解 ```java @Documented @Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = IdentityCardNumberValidator.class) public @interface IdentityCardNumber { String message() default "身份证号码不合法"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};} ``` 这个注解是作用在Field字段上,运行时生效,触发的是IdentityCardNumber这个验证类。 * message 定制化的提示信息,主要是从ValidationMessages.properties里提取,也可以依据实际情况进行定制 * groups 这里主要进行将validator进行分类,不同的类group中会执行不同的validator操作 * payload 主要是针对bean的,使用不多 ### 1.3.2、 **然后自定义Validator** 这个是真正进行验证的逻辑代码: ```java public class IdentityCardNumberValidator implements ConstraintValidator<IdentityCardNumber, Object> { @Override public void initialize(IdentityCardNumber identityCardNumber) { } @Override public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) { return IdCardValidatorUtils.isValidate18Idcard(o.toString()); } } ```
Java
UTF-8
317
1.6875
2
[]
no_license
package com.youbenben.youbenben.skilltype; import com.youbenben.youbenben.EntityNotFoundException; public class SkillTypeVersionChangedException extends SkillTypeManagerException { private static final long serialVersionUID = 1L; public SkillTypeVersionChangedException(String string) { super(string); } }
Python
UTF-8
110
3.28125
3
[]
no_license
def single_occurrence(txt): return ''.join([i.upper() for i in txt if (txt.lower()).count(i.lower())==1])
Java
UTF-8
13,995
2.40625
2
[]
no_license
package com.futchampionsstats.models; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.util.Log; import com.futchampionsstats.BR; import java.io.Serializable; import java.util.ArrayList; import java.util.Locale; import static com.futchampionsstats.utils.Utils.calculateAverage; /** * Created by yiannitzan on 12/30/16. */ public class WeekendLeague extends BaseObservable implements Serializable{ public static final String TAG = WeekendLeague.class.getSimpleName(); @Bindable public String dateOfWL; @Bindable private ArrayList<Game> weekendLeague; @Bindable public ArrayList<Game> getWeekendLeague() { return weekendLeague; } public void setWeekendLeague(ArrayList<Game> weekendLeague) { this.weekendLeague = weekendLeague; } @Bindable public String getDateOfWL() { return dateOfWL; } public void setDateOfWL(String dateOfWL) { this.dateOfWL = dateOfWL; notifyPropertyChanged(BR.dateOfWL); } /** All below should be put in a view model class, set with databinding from views/presenters * This class should just be the model. */ public static String getTotalGamesPlayed(WeekendLeague weekendLeague){ if(weekendLeague!=null){ return String.valueOf(weekendLeague.getWeekendLeague().size()); } else{ return "0"; } } public static String getWinTotal(WeekendLeague weekendLeague){ int gamesWon = 0; if(weekendLeague!=null && weekendLeague.getWeekendLeague().size()>0){ int i = 0; while(i<weekendLeague.getWeekendLeague().size()){ Game currGame = weekendLeague.getWeekendLeague().get(i); if(currGame.getUser_won()){ gamesWon++; } i++; } } return Integer.toString(gamesWon); } public static String getGamesLeft(WeekendLeague wl){ if(wl!=null){ return String.valueOf(30 - wl.getWeekendLeague().size()); } else{ return "30"; } } public static String[] getAvgShotsFor(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> shotsFor = new ArrayList<>(); ArrayList<Integer> shotsForOnGoal = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if((game.getGame_disconnected()!=null && !game.getGame_disconnected()) && (game.getUser_shots()!=null || game.getUser_sog()!=null)){ shotsFor.add(Integer.parseInt(game.getUser_shots())); shotsForOnGoal.add(Integer.parseInt(game.getUser_sog())); } } Double avgShotsFor = calculateAverage(shotsFor); Double avgShotsOnG = calculateAverage(shotsForOnGoal); return new String[]{String.format(Locale.US, "%.2f", avgShotsFor), String.format(Locale.US, "%.2f", avgShotsOnG)}; } catch(NumberFormatException e){ Log.d(TAG, "avgShotsWatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgShotsString(WeekendLeague wl){ return getAvgShotsFor(wl)[0] + "(" + getAvgShotsFor(wl)[1] + ")"; } public static String[] getAvgPoss(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> possFor = new ArrayList<>(); ArrayList<Integer> possAgainst = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getUser_possession()!=null || game.getOpp_possession()!=null)){ possFor.add(Integer.parseInt(game.getUser_possession())); possAgainst.add(Integer.parseInt(game.getOpp_possession())); } } Double avgPossFor = calculateAverage(possFor); Double avgPossAgainst= calculateAverage(possAgainst); return new String[]{String.format(Locale.US, "%.2f", avgPossFor), String.format(Locale.US, "%.2f", avgPossAgainst)}; } catch(NumberFormatException e){ Log.d(TAG, "avgPossWatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgPossString(WeekendLeague wl){ return getAvgPoss(wl)[0] + "%(" + getAvgPoss(wl)[1] + "%)"; } public static String[] getAvgPassAcc(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> passFor = new ArrayList<>(); ArrayList<Integer> passAgainst = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getUser_pass_acc()!=null || game.getOpp_pass_acc()!=null)){ passFor.add(Integer.parseInt(game.getUser_pass_acc())); passAgainst.add(Integer.parseInt(game.getOpp_pass_acc())); } } Double avgPassFor = calculateAverage(passFor); Double avgPassAgainst= calculateAverage(passAgainst); return new String[]{String.format(Locale.US, "%.2f", avgPassFor), String.format(Locale.US, "%.2f", avgPassAgainst)}; } catch(NumberFormatException e){ Log.d(TAG, "avgPassWatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgPassAccString(WeekendLeague wl){ return getAvgPassAcc(wl)[0] + "%(" + getAvgPassAcc(wl)[1] + "%)"; } public static String getAvgGoalPerShotString(WeekendLeague wl){ Double userGoalsAvg = Double.parseDouble(getAvgGoals(wl)[0]); Double userSOGAvg = Double.parseDouble(getAvgShotsFor(wl)[1]); Double userAvgGPSOG = userGoalsAvg / userSOGAvg; Double oppGoalsAvg = Double.parseDouble(getAvgGoals(wl)[1]); Double oppSOGAvg = Double.parseDouble(getAvgShotsAgainst(wl)[1]); Double oppAvgGPSOG = oppGoalsAvg / oppSOGAvg; if(!userAvgGPSOG.isNaN() && !oppAvgGPSOG.isNaN()){ return String.format(Locale.US, "%.2f", userAvgGPSOG) + "(" + String.format(Locale.US, "%.2f", oppAvgGPSOG) + ")"; } else{ return "0.00(0.00)"; } } public static String[] getAvgShotsAgainst(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> shotsAgainstFor = new ArrayList<>(); ArrayList<Integer> shotsAgainstOnGoal = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getOpp_shots()!=null || game.getOpp_sog()!=null)){ shotsAgainstFor.add(Integer.parseInt(game.getOpp_shots())); shotsAgainstOnGoal.add(Integer.parseInt(game.getOpp_sog())); } } Double avgShotsAgainstFor = calculateAverage(shotsAgainstFor); Double avgShotsAgainstOnG = calculateAverage(shotsAgainstOnGoal); return new String[]{String.format(Locale.US, "%.2f", avgShotsAgainstFor), String.format(Locale.US, "%.2f", avgShotsAgainstOnG)}; } catch(NumberFormatException e){ Log.d(TAG, "avgShotsAgainstWatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgShotsAgainstString(WeekendLeague wl){ return getAvgShotsAgainst(wl)[0] + "(" + getAvgShotsAgainst(wl)[1] + ")"; } public static String[] getAvgGoals(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> goalsFor = new ArrayList<>(); ArrayList<Integer> goalsAgainst = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getUser_goals()!=null || game.getOpp_goals()!=null)){ goalsFor.add(Integer.parseInt(game.getUser_goals())); goalsAgainst.add(Integer.parseInt(game.getOpp_goals())); } } Double avgGoalsFor = calculateAverage(goalsFor); Double avgGoalsAgainst = calculateAverage(goalsAgainst); return new String[]{String.format(Locale.US, "%.2f", avgGoalsFor), String.format(Locale.US, "%.2f", avgGoalsAgainst)}; } catch(NumberFormatException e){ Log.d(TAG, "avgGoalsWatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgGoalsString(WeekendLeague wl){ return getAvgGoals(wl)[0] + "(" + getAvgGoals(wl)[1] + ")"; } public static String[] getTotalGoals(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ int goalsFor = 0; int goalsAgainst = 0; for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getUser_goals()!=null || game.getOpp_goals()!=null)){ goalsFor += Integer.parseInt(game.getUser_goals()); goalsAgainst += Integer.parseInt(game.getOpp_goals()); } } return new String[]{String.valueOf(goalsFor), String.valueOf(goalsAgainst)}; } catch(NumberFormatException e){ Log.d(TAG, "totalGoalsWatcher: " + e); return new String[]{"0", "0"}; } }else{ return new String[]{"0", "0"}; } } public static String[] getAvgTackles(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> tacklesFor = new ArrayList<>(); ArrayList<Integer> tacklesAgainst = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && (game.getUser_tackles()!=null || game.getOpp_tackles()!=null)){ tacklesFor.add(Integer.parseInt(game.getUser_tackles())); tacklesAgainst.add(Integer.parseInt(game.getOpp_tackles())); } } Double avgTacklesFor = calculateAverage(tacklesFor); Double avgTacklesAgainst= calculateAverage(tacklesAgainst); return new String[]{String.format(Locale.US, "%.2f", avgTacklesFor), String.format(Locale.US, "%.2f", avgTacklesAgainst)}; } catch(NumberFormatException e){ Log.d(TAG, "avgTacklesatcher: " + e); return new String[]{"0.00", "0.00"}; } }else{ return new String[]{"0.00", "0.00"}; } } public static String getAvgTacklesString(WeekendLeague wl){ return getAvgTackles(wl)[0] + "(" + getAvgTackles(wl)[1] + ")"; } public static String getAvgTeamRating(WeekendLeague wl){ if(wl !=null && wl.getWeekendLeague()!=null){ try{ ArrayList<Integer> teamRating = new ArrayList<>(); for(Game game : wl.getWeekendLeague()){ if(!game.getGame_disconnected() && game.getOpp_team_rating()!=null){ teamRating.add(Integer.parseInt(game.getOpp_team_rating())); } } Double avgTeamRating = calculateAverage(teamRating); return String.format(Locale.US, "%.2f", avgTeamRating); } catch(NumberFormatException e){ Log.d(TAG, "avgTeamRatingWatcher: " + e); return "0.00"; } }else{ return "0.00"; } } public static String getDisconnectTotal(WeekendLeague weekendLeague){ int gamesDisconnected = 0; if(weekendLeague!=null && weekendLeague.getWeekendLeague().size()>0){ int i = 0; while(i<weekendLeague.getWeekendLeague().size()){ Game currGame = weekendLeague.getWeekendLeague().get(i); if(currGame.getGame_disconnected()){ gamesDisconnected++; } i++; } } return Integer.toString(gamesDisconnected); } public static String getQuitTotal(WeekendLeague weekendLeague){ int totalQuits = 0; if(weekendLeague!=null && weekendLeague.getWeekendLeague().size()>0){ int i = 0; while(i<weekendLeague.getWeekendLeague().size()){ Game currGame = weekendLeague.getWeekendLeague().get(i); if(currGame.isRage_quit()){ totalQuits++; } i++; } } return Integer.toString(totalQuits); } }
Python
UTF-8
4,209
2.875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Mar 5 16:28:12 2019 @author: rockywin.wang """ import time import numpy as np import cv2 import matplotlib.pyplot as plt def CenterLabelHeatMap(img_width, img_height, c_x, c_y, sigma): X1 = np.linspace(1, img_width, img_width) Y1 = np.linspace(1, img_height, img_height) [X, Y] = np.meshgrid(X1, Y1) X = X - c_x Y = Y - c_y D2 = X * X + Y * Y E2 = 2.0 * sigma * sigma Exponent = D2 / E2 heatmap = np.exp(-Exponent) return heatmap # Compute gaussian kernel def CenterGaussianHeatMap(img_height, img_width, c_x, c_y, variance): gaussian_map = np.zeros((img_height, img_width)) for x_p in range(img_width): for y_p in range(img_height): dist_sq = (x_p - c_x) * (x_p - c_x) + \ (y_p - c_y) * (y_p - c_y) exponent = dist_sq / 2.0 / variance / variance gaussian_map[y_p, x_p] = np.exp(-exponent) gaussian_map = np.where(gaussian_map < 1e-8, 0, gaussian_map) return gaussian_map def gaussian_limit(heatmap, c_x, c_y): gaussian_stride = np.array([[-1,-1],[0,-1], [1,-1],[-1,0],[0,0],[1,0],[-1,1],[0,1],[1,1]]) #gaussian_stride = np.array([[-1,-1],[0,-1], [1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]) search_num = gaussian_stride.shape[0] heatmap_sum = 0 heatmap_new = np.zeros(heatmap.shape) x_index = [] y_index = [] ep = 1e-8 for i in range(search_num): x_stride = c_x + gaussian_stride[i, 0] y_stride = c_y + gaussian_stride[i, 1] if x_stride <0: x_stride = 0 continue if x_stride > heatmap.shape[1] - 1: x_stride = heatmap.shape[1] - 1 continue if y_stride <0: y_stride = 0 continue if y_stride > heatmap.shape[0] - 1: y_stride = heatmap.shape[0] - 1 continue heatmap_sum = heatmap_sum + heatmap[y_stride, x_stride] x_index.append(x_stride) y_index.append(y_stride) for i in range(np.shape(x_index)[0]): heatmap_new[y_index[i], x_index[i]] = heatmap[y_index[i], x_index[i]] / (ep + heatmap_sum) return heatmap_new # normalize #def normalize_gaussian(heatmap, c_x, c_y): def normalize_gaussian(heatmap): gaussian_len = 1 ep = 1e-7 row, col = np.shape(heatmap) print '---np.shape(heatmap)=', np.shape(heatmap) point_sum = np.sum(heatmap) for y_p in range(row): for x_p in range(col): heatmap[y_p, x_p] = heatmap[y_p, x_p] / (point_sum + ep) return heatmap #def truncation(heatmap): #low_thresh def gaussian_softmax(heatmap): #shiftx = heatmap - np.max(heatmap) shiftx = heatmap ep = 1e-8 exps = np.exp(shiftx) heatmap = exps / (np.sum(exps) + ep) return heatmap def get_gaussian_map(center_x, center_y): feature_map_size = 28 cx = center_x cy = center_y heatmap2 = CenterGaussianHeatMap(feature_map_size, feature_map_size, cx, cy, 1) #heatmap3 = normalize_gaussian(heatmap2) #heatmap3 = gaussian_softmax(heatmap2) plt.imshow(heatmap2) plt.show() return heatmap2 if __name__ == "__main__": center_x = 14 center_y = 14 #center_x = 0 #center_y = 1 a = get_gaussian_map(center_x,center_y) norm = normalize_gaussian(a) #b = gaussian_limit(a, center_x, center_y) softmax = gaussian_softmax(norm) #np.mu ''' image_file = 'test.jpg' img = cv2.imread(image_file) img = cv2.resize(img, (100,100)) img = img[:,:,::-1] img = np.zeros([28,28]) #height, width,_ = np.shape(img) height, width = np.shape(img) cy, cx = height/2.0 - 14, width/2.0 - 10 print 'cy=', cy print 'cx=', cx #start = time.time() #heatmap1 = CenterLabelHeatMap(width, height, cx, cy, 21) #t1 = time.time() - start #start = time.time() heatmap2 = CenterGaussianHeatMap(height, width, cx, cy, 1) #t2 = time.time() - start #print(t1, t2) #plt.subplot(1,2,1) #plt.imshow(heatmap1) #plt.subplot(1,2,2) plt.imshow(heatmap2) plt.show() print('End.') '''
Java
ISO-8859-3
1,823
2.796875
3
[]
no_license
package de.mwvb.teeuhr.service; import java.util.ArrayList; import java.util.List; import javafx.geometry.Bounds; import javafx.stage.Stage; public class Config { public void saveWindowPosition(String name, Stage stage) { if (stage.isIconified()) { // x+y sind versaut return; } String data = stage.getX() + ";" + stage.getY(); if (stage.isResizable()) { data += ";" + stage.getWidth() + ";" + stage.getHeight(); } List<String> arr = new ArrayList<>(); arr.add(data); new DAO().save("WindowPosition-" + name, arr); } public void loadWindowPosition(String name, Stage stage, Bounds allScreenBounds) { List<String> data = new DAO().load("WindowPosition-" + name); if (data.size() > 0 && data.get(0).contains(";")) { String w[] = data.get(0).split(";"); stage.setX(Double.parseDouble(w[0])); stage.setY(Double.parseDouble(w[1])); if (stage.isResizable()) { stage.setWidth(Double.parseDouble(w[2])); stage.setHeight(Double.parseDouble(w[3])); } } if (allScreenBounds != null) { fensterSichtbarAufMonitor(stage, allScreenBounds); } } private void fensterSichtbarAufMonitor(Stage stage, Bounds allScreenBounds) { // Dies ist gerade wichtig beim Wechsel von 2-Monitor (Bro) auf 1-Monitor (HomeOffice/RemoteDesktop). double x = stage.getX(); double y = stage.getY(); double w = stage.getWidth(); double h = stage.getHeight(); if (x < allScreenBounds.getMinX()) { stage.setX(allScreenBounds.getMinX()); } if (x + w > allScreenBounds.getMaxX()) { stage.setX(allScreenBounds.getMaxX() - w); } if (y < allScreenBounds.getMinY()) { stage.setY(allScreenBounds.getMinY()); } if (y + h > allScreenBounds.getMaxY()) { stage.setY(allScreenBounds.getMaxY() - h); } } }
Java
ISO-8859-1
799
2.609375
3
[]
no_license
package me.jonasxpx.meuplugin2.comandos.warps; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.jonasxpx.meuplugin2.managers.Warp; public class SetWarp implements CommandExecutor{ @Override public boolean onCommand(CommandSender sender, Command arg1, String arg2, String[] args) { if(!sender.isOp() || !sender.hasPermission("draco.setwarp")){ sender.sendMessage("c Voc no pode marcar warps"); return true; } if(args.length >= 1){ Warp.makeWarp(((Player)sender).getLocation(), args[0]); sender.sendMessage("6" + args[0] + " Marcada!."); return true; } sender.sendMessage("cUse /setwarp <nome>"); return false; } }
Java
UTF-8
1,125
2.296875
2
[]
no_license
package ir.adicom.app.checkmanagmentapp; /** * Created by adicom on 12/6/16. */ public class Check { private int id; private String price; private String vajhe; private String babat; private String date; public String getBabat() { return babat; } public void setBabat(String babat) { this.babat = babat; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getVajhe() { return vajhe; } public void setVajhe(String vajhe) { this.vajhe = vajhe; } public Check() {} public Check(int id, String price, String vajhe, String babat, String date) { this.id = id; this.price = price; this.vajhe = vajhe; this.babat = babat; this.date = date; } }
Markdown
UTF-8
8,476
2.5625
3
[]
no_license
# 1 简介 <a id=1.1></a> ## 1.1 SMOKE概要 社区已经开发了先进的空气质量模型(air quality models,AQMs),以了解气象、排放源(人为源和生物源)以及污染物在化学和动力学之间的相互作用。来自排放源模型和监管清单的排放源数据是这些空气质量模型最重要的输入文件之一。科学家将空气质量模型用于许多目的:包括州和联邦环境实施计划的制定、改进建模方法的研究、以及近期的空气质量预测。在所有这些应用中,研究趋势都是以更精细的网格分辨率、更完整的排放源和研究对象(例如臭氧、颗粒物、有毒物质),对更大的区域进行建模。而这些需求需要可以高效计算、用户友好且灵活的排放源数据处理系统。 MCNC环境建模中心(Environmental Modeling Center,EMC)创建了稀疏矩阵运算符内核排放(Sparse Matrix Operator Kernel Emissions,SMOKE)模型系统,以使排放源数据的处理方法能够集成高性能计算(high-performance-computing,HPC)的稀疏矩阵算法。SMOKE系统大大增加了城市和区域尺度排放源控制决策的可用资源。它提供了一种为空气质量模型准备输入文件的机制,并使空气质量预测成为可能。北卡罗来纳大学教堂山环境研究所(IE)负责继续发展和完善SMOKE系统。 SMOKE原型发布于1996年,是许多区域尺度空气质量模型中排放源处理的有效工具。1998年和1999年,在EPA的支持下,SMOKE进行了重新设计和改进。第一次SMOKE重新设计的主要目的是支持:(1)使用用户选择的化学机制进行排放源的化学物种分配,详见[第2.11节,化学物种分配](ch02.md#2.11);(2)用于大气化学反应性评估的排放源处理(详见[第2.14.3节,创建反应性控制矩阵](ch02.md#2.14.3))。2002年,SMOKE升级为v1.5版本,以支持驱动MOBILE6模型用于创建道路移动源排放因子,并支持道路移动源和非道路移动源有毒物质清单。2003年,SMOKE发布了v2.0版本,以包括所有有毒物质清单,包括点源和非点源(按县级统计的固定源)。2004年,SMOKE发布了v2.1版本,包括了BEIS3和MOBILE6.2模型的更新,在使用MOBILE6处理道路移动源时可以使用湿度数据,并支持极坐标投影网格。2009年,SMOKE发布v2.6版本,增强了火灾数据的处理,简化了CAMx和UAM模型的处理,并增加了新的方法来处理CEM数据。SMOKE的2.7版支持处理通过SMOKE系统输出的MOVES(Moter Vehicle Emission Simulator,机动车排放模拟器)排放速率对道路移动源和非道路移动源进行建模。从4.0版开始,SMOKE可以处理全球网格化排放清单(例如EDGAR)作为化学传输模型的输入文件,以支持半球尺度的建模。 SMOKE可以处理标准的气态污染物,例如一氧化碳(CO)、氮氧化物(NOx)、挥发性有机物(VOC)、氨(NH<sub>3</sub>)、二氧化硫(SO<sub>2</sub>),颗粒物(PM),如PM<sub>2.5</sub>和PM<sub>10</sub>,以及大量有毒污染物,例如汞、镉、苯和甲醛。实际上,SMOKE对于处理的污染物的数量或类型没有限制。 SMOKE(或任何排放源处理程序)的目的是将排放源清单数据的分辨率转换为空气质量模型所需的分辨率。排放源清单通常提供每个排放源的年度总排放量,或者日均排放量。但是,空气质量模型通常需要每个网格单元(还可能是模型层)以及每个模型物种的每小时的排放数据(有关这些术语的定义,请参见[附录A 术语表](go01.md))。因此,排放源处理的过程就是对排放源清单进行时间分配、化学物种分配和空间分配,以实现空气质量模型的输入需求。 <a id=1.2></a> # 1.2 SMOKE用户 可能的SMOKE用户是需要为以下空气质量模型之一准备排放源输入文件的人: - CMAQ - CAMX - UAM-IV - UAM-V 我们预计典型的SMOKE用户应具有以下经验和需求: 1. 了解排放源清单的人员。 2. 具有UNIX(包括Linux)使用经验的人员。 3. 具有很少或没有排放源模型背景的人员。 4. 稍微熟悉基于网格的空气质量模型及其排放源输入需求的人员。 5. 持有排放源清单的人,需要处理数据以输入到空气质量模型。 6. 想要为空气质量模型的研究或监管工作创建排放源输入数据的EPA人员。 7. 想要为空气质量模型创建排放源输入数据以进行监管工作——包括州实施计划(State Implementation Plans,SIPs)——的州环境人员。 8. 希望使用MOVES和WRF/MM5网格化的每小时气象数据生成道路移动源清单的人。 与必须同时学习UNIX和SMOKE的用户相比,具有UNIX经验的SMOKE用户可以更轻松地运行SMOKE。这是因为运行SMOKE的标准方法是来自UNIX脚本。 <a id=1.3></a> # 1.3 如何使用本手册 本文档是SMOKE最完整的参考资料。它可以从[CMAS中心]( https://www.cmascenter.org/ )以一组HTML页面或PDF文档的形式获得。 以下是用户对本手册的典型需求,以及可满足这些需求的可用资源。 - **安装SMOKE:** 安装说明可在[第12章,下载,安装和编译SMOKE](ch12.md)中找到。要注册和下载SMOKE,请访问[CMAS模型信息交换所]( https://www.cmascenter.org/smoke/ )。 - **编译SMOKE:**[第12.4节,为UNIX编译SMOKE](ch12.md#12.4)提供了有关为CMAS中心支持的默认平台以外的平台编译SMOKE的说明。 - **运行SMOKE测试案例:**[第4.3节,运行SMOKE测试案例](ch04.md#4.3)提供了与SMOKE一同发布的有关测试案例运行的说明。 - **设置新的清单、网格、时段等并运行SMOKE:**[第4.4节,如何使用SMOKE](ch04.md#4.4)中说明了用户应如何针对自己的情况设置SMOKE。CMAS中心的[SMOKE培训课堂]( https://www.cmascenter.org/training/classes.cfm )涵盖了这些主题的详细内容。 - **准备输入文件:** 大多数SMOKE输入文件都是ASCII文件,可以使用数据库程序或其他工具来准备。有关所有输入文件格式的说明,请参见[第8章,SMOKE输入文件](ch08.md)。用户可以从EPA网站,例如[清单和排放因子信息交换所(CHIEF)]( https://www.epa.gov/chief )获得输入文件(可能不是SMOKE的输入文件格式)。 - **如何设置运行脚本:** 在[第4章,如何使用SMOKE](ch04.md)中,我们介绍了SMOKE脚本以及如何使用它们。设置是通过环境变量分配的,在[第2.2节,分配文件和环境变量](ch02.md#2.2)中对环境变量进行了概述。[第4.2.4节,脚本设置](ch04.md#4.2.4)中描述了用于控制脚本(而不是程序)的设置。在[第5章,SMOKE实用工具](ch05.md)、[第6章,SMOKE核心程序](ch06.md)和[第7章,SMOKE质量控制](ch07.md)中进一步说明了由SMOKE程序读取并直接影响其行为的设置。 - **检查SMOKE是否正常运行:**[第7.5节,质量控制方法](ch07.md#7.5)中包含了有关如何验证SMOKE已正常运行的步骤。本章还包括有关运行SMOKE的质量控制(quality assurance,QA)功能的说明,以及配置不同类型的质量控制报告文件([第7.3节,REPCONFIG输入文件](ch07.md#7.3))。 - **了解SMOKE正在执行的操作:**[第5章,SMOKE实用工具](ch05.md)、[第6章,SMOKE核心程序](ch06.md)和[第7章,SMOKE质量控制](ch07.md)为每个SMOKE程序提供了相关的技术文档。我们一直在努力完善此文档,用户可以通过[CMAS中心服务台]( https://www.cmascenter.org/help-desk.cfm )提出建议。 - **提交有关SMOKE的问题报告或疑问:** 有关SMOKE和其他Models-3组件的所有问题均应通过[CMAS中心服务台]( https://www.cmascenter.org/help-desk.cfm )提交。 尽管[第11章,源代码和Include文件](ch11.md)中提供了一些信息,但本手册并未提供有关代码本身的大量技术文档。程序代码具有大量的内置注释说明,以帮助精通Fortran的用户了解其工作原理。我们希望将来能够完善[第11章,源代码和Include文件](ch11.md)中的文档,但不确定是否必要,迄今为止也尚未获得完善此类文档的资源。 ------------------------------------------------------------------------ [返回](README.md)>>>>>[下一章](ch02.md)
Markdown
UTF-8
821
2.640625
3
[]
no_license
# Submissão de Exercicio **Exercicio:** 4 - Cifra de César **Nickname:** Clerijr **Nível Técnico:** Estudante **Twitter**: https://twitter.com/clerijr **Dificuldade de Resolução:** Média **Gostaria ainda de adicionar:** Um exercício muito bom, que acredito que existam diversas outras formas de realizá-lo. Utilizei uma estrutura de if para dar a impressão de ciclar apenas pelo alfabeto, porém também converterá demais caracteres ascii. Qualquer sinalização de bugs ou alterações recomendadas são muito bem vindas. Devido ao input com o número de posições, achei desnecessário colocar uma opção para sair no final do código. **Como rodar o desafio**: Use o comando abaixo: ```bash python main.py; digitar o numero de casos, digitar a cifra desejada, digitar o número de posições ```
JavaScript
UTF-8
2,614
2.515625
3
[]
no_license
import React, { Component } from "react"; import api from "../../../api/api_board"; import { Link } from "react-router-dom"; import Container from "@material-ui/core/Container"; import Paper from "@material-ui/core/Paper"; class RecruitUpdate extends Component { state = { title: "", body: "", purpose: "" }; componentDidMount() { console.log("Detail ComponentDidMount"); this.getRecruit(); } async getRecruit() { await api .getPost("recruit", this.props.match.params.id) .then(res => { const data = res.data; this.setState({ title: data.title, body: data.body, id: data.id, purpose: data.purpose }); }) .catch(err => console.log(err)); } async updateRecruit(id, data) { await api .updatePost("recruit", id, data) .then(result => console.log("정상적으로 update됨.", result)) .catch(err => console.log(err)); } handlingChange = event => { this.setState({ [event.target.name]: event.target.value }); }; handlingSubmit = async event => { event.preventDefault(); //event의 디폴트 기능(새로고침 되는 것 등..) -> 막는다. this.updateRecruit(this.props.match.params.id, { title: this.state.title, body: this.state.body, purpose: this.state.purpose }); this.setState({ title: "", content: "", purpose: "" }); // this.getPosts() document.location.href = "/recruit"; }; render() { return ( <Container maxWidth="lg" className="PostingSection"> <Paper className="PostingPaper"> <h2>Update Recruit</h2> <form onSubmit={this.handlingSubmit} className="PostingForm"> <input id="title" name="title" value={this.state.title} onChange={this.handlingChange} required="required" placeholder="Title" /> <input id="body" name="body" value={this.state.body} onChange={this.handlingChange} required="required" placeholder="Content" /> <input name="purpose" value={this.state.purpose} onChange={this.handlingChange} required="required" placeholder="purpose" /> <button type="submit">제출</button> </form> <Link to="/recruit">Cancel</Link> </Paper> </Container> ); } } export default RecruitUpdate;
Markdown
UTF-8
1,911
2.921875
3
[ "MIT" ]
permissive
# OngairRuby Ruby gem for using Ongair to to interact with WhatsApp; send messages, send media, add contacts, create groups, create lists, send broadcasts and many more. ## Installation Add this line to your application's Gemfile: gem 'ongair_ruby' And then execute: $ bundle Or install it yourself as: $ gem install ongair_ruby Get the Ongair API key by signing up here: http://app.ongair.im ## Usage client = OngairRuby::ClientV2.new("YOUR_ONGAIR_API_KEY") # Add a contact client.create_contact("Name of contact", "254711223344") # Send a message client.send_message("254711223344", "Hello") # Send an image client.send_image("254722123456", "http://domain.com/image.jpg") ## Coming soon # List of contacts client.contacts # Create a WhatsApp group client.create_group("group_name", "group_type", "group_jid") # List of groups client.groups # Create a distribution list client.create_list("list_name", "list_description") # List of distribution lists client.lists # Add contact to a distribution list client.add_list_member(list_id, contact_id) # List of distribution list members client.list_members(list_id) # remove contact from a distribution list client.remove_list_member(list_id, contact_id) # send broadcasts to a distribution list client.send_broadcast(list_id, "Hello everyone") ## Contributing 1. Fork it ( https://github.com/[my-github-username]/ongair_ruby/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request
Java
UTF-8
1,332
2.1875
2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package em.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import em.domain.Jgpush; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class JgpushSvc { private Logger _log = Logger.getLogger(SmsSvc.class); @Autowired private RdbSvc rdbSvc; /** * 保存或修改信息 * @param jp * @return */ public Jgpush save(Jgpush jp){ try{ rdbSvc.save(jp); _log.info("12312312312"); }catch(Exception ee){ ee.printStackTrace(); } return jp; } /** * 根据id查询极光信息 * @param id * @return */ public Jgpush findJgpushById(Integer id){ String findsql = " from Jgpush jp where jp.id=:id "; Map<String,String> param = new HashMap<String,String>(); Jgpush jp = null; try{ jp = (Jgpush)rdbSvc.findObject(findsql,param); }catch(Exception ee){ ee.printStackTrace(); } return jp; } /** * 查询列表信息 * @param wheresql * @return */ public List<?> findJgpushs(String wheresql){ String findsql = " from Jgpush jp where 1=1 "; List<?> jlist = new ArrayList(); try{ jlist = rdbSvc.findList(findsql, null); }catch(Exception ee){ ee.printStackTrace(); } return jlist; } }
PHP
UTF-8
788
2.5625
3
[]
no_license
<html> <head> <title>Data Download</title> </head> <body> <h2 align="center">Data Download</h2> <a href="form_upload.php">Upload File</a> <table align="center" border="1px"; width="800px" > <tr> <th>No</th> <th>Nama File</th> <th>Tanggal</th> <th>Tipe File</th> <th>Ukuran</th> <th>Aksi</th> </tr> <?php include "koneksi.php"; $i=0; $tampil=mysqli_query($koneksi,"SELECT * FROM t_upload"); while($data=mysqli_fetch_array($tampil)){ $i++; ?> <tr> <td><?php echo"$i"; ?></td> <td><?php echo"$data[nama_file]"; ?></td> <td><?php echo"$data[tanggal]"; ?></td> <td><?php echo"$data[type]"; ?></td> <td><?php echo"$data[size]"; ?></td> <td><a href="upload/<?php echo"$data[file]"; ?>">Download</a></td> </tr> <?php }?> </table> </body> </html>
PHP
UTF-8
7,186
2.984375
3
[]
no_license
<?php namespace ryunosuke\Functions\Package; // @codeCoverageIgnoreStart require_once __DIR__ . '/../utility/function_configure.php'; // @codeCoverageIgnoreEnd /** * 変数をリソースのように扱えるファイルポインタを返す * * 得られたファイルポインタに fread すれば変数の値が見えるし、 fwrite すれば変数の値が書き換わる。 * 逆に変数を書き換えればファイルポインタで得られる値も書き換わる。 * * 用途は主にテスト用。 * 例えば「何らかのファイルポインタを要求する処理」に対して fopen や tmpfile を駆使して値の確認をするのは結構めんどくさい。 * (`rewind` したり `stream_get_contents` したり削除したりする必要がある)。 * それよりもこの関数で得られたファイルポインタを渡し、 `that($var)->is($expected)` とできる方がテストの視認性が良くなる。 * * Example: * ```php * // $var のファイルポインタを取得 * $fp = var_stream($var); * // ファイルポインタに書き込みを行うと変数にも反映される * fwrite($fp, 'hoge'); * that($var)->is('hoge'); * // 変数に追記を行うとファイルポインタで読み取れる * $var .= 'fuga'; * that(fread($fp, 1024))->is('fuga'); * // 変数をまるっと置換するとファイルポインタ側もまるっと変わる * $var = 'hello, world'; * that(stream_get_contents($fp, -1, 0))->is('hello, world'); * // ファイルポインタをゴリっと削除すると変数も空になる * ftruncate($fp, 0); * that($var)->is(''); * ``` * * @package ryunosuke\Functions\Package\stream * * @param string|null $var 対象の変数 * @param string $initial 初期値。与えたときのみ初期化される * @return resource 変数のファイルポインタ */ function var_stream(&$var, $initial = '') { static $STREAM_NAME, $stream_class, $registered = false; if (!$registered) { $STREAM_NAME = $STREAM_NAME ?: function_configure('var_stream'); if (in_array($STREAM_NAME, stream_get_wrappers())) { throw new \DomainException("$STREAM_NAME is registered already."); } $registered = true; stream_wrapper_register($STREAM_NAME, $stream_class = get_class(new class() { private static $ids = 0; private static $entries = []; private $id; private $entry; private $position; public static function create(string &$var): int { self::$entries[++self::$ids] = &$var; return self::$ids; } public function stream_open(string $path, string $mode, int $options, &$opened_path): bool { assert([$mode, $options, &$opened_path]); $this->id = parse_url($path, PHP_URL_HOST); $this->entry = &self::$entries[$this->id]; $this->position = 0; return true; } public function stream_close() { unset(self::$entries[$this->id]); } public function stream_lock(int $operation): bool { assert(is_int($operation)); // 競合しないので常に true を返す return true; } public function stream_flush(): bool { // バッファしないので常に true を返す return true; } public function stream_eof(): bool { // 変数の書き換えを検知する術はないので eof は殺しておく return false; } public function stream_read(int $count): string { $result = substr($this->entry, $this->position, $count); $this->position += strlen($result); return $result; } public function stream_write(string $data): int { $datalen = strlen($data); $posision = $this->position; // 一般的に、ファイルの終端より先の位置に移動することも許されています。 // そこにデータを書き込んだ場合、ファイルの終端からシーク位置までの範囲を読み込むと 値 0 が埋められたバイトを返します。 $current = str_pad($this->entry, $posision, "\0", STR_PAD_RIGHT); $this->entry = substr_replace($current, $data, $posision, $datalen); $this->position += $datalen; return $datalen; } public function stream_truncate(int $new_size): bool { $current = substr($this->entry, 0, $new_size); $this->entry = str_pad($current, $new_size, "\0", STR_PAD_RIGHT); return true; } public function stream_tell(): int { return $this->position; } public function stream_seek(int $offset, int $whence = SEEK_SET): bool { $strlen = strlen($this->entry); switch ($whence) { case SEEK_SET: if ($offset < 0) { return false; } $this->position = $offset; break; // stream_tell を定義していると SEEK_CUR が呼ばれない?(計算されて SEEK_SET に移譲されているような気がする) // @codeCoverageIgnoreStart case SEEK_CUR: $this->position += $offset; break; // @codeCoverageIgnoreEnd case SEEK_END: $this->position = $strlen + $offset; break; } // ファイルの終端から数えた位置に移動するには、負の値を offset に渡して whence を SEEK_END に設定しなければなりません。 if ($this->position < 0) { $this->position = $strlen + $this->position; if ($this->position < 0) { $this->position = 0; return false; } } return true; } public function stream_stat() { $size = strlen($this->entry); return [ 7 => $size, 'size' => $size, ]; } })); } if (func_num_args() > 1) { $var = $initial; } // タイプヒントによる文字列化とキャストによる文字列化は動作が異なるので、この段階で早めに文字列化しておく $var = (string) $var; return fopen($STREAM_NAME . '://' . $stream_class::create($var), 'r+b'); }
Java
UTF-8
7,159
1.828125
2
[]
no_license
package com.anning423.mibandapp.device; import android.app.Activity; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.anning423.mibandapp.R; import com.anning423.mibandapp.antilost.AntiLostService; import com.zhaoxiaodan.miband.ActionCallback; import com.zhaoxiaodan.miband.model.VibrationMode; public class DeviceFragment extends Fragment { private static final int REQUEST_SCAN = 100; private BleService.BleBinder mBinder; private View vScanDevice; private View vDisconnect; private View vVibrateOnce; private TextView vReadRssi; private TextView vReadBattery; private View vStartAntiLost; private View vStopAntiLost; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_device, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); vScanDevice = view.findViewById(R.id.vScanDevice); vScanDevice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), ScanActivity.class); startActivityForResult(intent, REQUEST_SCAN); } }); vDisconnect = view.findViewById(R.id.vDisconnect); vDisconnect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBinder.disconnect(); } }); vReadRssi = (TextView) view.findViewById(R.id.vReadRssi); vReadRssi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBinder.getMiband().readRssi(new ActionCallback() { @Override public void onSuccess(Object data) { vReadRssi.setText("rssi: " + data); } @Override public void onFail(int errorCode, String msg) { vReadRssi.setText("rssi: " + msg); } }); } }); vReadBattery = (TextView) view.findViewById(R.id.vReadBattery); vReadBattery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBinder.getMiband().getBatteryInfo(new ActionCallback() { @Override public void onSuccess(Object data) { vReadBattery.setText("battery: " + data); } @Override public void onFail(int errorCode, String msg) { vReadBattery.setText("battery: " + msg); } }); } }); vVibrateOnce = view.findViewById(R.id.vVibrateOnce); vVibrateOnce.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBinder.getMiband().startVibration(VibrationMode.VIBRATION_WITH_LED); } }); vStartAntiLost = view.findViewById(R.id.vStartAntiLost); vStartAntiLost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = getActivity(); Intent intent = new Intent(context, AntiLostService.class); context.startService(intent); updateViews(); } }); vStopAntiLost = view.findViewById(R.id.vStopAntiLost); vStopAntiLost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = getActivity(); Intent intent = new Intent(context, AntiLostService.class); context.stopService(intent); updateViews(); } }); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Context context = getActivity(); Intent intent = new Intent(context, BleService.class); context.bindService(intent, mConn, Context.BIND_AUTO_CREATE); IntentFilter filter = new IntentFilter(); filter.addAction(BleService.ACTION_STATE_CHANGED); context.registerReceiver(mReceiver, filter); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_SCAN && resultCode == Activity.RESULT_OK) { BluetoothDevice device = data.getParcelableExtra(ScanActivity.EXTRA_DEVICE); if (mBinder != null) { mBinder.connect(device); } } } @Override public void onDestroyView() { super.onDestroyView(); Context context = getActivity(); context.unbindService(mConn); context.unregisterReceiver(mReceiver); } private void updateViews() { int state = mBinder == null ? -1 : mBinder.getState(); boolean antiLostStarted = AntiLostService.isStarted(); vScanDevice.setEnabled(state == BleService.STATE_IDLE); vDisconnect.setEnabled(state != BleService.STATE_IDLE); vReadRssi.setEnabled(state == BleService.STATE_DISCOVERED); vReadBattery.setEnabled(state == BleService.STATE_DISCOVERED); vVibrateOnce.setEnabled(state == BleService.STATE_DISCOVERED); vStartAntiLost.setEnabled(state != BleService.STATE_IDLE && !antiLostStarted); vStopAntiLost.setEnabled(antiLostStarted); } private ServiceConnection mConn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mBinder = (BleService.BleBinder) service; updateViews(); } @Override public void onServiceDisconnected(ComponentName name) { mBinder = null; updateViews(); } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BleService.ACTION_STATE_CHANGED.equals(action)) { updateViews(); } } }; }
C#
UTF-8
2,968
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using DataLibrary.DTO; namespace DataLibrary.DAO { public class ThuViecDAO { TuyenDungModels db = new TuyenDungModels(); private ThuViecDAO() { } private static ThuViecDAO instance; public static ThuViecDAO Instance { get { if (instance == null) { instance = new ThuViecDAO(); } return instance; } } public List<tbl_ThuViec> GetAllData() { try { List<tbl_ThuViec> list = db.tbl_ThuViec.ToList<tbl_ThuViec>(); return list; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } } public tbl_ThuViec GetOneData(int id) { try { tbl_ThuViec data = db.tbl_ThuViec.Find(id); return data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } } public tbl_ThuViec GetOneDataByNVID(int id) { try { tbl_ThuViec data = db.tbl_ThuViec.Find(new tbl_ThuViec(){ NhanVienID = id }); return data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } } public tbl_ThuViec AddData(tbl_ThuViec data) { try { tbl_ThuViec d = db.tbl_ThuViec.Add(data); db.SaveChanges(); return d; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } } public int UpdateData(tbl_ThuViec data) { try { var update = db.tbl_ThuViec.Find(data.ThuViecID); update.copy(data); db.SaveChanges(); return 1; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return 0; } } public int DeleteData(int id) { try { tbl_ThuViec tb = db.tbl_ThuViec.Find(id); db.tbl_ThuViec.Remove(tb); db.SaveChanges(); return 1; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return -1; } } } }
Markdown
UTF-8
575
3.421875
3
[]
no_license
# predict-age-after-100-years predict age after 100 years and an input year using python Your Age In 2090 Take age or year or birth as an input from the user and tell them when they will turn 100 years old.(5 points) Don’t use any type of module like datetime or dateutils(-5 points). They can then optionally provide a year and your program must tell their age in that particular year. (3 points) You should be handling all sorts of errors like (2 points): You are not yet born You seem to be the oldest person alive You can also handle any other error if possible!
Java
UTF-8
5,914
2.375
2
[]
no_license
package com.example.yash.registerlogin; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DatabaseHelper extends SQLiteOpenHelper{ public static final String DATABASE_NAME = "StudentList.db"; public static final String TABLE_NAME = "student_table"; public static final String COL_1 = "batch"; public static final String COL_2 = "eno"; public static final String COL_3 = "name"; public static final String TABLE_NAME1 = "attendance_table"; public static final String COL_4 = "date"; public static final String COL_5 = "time"; public static final String COL_6 = "eno"; public static final String COL_7 = "status"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME + "(batch String ,eno String Primary Key,name String )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME); // onCreate(db); } public void insertdata(String batch, String enno, String name) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_1, batch); contentValues.put(COL_2, enno); contentValues.put(COL_3, name); final Cursor cursor = db.rawQuery("SELECT eno FROM student_table ", null); // if (cursor.getCount() == 0) { // System.out.println("Hii" + cursor.getCount()); db.insert(TABLE_NAME, null, contentValues); // cursor.close(); //} } public Cursor getInformation() { System.out.println("I am starting!!!!"); SQLiteDatabase db = this.getWritableDatabase(); System.out.println(db); final Cursor c = db.rawQuery("SELECT eno FROM " + TABLE_NAME , null); if(c != null) System.out.println("I am not here!!!!" + "JJJJJ" + c.getCount()); return c; } public Cursor getNames() { System.out.println("I am starting!!!!"); SQLiteDatabase db = this.getWritableDatabase(); System.out.println(db); final Cursor c = db.rawQuery("SELECT name FROM " + TABLE_NAME , null); if(c != null) System.out.println("I am not here!!!!" + "JJJJJ" + c.getCount()); return c; } public Cursor getStatus(String enno){ SQLiteDatabase db = this.getWritableDatabase(); Date now = new Date(); String dateis = new SimpleDateFormat("ddMMyyyy").format(now); String temptable=TABLE_NAME1 + dateis; Cursor cr = db.rawQuery("SELECT status FROM " + temptable + " where eno = '" + enno + "'", null); // System.out.println(cr.getCount()); // if( cr != null) return cr; // return null; } public void onAttendanceInsert(String enno,String status){ SQLiteDatabase db = this.getWritableDatabase(); Date now = new Date(); String dateis = new SimpleDateFormat("ddMMyyyy").format(now); String temptable=TABLE_NAME1 + dateis; final Cursor cr1 = db.rawQuery("SELECT eno FROM " + temptable + " where eno = '" + enno + "'", null); System.out.println(cr1.getCount()); if(cr1.getCount() != 0){ ContentValues values = new ContentValues(); values.put(COL_7, status); db.update(temptable, values, COL_6+"="+enno, null); System.out.println("I am yes"); } else{ ContentValues contentValues = new ContentValues(); Date now1 = new Date(); String date = new SimpleDateFormat("dd-MM-yyyy").format(now1); /* Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00")); Date currentLocalTime = cal.getTime(); DateFormat date12 = new SimpleDateFormat("HH:mm a"); date12.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); String localTime = date.format(String.valueOf(currentLocalTime));*/ Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR); // long localTime= System.currentTimeMillis(); contentValues.put(COL_4, date); contentValues.put(COL_5,hour); contentValues.put(COL_6, enno); contentValues.put(COL_7,status); db.insert(temptable, null, contentValues); } } public void createTable(){ SQLiteDatabase db = this.getWritableDatabase(); Date now = new Date(); String date = new SimpleDateFormat("ddMMyyyy").format(now); String temp=TABLE_NAME1 + date; Cursor f = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name ='" + temp +"'",null); if(f.getCount() == 0) { db.execSQL("create table " + temp + "(date Date ,time DateTime,eno String Primary Key,status string)"); System.out.println("Table Created"); } else { System.out.println("Table Not Created"); } } public Cursor getList() { System.out.println("I am starting!!!!"); SQLiteDatabase db = this.getWritableDatabase(); System.out.println(db); final Cursor c = db.rawQuery("SELECT name FROM " + TABLE_NAME , null); if(c != null) System.out.println("I am not here!!!!" + "JJJJJ" + c.getCount()); return c; } }
Swift
UTF-8
718
2.796875
3
[]
no_license
// // TaskModel.swift // todoloc WatchKit Extension // // Created by Jean-Christophe MELIKIAN on 20/01/2018. // Copyright © 2018 Nico. All rights reserved. // import Foundation public class TaskModel: Codable { var id: String = "" var name: String = "" var detail: String = "" var finished: Bool = false init(name: String) { self.name = name } init(name: String, detail: String, completed: Bool) { self.name = name self.detail = detail self.finished = completed } init(entity: Task) { self.id = (entity.id?.uuidString)! self.name = entity.name! self.detail = entity.detail! self.finished = entity.finished } }
TypeScript
UTF-8
1,351
2.921875
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
import {lazy, ILazyParams, ILazyComponent} from './lazy'; const wait = (loader, delay) => new Promise((resolve) => setTimeout(() => resolve(loader()), delay) ); const RIC = (window as any).requestIdleCallback || ((callback) => setTimeout(callback, 300)); const PRIC = (loader) => new Promise((resolve) => RIC(() => resolve(loader()))); const RAF = requestAnimationFrame; const PRAF = (value) => new Promise((resolve) => RAF(() => resolve(value))); export interface IDelayedParams<TProps> extends ILazyParams<TProps> { delay?: number; draf?: boolean; idle?: boolean; } export type TDelayed = <TProps>(params: IDelayedParams<TProps>) => ILazyComponent<TProps>; export const delayed: TDelayed = <TProps>(params: IDelayedParams<TProps>) => { let { delay, draf, idle } = params; if (delay) { const loader = params.loader; params.loader = () => wait(loader, delay) as Promise<React.ComponentClass<any> | React.StatelessComponent<any>>; } if (idle) { const loader = params.loader; params.loader = () => PRIC(loader) as Promise<React.ComponentClass<any> | React.StatelessComponent<any>>; } if (draf) { const loader = params.loader; params.loader = () => loader().then(PRAF).then(PRAF) as Promise<React.ComponentClass<any> | React.StatelessComponent<any>>; } return lazy(params); };
JavaScript
UTF-8
2,543
2.75
3
[]
no_license
import {GET_STUDENT_WITH_BRANCH_FAIL,GET_STUDENT_WITH_BRANCH_SUCCESS, GET_STUDENT_FAIL,GET_STUDENT,GET_SINGLE_STUDENT, SET_ATTENDANCE,SET_ATTENDANCE_FAIL,SORT_STUDENT_BY_BRANCH,SORT_STUDENT_FAIL_BRANCH, SEARCH_STUDENT,SEARCH_STUDENT_FAIL,SEARCH_STUDENT_FAIL_BRANCH, SEARCH_STUDENT_BY_BRANCH} from "./../actions/types"; const initState={ classStudent:[], student:[], singleStudent:{}, search:[], error:[], count:0, loading:true, isAscending:false } export default function(state=initState,action){ switch(action.type){ case GET_STUDENT_WITH_BRANCH_SUCCESS: return{ ...state, classStudent:action.payload, loading:false } case GET_STUDENT: return{ ...state, student:action.payload, count:action.payload.length, avg:action.payload.reduce((tot,student)=> tot+(student.total/action.payload.length),0).toFixed(2), loading:false } case GET_SINGLE_STUDENT: return{ ...state, singleStudent:action.payload, loading:false } case SET_ATTENDANCE: return{ ...state, classStudent:state.classStudent.map(student=>student._id==action.payload._id?action.payload:student), loading:false } case SEARCH_STUDENT: return{ ...state, search:action.payload, loading:false } case SEARCH_STUDENT_BY_BRANCH: return{ ...state, search:state.classStudent.filter(st=>st.name.toLowerCase().includes(action.payload)), loading:false } case SORT_STUDENT_BY_BRANCH: let compare="" if(!state.isAscending) compare=(a,b)=>a.name < b.name? -1:(a.name > b.name?1:0) else{ compare=(a,b)=>a.name < b.name? 1:(a.name > b.name?-1:0) } return{ ...state, classStudent: state.classStudent.sort(compare), isAscending:!state.isAscending } case GET_STUDENT_WITH_BRANCH_FAIL: case SEARCH_STUDENT_FAIL_BRANCH: case GET_STUDENT_FAIL: case SET_ATTENDANCE_FAIL: case SEARCH_STUDENT_FAIL: case SORT_STUDENT_FAIL_BRANCH: return{ ...state, error:action.payload, loading:false } default: return state } }
Rust
UTF-8
2,733
3.265625
3
[]
no_license
use crate::projects_and_tasks::{ list_with_names::ListWithNames, project::{Project, ProjectWithTasks}, project_error::ProjectError, task::Task, }; #[derive(Debug, PartialEq)] pub struct Projects { projects: Vec<ProjectWithTasks>, } impl ListWithNames<ProjectWithTasks> for Projects { fn items(&self) -> std::slice::Iter<ProjectWithTasks> { self.projects.iter() } } impl Projects { pub fn get_project_with_task( &self, project_string: &str, task_string: &str, ) -> Result<(Project, Task), ProjectError> { let project_with_tasks = self.find(project_string).map_err(ProjectError::Project)?; let project = Project::new(project_with_tasks); let task = project_with_tasks.find_task(task_string)?; Ok((project, task.clone())) } } #[cfg(test)] mod tests { use super::*; use crate::projects_and_tasks::{ project::ProjectWithTasksBuilder, task::TaskBuilder, tasks::TasksBuilder, }; #[test] fn it_finds_project_and_task() { let task_to_be_found = TaskBuilder::new() .with_name("Some special task I want to find".to_string()) .build(); let project_to_be_found = ProjectWithTasksBuilder::new() .with_name("Some specific Project I want to find".to_string()) .with_tasks( TasksBuilder::new() .with_tasks(vec![ TaskBuilder::new() .with_name("Another task".to_string()) .build(), task_to_be_found.clone(), ]) .build(), ) .build(); let projects = ProjectsBuilder::new() .with_projects(vec![ ProjectWithTasksBuilder::new() .with_name("Another project".to_string()) .build(), project_to_be_found.clone(), ]) .build(); let (project, task) = projects .get_project_with_task("specific project", "special task") .unwrap(); assert_eq!(project, Project::new(&project_to_be_found)); assert_eq!(task, task_to_be_found); } } pub struct ProjectsBuilder { projects: Vec<ProjectWithTasks>, } impl ProjectsBuilder { pub fn new() -> Self { Self::empty() } pub fn empty() -> Self { Self { projects: vec![] } } pub fn with_projects(mut self, projects: Vec<ProjectWithTasks>) -> Self { self.projects = projects; self } pub fn build(self) -> Projects { Projects { projects: self.projects, } } }
C++
UTF-8
1,542
3.46875
3
[]
no_license
// vegnews.cpp -- using new and delete with classes // compile with strngbad.cpp #include <iostream> using std::cout; #include "string1.h" void callme1(String &); // pass by reference void callme2(String); // pass by value int main() { using std::endl; { cout << "Starting an inner block.\n"; String headline1("Celery Stalks at Midnight"); String headline2("Lettuce Prey"); String headline3 = headline2; String sports("Spinach Leaves Bowl for Dollars"); cout << "headline1: " << headline1 << endl; cout << "headline2: " << headline2 << endl; cout << "sports: " << sports << endl; callme1(headline1); // pass by reference cout << "headline1: " << headline1 << endl; callme2(headline2); // pass by value cout << "headline2: " << headline2 << endl; cout << "Initialize one object to another:\n"; String sailor = sports; cout << "sailor: " << sailor << endl; cout << "Assign one object to another:\n"; String knot; knot = headline1; cout << "knot: " << knot << endl; cout << "Exiting the block.\n"; } cout << "End of main()\n"; // std::cin.get(); return 0; } void callme1(String & rsb) { cout << "String passed by reference:\n"; cout << " \"" << rsb << "\"\n"; } void callme2(String sb) { cout << "String passed by value:\n"; cout << " \"" << sb << "\"\n"; }
Markdown
UTF-8
1,495
3.125
3
[]
no_license
# React Google Maps Example I created this little web app in order to learn react and google map API. It provides a query box and and then calls the Places Library for Google Maps. Results are formatted to give a good user experience. The app includes: 1. A map with location markers/pins 2. A list of locations, the first location gets centered by default 3. If the user clicks on any of the location, the map will be centered by the new location. ### Installing Simply run this in your command line tool ``` npm install ``` And run this to start the application ``` npm run start ``` ## Features 1. query box that can search for any locations as you type in ![Alt text](/screenshots/home.png?raw=true "Home Page") 2. responsive map, refined UI to give good user experience with locations ![Alt text](/screenshots/locations.png?raw=true "searching locations") 3. interactivity between location you searched and the map 4. one page app with routes ## Technology React (^15.6.1), React Router Dom (^4.1.2), Sass, Gulp (^3.9.1), Google Map Web API ## Built With * [React](https://facebook.github.io/react/) - The web framework used * [Sass](http://sass-lang.com/) - css extension language * [Gulp](https://gulpjs.com/) - A toolkit for automating tasks in web development * [Location Library for Google Map](https://developers.google.com/maps/documentation/javascript/places) - The API provided by Google ## Authors * **Chang Meng** - *creater* - (https://github.com/mercyme)
Java
UTF-8
2,216
2.546875
3
[]
no_license
package com.psi_stud.arturas.ggdb; import android.os.StrictMode; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.LinkedList; /** * Created by Arturas on 2015-12-16. */ public class Game { private int gameID; private String name; private String rating; private String description; public Game(int gameID){ this.gameID = gameID; } public Game(int gameID, String name){ this.gameID = gameID; this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGameID() { return gameID; } public void loadGame(){ String hostIP = "192.168.43.52"; String port = "49170"; Connection con = null; Statement stat = null; ResultSet rs = null; try { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance(); String ConnectionString = "jdbc:jtds:sqlserver://" + hostIP + ":" + port + "/GGDB;user=admin;password=troll;"; //>><<AB001 con = DriverManager.getConnection(ConnectionString, "admin", "troll"); stat = con.createStatement(); String queryString = "select * from dbo.Games where ID = "+gameID+";"; rs = stat.executeQuery(queryString); while (rs.next()) { name = rs.getString(2); description = rs.getString(6); } con.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } @Override public String toString() { return name; } }
Java
UTF-8
279
1.859375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author shital */ import java.awt.*; import javax.swing.*; public class hell extends JApplet{ Label l = new Label("heelo this is me your shital"); }
SQL
UTF-8
3,385
3.515625
4
[]
no_license
set serveroutput on; set verify off; -- QUESTION 2a create or replace procedure generate_multiplication_table_for (usr_input number) as small_buff varchar(10); large_buff varchar(20); begin if (usr_input < 1 OR usr_input > 10) then dbms_output.put_line('Please enter a value between 1 and 10.'); return; end if; for j in 1..usr_input loop small_buff := ' '; large_buff := ' '; for i in 1..usr_input loop if (i = 0 AND j > 0) then if (j > 9) then dbms_output.put(j || small_buff); elsif (j < 10) then dbms_output.put(j || large_buff); end if; elsif (j = 0 AND i > 0) then if (i > 9) then dbms_output.put(i || small_buff); elsif (i < 10) then dbms_output.put(i || large_buff); end if; elsif (i > 0 AND j > 0) then if (i*j > 9) then dbms_output.put(i*j || small_buff); elsif (i*j < 10) then dbms_output.put(i*j || large_buff); end if; end if; end loop; dbms_output.put_line(''); end loop; end; / begin generate_multiplication_table_for(10); end; / -- QUESTION 2c CREATE OR REPLACE PROCEDURE generate_multiplication_table_simple ( usr_input IN NUMBER ) AS count1 NUMBER; count2 NUMBER; BEGIN count1 := 1; IF usr_input < 1 OR usr_input > 10 THEN dbms_output.put_line('Please enter a value between 1 and 10.'); ELSE LOOP count2 := 1; LOOP IF count2 = usr_input THEN dbms_output.put_line(count1 * count2); ELSE dbms_output.put(rpad(count1 * count2, 5)); END IF; count2 := count2 + 1; EXIT WHEN count2 > usr_input; END LOOP; count1 := count1 + 1; EXIT WHEN count1 > usr_input; END LOOP; END IF; END; / begin generate_multiplication_table_simple(10); end; /* QUESTION 2a Procedure GENERATE_MULTIPLICATION_TABLE_FOR compiled 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 PL/SQL procedure successfully completed. QUESTION 2c Procedure GENERATE_MULTIPLICATION_TABLE_SIMPLE compiled 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 8 16 24 32 40 48 56 64 72 80 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 PL/SQL procedure successfully completed. */
Java
UTF-8
41,919
1.625
2
[ "MIT" ]
permissive
/* * The MIT License (MIT) * * Copyright (c) 2017 by Norman Fomferra (https://github.com/forman) and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dedopfx.ui; import com.sun.javafx.geom.Rectangle; import dedopfx.algo.Algorithm; import dedopfx.algo.AlgorithmInputs; import dedopfx.audio.*; import dedopfx.store.PreferencesStore; import dedopfx.store.PropertiesStore; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.binding.DoubleBinding; import javafx.beans.property.BooleanProperty; import javafx.beans.property.DoubleProperty; import javafx.beans.property.IntegerProperty; import javafx.beans.property.Property; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.concurrent.Worker; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.image.*; import javafx.scene.input.KeyCombination; import javafx.scene.layout.*; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import java.util.stream.Collectors; import java.util.stream.IntStream; public class App extends Application { public static String NAME = "DeDop FX"; public static String VERSION = "0.1"; public static final String DOC_FILE_EXTENSION = ".ddfx"; public static final FileChooser.ExtensionFilter DOC_EXTENSION_FILTER = new FileChooser.ExtensionFilter("DeDop FX Files", "*" + DOC_FILE_EXTENSION); public static final int DEFAULT_INSET_SIZE = 10; private final Preferences preferences = Preferences.userNodeForPackage(App.class).node("v" + VERSION); private Controller controller; private Button playButton; private Button stopButton; private Label fileLabel; private ObservableList<String> recentDocumentFileList; private ObservableList<String> recentSourceFileList; private Menu loadRecentSourceFileMenu; private MenuItem loadSourceFileMenuItem; private Stage primaryStage; private ProgressBar progressBar; private Label progressLabel; private Menu openRecentDocumentFileMenu; private MenuItem saveMenuItem; private MenuItem newMenuItem; private MenuItem openMenuItem; private byte[] imageData; private WritableImage recordImage; private ImageView recordImageView; private ImageUpdateService imageUpdateService; public static void main(String[] args) { launch(args); } @Override public void start(final Stage primaryStage) throws Exception { if (System.getProperty("dedopfx.clearPrefs", "false").equalsIgnoreCase("true")) { clearPreferences(); } this.primaryStage = primaryStage; imageUpdateService = new ImageUpdateService(); imageUpdateService.onSucceededProperty().setValue(event -> { PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteRgbInstance(); recordImage.getPixelWriter().setPixels(0, 0, (int) recordImage.getWidth(), (int) recordImage.getHeight(), pixelFormat, imageData, 0, (int) recordImage.getWidth() * 3); }); Algorithm.RecordObserver recordObserver = (recordIndex, recordCount, inputSamples) -> Platform.runLater(() -> { updateProgress(recordIndex, recordCount); updateRecordImage(inputSamples); }); controller = new Controller(recordObserver); controller.getAlgorithmInputs().fromStore(new PreferencesStore(preferences.node("input"))); ChangeListener<File> sourceFileListener = (observable, oldValue, newValue) -> { if (oldValue != null) { updateRecentSourceFileList(oldValue); } updateSourceFileLabel(); }; controller.getAlgorithmInputs().sourceFileProperty().addListener(sourceFileListener); controller.getAlgorithmInputs().sourceValuesProperty().addListener((observable, oldValue, newValue) -> { updateSourceFileLabel(); }); ChangeListener<Worker.State> enabledStateUpdater = (observable, oldValue, newValue) -> Platform.runLater(this::updateEnabledState); controller.getLoadSourceFileService().stateProperty().addListener(enabledStateUpdater); controller.getPlayService().stateProperty().addListener(enabledStateUpdater); ChangeListener<File> documentFileListener = (observable, oldValue, newValue) -> { if (oldValue != null) { updateRecentDocumentFileList(oldValue); } updateTitle(); updateEnabledState(); }; controller.documentFileProperty().addListener(documentFileListener); Menu fileMenu = createFileMenu(); Menu helpMenu = createHelpMenu(); MenuBar menuBar = new MenuBar(); menuBar.getMenus().addAll(fileMenu, helpMenu); if (System.getProperty("os.name", "").contains("Mac")) { menuBar.useSystemMenuBarProperty().set(true); } recentDocumentFileList = FXCollections.observableArrayList(getRecentDocumentFileList()); //noinspection Convert2Lambda recentDocumentFileList.addListener(new ListChangeListener<String>() { @Override public void onChanged(Change<? extends String> change) { updateOpenRecentDocumentFileMenu(); } }); updateOpenRecentDocumentFileMenu(); recentSourceFileList = FXCollections.observableArrayList(getRecentSourceFileList()); //noinspection Convert2Lambda recentSourceFileList.addListener(new ListChangeListener<String>() { @Override public void onChanged(Change<? extends String> change) { updateOpenRecentSourceFileMenu(); } }); updateOpenRecentSourceFileMenu(); playButton = new Button("Play"); playButton.setOnAction((event) -> controller.getPlayService().restart()); stopButton = new Button("Stop"); stopButton.setOnAction((event) -> controller.getPlayService().cancel()); fileLabel = new Label(); updateSourceFileLabel(); Tab playbackSettingsTab = new Tab("Playback", createPlaybackSettingsPane()); playbackSettingsTab.setTooltip(new Tooltip("Settings that control the playback of the generated audio signal")); playbackSettingsTab.setClosable(false); Tab sourceMappingSettingsTab = new Tab("Source Mapping", createSourceMappingSettingsPane()); sourceMappingSettingsTab.setTooltip(new Tooltip("Settings that control the mapping from source data to amplitudes and pitches")); sourceMappingSettingsTab.setClosable(false); Tab soundSynthesisSettingsTab = new Tab("Sound Synthesis", createSoundSynthesisSettingsPane()); soundSynthesisSettingsTab.setTooltip(new Tooltip("Settings that control the timbre of the generated sound")); soundSynthesisSettingsTab.setClosable(false); TabPane settingsTabPane = new TabPane(playbackSettingsTab, sourceMappingSettingsTab, soundSynthesisSettingsTab); progressBar = new ProgressBar(); progressBar.setPrefWidth(200); progressLabel = new Label(); recordImageView = new ImageView(); recordImageView.setFitHeight(128); StackPane recordImageViewPane = new StackPane(); recordImageViewPane.setAlignment(Pos.TOP_LEFT); recordImageViewPane.getChildren().add(recordImageView); HBox recordImageViewBox = new HBox(); recordImageViewBox.setPadding(new Insets(DEFAULT_INSET_SIZE)); recordImageViewBox.getChildren().add(recordImageViewPane); // This is a hack to make the recordImageViewPane never larger than the recordImageViewBox DoubleBinding halfWidth = recordImageViewBox.widthProperty().divide(2); recordImageViewPane.minWidthProperty().bind(halfWidth); recordImageViewPane.maxWidthProperty().bind(halfWidth); recordImageViewPane.prefWidthProperty().bind(halfWidth); recordImageView.fitWidthProperty().bind(recordImageViewBox.widthProperty().subtract(2 * DEFAULT_INSET_SIZE)); HBox progressBox = new HBox(); progressBox.setPadding(new Insets(DEFAULT_INSET_SIZE)); progressBox.setSpacing(DEFAULT_INSET_SIZE / 2); progressBox.getChildren().addAll(progressBar, progressLabel); HBox buttonBox = new HBox(); buttonBox.setPadding(new Insets(DEFAULT_INSET_SIZE)); buttonBox.setSpacing(DEFAULT_INSET_SIZE); buttonBox.getChildren().addAll(playButton, stopButton); AnchorPane bottomAnchorPane = new AnchorPane(); bottomAnchorPane.getChildren().addAll(recordImageViewBox, progressBox, buttonBox); AnchorPane.setTopAnchor(recordImageViewBox, 5.0); AnchorPane.setLeftAnchor(recordImageViewBox, 5.0); AnchorPane.setRightAnchor(recordImageViewBox, 5.0); AnchorPane.setBottomAnchor(recordImageViewBox, 40.0); AnchorPane.setBottomAnchor(progressBox, 5.0); AnchorPane.setLeftAnchor(progressBox, 5.0); AnchorPane.setBottomAnchor(buttonBox, 5.0); AnchorPane.setRightAnchor(buttonBox, 5.0); HBox hBox = new HBox(fileLabel); hBox.setPadding(new Insets(5, 5, 5, 5)); BorderPane borderPane0 = new BorderPane(); borderPane0.setTop(hBox); borderPane0.setCenter(settingsTabPane); // borderPane0.setBottom(); BorderPane borderPane = new BorderPane(); borderPane.setTop(menuBar); borderPane.setCenter(borderPane0); borderPane.setBottom(bottomAnchorPane); Scene scene = new Scene(borderPane, 480, 520); updateEnabledState(); updateTitle(); primaryStage.getIcons().addAll(IntStream .of(16, 24, 32, 48, 64, 128, 210, 256) .mapToObj(value -> new Image(String.format("dedopfx/resources/dedop-%d.png", value))) .toArray(Image[]::new)); primaryStage.setScene(scene); Rectangle windowRectangle = getWindowRectangle(); if (windowRectangle != null) { primaryStage.setX(windowRectangle.x); primaryStage.setY(windowRectangle.y); primaryStage.setWidth(windowRectangle.width); primaryStage.setHeight(windowRectangle.height); } else { primaryStage.centerOnScreen(); } primaryStage.show(); } private Node createSourceMappingSettingsPane() { GridPane settingsPane = createSettingsGridPane(); int rowIndex = -1; DoubleProperty minSampleProperty = controller.getAlgorithmInputs().minSourceValueProperty(); DoubleProperty maxSampleProperty = controller.getAlgorithmInputs().maxSourceValueProperty(); InputFieldWithSlider minSource = new InputFieldWithSliderDoubleBase10("Minimum source value", AlgorithmInputs.DEFAULT_MIN_SOURCE_VALUE, AlgorithmInputs.DEFAULT_MAX_SOURCE_VALUE, minSampleProperty, "%.0f"); minSource.addToGrid(settingsPane, ++rowIndex); InputFieldWithSlider maxSourceValue = new InputFieldWithSliderDoubleBase10("Maximum source value", AlgorithmInputs.DEFAULT_MIN_SOURCE_VALUE, AlgorithmInputs.DEFAULT_MAX_SOURCE_VALUE, maxSampleProperty, "%.0f"); maxSourceValue.addToGrid(settingsPane, ++rowIndex); DoubleProperty amplitudeWeightingProperty = controller.getAlgorithmInputs().amplitudeWeightingProperty(); InputFieldWithSlider amplitudeWeighting = new InputFieldWithSliderDouble("Amplitude weighting", 0.0, 1.0, amplitudeWeightingProperty, "%.2f"); amplitudeWeighting.addToGrid(settingsPane, ++rowIndex); ++rowIndex; Property<TuningSystem> tuningSystemProperty = controller.getAlgorithmInputs().tuningSystemProperty(); ChoiceBox<TuningSystem> tuningSystemChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(TuningSystem.values())); tuningSystemChoiceBox.valueProperty().bindBidirectional(tuningSystemProperty); settingsPane.add(new Label("Tuning system"), 0, rowIndex, 1, 1); settingsPane.add(tuningSystemChoiceBox, 2, rowIndex, 1, 1); DoubleProperty minFrequencyProperty = controller.getAlgorithmInputs().minFrequencyProperty(); InputFieldWithSlider minFrequency = new InputFieldWithSliderDoubleBase2("Minimum frequency (Hz)", 20.0, 16000.0, minFrequencyProperty, "%.1f"); minFrequency.addToGrid(settingsPane, ++rowIndex); DoubleProperty maxFrequencyProperty = controller.getAlgorithmInputs().maxFrequencyProperty(); InputFieldWithSlider maxFrequency = new InputFieldWithSliderDoubleBase2("Maximum frequency (Hz)", 20.0, 16000.0, maxFrequencyProperty, "%.1f"); IntegerProperty octaveSubdivisionCountProperty = controller.getAlgorithmInputs().octaveSubdivisionCountProperty(); InputFieldWithSlider octaveSubdivisionCount = new InputFieldWithSliderInteger("Octave subdivisions", 1, 128, octaveSubdivisionCountProperty); IntegerProperty octaveCountProperty = controller.getAlgorithmInputs().octaveCountProperty(); InputFieldWithSlider octaveCount = new InputFieldWithSliderInteger("Number of octaves", 1, 10, octaveCountProperty); final int extraRowIndex = ++rowIndex; Runnable installTuningSystem = () -> { TuningSystem tuningSystem = tuningSystemProperty.getValue(); octaveSubdivisionCount.removeFromGrid(settingsPane); octaveCount.removeFromGrid(settingsPane); maxFrequency.removeFromGrid(settingsPane); if (tuningSystem == TuningSystem.LINEAR) { maxFrequency.addToGrid(settingsPane, extraRowIndex); } else if (tuningSystem == TuningSystem.EQUAL_TEMPERAMENT) { octaveSubdivisionCount.addToGrid(settingsPane, extraRowIndex); } else { octaveCount.addToGrid(settingsPane, extraRowIndex); } }; installTuningSystem.run(); tuningSystemProperty.addListener((observable, oldValue, newValue) -> Platform.runLater(installTuningSystem)); return settingsPane; } private Node createSoundSynthesisSettingsPane() { GridPane settingsPane = createSettingsGridPane(); int rowIndex = 0; Property<Waveform> carrierWaveformProperty = controller.getAlgorithmInputs().carrierWaveformProperty(); ChoiceBox<Waveform> carrierWaveformChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Waveform.WAVEFORMS)); carrierWaveformChoiceBox.valueProperty().bindBidirectional(carrierWaveformProperty); settingsPane.add(new Label("Carrier waveform"), 0, rowIndex, 1, 1); settingsPane.add(carrierWaveformChoiceBox, 2, rowIndex, 1, 1); rowIndex++; Property<Harmonics> harmonicsModeProperty = controller.getAlgorithmInputs().harmonicsModeProperty(); ChoiceBox<Harmonics> harmonicsModeBox = new ChoiceBox<>(FXCollections.observableArrayList(Harmonics.values())); harmonicsModeBox.valueProperty().bindBidirectional(harmonicsModeProperty); settingsPane.add(new Label("Harmonics mode"), 0, rowIndex, 1, 1); settingsPane.add(harmonicsModeBox, 2, rowIndex, 1, 1); rowIndex++; IntegerProperty timbreComplexityProperty = controller.getAlgorithmInputs().partialCountProperty(); InputFieldWithSlider timbreComplexity = new InputFieldWithSliderInteger("Number of partials", 2, 16, timbreComplexityProperty); timbreComplexity.addToGrid(settingsPane, rowIndex); rowIndex++; BooleanProperty useModulationProperty = controller.getAlgorithmInputs().modulationEnabledProperty(); CheckBox useModulationCheckBox = new CheckBox("Enable frequency modulation (FM)"); useModulationCheckBox.selectedProperty().bindBidirectional(useModulationProperty); settingsPane.add(useModulationCheckBox, 0, rowIndex, 3, 1); rowIndex++; Property<Waveform> modulationWaveformProperty = controller.getAlgorithmInputs().modulationWaveformProperty(); ChoiceBox<Waveform> modulationWaveformChoiceBox = new ChoiceBox<>(FXCollections.observableArrayList(Waveform.WAVEFORMS)); modulationWaveformChoiceBox.valueProperty().bindBidirectional(modulationWaveformProperty); settingsPane.add(new Label("Modulation waveform"), 0, rowIndex, 1, 1); settingsPane.add(modulationWaveformChoiceBox, 2, rowIndex, 1, 1); rowIndex++; DoubleProperty modulationIndexProperty = controller.getAlgorithmInputs().modulationDepthProperty(); InputFieldWithSlider modulationIndex = new InputFieldWithSliderDoubleBase10("Modulation depth", 0.001, 10., modulationIndexProperty, "%.3f"); modulationIndex.addToGrid(settingsPane, rowIndex); rowIndex++; IntegerProperty modulationNomProperty = controller.getAlgorithmInputs().modulationNomProperty(); InputFieldWithSlider modulationNom = new InputFieldWithSliderInteger("Modulation freq. nom.", 1, 16, modulationNomProperty); modulationNom.addToGrid(settingsPane, rowIndex); rowIndex++; IntegerProperty modulationDenomProperty = controller.getAlgorithmInputs().modulationDenomProperty(); InputFieldWithSlider modulationDenom = new InputFieldWithSliderInteger("Modulation freq. denom.", 1, 32, modulationDenomProperty); modulationDenom.addToGrid(settingsPane, rowIndex); return settingsPane; } private Node createPlaybackSettingsPane() { GridPane settingsPane = createSettingsGridPane(); int rowIndex = 0; IntegerProperty minRecordIndexProperty = controller.getAlgorithmInputs().minRecordIndexProperty(); InputFieldWithSlider minRecordIndex = new InputFieldWithSliderInteger("Minimum position", 0, 1, minRecordIndexProperty); minRecordIndex.addToGrid(settingsPane, ++rowIndex); IntegerProperty maxRecordIndexProperty = controller.getAlgorithmInputs().maxRecordIndexProperty(); InputFieldWithSlider maxRecordIndex = new InputFieldWithSliderInteger("Maximum position", 0, 1, maxRecordIndexProperty); maxRecordIndex.addToGrid(settingsPane, ++rowIndex); controller.getAlgorithmInputs().sourceValuesProperty().addListener((observable, oldValue, newValue) -> { int newMax = newValue != null ? newValue.length - 1 : 1; minRecordIndex.getSlider().setMax(newMax); maxRecordIndex.getSlider().setMax(newMax); minRecordIndexProperty.setValue(0); maxRecordIndexProperty.setValue(newMax); }); IntegerProperty velocityProperty = controller.getAlgorithmInputs().velocityProperty(); InputFieldWithSlider velocity = new InputFieldWithSliderInteger("Velocity", 1, 32, velocityProperty); velocity.addToGrid(settingsPane, ++rowIndex); DoubleProperty gainProperty = controller.getAlgorithmInputs().gainProperty(); InputFieldWithSlider gain = new InputFieldWithSliderDoubleBase10("Gain", 0.01, 1000.0, gainProperty, "%.3f"); gain.addToGrid(settingsPane, ++rowIndex); return settingsPane; } private GridPane createSettingsGridPane() { ColumnConstraints column1 = new ColumnConstraints(); ColumnConstraints column2 = new ColumnConstraints(); ColumnConstraints column3 = new ColumnConstraints(); column2.setHgrow(Priority.ALWAYS); GridPane gridPane = new GridPane(); gridPane.getColumnConstraints().addAll(column1, column2, column3); gridPane.setAlignment(Pos.TOP_LEFT); gridPane.setHgap(8); gridPane.setVgap(4); gridPane.setPadding(new Insets(DEFAULT_INSET_SIZE)); return gridPane; } private void updateRecordImage(double[] inputSamples) { if (imageUpdateService.getState() == Worker.State.READY || imageUpdateService.getState() == Worker.State.SUCCEEDED) { imageUpdateService.reset(); imageUpdateService.setInputSamples(inputSamples); imageUpdateService.start(); } } private void updateProgress(int recordIndex, int recordCount) { double progress = recordIndex / (double) recordCount; progressBar.setProgress(progress); progressLabel.setText(String.format("%d of %d (%.0f%%)", recordIndex, recordCount, progress * 100.)); } private void updateTitle() { File docFile = controller.getDocumentFile(); String docFileInfo; if (docFile != null) { docFileInfo = docFile.getPath(); } else { docFileInfo = "<New>"; } primaryStage.setTitle(String.format("%s %s - %s", NAME, VERSION, docFileInfo)); } private Menu createHelpMenu() { Menu helpMenu = new Menu("Help"); MenuItem helpMenuItem1 = createLinkMenuItem("DeDop Website", "http://dedop.org/"); MenuItem helpMenuItem2 = createLinkMenuItem("DeDop on GitHub", "https://github.com/DeDop"); MenuItem helpMenuItem3 = createLinkMenuItem("S-3 Altimetry Test Data Set", "https://sentinel.esa.int/web/sentinel/user-guides/sentinel-3-altimetry/test-data-set"); MenuItem aboutMenuItem = new MenuItem("About " + NAME); aboutMenuItem.setOnAction(event -> { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("About " + NAME); alert.setHeaderText("DeDopFX is a sound generator that operates on satellite altimetry\n" + "data and has been developed just for fun."); alert.setContentText("Copyright (c) 2017 by Norman Fomferra.\n" + "This software is free and distributed under the terms an conditions of \n" + "the MIT license."); alert.showAndWait(); }); helpMenu.getItems().addAll( helpMenuItem1, helpMenuItem2, helpMenuItem3, new SeparatorMenuItem(), aboutMenuItem); return helpMenu; } private Menu createFileMenu() { newMenuItem = new MenuItem("New"); newMenuItem.setOnAction(t -> { controller.getAlgorithmInputs().setDefaults(); updateEnabledState(); }); openMenuItem = new MenuItem("Open..."); openMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+O")); openMenuItem.setOnAction(t -> { String initialDirectoryPath = preferences.get("lastDocumentDirectory", System.getProperty("user.home")); final FileChooser fileChooser = createOpenDocumentFileChooser(initialDirectoryPath); final File file = fileChooser.showOpenDialog(primaryStage); if (file != null) { openDocument(file); preferences.put("lastDocumentDirectory", file.getParent() != null ? file.getParent() : ""); } }); openRecentDocumentFileMenu = new Menu("Open Recent"); saveMenuItem = new MenuItem("Save"); saveMenuItem.setAccelerator(KeyCombination.keyCombination("Ctrl+S")); saveMenuItem.setOnAction(event -> saveDocument()); MenuItem saveAsMenuItem = new MenuItem("Save As..."); saveAsMenuItem.setOnAction(t -> saveDocumentAs()); loadSourceFileMenuItem = new MenuItem("Load Source File..."); loadSourceFileMenuItem.setOnAction(t -> loadSourceFile()); loadRecentSourceFileMenu = new Menu("Load Recent Source File"); MenuItem quitMenuItem = new MenuItem("Quit"); quitMenuItem.setOnAction(t -> Platform.exit()); Menu fileMenu = new Menu("File"); fileMenu.getItems().addAll( newMenuItem, openMenuItem, openRecentDocumentFileMenu, new SeparatorMenuItem(), loadSourceFileMenuItem, loadRecentSourceFileMenu, new SeparatorMenuItem(), saveMenuItem, saveAsMenuItem, new SeparatorMenuItem(), quitMenuItem); return fileMenu; } private void clearPreferences() { try { preferences.node("input").clear(); preferences.clear(); preferences.sync(); } catch (BackingStoreException e) { // ok } } private void loadSourceFile() { String initialDirectoryPath = preferences.get("lastSourceDirectory", System.getProperty("user.home")); final FileChooser fileChooser = createLoadSourceFileChooser(initialDirectoryPath); final File file = fileChooser.showOpenDialog(primaryStage); if (file != null) { loadSourceFile(file); preferences.put("lastSourceDirectory", file.getParent() != null ? file.getParent() : ""); } } private void openDocument(File file) { file = ensureDocExtension(file); if (!checkFile(file, recentDocumentFileList)) { return; } Properties properties = new Properties(); try { try (FileReader reader = new FileReader(file)) { properties.load(reader); controller.getAlgorithmInputs().fromStore(new PropertiesStore(properties)); controller.setDocumentFile(file); File sourceFile = controller.getAlgorithmInputs().getSourceFile(); if (sourceFile != null) { loadSourceFile(sourceFile); } } } catch (IOException e) { ExceptionDialog.showError(String.format("Failed to open file '%s'", file), e); } } private void saveDocument() { if (controller.getDocumentFile() != null) { saveDocument(controller.getDocumentFile()); } else { saveDocumentAs(); } } private void saveDocument(File file) { file = ensureDocExtension(file); Properties properties = new Properties(); controller.getAlgorithmInputs().toStore(new PropertiesStore(properties)); try { try (FileWriter writer = new FileWriter(file)) { properties.store(writer, String.format("%s %s Document", NAME, VERSION)); controller.setDocumentFile(file); } } catch (IOException e) { ExceptionDialog.showError(String.format("Failed to save file '%s'", file), e); } } private void saveDocumentAs() { String initialDirectoryPath = preferences.get("lastDocumentDirectory", System.getProperty("user.home")); final FileChooser fileChooser = createSaveDocumentAsFileChooser(initialDirectoryPath); final File file = fileChooser.showSaveDialog(primaryStage); if (file != null) { saveDocument(file); preferences.put("lastDocumentDirectory", file.getParent() != null ? file.getParent() : ""); } } private File ensureDocExtension(File file) { if (!file.getName().endsWith(DOC_FILE_EXTENSION)) { return new File(file.getParentFile(), file.getName() + DOC_FILE_EXTENSION); } return file; } private MenuItem createLinkMenuItem(String text, String urlStr) { MenuItem menuItem = new MenuItem(text); menuItem.setOnAction(event -> { try { java.awt.Desktop.getDesktop().browse(URI.create(urlStr)); } catch (IOException e) { // ? } }); return menuItem; } @Override public void stop() { putWindowRectangle(new Rectangle( (int) this.primaryStage.getX(), (int) this.primaryStage.getY(), (int) this.primaryStage.getWidth(), (int) this.primaryStage.getHeight())); if (controller.getDocumentFile() != null) { updateRecentDocumentFileList(controller.getDocumentFile()); } if (controller.getAlgorithmInputs().getSourceFile() != null) { updateRecentSourceFileList(controller.getAlgorithmInputs().getSourceFile()); } controller.getAlgorithmInputs().setSourceFile(null); controller.getAlgorithmInputs().toStore(new PreferencesStore(preferences.node("input"))); try { preferences.sync(); } catch (BackingStoreException e) { // ok } } private interface FileOpenHandler { void openFile(File file); } private void updateRecentDocumentFileList(File file) { updateRecentFileList(recentDocumentFileList, file); putRecentFileList("recentDocumentFileList", recentDocumentFileList); } private void updateRecentSourceFileList(File file) { updateRecentFileList(recentSourceFileList, file); putRecentFileList("recentSourceFileList", recentSourceFileList); } private void updateRecentFileList(ObservableList<String> list, File file) { int index = list.indexOf(file.getPath()); if (index < 0) { list.add(0, file.getPath()); } else if (index > 0) { list.remove(index); list.add(0, file.getPath()); } } private void updateOpenRecentDocumentFileMenu() { updateRecentFileMenu(openRecentDocumentFileMenu, recentDocumentFileList, this::openDocument); } private void updateOpenRecentSourceFileMenu() { updateRecentFileMenu(loadRecentSourceFileMenu, recentSourceFileList, this::loadSourceFile); } private void updateRecentFileMenu(Menu menu, ObservableList<String> recentFileList, FileOpenHandler handler) { menu.getItems().setAll(recentFileList.stream().map(path -> { MenuItem menuItem = new MenuItem(path); menuItem.setOnAction(event -> handler.openFile(new File(path))); return menuItem; }).collect(Collectors.toList())); } private void loadSourceFile(File file) { if (file == null) { return; } if (!checkFile(file, recentSourceFileList)) { return; } Controller.LoadSourceFileService service = controller.getLoadSourceFileService(); if (service.getState() == Worker.State.RUNNING || service.getState() == Worker.State.SCHEDULED) { throw new IllegalStateException(); } if (file.equals(service.getSourceFile())) { return; } service.reset(); service.setSourceFile(file); service.setOnSucceeded(workerStateEvent -> controller.getAlgorithmInputs().setSourceFile(file)); service.setOnFailed(workerStateEvent -> { ExceptionDialog.showError("A problem occurred while opening the source data file", workerStateEvent.getSource().getException()); controller.getAlgorithmInputs().setSourceFile(null); }); service.start(); } private boolean checkFile(File file, ObservableList<String> recentFileList) { if (!file.exists() || !file.isFile()) { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setHeaderText("Invalid source data file selected."); alert.setContentText(String.format("File '%s'\n" + "does not exists or is invalid.", file)); alert.showAndWait(); recentFileList.remove(file.getPath()); return false; } return true; } private void updateSourceFileLabel() { File sourceFile = controller.getAlgorithmInputs().getSourceFile(); if (sourceFile != null) { double[][] sourceValues = controller.getAlgorithmInputs().getSourceValues(); if (sourceValues != null) { fileLabel.setText(String.format("%s (%d records)", sourceFile.getPath(), sourceValues.length)); } else { fileLabel.setText(String.format("%s (not loaded)", sourceFile.getPath())); } } else { fileLabel.setText("No source data file selected. Use 'Open' from the 'File' menu."); } } private Rectangle getWindowRectangle() { int invalid = Integer.MAX_VALUE; int windowX = preferences.getInt("windowX", invalid); int windowY = preferences.getInt("windowY", invalid); int windowWidth = preferences.getInt("windowWidth", invalid); int windowHeight = preferences.getInt("windowHeight", invalid); if (windowX != invalid && windowY != invalid && windowWidth != invalid && windowHeight != invalid) { return new Rectangle(windowX, windowY, windowWidth, windowHeight); } return null; } private void putWindowRectangle(Rectangle rectangle) { preferences.putInt("windowX", rectangle.x); preferences.putInt("windowY", rectangle.y); preferences.putInt("windowWidth", rectangle.width); preferences.putInt("windowHeight", rectangle.height); } private List<String> getRecentDocumentFileList() { return getRecentFileList("recentDocumentFileList"); } private List<String> getRecentSourceFileList() { return getRecentFileList("recentSourceFileList"); } private List<String> getRecentFileList(String key) { String value = preferences.get(key, null); if (value != null && !value.trim().isEmpty()) { return Arrays.asList(value.split(File.pathSeparator)); } else { return new ArrayList<>(); } } private void putRecentFileList(String key, List<String> recentFileList) { preferences.put(key, recentFileList.stream().collect(Collectors.joining(File.pathSeparator))); } private void updateEnabledState() { boolean hasSamples = controller.getAlgorithmInputs().hasSourceValues(); boolean isLoadingSource = isScheduledOrRunning(controller.getLoadSourceFileService().getState()); boolean isPlaying = isScheduledOrRunning(controller.getPlayService().getState()); boolean canOpen = !isLoadingSource && !isPlaying; boolean canOpenRecentDocument = canOpen && !recentDocumentFileList.isEmpty(); boolean canOpenRecentSource = canOpen && !recentSourceFileList.isEmpty(); boolean canSave = controller.getDocumentFile() != null; boolean canPlay = hasSamples && !isLoadingSource && !isPlaying; newMenuItem.disableProperty().setValue(!canOpen); openMenuItem.disableProperty().setValue(!canOpen); openRecentDocumentFileMenu.disableProperty().setValue(!canOpenRecentDocument); saveMenuItem.disableProperty().setValue(!canSave); loadSourceFileMenuItem.disableProperty().setValue(!canOpen); loadRecentSourceFileMenu.disableProperty().setValue(!canOpenRecentSource); progressBar.disableProperty().setValue(!isPlaying); playButton.disableProperty().setValue(!canPlay); stopButton.disableProperty().setValue(!isPlaying); if (canPlay) { playButton.requestFocus(); } } private static boolean isScheduledOrRunning(Worker.State state) { return state == Worker.State.SCHEDULED || state == Worker.State.RUNNING; } private FileChooser createOpenDocumentFileChooser(String initialDirectoryPath) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Open"); fileChooser.setInitialDirectory(new File(initialDirectoryPath)); fileChooser.getExtensionFilters().addAll(DOC_EXTENSION_FILTER); return fileChooser; } private FileChooser createSaveDocumentAsFileChooser(String initialDirectoryPath) { File documentFile = controller.getDocumentFile(); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Save As"); fileChooser.setInitialDirectory(documentFile != null ? documentFile.getParentFile() : new File(initialDirectoryPath)); fileChooser.setInitialFileName(documentFile != null ? documentFile.getName() : null); fileChooser.getExtensionFilters().addAll(DOC_EXTENSION_FILTER); return fileChooser; } private FileChooser createLoadSourceFileChooser(String initialDirectoryPath) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Load Source File"); fileChooser.setInitialDirectory(new File(initialDirectoryPath)); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("S-3 SRAL L1B Files", "*.nc"), new FileChooser.ExtensionFilter("All Files", "*.*") ); return fileChooser; } private class ImageUpdateService extends Service<Void> { private double[] inputSamples; public ImageUpdateService() { } public void setInputSamples(double[] inputSamples) { this.inputSamples = inputSamples; } @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { int imageWidth = inputSamples.length; int imageHeight = 128; if (imageData == null || imageData.length != imageWidth * imageHeight * 3) { recordImage = new WritableImage(imageWidth, imageHeight); imageData = new byte[imageWidth * imageHeight * 3]; // System.out.println("imageWidth = " + imageWidth); recordImageView.setImage(recordImage); // System.out.println("recordImageView = " + recordImageView.getFitWidth()); } int decay = 2; for (int k = 0; k < imageWidth * imageHeight * 3; k++) { int v = imageData[k] & 0xff; if (v - decay >= 0) { imageData[k] = (byte) (v - decay); } else { imageData[k] = 0; } } for (int y = 1; y < imageHeight; y++) { final int j1 = y * imageWidth; for (int x = 0; x < imageWidth; x++) { final int i1 = 3 * (j1 + x); final int i0 = i1 - 3 * imageWidth; imageData[i0] = imageData[i1]; imageData[i0 + 1] = imageData[i1 + 1]; imageData[i0 + 2] = imageData[i1 + 1]; } } for (int x = 0; x < inputSamples.length; x++) { double inputSample = inputSamples[x]; int h = (int) (imageHeight * inputSample); if (h < 0) { h = 0; } if (h > imageHeight - 1) { h = imageHeight - 1; } for (int y = imageHeight - h; y < imageHeight; y++) { int k = (y * imageWidth + x) * 3; imageData[k] = (byte) 255; imageData[k + 1] = (byte) 255; imageData[k + 2] = 0; } } return null; } }; } } }
Shell
UTF-8
500
2.671875
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # MidoNet repo MIDONET_REPO=${MIDONET_REPO:-http://github.com/midonet/midonet.git} MIDONET_BRANCH=${MIDONET_BRANCH:-master} MIDONET_DIR=${MIDONET_DIR:-$DEST/midonet} # MidoNet service endpoint configuration MIDONET_API_PORT=${MIDONET_API_PORT:-8081} MIDONET_SERVICE_PROTOCOL=${MIDONET_SERVICE_PROTOCOL:-$SERVICE_PROTOCOL} MIDONET_SERVICE_HOST=${MIDONET_SERVICE_HOST:-$SERVICE_HOST} MIDONET_API_URL="${MIDONET_SERVICE_PROTOCOL}://${MIDONET_SERVICE_HOST}:${MIDONET_API_PORT}/midonet-api"
Java
UTF-8
6,329
1.984375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.text.write.tables.settings.creation; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.rf.ide.core.testdata.model.FileFormat; import org.rf.ide.core.testdata.model.RobotFile; import org.rf.ide.core.testdata.model.presenter.DocumentationServiceHandler; import org.rf.ide.core.testdata.model.table.SettingTable; import org.rf.ide.core.testdata.model.table.setting.SuiteDocumentation; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.write.NewRobotFileTestHelper; public class CreationOfSettingsSuiteDocumentationTest { private static final String ROBOT_VERSION = "3.0"; @ParameterizedTest @EnumSource(value = FileFormat.class, names = { "TXT_OR_ROBOT", "TSV" }) public void test_emptyFile_and_thanCreateSuiteDoc(final FileFormat format) throws Exception { // prepare final String fileName = convert("EmptySuiteDocumentationDeclarationOnly", format); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify(ROBOT_VERSION); // test data prepare modelFile.includeSettingTableSection(); final SettingTable settingTable = modelFile.getSettingTable(); settingTable.newSuiteDocumentation(); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(fileName, modelFile); } @ParameterizedTest @EnumSource(value = FileFormat.class, names = { "TXT_OR_ROBOT", "TSV" }) public void test_emptyFile_createSuiteDoc_andAddComments(final FileFormat format) throws Exception { // prepare final String fileName = convert("SuiteDocumentationDeclarationWithCommentsOnly", format); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify(ROBOT_VERSION); // test data prepare modelFile.includeSettingTableSection(); final SettingTable settingTable = modelFile.getSettingTable(); final SuiteDocumentation suiteDoc = settingTable.newSuiteDocumentation(); final RobotToken cm1 = new RobotToken(); cm1.setText("cm1"); final RobotToken cm2 = new RobotToken(); cm2.setText("cm2"); final RobotToken cm3 = new RobotToken(); cm3.setText("cm3"); suiteDoc.addCommentPart(cm1); suiteDoc.addCommentPart(cm2); suiteDoc.addCommentPart(cm3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(fileName, modelFile); } @ParameterizedTest @EnumSource(value = FileFormat.class, names = { "TXT_OR_ROBOT", "TSV" }) public void test_emptyFile_createSuiteDoc_withText(final FileFormat format) throws Exception { // prepare final String fileName = convert("SuiteDocumentationDeclarationWithTextOnly", format); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify(ROBOT_VERSION); // test data prepare modelFile.includeSettingTableSection(); final SettingTable settingTable = modelFile.getSettingTable(); final SuiteDocumentation suiteDoc = settingTable.newSuiteDocumentation(); final RobotToken text1 = new RobotToken(); text1.setText("text1"); final RobotToken text2 = new RobotToken(); text2.setText("text2"); final RobotToken text3 = new RobotToken(); text3.setText("text3"); suiteDoc.addDocumentationText(text1); suiteDoc.addDocumentationText(text2); suiteDoc.addDocumentationText(text3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(fileName, modelFile); } @ParameterizedTest @EnumSource(value = FileFormat.class, names = { "TXT_OR_ROBOT", "TSV" }) public void test_emptyFile_createSuiteDoc_withMultipleLines(final FileFormat format) throws Exception { // prepare final String fileName = convert("EmptySuiteDocumentationThreeLines", format); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify(ROBOT_VERSION); // test data prepare modelFile.includeSettingTableSection(); final SettingTable settingTable = modelFile.getSettingTable(); final SuiteDocumentation suiteDoc = settingTable.newSuiteDocumentation(); DocumentationServiceHandler.update(suiteDoc, "doc me" + "\n" + "ok" + "\n" + "ok2"); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(fileName, modelFile); } @ParameterizedTest @EnumSource(value = FileFormat.class, names = { "TXT_OR_ROBOT", "TSV" }) public void test_emptyFile_createSuiteDoc_withTextAndComment(final FileFormat format) throws Exception { // prepare final String fileName = convert("SuiteDocumentationDeclarationWithTextAndCommentOnly", format); final RobotFile modelFile = NewRobotFileTestHelper.getModelFileToModify(ROBOT_VERSION); // test data prepare modelFile.includeSettingTableSection(); final SettingTable settingTable = modelFile.getSettingTable(); final SuiteDocumentation suiteDoc = settingTable.newSuiteDocumentation(); final RobotToken text1 = new RobotToken(); text1.setText("text1"); final RobotToken text2 = new RobotToken(); text2.setText("text2"); final RobotToken text3 = new RobotToken(); text3.setText("text3"); suiteDoc.addDocumentationText(text1); suiteDoc.addDocumentationText(text2); suiteDoc.addDocumentationText(text3); final RobotToken cm1 = new RobotToken(); cm1.setText("cm1"); final RobotToken cm2 = new RobotToken(); cm2.setText("cm2"); final RobotToken cm3 = new RobotToken(); cm3.setText("cm3"); suiteDoc.addCommentPart(cm1); suiteDoc.addCommentPart(cm2); suiteDoc.addCommentPart(cm3); // verify NewRobotFileTestHelper.assertNewModelTheSameAsInFile(fileName, modelFile); } private String convert(final String fileName, final FileFormat format) { return "settings/suiteDoc/new/" + fileName + "." + format.getExtension(); } }
TypeScript
UTF-8
598
2.953125
3
[ "MIT" ]
permissive
import { PHASE_TRANSITION, CHANGE_MODE, SystemState, SystemActionTypes, Phase, Mode } from "./types"; const initialState: SystemState = { phase: Phase.NEW, mode: Mode.LIGHT }; export function systemReducer( state = initialState, action: SystemActionTypes ): SystemState { switch (action.type) { case PHASE_TRANSITION: { return { ...state, ...action.payload }; } case CHANGE_MODE: { return { ...state, mode: state.mode === Mode.LIGHT ? Mode.DARK : Mode.LIGHT }; } default: return state; } }
Markdown
UTF-8
3,844
2.75
3
[ "CC0-1.0" ]
permissive
# MongoDB - Aula 02 - Exercício autor: Alison Monteiro ## Crie uma database chamada be-mean-pokemons; ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> use be-mean-pokemons switched to db be-mean-pokemons ``` ## 2. Liste quais databases você possui nesse servidor; ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> show dbs be-mean → 0.078GB local → 0.078GB test → 0.078GB ``` ## 3. Liste quais coleções você possui nessa database; Obs.: Criando a coleção antes pra ficar mais show. ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> db.createCollection('pokemons') { "ok": 1 } MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> show collections pokemons → 0.000MB / 0.008MB system.indexes → 0.000MB / 0.008MB ``` ## 4. Insira pelo menos 5 pokemons A SUA ESCOLHA ``` var pokemons = { name:'Nidorino', description:'Chifre tão duro quanto um diamante', type: 'poison-pin', atack:40, height:0.9 }; var pokemons = { name:'Clefable', description:'Se move saltando levemente', type: 'fairy', atack:40, height:1.3 }; var pokemons = { name:'Weedle', description:'Olfato agudo', type: 'hairy-bug', atack:20, height:0.3 }; var pokemons = { name:'Ekans', description:'Fica em espiral enquanto descança', type: 'snake', atack:30, height:2.0 }; var pokemons = { name:'Nidoking', description:'Poder na calda', type: 'drill', atack:50, height:1.4 }; MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> db.pokemons.insert(pokemons); Inserted 1 record(s) in 2ms WriteResult({ "nInserted": 1 }) ``` ## 5. Liste os pokemons existentes na sua coleção; ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> db.pokemons.find(); { "_id": ObjectId("564510a0909feebcd301cad3"), "name": "Nidorino", "description": "Chifre tão duro quanto um diamante", "type": "poison-pin", "atack": 40, "height": 0.9 } { "_id": ObjectId("564510a9909feebcd301cad4"), "name": "Clefable", "description": "Se move saltando levemente", "type": "fairy", "atack": 40, "height": 1.3 } { "_id": ObjectId("564510ae909feebcd301cad5"), "name": "Weedle", "description": "Olfato agudo", "type": "hairy-bug", "atack": 20, "height": 0.3 } { "_id": ObjectId("564510b3909feebcd301cad6"), "name": "Ekans", "description": "Fica em espiral enquanto descança", "type": "snake", "atack": 30, "height": 2 } { "_id": ObjectId("564510ba909feebcd301cad7"), "name": "Nidoking", "description": "Poder na calda", "type": "drill", "atack": 50, "height": 1.4 } Fetched 5 record(s) in 5ms ``` ## 6. Busque o pokemons a sua escolha, pelo nome, e armazene-o em uma variável chamada `poke`; ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> var query = { name: 'Ekans' } MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> var poke = db.pokemons.findOne(query) MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> poke { "_id": ObjectId("564510b3909feebcd301cad6"), "name": "Ekans", "description": "Fica em espiral enquanto descança", "type": "snake", "atack": 30, "height": 2 } ``` ## 7. Modifique sua `description` e salvê-o ``` MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> poke.description = 'Fica em espiral enquanto descança para ter mais agilidade quando precisar' MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> poke { "_id": ObjectId("564510b3909feebcd301cad6"), "name": "Ekans", "description": "Fica em espiral enquanto descança para ter mais agilidade quando precisar", "type": "snake", "atack": 30, "height": 2 } MacBook-Pro-de-Alison-monteiro(mongod-3.0.6) be-mean-pokemons> db.pokemons.save(poke) Updated 1 existing record(s) in 3ms WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 }) ```
C
UTF-8
4,041
3.09375
3
[]
no_license
#include "functions.h" /* initialize foreground-only mode to false */ int foreground_only = 0; /* expand '$$' in command into process ID of the shell several lines adapted from https://www.linuxquestions.org/questions/programming-9/replace-a-substring-with-another-string-in-c-170076/ */ void expandPID(char command[], char expanded_cmd[]) { /* point to first instance of "$$" in string */ char* pidInsertPt; /* if command contains "$$" substring */ while ((pidInsertPt = strstr(command, "$$"))){ /* pointer arithmetic to find length from start to $$ */ int firstChunk = pidInsertPt - command; /* copy characters from start of cmd string to the beginning of the $$ substring */ strncpy(expanded_cmd, command, firstChunk); expanded_cmd[firstChunk] = '\0'; /* append pid and rest of command string past the $$ */ sprintf(expanded_cmd + firstChunk, "%d%s", getpid(), pidInsertPt + 2); /* update command with the expansion for next loop */ strcpy(command, expanded_cmd); } } /* updates array of user commands and returns the number of arguments*/ int promptUser(char command[], char* argArray[], sigset_t* sigtstp_set) { /* number of user-entered command arguments */ int numArgs = 0; /* set up buffer for getline */ char* line = NULL; size_t lineSize = 0; /* prompt for input */ printf(": "); fflush(stdout); /* get user line and save to command string */ int numCharsEntered = getline(&line, &lineSize, stdin); /* loop to get user input */ while(numCharsEntered == -1){ /* if getline was interrupted, clear error and re-prompt */ clearerr(stdin); printf(": "); fflush(stdout); numCharsEntered = getline(&line, &lineSize, stdin); } /* save to char array */ strncpy(command, line, numCharsEntered - 1); command[numCharsEntered - 1] = '\0'; /* string copy for pid expansion and strtok */ char expanded_cmd[2048]; strcpy(expanded_cmd, command); /* convert "$$" in command string to PID */ expandPID(command, expanded_cmd); /* divide copy string on whitespace into array of arguments */ argArray[0] = strtok(expanded_cmd, " "); while (argArray[numArgs] != NULL){ numArgs++; argArray[numArgs] = strtok(NULL, " "); /* make next arg NULL to create stopping point for exec */ argArray[numArgs + 1] = NULL; } /* make sure argArray[0] is not null pointer */ if(!argArray[0]){ argArray[0] = " "; numArgs++; } /* block SIGTSTP so that it won't kill foreground proc */ sigprocmask(SIG_BLOCK, sigtstp_set, NULL); free(line); return numArgs; } /* built-in cd command */ int changeDir(char* argArray[], int numArgs) { int result; /* cd by itself changes to HOME directory */ if (numArgs == 1){ if (getenv("HOME") != NULL){ result = chdir(getenv("HOME")); } else { perror("HOME variable couldn't be accessed"); } } /* or takes one argument: the directory path to change to */ else { result = chdir(argArray[1]); } return result; } /* initialize the Ctrl-C and Ctrl-Z signal action structs and handlers */ void initSigHandlers(struct sigaction* sigint_action, struct sigaction* sigtstp_action) { /* set sigint to be ignored and custom handler for sigtstp */ sigint_action->sa_handler = SIG_IGN; sigtstp_action->sa_handler = catchSIGTSTP; /* block signals while executing handler */ sigfillset(&sigint_action->sa_mask); sigfillset(&sigtstp_action->sa_mask); /* restart interrupted process for sig int */ sigint_action->sa_flags = SA_RESTART; sigtstp_action->sa_flags = 0; /* register sigint ignore and sigtstp handler */ sigaction(SIGINT, sigint_action, NULL); sigaction(SIGTSTP, sigtstp_action, NULL); } /* Ctrl-Z signal handler */ void catchSIGTSTP() { /* toggle mode */ foreground_only = 1 - foreground_only; /* print informative messages to stdout */ if (foreground_only == 1){ char* msg1 = "\nEntering foreground-only mode (& is now ignored)\n"; write(2, msg1, 50); } else if (foreground_only == 0){ char* msg2 = "\nExiting foreground-only mode\n"; write(2, msg2, 30); } }
Markdown
UTF-8
524
2.9375
3
[ "MIT" ]
permissive
## CN 简单 LRU 缓存。 ### constructor |参数名|说明| |-----|---| |max|最大缓存数| ### has 检查是否有缓存。 |参数名|说明| |-----|---| |key|缓存键名| |返回值|如果有,返回真| ### remove 删除缓存。 |参数名|说明| |-----|---| |key|缓存键名| ### get 获取缓存。 |参数名|说明| |-----|---| |key|缓存键名| |返回值|缓存值| ### set 设置缓存。 |参数名|说明| |-----|---| |key|缓存键名| |val|缓存值| ### clear 清除所有缓存。
Markdown
UTF-8
503
2.53125
3
[]
no_license
layout 也就是 UI 组件的接口 无样式文件,有样式接口 它们的实现在 themes 文件夹 写作约定: 组件元素名应当和class名一致 example: ``` let main = E().P({ className: C( appearance.main, ), disabled: props.ifDisabled, }); ``` Button 中,你可以看到 `let main = ...`, `appearance.main` 两处用了同样的名称 "main" 为什么这样做? 为了让你看到 layout 就知道该用什么类名在 css 中
Java
UTF-8
1,948
1.867188
2
[]
no_license
package cn.tyyhoa.dao; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.tyyhoa.pojo.OaRlzybInterview; public interface OaRlzybInterviewMapper { int deleteByPrimaryKey(Integer interview_id); int insert(OaRlzybInterview record); int insertSelective(OaRlzybInterview record); OaRlzybInterview selectByPrimaryKey(Integer interview_id); int updateByPrimaryKeySelective(OaRlzybInterview record); int updateByPrimaryKey(OaRlzybInterview record); /*zl*/ List<OaRlzybInterview> selectAllPerson( @Param("interview_person")String emp_name, @Param("interview_date")Date interview_date, @Param("startPos")Integer startPos, @Param("PageSize")Integer PageSize); List<OaRlzybInterview> selectAllEmpName( @Param("emp_name")String emp_name, @Param("interview_date")Date interview_date, @Param("startPos")Integer startPos, @Param("PageSize")Integer PageSize); List<OaRlzybInterview> selectPerson( @Param("interview_person")String emp_name, @Param("interview_date")Date interview_date); List<OaRlzybInterview> selectEmpName( @Param("emp_name")String emp_name, @Param("interview_date")Date interview_date); /* int selectCount(@Param("interview_person")String interview_person, @Param("emp_name")String emp_name, @Param("interview_date")Date interview_date);*/ List<OaRlzybInterview> selectPersonByName(@Param("emp_name")String emp_name); List<OaRlzybInterview> selectIdByName(@Param("emp_name")String emp_name); OaRlzybInterview selectShowPerson(@Param("interview_id")Integer interview_id); OaRlzybInterview selectShowEmpName(@Param("interview_id")Integer interview_id); int updateDelete(@Param("interview_id")Integer interview_id); /*zl*/ }
C
UTF-8
231
2.609375
3
[]
no_license
typedef unsigned long size_t; extern void *memset(void *s, int c, size_t n); int main (){ char str[50] = "This is string.h library function"; char* str1 = memset(str,'$',7); ASSERT(str1[3] == '$' && str[2] == '$'); return 0; }
Markdown
UTF-8
1,629
2.796875
3
[]
no_license
--- layout: default title: About permalink: /about/ --- <img src="{{ '/assets/images/KQM.svg' | relative_url }}" alt="KQM logo" width="50%" height="auto" align="right"> # Stimulans til diskusjon og samarbeidslæring i matematikk **Prosjekt**: P34/2017 i [Norgesuniversitetet][Norgesuniversitetet]. Quiz, i ulike variantar, har vorte ein populær teknikk for å fremja aktivitet i klasserommet, men eksisterande system (t.d. Kahoot) manglar tilstrekkeleg støtte for matematikk. Målet med dette prosjektet er å innføra systematisk bruk av samarbeidslæring i to konkrete matematikkemne, ved hjelp av slike quiz-system. For å nå dette målet må me: 1. Utvikla eit quiz-system som tillet matematisk notasjon i spørsmål og svar, og som legg til rette for bruk i klasserommet. 2. Utvikla spørsmålssamlingar som er egna for å skapa relevant diskusjon i klasserommet. 3. Testa ut quiz som ein drivar for diskusjon og annan samarbeidslæring i klasserommet. Quiz-systemet vert utvikla som ein plugin i Moodle, og vil byggja på eksisterande plugins. Det overdordna målet med prosjektet er å utnytta sosiale læringsprosessar på ein måte som skalerer til klasser med fleire hundre studentar. Quizen tener direkte to formål, for det fyrste stimulerer han kvar einskild student til å ta stilling spørsmålet som vert stilt, og for det andre kan læraren identifisera tema som krev betre gjennomgang. Spørsmål der studentane gjev ulike svar er godt egna for diskusjon i små grupper, noko som er venta å gje betre læringsutbyte enn fasit frå førelesaren. [Norgesuniversitetet]: https://norgesuniversitetet.no/
Java
UTF-8
8,734
2.578125
3
[]
no_license
package generators.maths.northwestcornerrule; import generators.maths.northwestcornerrule.views.CodeView; import generators.maths.northwestcornerrule.views.GridView; import generators.maths.northwestcornerrule.views.VariableView; import interactionsupport.models.FillInBlanksQuestionModel; import java.awt.Color; import algoanim.primitives.generators.Language; import algoanim.util.Coordinates; public class Animation { private Language myAnimationScript; private DrawingUtils myDrawingUtils; private CodeView myCodeViewHandler; private VariableView myVariableViewHandler; private GridView myGridViewHandler; private static String TXT_ANIMATION_TITLE = "Nordwest-Ecken-Regel"; private static String TXT_INTRO = "Das Nord-West-Ecken-Verfahren ist ein Verfahren aus dem Operations Research,<br>" + "das eine zulässige Anfangslösung für das Transportproblem liefern soll.<br> " + "Von dieser Lösung aus startet der Optimierungsalgorithmus des Transportproblems.<br>" + "Gegeben sind eine Menge an Anbietern (Supplier) mir der jeweiligen Liefermenge. <br>" + "Ebenso sind eine Menge an Nachfragern (Demander) gegeben mit einer gewissen Nachfrage. <br>" + "Ziel ist es die Angebotsmenge auf die Nachfrage zu verteilen. <br>" + "Vorsicht: Die gefundene Aufteilung ist nicht notwendigerweise eine optimale Lösung. <br>" + "Sie stellt eine mögliche Lösung (Basislösung) dar, auf der andere Verfahren aufbauen können,<br>" + "um eine optimale Lösung des Transportproblems zu kalkulieren.<br>" + "Voraussetzung: Außerdem gilt als Grundvoraussetzung, dass die kumulierte Nachfrage dem <br>" + "kumulierten Angebot gleichen muss.<br><br>" + "Folgende Anbieter bzw. Angebotsmengen wurden ausgewählt: <br>" + "Folgende Nachfrager bzw. Nachfragemengen wurden ausgewählt: <br>"; private static String TXT_LASTFRAME = "Durch das Nord-West-Ecken-Verfahren wurde eine Basislösung erzeugt. <br>" + "Aufbauend auf dieser Lösung kann z.B. der Simplex-Algorithmus angewendet werden."; public Animation(Language animationScript) { // Store the language object myAnimationScript = animationScript; // This initializes the step mode. Each pair of subsequent steps has to be divided by a call of lang.nextStep(); myAnimationScript.setStepMode(true); myAnimationScript.setInteractionType(Language.INTERACTION_TYPE_AVINTERACTION); // Initialize drawing utilities. myDrawingUtils = new DrawingUtils(myAnimationScript); // Initialize all view handlers for the animation myCodeViewHandler = new CodeView(myAnimationScript, myDrawingUtils); myVariableViewHandler = new VariableView(myAnimationScript, myDrawingUtils); myGridViewHandler = new GridView(myAnimationScript, myDrawingUtils); } public void buildIntroFrame(int[] supply, int[] demand){ myAnimationScript.nextStep("Einleitung"); // Build Title and introduction text myDrawingUtils.drawHeader(new Coordinates(5,20), TXT_ANIMATION_TITLE); myDrawingUtils.buildText(new Coordinates(100,100), TXT_INTRO); // Draw array with parameters of algorithm myAnimationScript.newIntArray(new Coordinates(600, 405),supply, "", null, AnimProps.ARRAY_PROPS); myAnimationScript.newIntArray(new Coordinates(600, 430),demand, "", null, AnimProps.ARRAY_PROPS); } public void buildDefaultViews(int[] supply, int[] demand){ myAnimationScript.nextStep("Initialisierung"); myAnimationScript.hideAllPrimitives(); myDrawingUtils.drawHeader(new Coordinates(5,20), TXT_ANIMATION_TITLE); myCodeViewHandler.setupView(); myVariableViewHandler.setupView(); myGridViewHandler.setupView(supply, demand); } public void buildLastFrame(Integer[][] base){ myGridViewHandler.getBasisGrid().unhighlightAll(0); myGridViewHandler.getRightGrid().unhighlightAll(0); myGridViewHandler.getBottomGrid().unhighlightAll(0); myCodeViewHandler.unhighlightAll(); myAnimationScript.nextStep("Ergebniss"); myAnimationScript.hideAllPrimitives(); myDrawingUtils.drawHeader(new Coordinates(5,20), TXT_ANIMATION_TITLE); myDrawingUtils.buildText(new Coordinates(100,100), TXT_LASTFRAME); myGridViewHandler.createLastFrameGrid(base); } public void buildExceptionFrame(String message){ myDrawingUtils.drawTextWithBox(new Coordinates(200, 200), message); } // public int nordwestEckenRegel (int[] angebot, int[] nachfrage){ public void buildLine0Animation(){ myCodeViewHandler.highlight(0, 1); myAnimationScript.nextStep(); } // int i = 0; public void buildLine2Animation(){ myCodeViewHandler.highlight(2); myAnimationScript.nextStep(); } // int j = 0; public void buildLine3Animation(){ myCodeViewHandler.highlight(3); myAnimationScript.nextStep(); } int counter = 1; // while (i<= angebot.length && j <=nachfrage.length) { public void buildLine4Animation(int supply_i, int demand_j){ myAnimationScript.nextStep(counter + ". Iteration"); counter ++; myGridViewHandler.getBasisGrid().unhighlightAll(0); myGridViewHandler.getRightGrid().unhighlightAll(0); myGridViewHandler.getBottomGrid().unhighlightAll(0); myGridViewHandler.getBasisGrid().highlightRow(supply_i, Color.YELLOW, 500); myGridViewHandler.getBasisGrid().highlightColumn(demand_j, Color.YELLOW, 1000); myGridViewHandler.getBasisGrid().highlightCell(demand_j,supply_i, Color.red, 1500); myGridViewHandler.getRightGrid().highlightRow(supply_i, Color.YELLOW, 500); myGridViewHandler.getRightGrid().highlightLastLabeledCellInRow(supply_i, Color.red, 1500); myGridViewHandler.getBottomGrid().highlightColumn(demand_j, Color.YELLOW, 1000); myGridViewHandler.getBottomGrid().highlightLastLabeledCellInColumn(demand_j, Color.red, 1500); myCodeViewHandler.highlight(4, 5); myAnimationScript.nextStep(); } // x = Math.min(angebot[i],nachfrage[i]); public void buildLine6Animation(int i, int j,int supply, int demand, int x){ myCodeViewHandler.highlight(6); FillInBlanksQuestionModel fibQuestion = new FillInBlanksQuestionModel(""); fibQuestion.addAnswer("" + Math.min(supply, demand),1, "Wie groß ist die zu liefernde Menge von Anbieter "+ i + "an Nachfrager " +j + " ?"); myAnimationScript.addFIBQuestion(fibQuestion); myGridViewHandler.getRightGrid().blinkLastLabeledCellInRow(i, Color.red, 0); myGridViewHandler.getBottomGrid().blinkLastLabeledCellInColumn(j, Color.red, 0); myVariableViewHandler.alter_variable_x(supply, demand, Math.min(supply, demand)); if(supply <= demand){ myGridViewHandler.getRightGrid().highlightLastLabeledCellInRow(i, Color.green, 3000); myGridViewHandler.getBottomGrid().highlightLastLabeledCellInColumn(j, Color.red, 3000); } else{ myGridViewHandler.getBottomGrid().highlightLastLabeledCellInColumn(j, Color.green, 3000); myGridViewHandler.getRightGrid().highlightLastLabeledCellInRow(i, Color.red, 3000); } myAnimationScript.nextStep(); } // saveToBasis(i, j, x); public void buildLine7Animation(int i, int j, int x){ myCodeViewHandler.highlight(7); myGridViewHandler.getBasisGrid().setLabel(j, i,"" + x ); myGridViewHandler.getBasisGrid().highlightCell(j, i, Color.green, 0); myAnimationScript.nextStep(); } // angebot[i] -= x; public void buildLine8Animation(int supply_i, int x, int i, int j){ myGridViewHandler.getRightGrid().setNextLabelInRow(i, "" + supply_i); myCodeViewHandler.highlight(8); myVariableViewHandler.alter_variable_angebot_i(supply_i, x, i); myAnimationScript.nextStep(); } // nachfrage[j] -= x; public void buildLine9Animation(int demand_j, int x, int j){ myGridViewHandler.getBottomGrid().setNextLabelInColumn(j, "" + demand_j); myCodeViewHandler.highlight(9); myVariableViewHandler.alter_variable_nachfrage_j(demand_j, x, j); myAnimationScript.nextStep(); } // if(angebot[i] == 0) public void buildLine10Animation(){ myCodeViewHandler.highlight(10); myAnimationScript.nextStep(); } // i++; public void buildLine11Animation(int i){ myCodeViewHandler.highlight(11); myVariableViewHandler.alter_variable_i(i); } // else public void buildLine12Animation(){ myCodeViewHandler.highlight(12); myAnimationScript.nextStep(); } // j++: public void buildLine13Animation(int j){ myCodeViewHandler.highlight(13); myVariableViewHandler.alter_variable_j(j); } public void printScript(){ System.out.println(myAnimationScript); } public Language getMyAnimationScript() { return myAnimationScript; } }
C++
UTF-8
138
2.53125
3
[ "MIT" ]
permissive
#include <sensor.h> void Sensor::setReading(double reading) { m_reading = reading; } double Sensor::reading() const { return m_reading; }
Markdown
UTF-8
696
2.703125
3
[]
no_license
# Dashboards There are various dashboarding tools and experiences, below are a few mockups. Her is a nice blog showcasing a few of them https://www.datarevenue.com/en-blog/data-dashboarding-streamlit-vs-dash-vs-shiny-vs-voila#:~:text=Streamlit%20is%20a%20full%20data%20dashboarding%20solution%2C%20while,develop%20code%20and%20share%20it%20with%20other%20engineers. ## Streamlit Dashboard High School Enrollment Read more about streamlit here https://www.streamlit.io/ Basically this will allow us to deploy our plots in a website that is interactive. Todo: Scope out the details of this dashboard. To run: ``` streamlit run interactive_streamlit.py ``` ![](high-school-enrollment.png)
Markdown
UTF-8
823
2.890625
3
[]
no_license
## Processing non-ending text In previous chapters we saw how to process a document with FreeLing. The text was first read into a string, and then processed by each of the required modules. But in some scenarios it is not possible to load a whole document into a string \(e.g. when the document is very long\), or we may simply want to process a never-ending incoming stream of text. This section presents some examples of how to use FreeLing to process non-ending text. We will assume that the text is input one line after another, and that each line may contain several sentences. It is also possible that the last sentence in the line is not finished and we need to wait for the next line to decide whether it is a continuation or a new sentence. * [Example 08: SVO Triple extractor on non-ending text](example08.md)
Java
UTF-8
2,780
3.46875
3
[]
no_license
//package algorithm; // ///** // * @author xiaoqi.zyq@alibaba-inc.com // * @date 2019/08/19 // */ //public class LongestPalindromicSubstring { // // public static void main(String[] args) { // String aba = new LongestPalindromicSubstring().longestPalindrome("babad"); // System.out.println(aba); // } // // public String longestPalindrome(String s) { // if (s.isEmpty()) { // return ""; // } // int length = s.length(); // int max = 0; // String result = ""; // for (int pivot = 0; pivot < length; pivot++) { // int currentMax = 0; // if (pivot > 0) { // //不存在中心 todo // //存在中心 // int leftSize = pivot; // //int rightSize = length - pivot - 1; // //for (int i = 0; i < Math.abs(rightSize - leftSize); i++) { // // char leftChar = s.charAt(pivot); // // char rightChar = s.charAt(pivot + i); // // if (leftChar == rightChar) { // // currentMax++; // // } else { // // break; // // } // //} // if (currentMax > max) { // max = currentMax; // result = s.substring(pivot - max, pivot + max + 1); // } // //存在中心 // if (leftSize > rightSize) { // for (int i = 1; i < rightSize; i++) { // char leftChar = s.charAt(pivot - i); // char rightChar = s.charAt(pivot + i); // if (leftChar == rightChar) { // currentMax++; // } else { // break; // } // } // if (currentMax > max) { // max = currentMax; // result = s.substring(pivot - max, pivot + max + 1); // } // } else { // for (int i = 1; i < leftSize; i++) { // char leftChar = s.charAt(pivot - i); // char rightChar = s.charAt(pivot + i); // if (leftChar == rightChar) { // currentMax++; // } else { // break; // } // } // if (currentMax > max) { // max = currentMax; // result = s.substring(pivot - max, pivot + max + 1); // } // } // } // } // return result; // } //}
C#
UTF-8
2,541
2.734375
3
[ "Apache-2.0" ]
permissive
namespace Web.DataModels { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using Model; public class GameDetailedOutputDataModel { public GameDetailedOutputDataModel() { this.YourGuesses = new HashSet<GuessDataModel>(); this.OpponentGuesses = new HashSet<GuessDataModel>(); } public int Id { get; set; } public string Name { get; set; } public DateTime DateCreated { get; set; } public string Red { get; set; } public string Blue { get; set; } public string YourNumber { get; set; } public virtual IEnumerable<GuessDataModel> YourGuesses { get; set; } public virtual IEnumerable<GuessDataModel> OpponentGuesses { get; set; } public string YourColor { get; set; } public string GameState { get; set; } public static Expression<Func<Game, GameDetailedOutputDataModel>> ToModelRed { get { return g => new GameDetailedOutputDataModel() { Id = g.Id, Name = g.Name, DateCreated = g.DateCreated, Red = g.Red.UserName, Blue = g.Blue.UserName, YourNumber = g.RedNumber, YourGuesses = g.RedGuesses.AsQueryable().Select(GuessDataModel.ToModel), OpponentGuesses = g.BlueGuesses.AsQueryable().Select(GuessDataModel.ToModel), YourColor = "red", GameState = g.GameState.ToString(), }; } } public static Expression<Func<Game, GameDetailedOutputDataModel>> ToModelBlue { get { return g => new GameDetailedOutputDataModel() { Id = g.Id, Name = g.Name, DateCreated = g.DateCreated, Red = g.Red.UserName, Blue = g.Blue.UserName, YourNumber = g.BlueNumber, YourGuesses = g.BlueGuesses.AsQueryable().Select(GuessDataModel.ToModel), OpponentGuesses = g.RedGuesses.AsQueryable().Select(GuessDataModel.ToModel), YourColor = "blue", GameState = g.GameState.ToString(), }; } } } }