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
661
2.171875
2
[]
no_license
package com.example.crawler_server.service.serviceImp; import com.example.crawler_server.dao.ITaskDao; import com.example.crawler_server.entity.Task; import com.example.crawler_server.service.ITaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class TaskService implements ITaskService { @Autowired private ITaskDao iTaskDao; @Override public void push_task(Task task) { iTaskDao.push_task(task); } @Override public Task pop_task(String spiderName, String taskType) { return iTaskDao.pop_task(spiderName, taskType); } }
C
UTF-8
360
3.1875
3
[]
no_license
// Lap trinh C tren Ubuntu su dung Geany // Build: gcc baitap4.c -o baitap4 -lm /* Tinh log(a, x) voi a, x nhap tu ban phim x>0, a>0 va a khac 1 */ #include <stdio.h> #include <math.h> int main(){ float a, x; printf("Nhap vao 2 so a, x: "); scanf("%f%f", &a, &x); float logax = log(x)/log(a); printf("Log(a, x): %0.5f\n", logax); return 0; }
Markdown
UTF-8
4,150
3
3
[ "MIT" ]
permissive
--- uid: first-terrain title: Your first terrain --- ## The Absolute Basics Creating a terrain in Gaea is very simple. If you are new to graph based workflows, let's look at how easy it is to get a realistic mountain in seconds. If you have worked in graph-based applications, you will find it very easy to use Gaea. In fact, you will find our @conveniences a massive boost to your workflow. You can skip to [Create a simple terrain](#create-a-simple-terrain). #### Using the Graph ![](/images/first/first-001.webp) Drag the @Mountain node from the @toolbox and drop it onto the @graph. This will create the mountain node. ![](/images/first/first-002.webp) Next, find and drag the @Erosion node and drop it on top of the @Mountain node. ![](/images/first/first-003.webp) You will see that Gaea automatically connects the two for you. ![](/images/first/first-004.webp) The other way to make nodes is to drag a line out from one of the ports and drop it into empty space. ![](/images/first/first-005.webp) In the menu that shows up, start typing and you will be able to find the node you want. ![](/images/first/first-006.webp) Click the node you want in the list and it will create that node and connect it to where you dragged the line out from. #### Further learning Learn more about the @graph, @conveniences, @dragout, and the @learning. ## Create a simple terrain The core Gaea workflow is: Create-Modify-Erode-Texture-Export. Using the graph creation process above, let's create the following graph. We don't need to change any settings yet, as we will use just the defaults. Gaea's defaults are fine-tuned to give you great results almost every time. If you don't like the shape of the initial node, you can try changing the Seed value or using the `Bulky` option in the @Mountain node to make it larger. ![](/images/guide/simple-graph.webp) #### Create All terrains start with Primitives. These nodes are divided into Core Primitives which contain basic shapes and noises, and GeoPrimitives which provide geological shapes like @Mountain, @Ridge, @Crater, etc. ![](/images/guide/primitive-01.webp) These serve as the starting point on which you can add further modifications. You can mix multiple primitives by connecting the output of two primitives to a @Combine node and using various combination modes. #### Modify Modifications using nodes such as Adjustment and Filter nodes let you modify the primitive to change the shape, adjust heights, or even stylized it. ![](/images/guide/modify.webp) In our case, we will add a @Warp node to add some warping randomness to the shape. #### Erode This is the crucial point for most terrains. Erosion is what makes your procedural shape look realistic by performing millennia of geological processing in seconds. ![](/images/guide/erode.webp) You can use the @Erosion or @Wizard nodes to erode the terrain. #### Texture Once you have your terrain ready, it needs to be textured and colorized. ![](/images/guide/texture.webp) The @Texture node is great way to create a sophisticated mask made from slope, soil, and other components. A mask like this is needed to colorize the terrain. ![](/images/guide/satmap.webp) Next, use the @SatMaps node to pick from over 1400 satellite color maps to flow color through the @Texture mask. #### Build Now that your terrain is ready, you need to "build" the terrain to convert the graph into actual asset files such as displacement maps, meshes, and texture maps that you can take to your DCC app or game engine. See @building for more details. ## Next Steps #### Learn More - Read how Primitives work in the @primitives section. - Erosion has many intricacies which are crucial to learn. You can read more about it in @erosions. - Try the @lookdev nodes. They can create entire "looks" for a terrain in a single pass. They can replace or augment erosion nodes. - @color-production goes into more detail about how to create color maps. - Read the other pages of the **Using Gaea** section. #### Tutorials Try the following tutorials for a more advanced workflow. - @tut-hero-mountain - @tut-shattered-mountain-lake
Java
UTF-8
2,111
2.171875
2
[]
no_license
package com.boneix.base.mail.test; import com.boneix.base.mail.HtmlVelocityEngine; import com.boneix.base.mail.MailSender; import org.apache.commons.collections.map.HashedMap; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamSource; import org.springframework.core.io.UrlResource; import javax.annotation.Resource; import java.util.Map; /** * Created by rzhang on 2017/7/3. */ public class DemoTest extends BaseSpringTest { private static final Logger logger = LoggerFactory.getLogger(DemoTest.class); @Resource private MailSender mailSender; @Resource private HtmlVelocityEngine htmlVelocityEngine; @Test public void demoTest() { } @Test public void demoTestSendEmail() { String filePath = "demo.vm"; Map<String, Object> model = new HashedMap(); model.put("userName", "大家好"); String htmlText = htmlVelocityEngine.customizeMailHtmlText(filePath, model); String toAddress = "rzhang@mo9.com"; String subject = "发送邮件内容为html模板"; mailSender.sendEmailWithHtml(toAddress, subject, htmlText); } @Test public void demoTestSendEmailWithAttachments() { String filePath = "demo.vm"; Map<String, Object> model = new HashedMap(); model.put("userName", "rzhang@mo9.com"); String htmlText = htmlVelocityEngine.customizeMailHtmlText(filePath, model); String toAddress = "rzhang@mo9.com"; String subject = "发送邮件内容为html模板带有附件"; Map<String, InputStreamSource> filePaths = new HashedMap(); try { filePaths.put("change.sql", new FileSystemResource("D:/work/江湖救急/change.sql")); filePaths.put("logo.png", new UrlResource("http://misc.manmanbuy.com/images/logo.png")); } catch (Exception e) { logger.error("Exception happened ,{}", e); } mailSender.sendEmailWithAttachment(toAddress, subject, htmlText, filePaths); } }
Java
UTF-8
927
2.15625
2
[]
no_license
package com.jaygoaler.pitools.service.impl; import com.jaygoaler.pitools.model.User; import com.jaygoaler.pitools.mapper.UserMapper; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.Md5Crypt; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; @SpringBootTest class UserServiceImplTest { @Resource private UserMapper userMapper; @Test void createUser() { String userName = "jaygoaler"; String password = "yangjie520"; System.out.println(Md5Crypt.md5Crypt(password.getBytes())); System.out.println(DigestUtils.md5Hex(password)); User user = new User(userName,DigestUtils.md5Hex(password)); System.out.println(Md5Crypt.md5Crypt(password.getBytes()).length()); int i = userMapper.insert(user); System.out.println(i); } }
PHP
UTF-8
1,287
2.515625
3
[]
no_license
<?php /* * 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. */ include_once '../control/pohv_pri.php'; $abc = new pp(); // objekt //$abc ->vstaviPohvaloPritozbo('ulala', 'Pohvala', 'no ja'); //echo "Text: " . $abc ->getText(). "<br>"; //echo "Pohvala ali pritozba: " . $abc ->getPohv_pri(). "<br>"; //echo "Vzrok/namen: " . $abc ->getVzrok(). "<br>"; $res = $abc ->vrniVseZaposlene(); ?> <?php if(pg_num_rows($res) > 0){ ?> <table border="1"> <thead> <tr> <th>ime & priimek</th> </tr> </thead> <tbody> <?php while($row = pg_fetch_assoc($res)){ ?> <tr> <td><?php echo $row['ime_prii'];?></td> </tr> <?php } ?> </tbody> </table> <?php } $res = $abc ->vrniVseProstore(); if(pg_num_rows($res) > 0){ ?> <table border="1"> <thead> <tr> <th>naziv</th> </tr> </thead> <tbody> <?php while($row = pg_fetch_assoc($res)){ ?> <tr> <td><?php echo $row['naziv'];?></td> </tr> <?php } ?> </tbody> </table> <?php } ?>
Java
UTF-8
5,989
1.914063
2
[]
no_license
package project.client.internshipPlatform.userActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.button.MaterialButton; import com.google.android.material.textfield.TextInputEditText; import com.google.gson.Gson; import org.json.JSONObject; import project.client.internshipPlatform.DTO.ApplicationDto; import project.client.internshipPlatform.DTO.InternshipDetailsDto; import project.client.internshipPlatform.DTO.ResponseDto; import project.client.internshipPlatform.R; import project.client.internshipPlatform.RecycleViewInternshipActivity; import project.client.internshipPlatform.threads.ThreadRequest; public class InternshipDetails extends AppCompatActivity { private TextView title; private TextView description; private TextView company; private TextView period; private TextView domain; private TextView role; private TextInputEditText additionalNote; private String id; private String idInternship; private RequestQueue requestQueue; private MaterialButton applyButton; private InternshipDetailsDto data; private final String URL_DETAILS = "http://10.0.2.2:8080/api/internship/details/"; private final String URL_APPLY = "http://10.0.2.2:8080/api/apply/internship"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_internship_details); Bundle bundle = getIntent().getExtras(); id = bundle.getString("idUser"); idInternship = bundle.getString("idInternship"); title = findViewById(R.id.titleText); description = findViewById(R.id.descriptionText); company = findViewById(R.id.companyText); period = findViewById(R.id.periodText); domain = findViewById(R.id.domainText); role = findViewById(R.id.role); additionalNote = findViewById(R.id.additionalNoteEdit); data = new InternshipDetailsDto(); requestQueue = Volley.newRequestQueue(getApplicationContext()); jsonParse(); applyButton = findViewById(R.id.apply_button); applyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ApplicationDto applicationDto = new ApplicationDto(idInternship, id, additionalNote.getText().toString()); ThreadRequest threadRequest = new ThreadRequest(applicationDto, URL_APPLY); Thread t = new Thread(threadRequest); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } validateResponse(threadRequest.getResponseDto()); } }); setUpToolbar(); } public void validateResponse(ResponseDto responseDto) { Toast.makeText(getApplicationContext(), responseDto.getMessage(), Toast.LENGTH_LONG).show(); } private void setUpToolbar() { Toolbar toolbar = findViewById(R.id.app_bar); this.setSupportActionBar(toolbar); role.setText("Student"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.favoriteInternships) { Intent i = new Intent(getApplicationContext(), FavouriteInternship.class); i.putExtra("idUser", id); startActivity(i); Toast.makeText(this, "Here are your favourites", Toast.LENGTH_SHORT).show(); } else if (item.getItemId() == R.id.allInternshipsUser) { Intent i = new Intent(getApplicationContext(), RecycleViewInternshipActivity.class); i.putExtra("idUser", id); startActivity(i); Toast.makeText(this, "Here are all the internships", Toast.LENGTH_SHORT).show(); } if (item.getItemId() == R.id.applications) { Intent i = new Intent(getApplicationContext(), ApplicationActivity.class); i.putExtra("idUser", id); startActivity(i); Toast.makeText(this, "Here are all the internships", Toast.LENGTH_SHORT).show(); } return true; } private void jsonParse() { JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_DETAILS + idInternship, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Gson gson = new Gson(); data = gson.fromJson(String.valueOf(response), InternshipDetailsDto.class); title.setText(data.getTitle()); description.setText(data.getDescription()); company.setText(data.getCompany()); period.setText(data.getPeriod()); domain.setText(data.getDomain()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); requestQueue.add(request); } }
JavaScript
UTF-8
5,346
2.609375
3
[]
no_license
$(document).ready(function(){ $(".cell").html("&nbsp;"); $("body").append("<div class='d8'>abc</div>"); start(); $(document).on("click",".btn",function(){ clicked($(this).attr("id")); }); }); function clicked(name){ orientation="empty";direction="empty"; if ((name==="left")||(name==="right")) orientation="horizontal"; else orientation="vertical"; if ((name==="left")||(name==="up")) direction="negative";//(1,1) is at bottom left corner else direction="positive"; //console.log("img/btn:"+name+" = "+orientation+" "+direction); move(orientation,direction); } function getId_traversal(orientation,i,j) { switch(orientation){ case 'horizontal' : return "#"+i+""+j; break; case 'vertical' : return "#"+j+""+i; break; default: } } function getStart_traversal_id(direction,len,p_len) { switch(direction){ case 'positive' : return len -p_len +1;//as will begun from end break; case 'negative' : return 1; break; default: } } function log_current(){ for(i=1;i<=4;i++){ col=""; for(j=1;j<=4;j++){ id="#"+i+""+j+""; col=col+" "+$(id).html(); } console.log(i+" "+col); } } function move(orientation,direction) { log_current(); //get values in array moving_space=false; same_neighbour=false; sensible_move=false; empty_neighbour=false; read_h=[]; for(i=1;i<=4;i++){ arr=[]; atleast_one=false; for(j=1;j<=4;j++) { id=getId_traversal(orientation,i,j);//difference of horizontal or vertical filled=($(id).hasClass("filled")); if(!filled){ oe=oppositeEdge(direction,4); //console.log("oe for "+id+" "+orientation+" "+direction+" "+ oe); if( j != oe )/*i.e. non-empty and not oppside, hence moving space*/ {moving_space=true;} } else{ if(direction==="positive"&&j!=4){ nextId=getId_traversal(orientation,i,j+1); empty_neighbour=(empty_neighbour||(!($(nextId).hasClass("filled")))); console.log(id+" "+ orientation+" "+direction +" "+empty_neighbour); } if(direction==="negative"&&j!=1){ nextId=getId_traversal(orientation,i,j-1); empty_neighbour=(empty_neighbour||(!($(nextId).hasClass("filled")))); console.log(id+" "+ orientation+" "+direction +" "+empty_neighbour); } atleast_one=true;arr.push($(id).html()); } } sensible_move=(sensible_move||moving_space&&atleast_one); //console.log(i+" moving_space"+moving_space+" atleast_one "+atleast_one+" sensible_move"+sensible_move); read_h.push(arr); } //console.log("read_h "+read_h); //calculate values into array print_h=[]; for(i=0;i<read_h.length;i++){ arr=[]; for(j=0;j<read_h[i].length;){ if(j+1==read_h[i].length){arr.push(read_h[i][j]);j=j+1;} else if(read_h[i][j]!==read_h[i][j+1]){arr.push(read_h[i][j]);j=j+1;} else{arr.push(""+parseInt(read_h[i][j])*2);j=j+2;same_neighbour=true;} } print_h.push(arr); } //console.log("print_h "+print_h.length+ " "+print_h); if(!(same_neighbour||empty_neighbour)){return;} //change contents clear_t(); //clear the current table display_h=[]; len = 4; for(i=0;i<print_h.length;i++) { si=i+1; p_len=print_h[i].length;//console.log("plen "+p_len); st=getStart_traversal_id(direction,len,p_len);//difference of positive and negative sj=st; // console.log(si+ " s: "+sj); for(j=0;j<p_len;j++) { //console.log(si+ " s: "+sj); id=getId_traversal(orientation,si,sj);//difference of horizontal or vertical //console.log(" to change: "+id+" val: "+print_h[i][j]); set(id,print_h[i][j]);//console.log("print_h index: "+j+" filling_index: "+si+" id: "+id+" val: "+print_h[i][j]); sj++; } } if(!(isOver())){ id=getEmptyId(); set(id,"2");} else{alert("gameOver");} } function oppositeEdge(direction,len) { switch(direction){ case 'positive': return 1; break; case 'negative': return len; break; default: } } function isOver() { allFilled=true; equalsGoal=false; goal="32"; for(i=1;i<=4;i++) { for(j=1;j<=4;j++) { id="#"+i+""+j; equalsGoal=( $(id).html()===goal ); if(equalsGoal) {console.log("Reached Goal");} allFilled=(allFilled&&( ($(id).hasClass("filled")) )); //console.log(id+" "+allFilled); } } if(allFilled){console.log("Sorry No valid move left");} return (allFilled || equalsGoal); } function clear_t(){ for(i=1;i<=4;i++){ for(j=1;j<=4;j++){ unset("#"+i+""+j); } } } function start(){ id1=getEmptyId();set(id1,"2"); id2=getEmptyId();set(id2,"2"); /*for(i=1;i<=4;i++) { for(j=1;j<=4;j++) { set("#"+i+""+j,10*i+j); } } unset("#44");set("#44","43"); unset("#33");set("#33","43"); unset("#12");set("#12","14"); unset("#13");*/ } function unset(id){ $(id).removeClass(); //removeall $(id).addClass("cell"); $(id).html("&nbsp;"); } function set(id,val){ $(id).html(val); $(id).addClass("d"+val); $(id).addClass("filled"); } function getEmptyId(){ id = randomId(); while($(id).hasClass("filled")){id=randomId();} return id; } function randomId(){ row= Math.floor((Math.random()*4)+1); column= Math.floor((Math.random()*4)+1); id="#"+row+""+column; return id; }
Java
UTF-8
3,092
2.3125
2
[]
no_license
package com.example.demo.client.api; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.example.demo.client.api.entity.DesireUserInGroupResponce; import com.example.demo.client.exception.NotFoundException; import com.example.demo.client.exception.NotInsertedGroupDesireException; import com.example.demo.client.rest.RestTemplateAdapter; import com.example.demo.security.UserDetailsImp; import lombok.Data; /** * グループ加入してほしい申請に関するAPIを呼び出すクラス */ @Component public class DesireGroupApi { @Autowired RestTemplateAdapter restTemplateAdapter; private static final String ROOT_URL = ApiUrlRootConfing.ROOT_URL + "/desire/group"; /** * グループに加入してほしい申請リストの取得 * @param user ログイン情報 * @return グループに加入してほしい申請リスト */ public List<DesireUserInGroupResponce> getDesireUserList(UserDetailsImp user) { final String URL = ROOT_URL + "/gets"; return restTemplateAdapter.getForListWhenLogined(URL, null, DesireUserInGroupResponce[].class, user); } /** * グループに加入してほしい申請を取得する * @param user ログイン情報 * @param talkRoomId グループトークルーム * @return グループに加入してほしい申請 * @throws NotFoundException */ public DesireUserInGroupResponce getDesireUser(UserDetailsImp user, Integer talkRoomId) throws NotFoundException{ final String URL = ROOT_URL + "/get"; var dto = new Dto(); dto.setTalkRoomId(talkRoomId); return restTemplateAdapter.getForObjectWhenLogined(URL, dto, DesireUserInGroupResponce.class, user); } /** * グループ加入してほしい申請を断る * @param user ログイン情報 * @param talkRoomId グループトークルームID * @throws NotFoundException * @throws NotInsertedGroupDesireException */ public void deleteDesireGroup(UserDetailsImp user, Integer talkRoomId) throws NotFoundException, NotInsertedGroupDesireException{ final String URL = ROOT_URL + "/delete"; var dto = new Dto(); dto.setTalkRoomId(talkRoomId); restTemplateAdapter.postForObjectWhenLogined(URL, dto, null, user); } /** * グループ加入してほしい申請を受ける * @param userログイン情報 * @param talkRoomId グループトークルームID * @throws NotFoundException * @throws NotInsertedGroupDesireException */ public void joinGroup(UserDetailsImp user, Integer talkRoomId) throws NotFoundException, NotInsertedGroupDesireException{ final String URL = ROOT_URL + "/join"; var dto = new Dto(); dto.setTalkRoomId(talkRoomId); restTemplateAdapter.postForObjectWhenLogined(URL, dto, null, user); } /** * 友達追加申請に関するAPIのパラメターを送るためのDtoクラス */ @Data public class Dto{ private Integer talkRoomId; } }
C++
ISO-8859-10
875
3.640625
4
[]
no_license
#include <iostream> #include <conio.h> #include <stdlib.h> //Pila= Es una estructura de datos ordenada en la que el modo // de acceso a sus elementos de tipo LIFO using namespace std; struct Nodo{ int dato; Nodo *siguiente; }; void agregarPila(Nodo *&,int);//Prototipo agregar Nodo int main(int argc, char** argv) { Nodo *pila = NULL; int nodo1,nodo2; cout<<" \n Insertar Dato 1: "; cin>>nodo1; agregarPila(pila,nodo1); cout<<" \n Insertar Dato 2: "; cin>>nodo2; agregarPila(pila,nodo2); return 0; } void agregarPila(Nodo *&pila, int a){ Nodo *nuevo_nodo = new Nodo(); //creamos espacio de memoria para guardar nuevo nodo nuevo_nodo->dato= a; //mandamos el valor a Nodo nuevo_nodo->siguiente=pila; //mandamos el nuevo nodo a pila pila = nuevo_nodo; //pila seala a nuevo nodo cout<<" \n Dato: "<<a<<" \n\n Agregado a Pila exitosamente"<<endl; }
C#
UTF-8
351
2.546875
3
[]
no_license
using System; namespace BasicAtmMachine { public class Customer { public Customer() { Id = Guid.NewGuid(); CardNo = Guid.NewGuid().ToString(); } #region Properties public Guid Id { get; set; } public string CardNo { get; set; } #endregion } }
TypeScript
UTF-8
528
2.546875
3
[ "MIT" ]
permissive
import { Currency } from '../Generated/web/org/xrpl/rpc/v1/amount_pb' /** * An issued currency on the XRP LEdger * @see: https://xrpl.org/currency-formats.html#currency-codes */ export default class XRPCurrency { public static from(currency: Currency): XRPCurrency { return new XRPCurrency(currency.getName(), currency.getCode_asU8()) } /** * @param name 3 character ASCII code * @param code 160 bit currency code. 20 bytes */ private constructor(readonly name: string, readonly code: Uint8Array) {} }
Markdown
UTF-8
973
3.734375
4
[]
no_license
# cs50 It is a repository of all my programs written for solving problem sets in the CS50 course of Harvard University. It is a C program that determines whether a provided credit card number is valid according to Luhn’s algorithm. In addition to that, the program is written in such a manner that it can also print the credit card's company name (either AMEX or VISA or MASTERCARD). So the output set of the program is { AMEX, VISA, MASTERCARD, INVALID }. Most cards use this algorithm invented by Hans Peter Luhn, a fellow from IBM. According to Luhn’s algorithm, we can determine if a credit card number is (syntactically) valid as follows: 1. Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products' digits together. 2. Add the sum to the sum of the digits that weren’t multiplied by 2. 3. If the total’s last digit is 0 (or, put more formally, if the total modulo 10 is congruent to 0), the number is valid!
Markdown
UTF-8
3,001
2.8125
3
[]
no_license
# As dez virgens {#as-dez-virgens} [Mateus 25:1-5](http://bibliaonline.com.br/acf/mt/25/1-5) Enquanto a primeira parte do [capítulo 24](http://bibliaonline.com.br/acf/mt/24) de Mateus trata da vinda do Messias e Rei para Israel no final da grande tribulação, o [capítulo 25](http://bibliaonline.com.br/acf/mt/25) fala de sua vinda em relação aos que professam crer nele, tanto falsos como verdadeiros. Se você se lembra de tudo o que vimos sobre o Reino dos céus, verá que esta parábola também começa se referindo a esse Reino de um Rei que está ausente. As dez virgens não representam a Igreja no singular, como a noiva, pois isso só seria revelado mais tarde ao apóstolo Paulo. Não representam tampouco um casamento poligâmico. A noiva, única e perfeita, formada apenas por aqueles que são genuínos, não aparece aqui como tal. As dez virgens representam o testemunho individual daqueles que professam crer em Jesus. Todas elas têm uma lamparina, dessas que funcionam com óleo ou azeite. Na Bíblia, a candeia ou lamparina aparece como símbolo de testemunho. Você se lembra do [capítulo 5](http://bibliaonline.com.br/acf/mt/5), quando Jesus chamou os discípulos de “luz do mundo” ([Mt 5:14](http://bibliaonline.com.br/acf/mt/5/14))? Pois é, quem acendesse uma candeia devia colocá-la num lugar alto para iluminar toda a casa, e não debaixo de uma vasilha. Assim também deveria brilhar a luz dos que professam crer em Jesus, para que os homens vissem e dessem glória a Deus. Mas, das dez virgens, cinco são insensatas e não têm azeite, e cinco são prudentes, e suas lâmpadas estão abastecidas. Na Bíblia, o azeite aparece como figura do Espírito Santo, portanto temos aqui uma mistura de pessoas com e sem o combustível de um testemunho real. Apesar disso, todas caem no sono da indiferença. Tanto as prudentes como as insensatas sabiam da vinda do noivo, mas perderam a expectativa disso ocorrer a qualquer momento. Acaso não foi o que aconteceu com a cristandade como um todo? Não sei se você sabe, mas nestes dois mil anos de história nem sempre os cristãos esperaram pela vinda de Jesus. A grande maioria sempre acreditou que se encontrar com Jesus significava morrer, e se você chegasse para alguém assim e dissesse que Jesus poderia vir naquele exato momento, é bem provável que veria uma expressão de horror na cara da pessoa. Outros achavam que a vinda de Cristo para a Igreja seria precedida da tribulação, portanto não podia acontecer num piscar de olhos. Essa ideia também excluía Israel e só contemplava a Igreja. Não precisou muito para os cristãos passarem a enxergar os judeus como descartáveis. Procure na Internet um manifesto escrito por Martinho Lutero com o título “Sobre os judeus e suas mentiras” e você ficará surpreso com o pensamento que era corrente em sua época. Bem, meus 3 minutos terminaram e vou deixar para falar do que acontece à meia noite nos próximos 3 minutos. tic-tac-tic-tac...
Markdown
UTF-8
3,596
3.984375
4
[]
no_license
# 斐波那契数列 ## 1.数学定义 斐波那契数列: [维基百科](https://en.wikipedia.org/wiki/Fibonacci_number) <img src = "https://github.com/shawshanks/Data-Structure-and-Algrithm/blob/master/image/%E8%8F%B2%E6%B3%A2%E9%82%A3%E5%88%87%E6%95%B0%E5%88%97%E5%AE%9A%E4%B9%89.PNG" width = '100%'> 即 ```python Fib(n) = n , if n = 0,1 = Fib(n-1) + Fib(n-2) , if n >2 ``` # 递归完成 ## 1.Python的第一种完成 (效率比较差的递归) 根据定义写 ```python def Fib(n): if n <= 1: return n else: return Fib(n-1) + Fib(n-2) ``` Fib() 每次调用时, 都会再调用两次Fib(). 所以这种写法的复杂度是 `O(2^n)`, 指数函数.不可接受. ## 2. 递归的优化写法 ### 思路 尝试 Fib()中每次只调用一次自身.那么我们需要在函数完成其中一个调用函数(`fib(n-1)`或`fib(n-2)`的过程. 这个递归函数`fib(n)`返回一个连续的斐波那契数列数列中的两个数`(f(n), f(n-1))`. 每次调用`fib(n)`时想要达到的效果如下: ``` f(0) f(1) f(2) f(3) f(4) f(5) f(6) f(7) f(8) ... f(n) (0,1) (1,1) (1,2) (2,3) (3,5) (5,8) (8,13) (13,21) (21,34) (...) (an, an+1) / \ / \ / \ a0 a1 a1 a2 a2 a3 ................................................ 注: a0表示斐波那契数列第0项,a1 表示第1项,依次类推, an表示第n项,an+1表示第 n+1项 ``` ### 实现 ```python def fib(n): if n <= 1: return (n, 1) # 这里不返回(0,1),因为f(n)返回的是左边的元素. else: # f(0)[0]返回0, f(1)[0]返回的还是1 (a, b) = fib(n-1) return (b, a+b) ``` ### 调用fib(n)过程图示 注: 绿线表示从上往下的调用过程 黄线表示从下往上的返回过程 <img src= 'https://github.com/shawshanks/Data-Structure-and-Algrithm/blob/master/image/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E5%87%BD%E6%95%B0%E8%B0%83%E7%94%A8.png' width= '100%'> ### 包装调用,F(n)返回第n项的值 如果我们想要返回一个相应的值,只需再调用`fib()`的结果就行了.可以写成以下两种形式: ```python def fib(n): if n <= 1: return (n, 1) # 这里不返回(0,1),因为f(n)返回的是左边的元素. else: # f(0)[0]返回0, f(1)[0]返回的还是1 (a, b) = fib(n-1) return (b, a+b) def F(n): return fib(n)[0] ``` 或者 ```python def F(n): def fib(n): if n <= 1: return (n, 1) # 这里不返回(0,1),因为f(n)返回的是左边的元素. else: # f(0)[0]返回0, f(1)[0]返回的还是1 (a, b) = fib(n-1) return (b, a+b) return fib(n)[0] ``` ## 也可以用字典暂时存储递归中的值 ```python memo = {0:0, 1:1} def fib2(n): if not n in memo: memo[n] = fib2(n-1)+fib2(n-2) return memo[n] ``` 与上面 元组 的作用一样, 存储之前计算的值. 不同的是, 返回的元组 有固定结构 (an, an+1), 每次返回只存储两个值. 而这个字典把之前所有的值都存储起来. # 迭代完成 ## for-loop完成 ```python def fib(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return a ``` ## while-loop 完成 ```python: def fib(n): a, b = 0, 1 while n >= 1: a, b = b, a+b n -= 1 return a ``` 或者 用`yield`生成器 ```python def fib(n): a, b = 0, 1 while n > 0: yield a a, b = b, a+b n -= 1 ``` # 听说还能用矩阵方法表示, 不过暂时就到这里吧
Markdown
UTF-8
4,972
2.984375
3
[]
no_license
# Git ## 使用频率较高的操作 ### 分支 * `git checkout master` 切换分支 * `git branch dev` 新建分支dev * `git checkout -b dev` 新建dev分支并切换到dev * `git merge dev` 在当前分支上将dev合并进来 * `git stash` 将当前工作现场“储藏”起来,等以后恢复现场后继续工作,存储之后status是干净的,可以切其他分支操作,操作完成之后再切回来,取回暂存 * `git stash list` 查看暂存区有哪些 * `git stash apply` 将暂存区内容回复到本地,但是暂存区内容不删除 * `git stash drop` 删除暂存区内容 * `git stash pop` 恢复并删除,相当于前面两步 * `git symbolic-ref --short -q HEAD` 获取当前分支名 * 分支开发策略 ![](https://cdn.liaoxuefeng.com/cdn/files/attachments/001384909239390d355eb07d9d64305b6322aaf4edac1e3000/0) * 合并冲突:在两个同时提交合并是,手动合并冲突。 ### 版本回退 * `git reset --hard HEAD^`回退到上一个版本,几个`^`表示回退到往前第几个版本。 * 使用`HEAD^`经常遇到提示More?的问题, 这是因为换行符`\n`的问题,可以使用 `HEAD~1`或者`HEAD~n`或者`git reset --hard "HEAD^"` * `git reset --hard commitID的前几位` 回退到指定提交ID的那个版本 * 经常遇到以下场景,回退到上一个版本,又发现不好,想回到回退之前的版本,又忘了上一个commitID,使用`git reflog`查看上一个ID,再使用`git reset --hard commitID的前几位` ### 撤销修改 * `git checkout -- file`可以丢弃工作区的修改, 分两种情况 * 一种是readme.txt自修改后还没有被放到暂存区,现在,撤销修改就回到和版本库一模一样的状态; * 一种是readme.txt已经添加到暂存区后,又作了修改,现在,撤销修改就回到添加到暂存区后的状态。 * * `git reset HEAD <file>` 把暂存区的修改撤销掉(unstage),重新放回工作区 在使用撤销修改时,基本有以下三种场景: * 场景1:当你改乱了工作区某个文件的内容,想直接丢弃工作区的修改时,用命令git checkout -- file。 * 场景2:当你不但改乱了工作区某个文件的内容,还添加到了暂存区时,想丢弃修改,分两步,第一步用命令git reset HEAD <file>,就回到了场景1,第二步按场景1操作。 * 场景3:已经提交了不合适的修改到版本库时,想要撤销本次提交,参考版本回退一节,不过前提是没有推送到远程库。 `git checkout`不能对新增的文件进行撤销,这时候就该`git clean`上场了 #### 强大的 git clean 命令 `git clean`命令用来从你的工作目录中删除所有没有tracked过的文件 注意区分与`reset`之间的区别, - `reset`命令影响的是被tracked的文件 - `clean`删除的没有被tracked的文件 先介绍一下命令参数 - `-n`: 是一次clean的演习, 告诉你哪些文件会被删除. 记住他不会真正的删除文件, 只是一个提醒 - `-f`: 删除当前目录下所有没有track过的文件. 他不会删除`.gitignore`文件里面指定的文件, 不管这些文件有没有被track过 - `-d`: 删除当前目录下所有没有track过的文件夹. 他不会删除`.gitignore`文件里面指定的文件夹, 不管这些文件有没有被track过 - `-x`: 删除当前目录下所有没有track过的文件. 不管他是否是`.gitignore`文件里面指定的文件夹和文件 - 命令可以组合使用,经常用的命令为`git clean -ndf` 删除,没有使用track过的的文件和文件夹。 - 命令后可以直接更路径`<path>` - 慎用`-x`, 因为他会把所有文件都删除,不会检查`.gitignore`文件 ### 删除文件 * `git rm file` 从版本库中删除文件 * 删除之后可以使用`git checkout --file`找回来 ### 暂存 ## 相似命令对比 ### merge VS rebase git merge ![](https://user-gold-cdn.xitu.io/2018/5/9/16342fbc3161f98e?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) - 保留所有的commit记录,合并到master上,master上有开发分支所有的commit记录。 - 会有一条合并的commit记录 git rebase ![](https://user-gold-cdn.xitu.io/2018/5/9/16342fc20a6c6c8f?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) - rebase会合并commit记录,使commit变得干净。 - 冲突解决不一样,无需执行 git-commit,只要执行 continue - 有一定危险性,尤其使多人开发同一个分支的时候,提交顺序不同,commit会被合并掉,其他人看不到。 ## 环境 ### git多平台换行符问题 window上配置如下 ``` $ git config --global core.autocrlf input $ git config --global core.safecrlf true ``` ## 参考 - [git book](https://www.progit.cn/#_git_stashing) - [廖雪峰Git](https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000) - [git clean的用法](https://www.jianshu.com/p/0b05ef199749)
Java
UTF-8
5,474
2.234375
2
[]
no_license
package com.qtpselenium.suiteA; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.RandomStringUtils; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.qtpselenium.util.ErrorUtil; import com.qtpselenium.util.TestUtil; public class New_Pharma extends TestSuiteBase{ String runmodes[]=null; static int count=-1; static boolean fail=false; static boolean skip=false; static boolean isTestPass=true; // Runmode of test case in a suite @BeforeTest public void checkTestSkip(){ if(!TestUtil.isTestCaseRunnable(suiteAxls,this.getClass().getSimpleName())){ APP_LOGS.debug("Skipping Test Case"+this.getClass().getSimpleName()+" as runmode set to NO");//logs throw new SkipException("Skipping Test Case"+this.getClass().getSimpleName()+" as runmode set to NO");//reports } runmodes=TestUtil.getDataSetRunmodes(suiteAxls, this.getClass().getSimpleName()); } @Test(dataProvider="getTestData") public void new_Pharma( String Display_Name, String Email, String Store_Name, String Address, String Address2, String City, String State, String Phone, String Zip_code, String Fax ) throws InterruptedException, IOException{ count++; if(!runmodes[count].equalsIgnoreCase("Y")){ skip=true; throw new SkipException("Runmode for test set data set to no "+count); } APP_LOGS.debug(" Executing TestCase_A2"); APP_LOGS.debug(Display_Name +" -- "+Email +" -- "+Store_Name+Address +" -- "+Address2 +" -- "+City+" -- "+State+" -- "+Phone+" -- "+Zip_code+" -- "+Fax ); // openBrowser(); login("sam", "password$1"); Thread.sleep(8000); try { wait_until_element_present_to_click("patient_button"); js_click("patient_button"); wait_until_element_present("lookup_window"); verify_title("lookup_window", "Patient Lookup"); wait_until_element_present_to_click("new"); js_click("new"); String str = RandomStringUtils.randomAlphabetic(5); verify_title("new_patient_title", "New Patient Information"); write_input("First_name", "Aakar11"+str); write_input("Last_name", "Gupte"); write_input("DOB", "05/02/1990"); click("DOB_label"); js_click("Sex_click"); String Sex= "Male"; WebElement ex = driver.findElement(By.xpath(OR.getProperty("Sex_click"))); if(Sex.equalsIgnoreCase("Male")) { ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ENTER); } else if(Sex.equalsIgnoreCase("Female")) { ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ENTER); } else if(Sex.equalsIgnoreCase("")) { ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ARROW_DOWN); ex.sendKeys(Keys.ENTER); } /*** * * Below code would open pharmacy and add the values into it * */ click("Pharma_bar"); click("Pharma_add"); click("Pharma_new"); write_input("Display_Name", Display_Name+str); write_input("Email", Email); write_input("Store_Name", Store_Name); write_input("Address", Address); write_input("Address2", Address2); write_input("City", City); write_input("State", State); write_input("Phone", Phone); write_input("Zip_code", Zip_code); write_input("Fax", Fax); click("New_pharma_ok"); click("New_pharma_ok_alert"); /*** * * Below code will search the pharmacy enter in the pharma name column */ String name_pharma=driver.findElement(By.xpath(OR.getProperty("Display_Name"))).getAttribute("value"); write_input("Pharma_name_Search", name_pharma); Thread.sleep(5000); /*** * Now clear the search and select the pharma from the list. (search pharma will not be selected as ID changes for every new) * */ driver.findElement(By.xpath(OR.getProperty("Pharma_name_Search"))).clear(); click("Select_pharma"); js_click("Pharma_final_ok"); js_click("new_pt_ok"); } catch(Exception t) { ErrorUtil.addVerificationFailure(t); fail=true; Assert.fail("Unable to proceed ahead", t); } } @AfterMethod public void reportDataSetResult(){ if(skip) TestUtil.reportDataSetResult(suiteAxls, this.getClass().getSimpleName(), count+2, "SKIP"); else if(fail){ isTestPass=false; TestUtil.reportDataSetResult(suiteAxls, this.getClass().getSimpleName(), count+2, "FAIL"); } else TestUtil.reportDataSetResult(suiteAxls, this.getClass().getSimpleName(), count+2, "PASS"); skip=false; fail=false; } @AfterTest public void reportTestResult(){ if(isTestPass) TestUtil.reportDataSetResult(suiteAxls, "Test Cases", TestUtil.getRowNum(suiteAxls,this.getClass().getSimpleName()), "PASS"); else TestUtil.reportDataSetResult(suiteAxls, "Test Cases", TestUtil.getRowNum(suiteAxls,this.getClass().getSimpleName()), "FAIL"); } @DataProvider public Object[][] getTestData(){ return TestUtil.getData(suiteAxls, this.getClass().getSimpleName()) ; } }
Java
UTF-8
348
1.84375
2
[]
no_license
package com.example.demo.model; import java.util.List; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface JobRepo extends CrudRepository<Job, String>{ public List<Job> findAll(); public Job findJobByjobId(String jobId); //public Job getjob(String id); }
JavaScript
UTF-8
1,119
2.734375
3
[]
no_license
const Application = require('./src/application'); const argv = require('yargs') .usage('Usage: $0 [options]') .describe('i', 'File with employees. Should be in JSON format.') .describe('y', 'Year to get vacation days') .describe('o', 'File to save result') .demandOption(['i', 'y']) .default({'o': 'output.json'}) .alias('i', 'input') .alias('y', 'year') .alias('o', 'output') .help(false) .version(false) .argv; const year = argv.year; const inputFileName = argv.input; const outputFileName = argv.output || 'output.json'; process.on('uncaughtException', (err) => { console.log(`Unhandled Exception: ${err}\n`); }); process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at:', p, 'reason:', reason); }); try { const results = Application.Start(inputFileName, outputFileName, year); console.log(`Operation completed.\nNumber of employees are ${results.length}.\nResults saved in ${outputFileName}`); } catch (error) { console.log(`Unable to perform operation.\n${error.toString()}`); }
Python
UTF-8
2,273
3.234375
3
[]
no_license
#!/usr/bin/env python3 import hashlib import base64 from typing import Callable def encode_decode_bytes(byte_message: bytes, encode_fn: Callable[[bytes], bytes]) -> bytes: return encode_fn(byte_message) def encode_text(text: str, encoding_format: str = 'ascii') -> str: return encode_decode_bytes(text.encode(encoding_format), base64.b64encode).decode(encoding_format) def decode_text(text: str, encoding_format: str = 'ascii') -> str: return encode_decode_bytes(text.encode(encoding_format), base64.b64decode).decode(encoding_format) def encode_file(path:str) -> bytes: with open(path, 'rb') as file_to_encode: return encode_decode_bytes(file_to_encode.read(), base64.b64encode) def decode_file(path:str) -> bytes: file_to_encode = open(path, 'rb') return encode_decode_bytes(file_to_encode.read(), base64.b64decode) def save_file(path: str,content: bytes) -> None: with open(path, 'wb') as file_to_save: file_to_save.write(content) def encode_plus_one(word:str) -> str: return "".join([chr(ord(character)+2) for character in word]) if __name__ == '__main__': import sys cmds = {'encode': base64.b64encode, 'decode': base64.b64decode} if len(sys.argv) > 1: main_cmd = sys.argv[1] encode_format = sys.argv[2] if len(sys.argv) > 2 else 'ascii' code_function = cmds.get(main_cmd, cmds.get('encode')) print(encode_decode_bytes(sys.stdin.read(), code_function)) #Codifica y guarda el msg.txt save_file('msg_codificado.txt', encode_file('msg.txt')) #Codifica y guarda fcfm.png a un .txt save_file('fcfm_codificado.txt', encode_file('fcfm.png')) #Decodifica y guarda la imagen misteriosa de txt a un png. save_file('mystery_img.png', decode_file('mystery_img.txt')) #Decodifica y guarda la imagen misteriosa 2 de txt a un png. save_file('mystery_img2.png', decode_file('mystery_img2.txt')) #Verfifica que las imagenes tengan el sha256 correcto filename = input("Ingrese el nombre del archivo con su extensión: ") sha256_hash = hashlib.sha256() with open(filename,"rb") as f: for byte_block in iter(lambda: f.read(4096),b""): sha256_hash.update(byte_block) print(sha256_hash.hexdigest())
Java
UTF-8
545
2.53125
3
[]
no_license
package org.jugru.minijunit.assertion; import static org.jugru.minijunit.assertion.AssertUtils.buildPrefix; import static org.jugru.minijunit.assertion.AssertUtils.fail; public class AssertNull { private static final String EXPECTED_NULL = "expected: <null>"; static void assertNull(Object object) { assertNull(object, null); } static void assertNull(Object object, String message) { if (object != null) { fail(buildPrefix(message + EXPECTED_NULL)); } } private AssertNull() {} }
JavaScript
UTF-8
1,230
3
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Introduction to the DOM Lab</title> </head> <body> <!--All our work for this lesson will go here--> <h1>My HTML adventure</h1> <p> We're writing HTML markup to display in our <strong>browser</strong>. We're basically telling computers what to do. <em>Neat!</em> We're writing <a href="https://developer.mozilla.org/en-US/docs/Web/HTML">HTML</a> markup to display in our <strong>browser</strong>. </p> <table> <thead> <tr> <th>Element name</th> <th>Display value</th> </tr> </thead> <tbody> <tr> <td>h1</td> <td>block</td> </tr> <tr> <td>p</td> <td>block</td> </tr> <tr> <td>strong</td> <td>inline</td> </tr> <tr> <td>em</td> <td>inline</td> </tr> </tbody> </table> </body> </html>
C#
UTF-8
1,143
3.40625
3
[]
no_license
//----------------------------------------------------------------------- // <copyright file="Program.cs" company="Telerik Academy"> // Telerik Academy by Progress // </copyright> // <author>Petromil "Dominent" Pavlov </author> //----------------------------------------------------------------------- namespace IEnumerableExtensions { using System; using System.Linq; /// <summary> /// Public class holding the main starting point of our program. /// </summary> public class Program { /// <summary> /// Main starting point of our program /// </summary> public static void Main() { var array = new int[] { 1, 2, 3, 4, 5, 6 }; array = array.Add<int>(22).ToArray<int>(); foreach (var item in array) { Console.WriteLine(item); } Console.WriteLine(array.Product<int>(array[0], array[1])); Console.WriteLine(array.Min<int>(array[0], array[1])); Console.WriteLine(array.Max<int>(array[0], array[1])); } } }
Python
UTF-8
2,045
2.703125
3
[]
no_license
import numpy as np from astropy import wcs from astropy.io import fits import pdb import astropy.coordinates as coord import astropy.units as u def add_wcs_to_nirc2(nirc2_file, x_16C, y_16C): """ x_16C -- pixel position y_16C -- pixel position """ # Create a new WCS object. The number of axes must be set # from the start w = wcs.WCS(naxis=2) scale = 0.00995 # arcsec / pixel scale /= 3600.0 # degrees / pixel img, hdr = fits.getdata(nirc2_file, header=True) pa = hdr['ROTPOSN'] - hdr['INSTANGL'] + 0.252 # degrees print pa cpa = np.cos(np.radians(-pa)) spa = np.sin(np.radians(-pa)) # cd = np.array([[-cpa, -spa], [-spa, cpa]]) # cd *= scale cd = np.array([[-cpa, -spa], [-spa, cpa]]) #cd *= scale print cd # Set up an "Airy's zenithal" projection # Vector properties may be set with Python lists, or Numpy arrays w.wcs.crpix = [x_16C, y_16C] w.wcs.crval = [266.41709, -29.007574] w.wcs.cdelt = np.array([scale, scale]) w.wcs.ctype = ['RA---TAN', 'DEC--TAN'] #w.wcs.cd = cd w.wcs.pc = cd # Some pixel coordinates of interest. pixcrd = np.array([[528.25, 644.94], [438.0, 98.0]]) # Convert pixel coordinates to world coordinates world = w.wcs_pix2world(pixcrd, 1) print(world) # Convert the same coordinates back to pixel coordinates. pixcrd2 = w.wcs_world2pix(world, 1) print(pixcrd2) c = coord.SkyCoord(ra=world[0, 0] * u.degree, dec=world[0, 1] * u.degree) print 'Sgr A*: ', c.to_string('hmsdms') c = coord.SkyCoord(ra=world[1, 0] * u.degree, dec=world[1, 1] * u.degree) print ' IRS 7: ', c.to_string('hmsdms') # Now, write out the WCS object as a FITS header header = w.to_header() for key in header.keys(): hdr[key] = (header[key], header.comments[key]) # # Save to FITS file fits.writeto(nirc2_file.replace('.fits', '_wcs.fits'), img, header=hdr, clobber=True, output_verify='silentfix') return hdr
Java
UTF-8
1,044
3.203125
3
[]
no_license
package by.it.malyshev.jd01_12; import java.util.*; /** * @author Sergey Malyshev */ public class TaskA2 { public static void main(String[] args) { Integer[] intArray={1,3,1,2,5,3,4,2,0,0,0,2,4,5,7,9,7,6,5}; List<Integer> a = Arrays.asList(intArray); List<Integer> arrayListA=new ArrayList<>(a); System.out.println("\nМножество A\n"+arrayListA); List<Integer> arrayListB = new ArrayList<>(15); Random randomMark = new Random(); for (int i = 0; i < 15; i++) { arrayListB.add(randomMark.nextInt(10) + 1); } System.out.println("\nМножество B\n"+arrayListB); List<Integer> resCross=MyCollect.getCross(arrayListA,arrayListB); System.out.println("\nРезультат пересечения множеств A и B\n"+resCross); List<Integer> resUnion=MyCollect.getUnion(arrayListA,arrayListB); System.out.println("\nРезультат объединения множеств A и B\n"+resUnion+"\n"); } }
PHP
UTF-8
1,895
2.953125
3
[ "MIT" ]
permissive
<?php /** * @package framework * @copyright Copyright (c) 2005-2020 The Regents of the University of California. * @license http://opensource.org/licenses/MIT MIT */ namespace Hubzero\Utility; /** * Cookie utility class * * Set and retrieve cookies in consistent manner */ class Cookie { /** * Drop a cookie * * @param (string) $namespace - make sure the cookie name is unique * @param (time) $lifetime - how long the cookie should last * @param (array) $data - data to be saved in cookie * @return void **/ public static function bake($namespace, $lifetime, $data=array()) { $hash = \App::hash(\App::get('client')->name . ':' . $namespace); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter( new \Hubzero\Encryption\Cipher\Simple, new \Hubzero\Encryption\Key('simple', $key, $key) ); $cookie = $crypt->encrypt(serialize($data)); // Determine whether cookie should be 'secure' or not $secure = false; $forceSsl = \Config::get('force_ssl', false); if (\App::isAdmin() && $forceSsl >= 1) { $secure = true; } else if (\App::isSite() && $forceSsl == 2) { $secure = true; } // Set the actual cookie setcookie($hash, $cookie, $lifetime, '/', '', $secure, true); } /** * Retrieve a cookie * * @param (string) $namespace - make sure the cookie name is unique * @return (object) $cookie data **/ public static function eat($namespace) { $hash = \App::hash(\App::get('client')->name . ':' . $namespace); $key = \App::hash(''); $crypt = new \Hubzero\Encryption\Encrypter( new \Hubzero\Encryption\Cipher\Simple, new \Hubzero\Encryption\Key('simple', $key, $key) ); if ($str = \App::get('request')->getString($hash, '', 'cookie')) { $sstr = $crypt->decrypt($str); $cookie = @unserialize($sstr); return (object)$cookie; } return false; } }
Python
UTF-8
405
3.9375
4
[]
no_license
""" Given two strings, determine if one is an anagram of the other. For example, the two strings “anagram” and “margana” are anagrams of each other. """ def is_anagram(string_1: str, string_2: str) -> bool: n = len(string_1) if len(string_2) != n: return False for i in range(n): if string_1[i] != string_2[-i-1]: return False return True
PHP
UTF-8
2,795
2.765625
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace AppBundle\Repository; /** * EventRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class EventRepository extends \Doctrine\ORM\EntityRepository { // requete sql sur mesure; /** * @param $date * @return Event[] */ public function findAllGreaterThanDate($date) { $qb = $this->createQueryBuilder('e') ->andWhere('e.date > :date') ->setParameter('date', $date) ->getQuery(); return $qb->execute(); } // nouveau filtre /** * @param $date,$theme * @return Event[] */ public function findByFilter($dateNow, $title, $place, $date, $theme) { $qb = $this->createQueryBuilder('e') ->where('e.date > :dateNow ')->setParameter('dateNow', $dateNow); if (!empty($date)) { $qb = $qb->andWhere('e.date = :date')->setParameter('date', $date); } if (!empty($title)) { $qb = $qb->andWhere('lower(e.title) like lower(:title)')->setParameter('title', "%" . $title . "%"); } if (!empty($theme)) { $qb = $qb->andWhere('lower(e.theme) like lower(:theme)')->setParameter('theme', "%" . $theme . "%"); } if (!empty($place)) { $qb = $qb->andWhere('lower(e.place) like lower(:place)')->setParameter('place', "%" . $place . "%"); } $qb = $qb->getQuery(); return $qb->execute(); } // par utilisateur /** * @param $date,$user * @return Event[] */ public function findByUser($dateNow,$user) { $qb = $this->createQueryBuilder('e') ->andWhere('e.user = :user') ->setParameter('user', $user) ->getQuery(); return $qb->execute(); } // // plus utilisé // /** // * @param $date,$place // * @return Event[] // */ // public function findByPlace($date,$place) // { // $qb = $this->createQueryBuilder('e') // ->where('e.date > :date') // ->andWhere('e.place like :place') // ->setParameter('date',$date ) // ->setParameter('place',"%".$place."%" ) // ->getQuery(); // return $qb->execute(); // } // // plus utilisé // /** // * @param $date,$theme // * @return Event[] // */ // public function findByTheme($date,$theme) // { // $qb = $this->createQueryBuilder('e') // ->where('e.date > :date') // ->andWhere('e.theme like :theme') // ->setParameter('date',$date ) // ->setParameter('theme',"%".$theme."%" ) // ->getQuery(); // return $qb->execute(); // } }
JavaScript
UTF-8
488
3.046875
3
[]
no_license
const $cards = document.querySelector(".cards"); const newCard = document.createElement("figure"); const cloneCards = $cards.cloneNode(true); newCard.innerHTML = ` <img src="https://placeimg.com/200/200/any" alt="Any"> <figcaption>Any</figcaption> `; newCard.classList.add("card"); //$cards.replaceChild(newCard,$cards.children[1]); //$cards.insertBefore(newCard,$cards.firstElementChild); //$cards.removeChild($cards.lastElementChild); document.body.appendChild(cloneCards);
TypeScript
UTF-8
911
2.984375
3
[ "MIT" ]
permissive
export const IGNORE_ERRORS = true export const THROW_ERRORS = false export const prettyPrint = (ugly: string, ignoreErrors: boolean = THROW_ERRORS): string => { let pretty: string = "" try { const jsonObject = JSON.parse(ugly) pretty = JSON.stringify(jsonObject, undefined, 4) } catch (error) { if (!ignoreErrors) { throw (error) } } return pretty } export const jsonParse = (json: string, ignoreErrors: boolean = THROW_ERRORS): any => { let jsonObject: any = {} try { jsonObject = JSON.parse(json) } catch (error) { if (! ignoreErrors) { throw (error) } } return jsonObject } export const jsonStringify = (jsonObject: any, ignoreErrors: boolean = THROW_ERRORS): string => { let json: string = "" try { json = JSON.parse(jsonObject) } catch (error) { if (! ignoreErrors) { throw (error) } } return json }
C++
UTF-8
2,900
2.765625
3
[]
no_license
#include <boost/asio/basic_waitable_timer.hpp> #include <boost/asio/io_service.hpp> #include <boost/math/tools/univariate_statistics.hpp> #include <boost/optional.hpp> #include <algorithm> #include <chrono> #include <iostream> #include <mutex> #include <string> #include <thread> #include <vector> template <class Clock> void display_precision() { typedef std::chrono::duration<double, std::nano> NS; NS ns = typename Clock::duration(1); std::cout << ns.count() << " ns\n"; } int main(int, char**) { using namespace std::chrono; using namespace std::chrono_literals; size_t const count = 100; auto interval = 100ms; //auto interval = 50ms; //size_t const count = 50; //auto interval = 200ms; boost::asio::io_service ios; boost::optional<boost::asio::io_service::work> work {ios}; std::thread worker { [&]{ ios.run(); } }; //boost::asio::basic_waitable_timer<steady_clock> timer {ios}; //std::vector<steady_clock::duration::rep> elapsed_times; boost::asio::basic_waitable_timer<system_clock> timer {ios}; std::vector<system_clock::duration::rep> elapsed_times; elapsed_times.reserve (count); std::mutex gate; std::cout << "========================================\n"; display_precision<std::chrono::high_resolution_clock>(); display_precision<std::chrono::system_clock>(); display_precision<std::chrono::steady_clock>(); std::cout << "========================================\n"; std::cout << "Starting timer measurement...\n"; for (auto samples = count; samples != 0 ; --samples) { auto const start {steady_clock::now()}; timer.expires_after (interval); gate.lock (); timer.async_wait ( [&] (boost::system::error_code const& ec) { if (ec) std::cerr << "!! got an ec in timer cb: " << ec.message() << "\n"; auto const end {steady_clock::now()}; auto const elapsed {end - start}; elapsed_times.emplace_back ( duration_cast<milliseconds>(elapsed).count()); gate.unlock (); }); std::unique_lock <std::mutex> waithere {gate}; if (samples % 10 == 0) std::cout << samples << "..."; std::cout.flush(); } std::cout << "\n"; work = boost::none; worker.join(); std::cout << "Done.\n"; std::cout << "========================================\n"; std::cout << "Mean: " << boost::math::tools::mean(elapsed_times) << "ms\n"; std::cout << "Median: " << boost::math::tools::median(elapsed_times) << "ms\n"; std::cout << "Max: " << *(std::max_element(elapsed_times.begin(),elapsed_times.end())) << "ms\n"; std::cout << "Min: " << *(std::min_element(elapsed_times.begin(),elapsed_times.end())) << "ms\n"; std::cout << "========================================\n"; return 0; }
JavaScript
UTF-8
10,996
2.53125
3
[]
no_license
const jwt = require('jsonwebtoken'); // Compact, URL-safe means of representing claims to be transferred between two parties. const bcrypt = require('bcrypt-nodejs'); // A native JS bcrypt library for NodeJS const url = require('url'); module.exports = (router) => { /* =============================================================== INSERT BUILDING =============================================================== */ router.post('/createBuilding', function (req, res, next) { var Password = null; var UserID = null; try { var reqObj = req.body; console.log(reqObj); req.getConnection(function (err, conn) { if (err) { console.error('SQL Connection error: ', err); return next(err); } else { //Check if BuildingCode was provided if (!req.body.BuildingCode) { res.json({ success: false, message: 'You must provide building code!' }); // Return error } else { //Check if BuildingName was provided if (!req.body.BuildingName) { res.json({ success: false, message: 'You must provide a building name!' }); //Return an error } else { //Check if LocationCode was provided if (!req.body.LocationCode) { res.json({ success: false, message: 'You must provide a location code' }); // Return error } else { //Check if BuildingCode already exist var BuildingCode = reqObj.BuildingCode; console.log("Building Code:" + BuildingCode); conn.query('select * from triune_building u where u.BuildingCode = ?', [BuildingCode], function (err, rows, fields) { if (err) { console.error('SQL error: ', err); return next(err); } console.log("Building Code Exist: " + rows); if (rows != '') { res.json({ success: false, message: 'Building Code already exist!!!' }); } else { var insertSql = "INSERT INTO triune_building SET ?"; // Apply encryption Password = reqObj.Password; //console.log("Password: " + Password); bcrypt.hash(Password, null, null, (err, hash) => { if (err) return next(err); // Ensure no errors Password = hash; // Apply encryption to password console.log("HASH : " + hash); console.log("HASH PASSWORD: " + Password); var insertValues = { "BuildingCode": reqObj.BuildingCode, "BuildingName": reqObj.BuildingName, "LocationCode": reqObj.LocationCode, "UserID": reqObj.UserID }; var query = conn.query(insertSql, insertValues, function (err, result) { if (err) { console.error('SQL error: ', err); return next(err); } console.log("result: " + result); console.log("insertvalues: " + insertValues); //var ID = result.ID; res.json({ success: true }); }); // next(); // Exit middleware }); //console.log("Hashed Password: " + Password); /*var insertValues = { "UserID" : UserID, "Password" : Password, "EmailAddress" : reqObj.EmailAddress, "FirstNameUser" : reqObj.FirstNameUser, "LastNameUser" : reqObj.LastNameUser, "UserNumber" : reqObj.UserNumber };*/ /* var query = conn.query(insertSql, insertValues, function (err, result){ if(err){ console.error('SQL error: ', err); return next(err); } console.log("result: " + result); console.log("insertvalues: " + insertValues); var id = result.insertId; res.json({"id":id, success: true}); });*/ } }); } } } } }); } //try catch (ex) { console.error("Internal error:" + ex); return next(ex); } }); /* =============================================================== GET BUILDING =============================================================== */ router.post('/getBuilding', function (req, res, next) { try { var ID = req.body.ID; console.log("ID: " + ID); req.getConnection(function (err, conn) { if (err) { console.error('SQL Connection error: ', err); return next(err); } else { conn.query('select * from triune_building u where u.ID = ?', [ID], function (err, rows, fields) { if (err) { console.error('SQL error: ', err); return next(err); } var resEmp = []; for (var empIndex in rows) { var empObj = rows[empIndex]; resEmp.push(empObj); } res.json(resEmp); }); } }); } catch (ex) { console.error("Internal error:" + ex); return next(ex); } }); /* =============================================================== GET ALL BUILDINGS =============================================================== */ router.get('/getBuildings', function (req, res, next) { try { req.getConnection(function (err, conn) { if (err) { console.error('SQL Connection error: ', err); return next(err); } else { conn.query('select * from triune_building', function (err, rows, fields) { if (err) { console.error('SQL error: ', err); return next(err); } var resEmp = []; for (var empIndex in rows) { var empObj = rows[empIndex]; resEmp.push(empObj); } //console.log(resEmp); res.json(resEmp); }); } }); } catch (ex) { console.error("Internal error:" + ex); return next(ex); } }); /* =============================================================== DELETE BUILDING =============================================================== */ router.delete('/deleteBuilding/:ID', (req, res, next) => { try { var ID = req.params.ID; console.log(ID); req.getConnection(function (err, conn) { if (err) { console.error('SQL Connection error: ', err); return next(err); } else { conn.query('delete from triune_building where ID = ?', [ID], function (err, rows, fields) { if (err) { console.error('SQL error: ', err); return next(err); } res.json({ "ID": ID, success: true }); }); } }); } catch (ex) { console.error("Internal error:" + ex); return next(ex); } }); /* =============================================================== UPDATE BUILDING =============================================================== */ router.post('/updateBuilding', function (req, res, next) { try { var BuildingCode = req.body.BuildingCode; var ID = req.body.ID; console.log("BuildingCode: " + BuildingCode); console.log("ID: " + ID); req.getConnection(function (err, conn) { if (err) { console.error('SQL Connection error: ', err); return next(err); } else { conn.query('UPDATE triune_building set BuildingCode = ? WHERE ID = ?', [BuildingCode, ID], function (err, rows, fields) { if (err) { console.error('SQL error: ', err); return next(err); } res.json({ success: true, message: 'Building code updated' }); }); } }); } catch (ex) { console.error("Internal error:" + ex); return next(ex); } }); return router; // Return router object to main index.js }
Markdown
UTF-8
1,364
2.921875
3
[]
no_license
# TMDB-Movie-App This application integrates with TMDB APIs and displays list of now playing movies with filter capability. The application uses [The Movie Database (TMDb) API](https://www.themoviedb.org/documentation/api) to display movie data. ## Installation Please install node.js to run this application. Follow below steps to install in your local machine: * Clone the repo: https://github.com/de326729/TMDB-Movie-App.git * Go to TMDB-Movie-App: cd TMDB-Movie-App * Install the required npm packages: npm install * Build project and launch: npm run dev * Open your browser at: http://localhost:8080 ## Documentation Please download docs folder in your local machine and run index.html file to view project documentation. Documentation can also be found in the wiki section of this repository. ## Functional Highlights * Integrates with the TMDB API to fetch and display movies * Displays a list of movies based on the Now Playig TMDB API response * Movies can be filtered basd on their Rating and Genres * Uses Enzyme Jest for unit testing of components ## Technical Details * Used front end development library provided by Facebook - [React](https://reactjs.org/ * Used Material Design components provided by library [Material UI](https://material-ui.com/) * Application wide state is managed by [React-Redux](https://github.com/reactjs/react-redux)
C++
UTF-8
964
3.265625
3
[ "MIT" ]
permissive
/** Name: Pavan Kumar Kamra Course: BTP200 **/ #include <iostream> #include "Molecule.h" #include <cstring> using namespace std; int main() { int n; Molecule * molecule; cout << "Molecular Information\n"; cout << "=====================" << endl; cout << "Number of Molecules : "; cin >> n; // allocate dynamic memory for an array of n Molecules molecule = new Molecule[n]; for (int i = 0; i < n; i++) { char symbol[21]; char description[201]; double weight; cout << "Enter Structure: "; cin >> symbol; cout << "Enter Full Name: "; cin.ignore(2000, '\n'); cin.getline(description, 30); cout << "Enter weight: "; cin >> weight; Molecule temp(weight, symbol, description); molecule[i] = temp; } cout << endl; cout << "Structure Mass Name\n"; cout << "========================================" << endl; for (int i = 0; i < n; i++) { molecule[i].display(); cout << endl; } }
Python
UTF-8
797
3.484375
3
[]
no_license
import random def sorted_merge(arr_a, arr_b): i = len(arr_a) - len(arr_b) - 1 j = len(arr_b) - 1 k = len(arr_a) - 1 while i >= 0 and j >= 0: if arr_a[i] >= arr_b[j]: arr_a[k] = arr_a[i] i -= 1 else: arr_a[k] = arr_b[j] j -= 1 k -= 1 while i >= 0: arr_a[k] = arr_a[i] i -= 1 while j >= 0: arr_a[k] = arr_b[j] j -= 1 def main(): lo = 1 hi = 100 count = 10 arr_c = [random.randint(lo, hi) for n in range(count)] arr_a = [None] * count arr_a[:count//2] = sorted(arr_c[:count//2]) arr_b = sorted(arr_c[count//2:]) sorted_merge(arr_a, arr_b) assert arr_a == sorted(arr_c), "array a is not sorted" if __name__ == "__main__": main()
Markdown
UTF-8
2,850
2.6875
3
[]
no_license
--- name: "Karwar Style Madgane Recipe With Oats & Rajgira" slug: "karwar-style-madgane-recipe-with-oats-rajgira" layout: 'RecipeLayout' prepTime: "55" cuisine: "Karnataka" cuisineSlug: "karnataka" image: "https://www.archanaskitchen.com/images/archanaskitchen/1-Author/panditp253-gmail.com/MADGANE_.jpg" excerpt: "To begin making Karwar Style Madgane Recipe With Oats Rajgira, soak dal in adequate water for about an hour" --- ### Ingredients - 1-1/2 tablespoons Rajgira Flour (Amaranth Flour). - 1/4 cup Instant Oats (Oatmeal). - 1 pinch Salt. - 1 teaspoon Ghee. - 1-1/2 cup Jaggery - (adjust). - 1-1/2 cups Fresh coconut - grated. - 20 Cashew nuts - halved. - 5 Dates - chopped. - 1 teaspoon Cardamom Powder (Elaichi). - 2 teaspoons Raisins - more to garnish. - 2 cups Water. - 1/2 cup Chana dal (Bengal Gram Dal). - 1 tablespoon Rice flour. ### Instructions 1. To begin making Karwar Style Madgane Recipe With Oats & Rajgira, soak dal in adequate water for about an hour. 1. Wash thoroughly and drain. 1. Take a big saucepan, add the given quantity of dal and water and bring it to boil on high heat. 1. When the water in the pan starts boiling, reduce the flame to medium and keep simmered for the dal to cook, (do not cover with lid at any stage) stirring occasionally till soft and done. 1. In the meantime, grind the coconut using water to extract coconut milk by squeezing tightly the ground coconut over a sieve. 1. The first extract will be thick and should be about 3/4 to 1 cup. 1. Repeat this process using less water each time to get more coconut milk which will be comparatively thinner and the coconut milk should be about 2 cups. 1. Check the dal and when it is almost cooked, add to it the cashew nuts and mix well. 1. Here a little hot water can be added to daal if there is very less water in it. 1. When dal is completely cooked but not mushy (almost all water should be evaporated by now), add jaggery, cardamom powder and salt. 1. Stir till jaggery dissolves. 1. Using a little of the thin coconut extract make a slurry of the rice and rajgira flours in a mixing bowl. 1. (rice flour is a must as it prevents the coconut milk from splitting)Add this slurry, oats and all the thin coconut extract to the dal and bring to a boil stirring constantly. 1. Now add the dates, half of the raisins and the thick coconut extract and again bring to a boil stirring constantly on medium heat. 1. Switch off heat now since after adding coconut milk, too much cooking is not required not desirable for the recipe. 1. Heat ghee in a small kadai, add the cashew nuts and raisins (which were reserved) to garnish the Madgane. 1. Serve Karwar Style Madgane Recipe With Oats & Rajgira as a dessert with a meal of steamed rice, Karwar Style Sol Kadhi Recipe, and Kadgi Chakko Recipe for lunch.
C
UTF-8
2,034
2.796875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lherbelo <lherbelo@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/30 19:39:39 by lherbelo #+# #+# */ /* Updated: 2016/08/17 12:56:10 by lherbelo ### ########.fr */ /* */ /* ************************************************************************** */ #include "../inc/fdf.h" t_coord *coord(int x, int y, int z) { t_coord *coord; coord = (t_coord *)ft_memalloc(sizeof(t_coord)); coord->x = x; coord->y = y; coord->z = z; return (coord); } void lst_map(t_fdf *fdf, t_list *pts, int x, int y) { int i; int **map; t_list *pouet; t_coord *coords; i = 0; pouet = pts; map = (int **)ft_memalloc(sizeof(int *) * x); while (i < x) { map[i] = (int *)ft_memalloc(sizeof(int *) * y); i++; } while (pouet) { coords = pouet->content; if (coords->x < x && coords->y < y) map[coords->x][coords->y] = coords->z; pouet = pouet->next; } fdf->map = map; fdf->zoom = 360 / (x + y); fdf->xpos = x * fdf->zoom * 1.3; fdf->ypos = y * fdf->zoom * 1.2; fdf->relief = 0.5; } void read_map(t_fdf *fdf, int fd) { int i; int j; t_list *pts; char *line; char **tmp; i = 0; while (get_next_line(fd, &line)) { j = 0; tmp = ft_strsplit(line, ' '); while (tmp[j] != NULL) { ft_set_color(fdf, ft_atoi(tmp[j])); ft_lstadd(&pts, ft_lstnew(coord(j, i, ft_atoi(tmp[j])),\ sizeof(t_coord))); j++; } i++; } fdf->x = j; fdf->y = i; lst_map(fdf, pts, j, i); }
Markdown
UTF-8
5,949
2.78125
3
[]
no_license
# Online Shopping Application Admin > This project has been refactored by Laravel, if you are interested in it, click here: [Online-Shopping-Admin-Lararvel](https://github.com/maorutian/Online-Shopping-Admin-Lararvel) ## Technical skills Pure PHP + DatabaseAPI:PDO + Bootstrap + XAMMP ## Introduction This is a cake online shopping application admin side. #### This application has the following functions: - Admin login/logout - Products - View available products and prices - Review, add, modify and delete individual product details - Employees - View individual employee information - Review, add, modify and delete employee details ## Files/Folders Structure Here is a brief explanation of the template folder structure and some of its main files usage: ``` └── src # Contains all template source files. │ └── private # Contains Classes and Libraries that should not be accessible by public. │ │ └── classes # Contains al classes. │ │ │ └── DatabaseObject.php # Database table parent Class. │ │ │ └── Employee.php # Employee table Model. │ │ │ └── Pagination.php # Manage pagination. │ │ │ └── Product.php # Product table Model. │ │ │ └── Session.php # Custom Session Class. │ │ │ │ │ └── shared # Contains page layout. │ │ │ └── admin_footer.php # Footer layout. │ │ │ └── admin_header.php # Headed layout. │ │ │ │ │ └── database_functions.php # Functions related to database. │ │ └── db_credentials.php # Database credentials. │ │ └── functions.php # Libray of functions. │ │ └── initialize.php # Load all the required files, all the php files in the public need import it │ │ └── validation_functions.php # Libray of data validation functions. │ │ │ └── public # Web document route. │ │ └── css # Contains all CSS files. │ │ │ └── bootstrap_admin.css # Custom CSS for the project. │ │ │ │ │ └── js # Contains all JavaScript files. │ │ │ └──chart.js # Chart.js(https://www.chartjs.org) │ │ │ └──script.js # Custom own chart using Chart.js. │ │ │ │ │ └── employees # Contains all employees pages. │ │ │ └── add.php # Create a new employee. │ │ │ └── delete.php # Delete individual employee. │ │ │ └── index.php # View all employees. │ │ │ └── update.php # Update individual employee inforation(except password). │ │ │ └── update_password.php # Update individual employee password. │ │ │ │ │ └── product # Contains all product pages. │ │ │ └── add.php # Create a new project. │ │ │ └── delete.php # Delete individual product. │ │ │ └── detail.php # Review individual product details. │ │ │ └── index.php # View all products. │ │ │ └── update.php # Update individual product details. │ │ │ │ │ └── customers # Contains all customer pages(empty). │ │ └── orders # Contains all orders pages(empty). │ │ └── statistic # Contains all statistic pages(empty). | | | │ │ └── index.php # Home page. │ │ └── login.php # Login page. │ │ └── logout.php # Logout page. | | └── database # Contains database setting. │ └── plugins # Sql file to import in databse. │ └── readme_media # Resources for readme.md. ``` ## Advantage 1. Create inheritable database table code(DatabaseObject class) to make project more robust - create, read, update, delete, select functions form all tables in database - override parent class's function to fit subclass(Employee class) 2. user authentication (session class) - keep track user authenticated state. - track of when the user last logged in adn set maximum login age - add access control to pages - dispaly messages from session 3. Back End Pagination - manage large sets of data, show a subset of records - SQL LIMIT and SQL OFFSET - Good UI(previous, next and numbered page links) 4. validation functions - diverse validation functions It's a good idea to have code in one place, so that it gets edited only one time, and it helps you to maintain the code, and also keeps you from making careless mistakes. ## Disadvantage 1. complicated relationship - Due to I create DatabaseObject class, I do not want to only hard code for "joing", I still want one to many and many to many relationships are inheritable functions, but it is diffcult to do. 2. Hard to do teamwork - Different team member create same functions. Different team member use different model. Therefore, I refactored the project using LARAVEL. Click here: [Online-Shopping-Admin-Lararvel](https://github.com/maorutian/Online-Shopping-Admin-Lararvel) ## Screen Views ![admin_home.png](readme_media/home.png) ![admin_home.png](readme_media/allproducts.png) ![admin_home.png](readme_media/resetpassword.png)
Python
UTF-8
466
2.96875
3
[]
no_license
import socket url = input('Enter url to connect to:\n>') url_parts = url.split('/') host = url_parts[2] mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: mysocket.connect((host, 80)) except: print('ERROR: URL MALFORMED OR NONEXISTANT!') exit() cmd = f'GET %s HTTP/1.0\r\n\r\n'%url mysocket.send(cmd.encode()) while True: data = mysocket.recv(512) if len(data) < 1: break print(data.decode(), end='') mysocket.close()
Swift
UTF-8
2,023
2.546875
3
[]
no_license
// // View1.swift // Sparta // // Created by Guillian Balisi on 2016-02-27. // Copyright © 2016 Sparta. All rights reserved. // import UIKit import ChameleonFramework class View1: UIViewController { @IBOutlet weak var realHelloLabel: UILabel! @IBOutlet weak var helloLabel: UILabel! @IBOutlet weak var topBackground: UIView! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var okButton: UIButton! var user = User() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { topLabel.textColor = UIColor.whiteColor() topBackground.backgroundColor = FlatWatermelon() okButton.backgroundColor = FlatWatermelon() okButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) okButton.layer.borderWidth = 1 okButton.layer.borderColor = FlatWatermelon().CGColor okButton.layer.cornerRadius = 6 okButton.layer.masksToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pressOK() { helloLabel.text = usernameTextField.text realHelloLabel.hidden = false helloLabel.hidden = false print("New user created") usernameTextField.text = "" viewTapped() } @IBAction func viewTapped() { usernameTextField.resignFirstResponder() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
TypeScript
UTF-8
1,513
2.515625
3
[]
no_license
export namespace ScrollEventNS { /** * 滚动事件 Use 入参 */ export interface ScrollEventUseOptions { value?: { el: any; }; /** * 默认监听滚动元素 querySelector 选择器 */ el?: string; /** * 防抖延迟时间[ms] */ debounceNumber?: number; /** * 过渡动画名 */ transformName?: string; /** * 首屏初始化时是否显示动画过渡 TODO: 首屏暂未完成 */ initTransform?: boolean; } interface CurrentElement extends HTMLElement { scrollUUID: string; pageYOffset: number; } /** * 事件 */ export interface EventElMap { [k: string]: { el: CurrentElement; list: { el: HTMLElement; binding: ScrollEventBindingOptions; }[]; } } /** * 元素绑定入参 */ export interface ScrollEventBindingOptions { value?: { /** * 默认监听滚动元素 querySelector 选择器 or 元素 */ el?: string | (() => HTMLElement); down?: string; up?: string; } /** * 滚动父级元素 */ currentElement?: CurrentElement; /** * 修饰符 */ modifiers?: any /** * 是否显示动画过渡 */ transform?: boolean; /** * 过渡动画名 */ transformName?: string; /** * 最后滚动的位置 */ lastScrollTop?: number; /** * 初始class */ previousClassName?: string; } }
C
UTF-8
1,360
3.9375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } ListNode; typedef struct { ListNode *first,*last; } list; ListNode *CreatNode(int n) { ListNode *temp; temp=(ListNode *)malloc(sizeof(ListNode)); temp->data=n; temp->next=NULL; return temp; } void MakeFirstLast(list *s,int n) { if(s->first==NULL) s->first=s->last=CreatNode(n); } void InsertToHead(list *s,int n) { ListNode *temp; if(s->first==NULL) s->first=s->last=CreatNode(n); else { temp=CreatNode(n); temp->next=s->first; s->first=temp;} } void InsertToLast(list *s,int n) { ListNode *temp; if(s->first==NULL) s->first=s->last=CreatNode(n); else { temp=CreatNode(n); s->last->next=temp; s->last=s->last->next;} } void InsertToMiddle(list *s,ListNode *prev,int n) { if(s->first==NULL) s->first=s->last=CreatNode(n); else { ListNode *temp; temp=CreatNode(n); temp->next=prev->next; prev->next=temp;} } void PrintScreen(list *s) { ListNode *temp; temp=s->first; while(temp!=NULL) { printf("%-3d",temp->data); temp=temp->next; } printf("\n"); } void Swap(ListNode **a,ListNode **b) { ListNode **c; (*c)->data=(*a)->data; (*a)->data=(*b)->data; (*b)->data=(*c)->data; } int SizeOfList(list *s) { ListNode *temp; int count=0; temp=s->first; while(temp!=NULL) { count++; temp=temp->next; } return count; }
Python
UTF-8
5,551
2.953125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri May 7 18:35:37 2021 @author: User """ def all_black_rows(): black_rows_y = [] for row in range(height): sum = 0 for pix in range(width): # sum of all pixels' red channel in a row (could be any channel of the RGB): sum += iar[row][pix][0] # last pixel in a row: if (pix == width - 1) and (sum == 0): # sum = 0 means it is a totally black row. We collect their y coordinates in a list: black_rows_y += [row] return black_rows_y def find_second_black_row(rows): prev_i = 0 for i in rows: if i - prev_i > 10: break prev_i = i return i # Python program to implement # Webcam Motion Detector # importing OpenCV, time and Pandas library import cv2, time, pandas # importing datetime class from datetime library from datetime import datetime import numpy as np import pyautogui # Assigning our static_back to None static_back = None # List when any moving object appear motion_list = [ None, None] # motion_list = [ None, None, None, None, None, None, None, None, ] # Time of movement time = [] # Initializing DataFrame, one column is start # time and other column is end time df = pandas.DataFrame(columns = ["Start", "End"]) # Capturing video # video = cv2.VideoCapture(0) # Infinite while loop to treat stack of image as video while True: # Reading frame(image) from video # check, frame = video.read() img=pyautogui.screenshot(region=(0,0,500,500)) # open_cv_image = np.array(img) # open_cv_image = open_cv_image[:, :, ::-1].copy() # cv2.imshow("img", open_cv_image) frame = np.array(img) # Initializing motion = 0(no motion) motion = 0 # Converting color image to gray_scale image gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Converting gray scale image to GaussianBlur # so that change can be find easily gray = cv2.GaussianBlur(gray, (21, 21), 0) #-------------------------------------------------- #threshold the image _, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) # get horizontal mask of large size since text are horizontal components kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1)) connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel) # find all the contours # _, contours, hierarchy,=cv2.findContours(connected.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contours, hierarchy,=cv2.findContours(connected.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) #Segment the text lines for idx in range(len(contours)): x, y, w, h = cv2.boundingRect(contours[idx]) cv2.rectangle(frame, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2) #-------------------------------------------------- text_first_row_bottom = find_second_black_row(all_black_rows()) cropped_image = frame.crop((0, text_first_row_bottom, height, width)) # cropped_image.show() # In first iteration we assign the value # of static_back to our first frame if static_back is None: static_back = gray continue # Difference between static background # and current frame(which is GaussianBlur) diff_frame = cv2.absdiff(static_back, gray) # If change in between static background and # current frame is greater than 30 it will show white color(255) thresh_frame = cv2.threshold(diff_frame, 30, 255, cv2.THRESH_BINARY)[1] thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) # Finding contour of moving object cnts,_ = cv2.findContours(thresh_frame.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in cnts: area=cv2.contourArea(contour) if area > 2000 or area<250: continue motion = 1 (x, y, w, h) = cv2.boundingRect(contour) # making green rectangle arround the moving object # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) # Appending status of motion motion_list.append(motion) motion_list = motion_list[-2:] # Appending Start time of motion if motion_list[-1] == 1 and motion_list[-2] == 0: time.append(datetime.now()) # Appending End time of motion if motion_list[-1] == 0 and motion_list[-2] == 1: time.append(datetime.now()) # Displaying image in gray_scale cv2.imshow("Gray Frame", gray) # Displaying the difference in currentframe to # the staticframe(very first_frame) cv2.imshow("Difference Frame", diff_frame) # Displaying the black and white image in which if # intensity difference greater than 30 it will appear white cv2.imshow("Threshold Frame", thresh_frame) # Displaying color frame with contour of motion of object cv2.imshow("Color Frame", frame) key = cv2.waitKey(1) # if q entered whole process will stop if key == ord('q'): # if something is movingthen it append the end time of movement if motion == 1: time.append(datetime.now()) break # Appending time of motion in DataFrame for i in range(0, len(time), 2): df = df.append({"Start":time[i], "End":time[i + 1]}, ignore_index = True) # Creating a CSV file in which time of movements will be saved df.to_csv("Time_of_movements.csv") video.release() # Destroying all the windows cv2.destroyAllWindows()
C
UTF-8
199
2.78125
3
[]
no_license
#include<stdio.h> int main() { int count=3,k,res=1,rem=3; for (k=1;k<=count;k++) { res=res*rem; printf("%d\n",res); } printf("%d\n",res); }
Python
UTF-8
2,050
2.5625
3
[]
no_license
import RPi.GPIO as GPIO import time import pyodbc indicatorParkingSlot1 = 0 indicatorParkingSlot2 = 0 vipParkingSlotAvailable = 8; GPIO.setmode(GPIO.BOARD) GPIO.setup(18,GPIO.IN) #parkingSlot1 GPIO.setup(16,GPIO.IN) #parkingSlot2 print ("IR Sensor Ready") def queryDatabase(count): conn = pyodbc.connect('DRIVER=FreeTDS;SERVER=RNR\SQLEXPRESS;PORT=1433;DATABASE=PARKING_MANAGEMENT;UID=sa;PWD=noname101;TDS_Version=8.0;') cursor = conn.cursor() cursor.execute("UPDATE DB_A6D6D2_Try.dbo.Parking_Slot SET VIP=" + str(count)) cursor.commit() cursor.close() try: while True: if GPIO.input(18) and indicatorParkingSlot1 == 0: print ("Parking Slot 1 Vehicle NOT detected!") indicatorParkingSlot1 = 1 #vipParkingSlotAvailable +=1 print("VIP Parking Slot available: " + str(vipParkingSlotAvailable)) queryDatabase(vipParkingSlotAvailable) if not GPIO.input(18) and indicatorParkingSlot1 == 1: print ("Parking Slot 1 Vehicle detected!") indicatorParkingSlot1 = 0 vipParkingSlotAvailable -=1 print("VIP Parking Slot available: " + str(vipParkingSlotAvailable)) queryDatabase(vipParkingSlotAvailable) if GPIO.input(16) and indicatorParkingSlot2 == 0: print ("Parking Slot 2 Vehicle NOT detected!") indicatorParkingSlot2 = 1 #vipParkingSlotAvailable +=1 print("VIP Parking Slot available: " + str(vipParkingSlotAvailable)) queryDatabase(vipParkingSlotAvailable) if not GPIO.input(16) and indicatorParkingSlot2 == 1: print ("Parking Slot 2 Vehicle detected!") indicatorParkingSlot2 = 0 vipParkingSlotAvailable -=1 print("VIP Parking Slot available: " + str(vipParkingSlotAvailable)) queryDatabase(vipParkingSlotAvailable) except KeyboardInterrupt: GPIO.cleanup()
Java
UTF-8
551
1.992188
2
[]
no_license
package me.kaimson.melonclient.ingames.utils.ReplayMod.core; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.server.S3FPacketCustomPayload; public class Restrictions { public static final String PLUGIN_CHANNEL = "Replay|Restrict"; public String handle(S3FPacketCustomPayload packet) { PacketBuffer buffer = packet.getBufferData(); if (buffer.isReadable()) { String name = buffer.readStringFromBuffer(64); boolean active = buffer.readBoolean(); return name; } return null; } }
Java
UTF-8
212
1.984375
2
[]
no_license
package com.estafet; public class ShellException extends Exception { /** * Serial ID */ private static final long serialVersionUID = 1L; public ShellException(String messgae) { super(messgae); } }
Markdown
UTF-8
1,458
2.5625
3
[]
no_license
--- layout: post title: Apple WWDC 2013 - New AppleTV World? category: digital tags: tech apple --- This years developer conference to be held by Apple beginning June, 10th is teased with a headline: > Where a whole new world is developing Apple wouldn't be Apple, if there wasn't a deeper meaning in this headline. So I started to think about, what this years headline could hint us to. Everybody talks about the known things, previews of iOS 7 and MacOS 10.9 the successor of Mountain Lion, some (minor) hardware refreshes etc. And everyone seems to be sure, that we shouldn't hold our breath hoping for a new iPhone or iPad. What do these things have to do with the 2013 claim? Nothing. Does the 'new world' mean to focus on the invasion of the iPhone into China or India, which are countries being obviously late to the iPhone party? No - we saw a China-focus in last years iOS 6. Dedicate the most import event of the Apple calendar to welcome the huge market of India? Surely not. What actually wonders me, is that noone talks about the iWatch or Apple TV (aka iTV) in context with WWDC - o.k. iWatch seems too far away, but what about the "new world" that's "developing" simply a *new world* of iOS devices, that weren't opened for the developers until now: the Apple TV? **Therefore my money would be on the introduction of the APIs for bringing all the great content and apps to the big screen via an App Store for the Apple TV.** We'll see.
Java
UTF-8
5,563
2.34375
2
[]
no_license
package com.Plugdisk1.tests; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import org.openqa.selenium.*; public class E013 extends BaseTestLogic { private static String System_Out = "", Success = "", Folder_Name = ""; Boolean folderPresent = false, sub_sharePresent = false; public E013(WebDriver webDriver, File fileConf, File fileReport) { super(webDriver, fileConf, fileReport); // TODO Auto-generated constructor stub } void startTest() throws InterruptedException { System.out.println("*****************************************************************"); System.out.println("* Share Setting *"); System.out.println("*****************************************************************"); System.out.println("Test E013 - Share - Share setting"); System.out.println("Share setting can be done for normal folder which is not shared? \n" + "웹탐색기형 UI에서 공유설정되어 있지 않은 폴더를 선택하여 공유를 생성한다? \n"+ "-----------------------------------------------------------------"); //go to Share menu // driver.findElement(By.id("share")).click(); // Thread.sleep(1000); // driver.findElement(By.xpath("//div[@id='tree_view']/ul/li[4]/ul/li/div/span")).click(); // Thread.sleep(1000); Success = ""; System_Out = ""; //Search Parent share --------------------------------- WebElement folderlist = driver.findElement(By.id("share-list")); List<WebElement> allfolder = folderlist.findElements(By.className("icon_folder")); int i = 0; for (WebElement folder : allfolder) { //System.out.println(share.getText()); i = i + 1; Folder_Name = folder.getText(); if (!Folder_Name.equals("")){ //System.out.println(Folder_Name); driver.findElement(By.xpath("//div[@id='share-list']/table/tbody/tr[" + i + "]/td/input")).click(); folderPresent = true; break; } } if (folderPresent){ driver.findElement(By.xpath("//li[contains(text(), '공유 설정')]")).click(); //click Delete button Thread.sleep(1000); if (isAlertPresent()){ //while Alert msg appears System_Out = driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); //Click OK from popup alert //driver.findElement(By.id("closeButton")).click(); System_Out = System_Out + "\nTest FAIL!" ; }else{ //switch to user creation frame driver.switchTo().frame(driver.findElement(By.id("boxIframe"))); //Click OK--> driver.findElement(By.id("okButton")).click(); Thread.sleep(1000); if (isAlertPresent()){ //while Alert msg appears System_Out = driver.switchTo().alert().getText(); driver.switchTo().alert().accept(); //Click OK from popup alert driver.findElement(By.id("closeButton")).click(); System_Out = System_Out + "\nTest FAIL!" ; }else{ driver.switchTo().defaultContent(); if (isElementPresent(By.id("boxIframe"))){ driver.switchTo().frame(driver.findElement(By.id("boxIframe"))); if (isElementVisible(By.id("shareName_errMsg"))){ System_Out = driver.findElement(By.id("shareName_errMsg")).getText(); System_Out = Folder_Name + ": " + System_Out; }else if (isElementVisible(By.id("ip_errMsg"))){ System_Out = driver.findElement(By.id("ip_errMsg")).getText(); System_Out = Folder_Name + ": " + System_Out; } //click cancel button driver.findElement(By.id("closeButton")).click(); System_Out = System_Out + "\nTest FAIL!" ; }else{ //check if share setting done successfully WebElement share_list = driver.findElement(By.id("share-list")); List<WebElement> all_share = share_list.findElements(By.className("icon_share")); Success = "Share setting FAIL."; for (WebElement shares : all_share) { //System.out.println(shares.getText()); if (shares.getText().equals(Folder_Name)){ Success = "Share setting successfull."; break; } } } } } driver.switchTo().defaultContent(); }else Success = "Folder not found for share setting."; System.out.println(System_Out + "\n" + Success); try { StringBuilder builder = new StringBuilder(); BufferedWriter out = new BufferedWriter(new FileWriter(fReport, true)); builder.append("\r\n*****************************************************************\r\n"); builder.append("* Delete Sub-Share *\r\n"); builder.append("*****************************************************************\r\n"); builder.append("Test E020 - Share - Delete Sub-Share\r\n"); builder.append("Can it delete sub-share successfully? \r\n" + "서브공유디스크 삭제는 공유 정보만 삭제 되는지 확인.\r\n"); builder.append("=================================================================\r\n"); builder.append(System_Out + "\r\n" + Success + "\r\n"); out.write(builder.toString()); if(Lisenter != null){ Lisenter.onReportLisenter(builder.toString()); } out.close(); } catch (IOException e) {} } }
Markdown
UTF-8
1,160
2.53125
3
[]
no_license
# Tanks - Tank game with 2 players - Top-down perspective - Shooting game ## Gameplay https://user-images.githubusercontent.com/12951412/120386231-ad633400-c328-11eb-95e6-7cd99373486b.mp4 ## Developers - [Luka Vujčić](https://github.com/LukaVujcic) - [Božidar Mitrović](https://github.com/AizenAngel) - [Dušan Petrović](https://github.com/dpns98) - [Nikola Mićić](https://github.com/nikolamicic) ## Dagger A fully-featured, modern game engine made for educational purposes. ## Features - Dagger is data-driven and event-based. - Dagger is extremely modular. - Dagger is clear and clearly educational. ## Setting up the development environment - [Windows](docs/setting_up_windows.md) - [Linux](docs/setting_up_linux.md) - Mac (WIP) ## Resources Any kind of data used by engine that is not source code is considered a resource. Root directory for resources is `data\` and so all references to resoruces begin there. For example, if you want to get a texture (from `data\textures`) you would use `textures\mytexture.png` instead `data\textures\mytexture.png`. ## Rights and Reservations Dagger is made as a part of Ubisoft Belgrade's game development course. All rights reserved.
C
UTF-8
2,982
3.0625
3
[]
no_license
#include "myLib.h" volatile unsigned short *videoBuffer = (volatile unsigned short *)0x6000000; // setPixel -- set the pixel at (row, col) to color void setPixel(int row, int col, unsigned short color) { videoBuffer[OFFSET(row, col, 240)] = color; } void waitForVblank() { while(*SCANLINECOUNTER > 160) ; while(*SCANLINECOUNTER<160) ; } /*drawImage3 * A function that will draw an arbitrary sized image * onto the screen (with DMA). * @param r row to draw the image * @param c column to draw the image * @param width width of the image * @param height height of the image * @param image Pointer to the first element of the image. */ void drawImage3(int r, int c, int width, int height, const u16* image) { for (int x = 0; x < height; x++) { DMA[3].cnt = 0; // clear old flags DMA[3].src = &image[OFFSET(x, 0, width)]; DMA[3].dst = &videoBuffer[OFFSET(r + x, c, 240)]; DMA[3].cnt = (width) | DMA_ON; } } void drawFullscreenImage3(const u16* image) { drawImage3(0, 0, 240, 160, image); } void drawHollowRect3(int row, int col, int height, int width, unsigned short color) { volatile unsigned short lineColor = color; DMA[3].cnt = 0; // clear old flags DMA[3].src = &lineColor; DMA[3].dst = &videoBuffer[OFFSET(row, col, 240)]; DMA[3].cnt = width | DMA_ON | DMA_SOURCE_FIXED; DMA[3].src = &color; DMA[3].dst = &videoBuffer[OFFSET(row + height - 1, col, 240)]; DMA[3].cnt = width | DMA_ON | DMA_SOURCE_FIXED; for(int r = row; r < height + row; r++) { setPixel(r, col, color); setPixel(r, col + width, color); } } // faster DMA loop (per row) version void drawRect3(int row, int col, int height, int width, unsigned short color) { volatile unsigned short lineColor = color; for(int r=0; r < height; r++) { DMA[3].cnt = 0; // clear old flags DMA[3].src = &lineColor; DMA[3].dst = &videoBuffer[OFFSET(row + r, col, 240)]; DMA[3].cnt = width | DMA_ON | DMA_SOURCE_FIXED; } } void drawHorizontalLine(int row, int col, int width, unsigned short color) { volatile unsigned short lineColor = color; DMA[3].cnt = 0; // clear old flags DMA[3].src = &lineColor; DMA[3].dst = &videoBuffer[OFFSET(row, col, 240)]; DMA[3].cnt = width | DMA_ON | DMA_SOURCE_FIXED; } void drawVerticalLine(int row, int col, int height, unsigned short color) { for (int i = 0; i < height; ++i) { setPixel(row + i, col, color); } } void drawEnemy(ENEMY* enemy, unsigned short Ecolor) { volatile unsigned short color = Ecolor; u16 size = enemy -> size; drawRect3(enemy -> row - size/2, enemy -> col - size/2, size, size, color); } void drawPlayer(player* player, unsigned short borderP, unsigned short insideP) { volatile unsigned short border = borderP; volatile unsigned short inside = insideP; u16 size = player -> size; drawRect3(player -> row - size/2, player -> col - size/2, size, size, inside); drawHollowRect3(player -> row - size/2, player -> col - size/2, size, size, border); }
Python
UTF-8
265
3.65625
4
[]
no_license
num = int(input()) from collections import OrderedDict d = OrderedDict() for i in range(num): inp = input() if inp not in d: d[inp] = 1 else: d[inp] += 1 print(len(d)) for i, j in d.items(): print(j, end = " ")
C#
UTF-8
1,796
3.46875
3
[]
no_license
using System; namespace Graph { /// <summary> /// 环检测(访问一个顶点v的连接顶点w,若此节点已经被访问且v的上个顶点不是w,则有环) /// </summary> public class CircleDetection { /// <summary> /// 图的表示 /// </summary> private readonly IAdjacency _adjacency; /// <summary> /// 记录节点是否被访问过 /// </summary> private readonly bool[] _visited; /// <summary> /// 是否有环 /// </summary> public bool IsHaveCircle { get; } /// <summary> /// 构造方法 /// </summary> /// <param name="iAdjacency"></param> public CircleDetection(IAdjacency iAdjacency) { if(iAdjacency.Directed) throw new Exception("direced graph can not be support!"); _adjacency = iAdjacency; _visited=new bool[_adjacency.V]; for (int i = 0; i < _adjacency.V; i++) { if (!_visited[i]) if (Dfs(i, i)) { IsHaveCircle = true; break; } } } /// <summary> /// 深度优先遍历并且记录是否有环 /// </summary> /// <param name="v"></param> /// <param name="parent"></param> /// <returns></returns> private bool Dfs(int v,int parent) { _visited[v] = true; foreach (var w in _adjacency.GetAllContiguousEdge(v)) { if(!_visited[w]) if (Dfs(w, v)) return true; else if (w != parent) return true; } return false; } } }
Java
UTF-8
915
2.21875
2
[]
no_license
package com.aho.gestionabscence.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Data @NoArgsConstructor @AllArgsConstructor @Entity public class Elimination { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @ManyToOne private Etudiant etudiant; @ManyToOne private Matiere matiere; private boolean isEliminated; public Elimination(Etudiant etudiant, Matiere matiere, boolean isEliminated) { this.etudiant = etudiant; this.matiere = matiere; this.isEliminated = isEliminated; } @Override public String toString() { return "Elimination{" + "id=" + id + ", etudiant=" + etudiant + ", matiere=" + matiere + ", isEliminated=" + isEliminated + '}'; } }
Java
UTF-8
953
3.296875
3
[]
no_license
package melwin.leetcode.medium; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; public class TopKFrequentElements { public static List<Integer> topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> char_count = new HashMap<>(); for (int n : nums) { int count = char_count.getOrDefault(n, 0); char_count.put(n, count + 1); } PriorityQueue<Integer> pq = new PriorityQueue<>(k, new Comparator<Integer>() { @Override public int compare(Integer arg0, Integer arg1) { return char_count.get(arg1) - char_count.get(arg0); } }); for (int n : char_count.keySet()) { pq.add(n); } List<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < k; i++) { result.add(pq.poll()); } return result; } public static void main(String[] args) { int[] nums = { 1 }; System.out.println(topKFrequent(nums, 1)); } }
Java
UTF-8
2,357
2.1875
2
[]
no_license
package com.xlw.test; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import com.xlw.goodscm.model.SupplierGroup; import com.xlw.goodscm.utils.JsonUtilTool; public class SupplierGroupTest extends BaseTest { @Test public void testAdd() { SupplierGroup supplier = new SupplierGroup(); supplier.setName("积极歪歪的"); HttpEntity<String> httpEntity = new HttpEntity<String>(JsonUtilTool.toJson(supplier), createJsonHeader()); ResponseEntity<String> responseEntity = restTemplate.exchange(localhost + "/suppliergroup/add", HttpMethod.POST, httpEntity, String.class); System.out.println(responseEntity.getBody()); } @Test public void testDel() { HttpEntity<String> httpEntity = new HttpEntity<String>(JsonUtilTool.toJson(new Object()), createJsonHeader()); ResponseEntity<String> responseEntity = restTemplate.exchange(localhost + "/suppliergroup/delete/2", HttpMethod.GET, httpEntity, String.class); System.out.println(responseEntity.getBody()); } @Test public void testGet() { HttpEntity<String> httpEntity = new HttpEntity<String>(JsonUtilTool.toJson(new Object()), createJsonHeader()); ResponseEntity<String> responseEntity = restTemplate.exchange(localhost + "/suppliergroup/get/2", HttpMethod.GET, httpEntity, String.class); System.out.println(responseEntity.getBody()); } @Test public void testUpdate() { SupplierGroup supplier = new SupplierGroup(); supplier.setId(2L); supplier.setName("积极歪歪的变牛鼻的"); HttpEntity<String> httpEntity = new HttpEntity<String>(JsonUtilTool.toJson(supplier), createJsonHeader()); ResponseEntity<String> responseEntity = restTemplate.exchange(localhost + "/suppliergroup/update", HttpMethod.POST, httpEntity, String.class); System.out.println(responseEntity.getBody()); } @Test public void testQuery() { HttpEntity<String> httpEntity = new HttpEntity<String>(JsonUtilTool.toJson(new SupplierGroup()), createJsonHeader()); ResponseEntity<String> responseEntity = restTemplate.exchange(localhost + "/suppliergroup/all", HttpMethod.GET, httpEntity, String.class); System.out.println(responseEntity.getBody()); } @Test public void test() { } }
Python
UTF-8
339
2.90625
3
[]
no_license
def aniversariantes_de_setembro(dic): novodic={} listadatas=[] listanomes=[] for nome,data in dic.items(): lisnomes.append(nome) lisdatas.append(data) i=0 while i<len(listadatas): if listadatas[i][3:5] == "09": novodic[listanomes[i]]=listadatas[i] i+=1 return novodic
Java
UTF-8
2,219
2.359375
2
[]
no_license
package com.sudigital.burnyourcalories.fragment; import android.content.Intent; import android.database.Cursor; import android.icu.text.SimpleDateFormat; import android.os.Bundle; 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.Button; import android.widget.TextView; import com.sudigital.burnyourcalories.KillerActivity; import com.sudigital.burnyourcalories.R; import com.sudigital.burnyourcalories.helper.DatabaseHelper; import java.util.Calendar; import butterknife.BindView; import butterknife.ButterKnife; public class BurnFragment extends Fragment implements View.OnClickListener{ @BindView(R.id.tvBurnCalories) TextView tvBurnCalories; @BindView(R.id.btnStart) Button btnStart; String dateNow; double totalCalories; public BurnFragment() { } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); SimpleDateFormat dateTimeFormat; dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy"); Calendar calendar = Calendar.getInstance(); dateNow = dateTimeFormat.format(calendar.getTime()); DatabaseHelper databaseHelper = new DatabaseHelper(getContext()); Cursor cursor = databaseHelper.selectActivity(); while(cursor.moveToNext()){ if(dateNow.equals(cursor.getString(4))){ totalCalories += cursor.getDouble(2); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_burn, container, false); ButterKnife.bind(this, view); tvBurnCalories.setText(String.valueOf( String.format("%.2f", totalCalories ))); btnStart.setOnClickListener(this); return view; } @Override public void onClick(View view) { if(view.equals(btnStart)){ getActivity().startActivity(new Intent(getContext(), KillerActivity.class)); } } }
Python
UTF-8
7,591
2.859375
3
[]
no_license
import time import scipy.signal import numpy as np import cv2 import util def normalize_window(window): return window / window.sum() def gaussian_window(window_length, standard_deviation): return normalize_window(scipy.signal.gaussian(window_length, standard_deviation)) def half_gaussian_window(window_length, standard_deviation): return normalize_window(scipy.signal.gaussian(2 * window_length, standard_deviation)[:window_length]) def reflect_signal(values, length): return np.r_[values[length - 1:0:-1], values, values[-2:-length - 1:-1]] def smooth(values, mode): if mode is None: return values elif isinstance(mode, tuple) and mode[0] == 'median': return scipy.signal.medfilt(values, mode[1]) elif isinstance(mode, tuple) and mode[0] == 'convolve': reflected = reflect_signal(values, len(mode[1]) - int(len(mode[1]) / 2)) smoothed = scipy.signal.convolve(mode[1], reflected, mode='valid') return smoothed def estimate_poly(times, values, degree): coef = np.polyfit(times, values, degree) return coef[degree] class SlidingWindowFilter(util.RingBuffer): """A 1-D sliding window noise filter.""" def __init__(self, window_size, smoothing_mode=None, estimation_mode=('poly', 3)): super(SlidingWindowFilter, self).__init__(window_size) self.smoothing_mode = smoothing_mode self.estimation_mode = estimation_mode def estimate_current(self): if self.estimation_mode == 'median': return self.get_median() elif self.estimation_mode == 'mean': return self.get_mean() elif self.estimation_mode == 'raw': return self.get_head() else: if self.length < self.data.size: return None (times, values) = self.get_timeseries() values = smooth(values, self.smoothing_mode) if isinstance(self.estimation_mode, tuple): if self.estimation_mode[0] == 'poly': return estimate_poly(times, values, self.estimation_mode[1]) elif self.estimation_mode[0] == 'kernel': return np.dot(self.estimation_mode[1], values) def get_mean(self): """Gets the mean of the values in the window.""" if self.length: return np.mean(self.data[:self.length]) else: return None def get_median(self): """Gets the median of the values in the window.""" if self.length: return np.median(self.data[:self.length]) else: return None def get_min(self): """Gets the min of the values in the window.""" return np.amin(self.data[:self.length]) def get_max(self): """Gets the min of the values in the window.""" return np.amax(self.data[:self.length]) def get_timeseries(self): values = self.get_continuous() times = np.arange(len(values)) - len(values) return (times, values) class SlidingWindowThresholdFilter(SlidingWindowFilter): def __init__(self, window_size=8, threshold=0, nonstationary_transition_smoothness=3, smoothing_mode=('convolve', gaussian_window(7, 2.0)), estimation_mode=('poly', 4)): super(SlidingWindowThresholdFilter, self).__init__(window_size, smoothing_mode, estimation_mode) self.threshold = threshold self._stationary_value = None self.nonstationary_transition_smoothness = nonstationary_transition_smoothness self._nonstationary_duration = 0 def estimate_current(self): if self.in_stationary_range(self.get_head()): if self._stationary_value is None: self._stationary_value = super(SlidingWindowThresholdFilter, self).estimate_current() self._nonstationary_duration = 0 return self._stationary_value else: self._nonstationary_duration += 1 if self._nonstationary_duration >= self.nonstationary_transition_smoothness: self._stationary_value = None return super(SlidingWindowThresholdFilter, self).estimate_current() else: return self._stationary_value def in_stationary_range(self, value): return (value >= self.estimate_stationary_value() - self.threshold and value <= self.estimate_stationary_value() + self.threshold) def estimate_stationary_value(self): return self.get_mean() class KalmanFilter(object): def __init__(self): self.kalman = cv2.KalmanFilter(3, 1, 0) self.kalman.statePre = np.zeros((3, 1), np.float32) self.kalman.measurementMatrix = np.array([[1, 0, 0]], np.float32) self.kalman.measurementNoiseCov = np.array([10], np.float32) self.kalman.errorCovPost = np.eye(3, dtype=np.float32) * 4 self.last_measurement_time = None self.estimated = None def append(self, x): current_time = time.time() if self.last_measurement_time is None: self.last_measurement_time = current_time else: dt = current_time - self.last_measurement_time self.last_measurement_time = current_time self.kalman.transitionMatrix = np.array( [[1, dt, 0.5 * dt ** 2], [0, 1, dt], [0, 0, 1]], np.float32) self.kalman.processNoiseCov = np.array( [[1.0 / 9 * dt ** 6, 1.0 / 6 * dt ** 5, 1.0 / 3 * dt ** 4], [1.0 / 6 * dt ** 5, 1.0 / 4 * dt ** 4, 1.0 / 2 * dt ** 3], [1.0 / 3 * dt ** 4, 1.0 / 2 * dt ** 3, dt]], np.float32) * 1000 self.kalman.predict() if x is not None: self.estimated = self.kalman.correct(np.array([[x]], np.float32)).ravel() else: self.estimated = prediction.ravel() #print self.estimated[1], self.estimated[2] def estimate_current(self): return self.estimated[0] class ThresholdKalmanFilter(KalmanFilter): def __init__(self, position_from_stationary=5, velocity_from_stationary=5, acceleration_from_stationary=8, velocity_to_stationary=5, acceleration_to_stationary=5): super(ThresholdKalmanFilter, self).__init__() self.position_from_stationary = position_from_stationary self.velocity_from_stationary = velocity_from_stationary self.acceleration_from_stationary = acceleration_from_stationary self.velocity_to_stationary = velocity_to_stationary self.acceleration_to_stationary = acceleration_to_stationary self._stationary_value = None def append(self, x): super(ThresholdKalmanFilter, self).append(x) abs_velocity = abs(self.estimated[1]) abs_acceleration = abs(self.estimated[2]) if self._stationary_value is None: if (abs_velocity < self.velocity_to_stationary and abs_acceleration < self.acceleration_to_stationary): self._stationary_value = self.estimated[0] else: abs_position = abs(self.estimated[0] - self._stationary_value) if (abs_position > self.position_from_stationary or abs_velocity > self.velocity_from_stationary or abs_acceleration > self.acceleration_from_stationary): self._stationary_value = None def estimate_current(self): if self._stationary_value is not None: return self._stationary_value return super(ThresholdKalmanFilter, self).estimate_current()
Java
UTF-8
560
2.03125
2
[]
no_license
package X; import javax.net.ssl.SSLException; /* renamed from: X.11f reason: invalid class name */ public final class AnonymousClass11f extends Exception { public final byte description; public final boolean errorTransient = false; public final SSLException ex; public AnonymousClass11f(byte b, SSLException sSLException) { this.description = b; this.ex = sSLException; } public AnonymousClass11f(byte b, SSLException sSLException, boolean z) { this.description = b; this.ex = sSLException; } }
Java
UTF-8
507
1.9375
2
[]
no_license
package com.hackathon.meetup.exceptions; import org.springframework.boot.context.config.ResourceNotFoundException; import org.springframework.core.io.Resource; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * Created by David Turk on 8/10/17. */ @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ContentNotFoundException extends RuntimeException { public ContentNotFoundException(String message) { super(message); } }
Markdown
UTF-8
1,130
2.6875
3
[]
no_license
--- title: Encontro noSQL e Ruby + Rails no Mundo Real author: Erick Sasse layout: post permalink: /encontro-nosql-e-ruby-rails-no-mundo-real/ dsq_thread_id: - 262151335 categories: - Geral --- Este mês pretendo participar de dois eventos apenas por curiosidade, pois não utilizo nenhuma das tecnologias no dia-a-dia. O primeiro é o [Encontro noSQL][1], que eu não tenho idéia do que seja e espero que o evento possa me apresentar a tecnologia. Mas o que eu mais gostei mesmo foi da criatividade na criação do site, acho que foi isso que me convenceu. <img src="http://www.ericksasse.com.br/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /> O segundo é [Ruby + Rails no Mundo Real][2], que não tem um site tão legal, mas o assunto já me interessa bem mais e eu ainda [ganhei][3] a inscrição participando da promoção no blog do Diego Garcia. Se alguém mais for participar de algum destes, nos encontramos lá para bater papo. [1]: http://nosqlbr.com/ [2]: http://www.temporealeventos.com.br/?area=130 [3]: http://unitonedev.blogspot.com/2010/04/ganhadores-dos-ingressos-para-evento.html
Java
UTF-8
1,163
2.46875
2
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
package com.oxygenxml.profiling; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Handler for find profile conditions from a document. * @author Cosmin Duna * */ public class ProfileDocsFinderHandler extends DefaultHandler { /** * Detector for conditions */ private AllConditionsDetector conditionsDetector; /** * Constructor * @param definedAttributesNames Set with defined conditions attributes names. */ public ProfileDocsFinderHandler(Set<String> definedAttributesNames) { conditionsDetector = new AllConditionsDetector(definedAttributesNames); } @Override public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); conditionsDetector.startElement( attributes, null); } /** * Get the found conditions. * @return a map with conditions. */ public LinkedHashMap<String, LinkedHashSet<String>> getProfilingMap() { return conditionsDetector.getAllConditionFromDocument(); } }
Shell
UTF-8
496
3.046875
3
[]
no_license
#!/bin/bash # gcc -c -I/usr/local/dislin orbital.c >& compiler.txt if [ $? -ne 0 ]; then echo "Errors compiling orbital.c" exit fi rm compiler.txt # gcc orbital.o -L/usr/local/dislin -ldislin -L/opt/local/lib -lXm -lm if [ $? -ne 0 ]; then echo "Errors linking and loading orbital.o." exit fi # rm orbital.o # mv a.out orbital ./orbital > orbital_output.txt if [ $? -ne 0 ]; then echo "Errors running orbital." exit fi rm orbital # echo "Program output written to orbital_output.txt"
PHP
UTF-8
10,772
3.046875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Nevena * Date: 7/23/14 * Time: 2:09 PM */ class Konobar implements JsonSerializable{ private $konobarID; private $ime; private $prezime; private $godinaRodjenja; private $mestoRodjenja; private $korisnickoIme; private $korisnickaSifra; private $role; private $slika; function __construct($konobarID, $ime, $prezime, $godinaRodjenja, $mestoRodjenja, $korisnickoIme, $korisnickaSifra, $role, $slika) { $this->konobarID = $konobarID; $this->ime = $ime; $this->prezime = $prezime; $this->godinaRodjenja = $godinaRodjenja; $this->mestoRodjenja = $mestoRodjenja; $this->korisnickoIme = $korisnickoIme; $this->korisnickaSifra = $korisnickaSifra; $this->role = $role; $this->slika = $slika; } /** * @param mixed $godinaRodjenja */ public function setGodinaRodjenja($godinaRodjenja) { $this->godinaRodjenja = $godinaRodjenja; } /** * @return mixed */ public function getGodinaRodjenja() { return $this->godinaRodjenja; } /** * @param mixed $ime */ public function setIme($ime) { $this->ime = $ime; } /** * @return mixed */ public function getIme() { return $this->ime; } /** * @param mixed $konobarID */ public function setKonobarID($konobarID) { $this->konobarID = $konobarID; } /** * @return mixed */ public function getKonobarID() { return $this->konobarID; } /** * @param mixed $korisnickaSifra */ public function setKorisnickaSifra($korisnickaSifra) { $this->korisnickaSifra = $korisnickaSifra; } /** * @return mixed */ public function getKorisnickaSifra() { return $this->korisnickaSifra; } /** * @param mixed $korisnickoIme */ public function setKorisnickoIme($korisnickoIme) { $this->korisnickoIme = $korisnickoIme; } /** * @return mixed */ public function getKorisnickoIme() { return $this->korisnickoIme; } /** * @param mixed $mestoRodjenja */ public function setMestoRodjenja($mestoRodjenja) { $this->mestoRodjenja = $mestoRodjenja; } /** * @return mixed */ public function getMestoRodjenja() { return $this->mestoRodjenja; } /** * @param mixed $prezime */ public function setPrezime($prezime) { $this->prezime = $prezime; } /** * @return mixed */ public function getPrezime() { return $this->prezime; } /** * @param mixed $role */ public function setRole($role) { $this->role = $role; } /** * @return mixed */ public function getRole() { return $this->role; } /** * @param mixed $slika */ public function setSlika($slika) { $this->slika = $slika; } /** * @return mixed */ public function getSlika() { return $this->slika; } public function expose(){ return get_object_vars($this); } function __toString() { // TODO: Implement __toString() method. return $this->ime ." ". $this->prezime ." (". $this->korisnickoIme .")"; } public function jsonSerialize() { return (object) get_object_vars($this); } public static function vratiSveKonobare(){ header ("Content-Type: application/json; charset=utf-8"); $db = Flight::db(); $db->select("konobar", "*", null, null, null, null, null); $niz = array(); while ($red=$db->getResult()->fetch_object()){ $niz[] = $red; } $json_niz = json_encode ($niz,JSON_UNESCAPED_UNICODE); return indent($json_niz); } public static function vratiKonobara($konobarID){ header ("Content-Type: application/json; charset=utf-8"); $db = Flight::db(); $db->select("konobar", "*", null, null, null, "konobarID = ".$konobarID, null); $niz=array(); while ($red=$db->getResult()->fetch_object()){ $niz[] = $red; } $json_niz = json_encode ($niz,JSON_UNESCAPED_UNICODE); echo indent($json_niz); } public function izmeniKonobara($konobarID){ header ("Content-Type: application/json; charset=utf-8"); $db = Flight::db(); $podaci_json = Flight::get("json_podaci"); $podaci = json_decode ($podaci_json); if ($podaci == null){ $odgovor["poruka"] = "Niste prosledili podatke"; $json_odgovor = json_encode ($odgovor); echo $json_odgovor; } else { if (!property_exists($podaci,'konobarID')||!property_exists($podaci,'prezime')||!property_exists($podaci,'godinaRodjenja')||!property_exists($podaci,'mestoRodjenja')||!property_exists($podaci,'korisnickoIme')||!property_exists($podaci,'korisnickaSifra')||!property_exists($podaci,'role')||!property_exists($podaci,'slika')){ $odgovor["poruka"] = "Niste prosledili korektne podatke"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } else { $podaci_query = array(); $odgovor["proba"]="uspesno, cekaj."; foreach ($podaci as $k=>$v){ $v = "'".$v."'"; $podaci_query[$k] = $v; } if ($db->update("konobar", $konobarID, array('ime', 'prezime', 'godinaRodjenja', 'mestoRodjenja', 'korisnickoIme', 'korisnickaSifra', 'role', 'slika'), array($podaci->ime, $podaci->prezime, $podaci->godinaRodjenja, $podaci->mestoRodjenja, $podaci->korisnickoIme, $podaci->korisnickaSifra, $podaci->role, $podaci->slika))){ $odgovor["poruka"] = "Konobar je uspešno izmenjen"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); //echo $json_odgovor; return true; } else { $odgovor["poruka"] = "Došlo je do greške pri izmeni konobara"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } } } } public function obrisiKonobara($konobarID){ header ("Content-Type: application/json; charset=utf-8"); $db = Flight::db(); if ($db->delete("konobar", array("konobarID"),array($konobarID))){ $odgovor["poruka"] = "Konobar je uspešno izbrisan"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } else { $odgovor["poruka"] = "Došlo je do greške prilikom brisanja konobara"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } } public function unesiKonobara(){ header ("Content-Type: application/json; charset=utf-8"); $db = Flight::db(); $podaci_json = Flight::get("json_podaci"); $podaci = json_decode ($podaci_json); if ($podaci == null){ $odgovor["poruka"] = "Niste prosledili podatke"; $json_odgovor = json_encode ($odgovor); echo $json_odgovor; } else { if (!property_exists($podaci,'prezime')||!property_exists($podaci,'godinaRodjenja')||!property_exists($podaci,'mestoRodjenja')||!property_exists($podaci,'korisnickoIme')||!property_exists($podaci,'korisnickaSifra')||!property_exists($podaci,'role')||!property_exists($podaci,'slika')){ $odgovor["poruka"] = "Niste prosledili korektne podatke"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } else { $podaci_query = array(); foreach ($podaci as $k=>$v){ $v = "'".$v."'"; $podaci_query[$k] = $v; } if ($db->insert("konobar", "ime, prezime, godinaRodjenja, mestoRodjenja, korisnickoIme, korisnickaSifra, role, slika", array($podaci_query["ime"], $podaci_query["prezime"], $podaci_query["godinaRodjenja"], $podaci_query["mestoRodjenja"], $podaci_query["korisnickoIme"], $podaci_query["korisnickaSifra"], $podaci_query["role"], $podaci_query["slika"]))){ $odgovor["poruka"] = "Ponuda je uspešno ubacena"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); //echo file_get_contents("/rest/konobar/1000"); //echo $json_odgovor; return false; } else { $odgovor["poruka"] = "Došlo je do greške pri ubacivanju ponude"; $json_odgovor = json_encode ($odgovor,JSON_UNESCAPED_UNICODE); echo $json_odgovor; return false; } } } } }
Python
UTF-8
208
2.75
3
[]
no_license
import math def main(): N, K = map(int, input().split()) count_list = [0] * N for i in l: index = i - 1 count_list[index] += 1 for out in count_list: print(out) main()
Swift
UTF-8
2,328
2.6875
3
[ "MIT" ]
permissive
// // MBXCompassMapView.swift // MapboxCompassMapViewSwift // // Created by Jordan Kiley on 7/19/17. // Copyright © 2017 Mapbox. All rights reserved. // import Mapbox class MBXCompassMapView: MGLMapView, MGLMapViewDelegate { var isMapInteractive : Bool = true { didSet { // Disable individually, then add custom gesture recognizers as needed. self.isZoomEnabled = false self.isScrollEnabled = false self.isPitchEnabled = false self.isRotateEnabled = false } } // Create a map view and set the style. override convenience init(frame: CGRect, styleURL: URL?) { self.init(frame: frame) self.styleURL = styleURL } // Create a map view. override init(frame: CGRect) { super.init(frame: frame) self.delegate = self self.alpha = 0.8 self.delegate = self hideMapSubviews() } // Make the map view a circle. override func layoutSubviews() { self.layer.cornerRadius = self.frame.width / 2 } // Hide the Mapbox wordmark, attribution button, and compass view. Move the attribution button and wordmark based on your design. See www.mapbox.com/help/how-attribution-works/#how-attribution-works for more information about attribution requirements. private func hideMapSubviews() { self.logoView.isHidden = true self.attributionButton.isHidden = true self.compassView.isHidden = true } // Set the user tracking mode to `.followWithHeading`. This rotates the map based on the direction that the user is facing. func mapViewWillStartLoadingMap(_ mapView: MGLMapView) { self.userTrackingMode = .followWithHeading } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Adds a border to the map view. func setMapViewBorderColorAndWidth(color: CGColor, width: CGFloat) { self.layer.borderWidth = width self.layer.borderColor = color } } extension MBXCompassMapView { func setupUserTrackingMode() { self.showsUserLocation = true self.setUserTrackingMode(.followWithHeading, animated: false) self.displayHeadingCalibration = false } }
TypeScript
UTF-8
206
2.734375
3
[]
no_license
export class HistoryPiece { hiddenText: string; shownText: string; public constructor(hiddenText: string, shownText: string) { this.hiddenText = hiddenText; this.shownText = shownText; } }
Java
UTF-8
1,349
2.109375
2
[]
no_license
package com.example.dennis.selfmademoney.view.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.example.dennis.selfmademoney.R; public class RegisterActivity extends AppCompatActivity { private Button btnRegister, btnBack; public RegisterActivity(){} @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); btnRegister = findViewById(R.id.btnRegister); btnBack = findViewById(R.id.btnBack); adButtonListener(); } private void adButtonListener(){ btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getBaseContext(), "Registrieren befindet sich in der Bearbeitung", Toast.LENGTH_SHORT).show(); } }); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(intent); } }); } }
Markdown
UTF-8
14,051
2.859375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: SignupCustomer Service Operation - Customer Management ms.service: bing-ads-customer-management-service ms.topic: article author: eric-urban ms.author: eur description: Creates a new customer and account that rolls up to your reseller payment method. dev_langs: - csharp - java - php - python --- # SignupCustomer Service Operation - Customer Management Creates a new customer and account that rolls up to your reseller payment method. > [!NOTE] > You must be a reseller with aggregator user permissions to call this operation. For more details see [Management Model for Resellers](../guides/management-model-resellers.md). Pass both [Customer](customer.md) and [AdvertiserAccount](advertiseraccount.md) objects in the request. The customer object includes the customer's name, the address where the customer is located, the market in which the customer operates, and the industry in which the customer participates. Although it is possible to add multiple customers with the same details, you should use unique customer names so that users can easily distinguish between customers in a user interface. The account object must specify the name of the account; the type of currency to use to settle the account; and the payment method identifier, which must be set to null. The operation generates an invoice account and sets the payment method identifier to the identifier associated with the reseller's invoice. You are invoiced for all charges incurred by the customers that you manage. If the operation succeeds, a new managed customer is created outside of the reseller customer and an account is created within the managed customer. ## <a name="request"></a>Request Elements The *SignupCustomerRequest* object defines the [body](#request-body) and [header](#request-header) elements of the service operation request. The elements must be in the same order as shown in the [Request SOAP](#request-soap). > [!NOTE] > Unless otherwise noted below, all request elements are required. ### <a name="request-body"></a>Request Body Elements |Element|Description|Data Type| |-----------|---------------|-------------| |<a name="account"></a>Account|An [AdvertiserAccount](advertiseraccount.md) that specifies the details of the customer's primary account.|[AdvertiserAccount](advertiseraccount.md)| |<a name="customer"></a>Customer|A [Customer](customer.md) that specifies the details of the customer that you are adding.|[Customer](customer.md)| |<a name="parentcustomerid"></a>ParentCustomerId|The customer identifier of the reseller that will manage this customer.|**long**| ### <a name="request-header"></a>Request Header Elements [!INCLUDE[request-header](./includes/request-header.md)] ## <a name="response"></a>Response Elements The *SignupCustomerResponse* object defines the [body](#response-body) and [header](#response-header) elements of the service operation response. The elements are returned in the same order as shown in the [Response SOAP](#response-soap). ### <a name="response-body"></a>Response Body Elements |Element|Description|Data Type| |-----------|---------------|-------------| |<a name="accountid"></a>AccountId|A system-generated account identifier corresponding to the new account specified in the request.<br/><br/>Use this identifier with operation requests that require an *AccountId* element and a *CustomerAccountId* SOAP header element.|**long**| |<a name="accountnumber"></a>AccountNumber|A system-generated account number that is used to identify the account in the Bing Ads web application. The account number has the form, X*nnnnnnn*, where *nnnnnnn* is a series of digits.|**string**| |<a name="createtime"></a>CreateTime|The date and time that the account was added. The date and time value reflects the date and time at the server, not the client. For information about the format of the date and time, see the dateTime entry in [Primitive XML Data Types](https://go.microsoft.com/fwlink/?linkid=859198).|**dateTime**| |<a name="customerid"></a>CustomerId|A system-generated customer identifier corresponding to the new customer specified in the request.<br/><br/>Use this identifier with operation requests that require a *CustomerId* SOAP header element.|**long**| |<a name="customernumber"></a>CustomerNumber|A system-generated customer number that is used in the Bing Ads web application. The customer number is of the form, C*nnnnnnn*, where *nnnnnnn* is a series of digits.|**string**| ### <a name="response-header"></a>Response Header Elements [!INCLUDE[response-header](./includes/response-header.md)] ## <a name="request-soap"></a>Request SOAP This template was generated by a tool to show the [order](../guides/services-protocol.md#element-order) of the [body](#request-body) and [header](#request-header) elements for the SOAP request. For supported types that you can use with this service operation, see the [Request Body Elements](#request-header) reference above. ```xml <s:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header xmlns="https://bingads.microsoft.com/Customer/v12"> <Action mustUnderstand="1">SignupCustomer</Action> <AuthenticationToken i:nil="false">ValueHere</AuthenticationToken> <DeveloperToken i:nil="false">ValueHere</DeveloperToken> </s:Header> <s:Body> <SignupCustomerRequest xmlns="https://bingads.microsoft.com/Customer/v12"> <Customer xmlns:e281="https://bingads.microsoft.com/Customer/v12/Entities" i:nil="false"> <e281:CustomerFinancialStatus i:nil="false">ValueHere</e281:CustomerFinancialStatus> <e281:Id i:nil="false">ValueHere</e281:Id> <e281:Industry i:nil="false">ValueHere</e281:Industry> <e281:LastModifiedByUserId i:nil="false">ValueHere</e281:LastModifiedByUserId> <e281:LastModifiedTime i:nil="false">ValueHere</e281:LastModifiedTime> <e281:MarketCountry i:nil="false">ValueHere</e281:MarketCountry> <e281:ForwardCompatibilityMap xmlns:e282="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false"> <e282:KeyValuePairOfstringstring> <e282:key i:nil="false">ValueHere</e282:key> <e282:value i:nil="false">ValueHere</e282:value> </e282:KeyValuePairOfstringstring> </e281:ForwardCompatibilityMap> <e281:MarketLanguage i:nil="false">ValueHere</e281:MarketLanguage> <e281:Name i:nil="false">ValueHere</e281:Name> <e281:ServiceLevel i:nil="false">ValueHere</e281:ServiceLevel> <e281:CustomerLifeCycleStatus i:nil="false">ValueHere</e281:CustomerLifeCycleStatus> <e281:TimeStamp i:nil="false">ValueHere</e281:TimeStamp> <e281:Number i:nil="false">ValueHere</e281:Number> <e281:CustomerAddress i:nil="false"> <e281:City i:nil="false">ValueHere</e281:City> <e281:CountryCode i:nil="false">ValueHere</e281:CountryCode> <e281:Id i:nil="false">ValueHere</e281:Id> <e281:Line1 i:nil="false">ValueHere</e281:Line1> <e281:Line2 i:nil="false">ValueHere</e281:Line2> <e281:Line3 i:nil="false">ValueHere</e281:Line3> <e281:Line4 i:nil="false">ValueHere</e281:Line4> <e281:PostalCode i:nil="false">ValueHere</e281:PostalCode> <e281:StateOrProvince i:nil="false">ValueHere</e281:StateOrProvince> <e281:TimeStamp i:nil="false">ValueHere</e281:TimeStamp> <e281:BusinessName i:nil="false">ValueHere</e281:BusinessName> </e281:CustomerAddress> </Customer> <Account xmlns:e283="https://bingads.microsoft.com/Customer/v12/Entities" i:nil="false"> <e283:BillToCustomerId i:nil="false">ValueHere</e283:BillToCustomerId> <e283:CurrencyCode i:nil="false">ValueHere</e283:CurrencyCode> <e283:AccountFinancialStatus i:nil="false">ValueHere</e283:AccountFinancialStatus> <e283:Id i:nil="false">ValueHere</e283:Id> <e283:Language i:nil="false">ValueHere</e283:Language> <e283:LastModifiedByUserId i:nil="false">ValueHere</e283:LastModifiedByUserId> <e283:LastModifiedTime i:nil="false">ValueHere</e283:LastModifiedTime> <e283:Name i:nil="false">ValueHere</e283:Name> <e283:Number i:nil="false">ValueHere</e283:Number> <e283:ParentCustomerId>ValueHere</e283:ParentCustomerId> <e283:PaymentMethodId i:nil="false">ValueHere</e283:PaymentMethodId> <e283:PaymentMethodType i:nil="false">ValueHere</e283:PaymentMethodType> <e283:PrimaryUserId i:nil="false">ValueHere</e283:PrimaryUserId> <e283:AccountLifeCycleStatus i:nil="false">ValueHere</e283:AccountLifeCycleStatus> <e283:TimeStamp i:nil="false">ValueHere</e283:TimeStamp> <e283:TimeZone i:nil="false">ValueHere</e283:TimeZone> <e283:PauseReason i:nil="false">ValueHere</e283:PauseReason> <e283:ForwardCompatibilityMap xmlns:e284="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false"> <e284:KeyValuePairOfstringstring> <e284:key i:nil="false">ValueHere</e284:key> <e284:value i:nil="false">ValueHere</e284:value> </e284:KeyValuePairOfstringstring> </e283:ForwardCompatibilityMap> <e283:LinkedAgencies i:nil="false"> <e283:CustomerInfo> <e283:Id i:nil="false">ValueHere</e283:Id> <e283:Name i:nil="false">ValueHere</e283:Name> </e283:CustomerInfo> </e283:LinkedAgencies> <e283:SalesHouseCustomerId i:nil="false">ValueHere</e283:SalesHouseCustomerId> <e283:TaxInformation xmlns:e285="http://schemas.datacontract.org/2004/07/System.Collections.Generic" i:nil="false"> <e285:KeyValuePairOfstringstring> <e285:key i:nil="false">ValueHere</e285:key> <e285:value i:nil="false">ValueHere</e285:value> </e285:KeyValuePairOfstringstring> </e283:TaxInformation> <e283:BackUpPaymentInstrumentId i:nil="false">ValueHere</e283:BackUpPaymentInstrumentId> <e283:BillingThresholdAmount i:nil="false">ValueHere</e283:BillingThresholdAmount> <e283:BusinessAddress i:nil="false"> <e283:City i:nil="false">ValueHere</e283:City> <e283:CountryCode i:nil="false">ValueHere</e283:CountryCode> <e283:Id i:nil="false">ValueHere</e283:Id> <e283:Line1 i:nil="false">ValueHere</e283:Line1> <e283:Line2 i:nil="false">ValueHere</e283:Line2> <e283:Line3 i:nil="false">ValueHere</e283:Line3> <e283:Line4 i:nil="false">ValueHere</e283:Line4> <e283:PostalCode i:nil="false">ValueHere</e283:PostalCode> <e283:StateOrProvince i:nil="false">ValueHere</e283:StateOrProvince> <e283:TimeStamp i:nil="false">ValueHere</e283:TimeStamp> <e283:BusinessName i:nil="false">ValueHere</e283:BusinessName> </e283:BusinessAddress> <e283:AutoTagType i:nil="false">ValueHere</e283:AutoTagType> <e283:SoldToPaymentInstrumentId i:nil="false">ValueHere</e283:SoldToPaymentInstrumentId> </Account> <ParentCustomerId i:nil="false">ValueHere</ParentCustomerId> </SignupCustomerRequest> </s:Body> </s:Envelope> ``` ## <a name="response-soap"></a>Response SOAP This template was generated by a tool to show the order of the [body](#response-body) and [header](#response-header) elements for the SOAP response. ```xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header xmlns="https://bingads.microsoft.com/Customer/v12"> <TrackingId d3p1:nil="false" xmlns:d3p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</TrackingId> </s:Header> <s:Body> <SignupCustomerResponse xmlns="https://bingads.microsoft.com/Customer/v12"> <CustomerId>ValueHere</CustomerId> <CustomerNumber d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</CustomerNumber> <AccountId d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</AccountId> <AccountNumber d4p1:nil="false" xmlns:d4p1="http://www.w3.org/2001/XMLSchema-instance">ValueHere</AccountNumber> <CreateTime>ValueHere</CreateTime> </SignupCustomerResponse> </s:Body> </s:Envelope> ``` ## <a name="example"></a>Code Syntax The example syntax can be used with [Bing Ads SDKs](../guides/client-libraries.md). See [Bing Ads Code Examples](../guides/code-examples.md) for more examples. ```csharp public async Task<SignupCustomerResponse> SignupCustomerAsync( Customer customer, AdvertiserAccount account, long? parentCustomerId) { var request = new SignupCustomerRequest { Customer = customer, Account = account, ParentCustomerId = parentCustomerId }; return (await CustomerManagementService.CallAsync((s, r) => s.SignupCustomerAsync(r), request)); } ``` ```java static SignupCustomerResponse signupCustomer( Customer customer, AdvertiserAccount account, java.lang.Long parentCustomerId) throws RemoteException, Exception { SignupCustomerRequest request = new SignupCustomerRequest(); request.setCustomer(customer); request.setAccount(account); request.setParentCustomerId(parentCustomerId); return CustomerManagementService.getService().signupCustomer(request); } ``` ```php static function SignupCustomer( $customer, $account, $parentCustomerId) { $GLOBALS['Proxy'] = $GLOBALS['CustomerManagementProxy']; $request = new SignupCustomerRequest(); $request->Customer = $customer; $request->Account = $account; $request->ParentCustomerId = $parentCustomerId; return $GLOBALS['CustomerManagementProxy']->GetService()->SignupCustomer($request); } ``` ```python response=customermanagement_service.SignupCustomer( Customer=Customer, Account=Account, ParentCustomerId=ParentCustomerId) ``` ## Requirements Service: [CustomerManagementService.svc v12](https://clientcenter.api.bingads.microsoft.com/Api/CustomerManagement/v12/CustomerManagementService.svc) Namespace: https\://bingads.microsoft.com/Customer/v12
PHP
UTF-8
2,976
2.609375
3
[]
no_license
<?php use bdk\CssXpath\CssSelect; /** * PHPUnit tests for CssSelect */ class CssSelectTest extends \PHPUnit\Framework\TestCase { /** * Test * * @return array of serialized logs */ public function selectProvider() { return array( array('*', 14), array('div', 1), array('div, p', 2), array('div , p', 2), array('div ,p', 2), array('div, p, ul li a', 3), array('div#article', 1), array('div#article.block', 1), array('div#article.large.block', 1), array('h2', 1), array('div h2', 1), array('div > h2', 1), array('ul li a', 1), array('ul > li > a', 1), array('a[href=#]', 1), array('a[href="#"]', 1), array('div[id="article"]', 1), array('h2:contains(Article)', 1), array('h2:contains(Article) + p', 1), array('h2:contains(Article) + p:contains(Contents)', 1), array('div p + ul', 1), array('ul li', 5), array('li ~ li', 4), array('li ~ li ~ li', 3), array('li + li', 4), array('li + li + li', 3), array('li:first-child', 1), array('li:last-child', 1), array('li:contains(One):first-child', 1), array('li:nth-child(2)', 1), array('li:nth-child(3)', 1), array('li:nth-child(4)', 1), array('li:nth-child(6)', 0), array('li:nth-last-child(2)', 1), array('li:nth-last-child(3)', 1), array('li:nth-last-child(4)', 1), array('li:nth-last-child(6)', 0), array('ul li! > a', 1), array(':scope ul li > a', 1), array('.a', 2), array('#article', 1), array('[id="article"]', 1), array('.classa > .classb', 1), array('ul > li:last-child [href]', 1), array('[class~=large] li[class~=a]', 2), array('li[class]:not(.bar)', 1), array(':header', 1), array('.bar.a', 1), ); } /** * test selector * * @param string $selector css selector * @param integer $count expected number of matches * * @return void * * @dataProvider selectProvider */ public function testSelect($selector, $count) { $html = <<<HTML <div id="article" class="block large"> <h2>Article Name</h2> <p>Contents of article</p> <ul> <li class="a">One</li> <li class="bar">Two</li> <li class="bar a">Three</li> <li>Four</li> <li><a href="#">Five</a></li> </ul> </div> <span class="classa"><span class="classb">hi</span></span> HTML; $found = CssSelect::select($html, $selector); $foundCount = count($found); $this->assertSame($count, $foundCount); } }
Markdown
UTF-8
10,807
3.109375
3
[ "Apache-2.0" ]
permissive
--- slug: /zh/engines/table-engines/mergetree-family/collapsingmergetree --- # CollapsingMergeTree {#table_engine-collapsingmergetree} 该引擎继承于 [MergeTree](mergetree.md),并在数据块合并算法中添加了折叠行的逻辑。 `CollapsingMergeTree` 会异步的删除(折叠)这些除了特定列 `Sign` 有 `1` 和 `-1` 的值以外,其余所有字段的值都相等的成对的行。没有成对的行会被保留。更多的细节请看本文的[折叠](#table_engine-collapsingmergetree-collapsing)部分。 因此,该引擎可以显著的降低存储量并提高 `SELECT` 查询效率。 ## 建表 {#jian-biao} ``` sql CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster] ( name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1], name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2], ... ) ENGINE = CollapsingMergeTree(sign) [PARTITION BY expr] [ORDER BY expr] [SAMPLE BY expr] [SETTINGS name=value, ...] ``` 请求参数的描述,参考[请求参数](../../../engines/table-engines/mergetree-family/collapsingmergetree.md)。 **CollapsingMergeTree 参数** - `sign` — 类型列的名称: `1` 是«状态»行,`-1` 是«取消»行。 列数据类型 — `Int8`。 **子句** 创建 `CollapsingMergeTree` 表时,需要与创建 `MergeTree` 表时相同的[子句](mergetree.md#table_engine-mergetree-creating-a-table)。 <details markdown="1"> <summary>已弃用的建表方法</summary> :::info "注意" 不要在新项目中使用该方法,可能的话,请将旧项目切换到上述方法。 ``` sql CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster] ( name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1], name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2], ... ) ENGINE [=] CollapsingMergeTree(date-column [, sampling_expression], (primary, key), index_granularity, sign) ``` 除了 `sign` 的所有参数都与 `MergeTree` 中的含义相同。 - `sign` — 类型列的名称: `1` 是«状态»行,`-1` 是«取消»行。 列数据类型 — `Int8`。 </details> ## 折叠 {#table_engine-collapsingmergetree-collapsing} ### 数据 {#shu-ju} 考虑你需要为某个对象保存不断变化的数据的情景。似乎为一个对象保存一行记录并在其发生任何变化时更新记录是合乎逻辑的,但是更新操作对 DBMS 来说是昂贵且缓慢的,因为它需要重写存储中的数据。如果你需要快速的写入数据,则更新操作是不可接受的,但是你可以按下面的描述顺序地更新一个对象的变化。 在写入行的时候使用特定的列 `Sign`。如果 `Sign = 1` 则表示这一行是对象的状态,我们称之为«状态»行。如果 `Sign = -1` 则表示是对具有相同属性的状态行的取消,我们称之为«取消»行。 例如,我们想要计算用户在某个站点访问的页面页面数以及他们在那里停留的时间。在某个时候,我们将用户的活动状态写入下面这样的行。 ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ 一段时间后,我们写入下面的两行来记录用户活动的变化。 ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ -1 │ │ 4324182021466249494 │ 6 │ 185 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ 第一行取消了这个对象(用户)的状态。它需要复制被取消的状态行的所有除了 `Sign` 的属性。 第二行包含了当前的状态。 因为我们只需要用户活动的最后状态,这些行 ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ 1 │ │ 4324182021466249494 │ 5 │ 146 │ -1 │ └─────────────────────┴───────────┴──────────┴──────┘ 可以在折叠对象的失效(老的)状态的时候被删除。`CollapsingMergeTree` 会在合并数据片段的时候做这件事。 为什么我们每次改变需要 2 行可以阅读[算法](#table_engine-collapsingmergetree-collapsing-algorithm)段。 **这种方法的特殊属性** 1. 写入的程序应该记住对象的状态从而可以取消它。«取消»字符串应该是«状态»字符串的复制,除了相反的 `Sign`。它增加了存储的初始数据的大小,但使得写入数据更快速。 2. 由于写入的负载,列中长的增长阵列会降低引擎的效率。数据越简单,效率越高。 3. `SELECT` 的结果很大程度取决于对象变更历史的一致性。在准备插入数据时要准确。在不一致的数据中会得到不可预料的结果,例如,像会话深度这种非负指标的负值。 ### 算法 {#table_engine-collapsingmergetree-collapsing-algorithm} 当 ClickHouse 合并数据片段时,每组具有相同主键的连续行被减少到不超过两行,一行 `Sign = 1`(«状态»行),另一行 `Sign = -1` («取消»行),换句话说,数据项被折叠了。 对每个结果的数据部分 ClickHouse 保存: 1. 第一个«取消»和最后一个«状态»行,如果«状态»和«取消»行的数量匹配和最后一个行是«状态»行 2. 最后一个«状态»行,如果«状态»行比«取消»行多一个或一个以上。 3. 第一个«取消»行,如果«取消»行比«状态»行多一个或一个以上。 4. 没有行,在其他所有情况下。 合并会继续,但是 ClickHouse 会把此情况视为逻辑错误并将其记录在服务日志中。这个错误会在相同的数据被插入超过一次时出现。 因此,折叠不应该改变统计数据的结果。 变化逐渐地被折叠,因此最终几乎每个对象都只剩下了最后的状态。 `Sign` 是必须的因为合并算法不保证所有有相同主键的行都会在同一个结果数据片段中,甚至是在同一台物理服务器上。ClickHouse 用多线程来处理 `SELECT` 请求,所以它不能预测结果中行的顺序。如果要从 `CollapsingMergeTree` 表中获取完全«折叠»后的数据,则需要聚合。 要完成折叠,请使用 `GROUP BY` 子句和用于处理符号的聚合函数编写请求。例如,要计算数量,使用 `sum(Sign)` 而不是 `count()`。要计算某物的总和,使用 `sum(Sign * x)` 而不是 `sum(x)`,并添加 `HAVING sum(Sign) > 0` 子句。 聚合体 `count`,`sum` 和 `avg` 可以用这种方式计算。如果一个对象至少有一个未被折叠的状态,则可以计算 `uniq` 聚合。`min` 和 `max` 聚合无法计算,因为 `CollaspingMergeTree` 不会保存折叠状态的值的历史记录。 如果你需要在不进行聚合的情况下获取数据(例如,要检查是否存在最新值与特定条件匹配的行),你可以在 `FROM` 从句中使用 `FINAL` 修饰符。这种方法显然是更低效的。 ## 示例 {#shi-li} 示例数据: ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ 1 │ │ 4324182021466249494 │ 5 │ 146 │ -1 │ │ 4324182021466249494 │ 6 │ 185 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ 建表: ``` sql CREATE TABLE UAct ( UserID UInt64, PageViews UInt8, Duration UInt8, Sign Int8 ) ENGINE = CollapsingMergeTree(Sign) ORDER BY UserID ``` 插入数据: ``` sql INSERT INTO UAct VALUES (4324182021466249494, 5, 146, 1) ``` ``` sql INSERT INTO UAct VALUES (4324182021466249494, 5, 146, -1),(4324182021466249494, 6, 185, 1) ``` 我们使用两次 `INSERT` 请求来创建两个不同的数据片段。如果我们使用一个请求插入数据,ClickHouse 只会创建一个数据片段且不会执行任何合并操作。 获取数据: SELECT * FROM UAct ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ -1 │ │ 4324182021466249494 │ 6 │ 185 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 5 │ 146 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ 我们看到了什么,哪里有折叠? 通过两个 `INSERT` 请求,我们创建了两个数据片段。`SELECT` 请求在两个线程中被执行,我们得到了随机顺序的行。没有发生折叠是因为还没有合并数据片段。ClickHouse 在一个我们无法预料的未知时刻合并数据片段。 因此我们需要聚合: ``` sql SELECT UserID, sum(PageViews * Sign) AS PageViews, sum(Duration * Sign) AS Duration FROM UAct GROUP BY UserID HAVING sum(Sign) > 0 ``` ┌──────────────UserID─┬─PageViews─┬─Duration─┐ │ 4324182021466249494 │ 6 │ 185 │ └─────────────────────┴───────────┴──────────┘ 如果我们不需要聚合并想要强制进行折叠,我们可以在 `FROM` 从句中使用 `FINAL` 修饰语。 ``` sql SELECT * FROM UAct FINAL ``` ┌──────────────UserID─┬─PageViews─┬─Duration─┬─Sign─┐ │ 4324182021466249494 │ 6 │ 185 │ 1 │ └─────────────────────┴───────────┴──────────┴──────┘ 这种查询数据的方法是非常低效的。不要在大表中使用它。
Ruby
UTF-8
1,230
2.734375
3
[]
no_license
# # https://github.com/heroku/rack-timeout # require "rack-timeout" # class Rack::TimeoutHelper # def initialize(app) # @app = app # end # def call(env) # @app.call(env) # rescue Rack::Timeout::RequestTimeoutError # [504, {"Content-Type" => "text/html"}, ["Gateway Timeout"]] # end # end # use Rack::TimeoutHelper # # Call as early as possible so rack-timeout runs before all other middleware. # # Setting service_timeout is recommended. If omitted, defaults to 15 seconds. # use Rack::Timeout, service_timeout: 5 # module Rack # class Logger # def call(env) # @app.call(env) # end # end # end class TestServer def call(env) req = Rack::Request.new(env) puts "#{req.path_info} start" case req.path_info when /long/ sleep(10) [200, {"Content-Type" => "text/html"}, ["Hello World!"]] when /medium/ sleep(5) # puts "#{req.path_info} end" [200, {"Content-Type" => "text/html"}, ["Hello World!"]] when /small/ sleep(2) # puts "#{req.path_info} end" [200, {"Content-Type" => "text/html"}, ["Hello World!"]] else [200, {"Content-Type" => "text/html"}, ["Hello World!"]] end end end run TestServer.new
SQL
UTF-8
238
3.515625
4
[]
no_license
SELECT dept_name, COUNT(student_id) AS student_number FROM department LEFT OUTER JOIN student ON department.dept_id = student.dept_id GROUP BY department.dept_name ORDER BY student_number DESC , department.dept_name ;
C++
UTF-8
518
3.078125
3
[]
no_license
#include "ArkMath.h" Vec4 ArkMath::operator*(Mat4 const & matrix, Vec4 const & vec4) { Vec4 vec; vec.x = matrix[0] * vec4.x + matrix[1] * vec4.y + matrix[2] * vec4.z + matrix[3] * vec4.w; vec.y = matrix[4] * vec4.x + matrix[5] * vec4.y + matrix[6] * vec4.z + matrix[7] * vec4.w; vec.z = matrix[8] * vec4.x + matrix[9] * vec4.y + matrix[10] * vec4.z + matrix[11] * vec4.w; vec.w = matrix[12] * vec4.x + matrix[13] * vec4.y + matrix[14] * vec4.z + matrix[15] * vec4.w; return vec; }
Markdown
UTF-8
305
2.578125
3
[]
no_license
# Work-day-scheduler This is a website that allows you to schedule your day out. To schedule something click on a time block and then write your to do item and then click the save icon. Project link: https://smashercoder.github.io/Work-day-scheduler/ ![image info](./assets/images/workdayscheduler.jpg)
Markdown
UTF-8
18,784
3.375
3
[ "Apache-2.0" ]
permissive
12 cool things you can do with GitHub ============================================================ translating by softpaopao I can’t for the life of me think of an intro, so… ### #1 Edit code on GitHub.com I’m going to start with one that I  _think_  most people know (even though I didn’t know until a week ago). When you’re in GitHub, looking at a file (any text file, any repository), there’s a little pencil up in the top right. If you click it, you can edit the file. When you’re done, hit Propose file change and GitHub will fork the repo for you and create a pull request. Isn’t that wild? It creates the fork for you! No need to fork and pull and change locally and push and create a PR. ![](https://cdn-images-1.medium.com/max/1600/1*w3yKOnVwomvK-gc7hlQNow.png) Not a real PR This is great for fixing typos and a somewhat terrible idea for editing code. ### #2 Pasting images You’re not just limited to text in comments and issue descriptions. Did you know you can paste an image straight from the clipboard? When you paste, you’ll see it gets uploaded (to the ‘cloud’, no doubt) and becomes the markdown for showing an image. Neat. ### #3 Formatting code If you want to write a code block, you can start with three backticks — just like you learned when you read the [Mastering Markdown][3] page — and GitHub will make an attempt to guess what language you’re writing. But if you’re posting a snippet of something like Vue, Typescript or JSX, you can specify that explicitly to get the right highlighting. Note the ````jsx` on the first line here: ![](https://cdn-images-1.medium.com/max/1600/1*xnt83oGWLtJzNzwp-YvSuA.png) …which means the snippet is rendered correctly: ![](https://cdn-images-1.medium.com/max/1600/1*FnOcz-bZi3S9Tn3dDGiIbQ.png) (This extends to gists, by the way. If you give a gist the extension of `.jsx`you’ll get JSX syntax highlighting.) Here’s a list of [all the supported syntaxes][4]. ### #4 Closing issues with magic words in PRs Let’s say you’re creating a pull request that fixes issue #234\. You can put the text “fixes #234” in the description of your PR (or indeed anywhere in any comment on the PR). Then, merging the PR automagically closes that issue. Isn’t that cool? There’s [more to learn in the help][5]. ### #5 Linking to comments Have you even wanted to link to a particular comment but couldn’t work out how? That’s because you don’t know how to do it. But those days are behind you my friend, because I am here to tell you that clicking on the date/time next to the name is how you link to a comment. ![](https://cdn-images-1.medium.com/max/1600/1*rSq4W-utQGga5GOW-w2QGg.png) Hey, gaearon got a picture! ### #6 Linking to code So you want to link to a specific line of code. I get that. Try this: while looking at the file, click the line number next to said code. Whoa, did you see that? The URL was updated with the line number! If you hold down shift and click another line number, SHAZAAM, the URL is updated again and now you’ve highlighted a range of lines. Sharing that URL will link to this file and those lines. But hold on, that’s pointing to the current branch. What if the file changes? Perhaps a permalink to the file in its current state is what you’re after. I’m lazy so I’ve done all of the above in one screenshot: ![](https://cdn-images-1.medium.com/max/1600/1*5Qg2GqTkTKuXLARasZN57A.png) Speaking of URLs… ### #7 Using the GitHub URL like the command line Navigating around GitHub using the UI is all well and fine. But sometimes the fastest way to get where you want to be is just to type it in the URL. For example, if I want to jump to a branch that I’m working on and see the diff with master, I can type `/compare/branch-name` after my repo name. That will land me on the diff page for that branch: ![](https://cdn-images-1.medium.com/max/2000/1*DqexM1y398gSaozLNllroA.png) That’s a diff with master though, if I was working off an integration branch, I’d type `/compare/integration-branch...my-branch` ![](https://cdn-images-1.medium.com/max/2000/1*roOXDuo_-9QKI5NLKmveGQ.png) For you keyboard short-cutters out there, `ctrl`+`L` or `cmd`+`L` will jump the cursor up into the URL (in Chrome at least). This — coupled with the fact that your browser is going to do auto-complete — can make it a handy way to jump around between branches. Pro-tip: use the arrow keys to move through Chrome’s auto-complete suggestions and hit `shift`+`delete` to remove an item from history (e.g. once a branch is merged). (I really wonder if those shortcuts would be easier to read if I did them like `shift + delete`. But technically the ‘+’ isn’t part of it, so I don’t feel comfortable with that. This is what keeps  _me_  up at night, Rhonda.) ### #8 Create lists, in issues Do you want to see a list of check boxes in your issue? ![](https://cdn-images-1.medium.com/max/1600/1*QIe-XOKOXTB3hXaLesr0zw.png) And would you like that to show up as a nifty “2 of 5” bar when looking at the issue in a list? ![](https://cdn-images-1.medium.com/max/1600/1*06WdEpxuasda2-lavjjvNw.png) That’s great! You can create interactive check boxes with this syntax: ``` - [ ] Screen width (integer) - [x] Service worker support - [x] Fetch support - [ ] CSS flexbox support - [ ] Custom elements ``` That’s a space and a dash and a space and a left bracket and a space (or an x) and a close bracket and a space and then some words. Then you can actually check/uncheck those boxes! For some reason this seems like technical wizardry to me. You can  _check_  the boxes! And it updates the underlying text! What will they think of next. Oh and if you have this issue on a project board, it will show the progress there too: ![](https://cdn-images-1.medium.com/max/1600/1*x_MzgCJXFp-ygsqFQB5qHA.png) If you don’t know what I’m talking about when I say “on a project board” then you’re in for a treat further down the page. Like, 2cm further down the page. ### #9 Project boards in GitHub I’ve always used Jira for big projects. And for solo projects I’ve always used Trello. I quite like both of them. When I learned a few weeks back that GitHub has its own offering, right there on the Projects tab of my repo, I thought I’d replicate a set of tasks that I already had on the boil in Trello. ![](https://cdn-images-1.medium.com/max/2000/1*NF7ZnHndZQ2SFUc5PK-Cqw.png) None of them are funny And here’s the same in a GitHub project: ![](https://cdn-images-1.medium.com/max/2000/1*CHsofapb4JtEDmveOvTYVQ.png) Your eyes adjust to the lack of contrast eventually For the sake of speed I added all of the above as ‘notes’ — which means they’re not actual GitHub issues. But the power of managing your tasks in GitHub is that it’s integrated with the rest of the repository — so you’ll probably want to add existing issues from the repo to the board. You can click Add Cards up in the top right and find the things you want to add. Here the special [search syntax][6] comes in handy, for example, type `is:pr is:open` and now you can drag any open PRs onto the board, or `label:bug` if you want to smash some bugs. ![](https://cdn-images-1.medium.com/max/2000/1*rTVCR92HhIPhrVnOnXRZkQ.png) Or you can convert existing notes to issues. ![](https://cdn-images-1.medium.com/max/1600/1*pTm7dygsyLxsOUDkM7CTcg.png) Or lastly, from an existing issue’s screen, add it to a project in the right pane. ![](https://cdn-images-1.medium.com/max/1600/1*Czs0cSc91tXv411uneEM9A.png) It will go into a triage list on that project board so you can decide which column to put it in. There’s a huge (huuuuge) benefit in having your ‘task’ definition in the same repo as the code that implements that task. It means that years from now you can do a git blame on a line of code and find your way back to the original rationale behind the task that resulted in that code, without needing to go and track it down in Jira/Trello/elsewhere. #### The downsides I’ve been trialling doing all tasks in GitHub instead of Jira for the last three weeks (on a smaller project that is kinda-sorta Kanban style) and I’m liking it so far. But I can’t imagine using it on scrum project where I want to do proper estimating and calculate velocity and all that good stuff. The good news is, there are so few ‘features’ of GitHub Projects that it won’t take you long to assess if it’s something you could switch to. So give it a crack, see what you think. FWIW, I have  _heard_  of [ZenHub][7] and opened it up 10 minutes ago for the first time ever. It effectively extends GitHub so you can estimate your issues and create epics and dependencies. There’s velocity and burndown charts too; it looks like it  _might just be_  the greatest thing on earth. Further reading: [GitHub help on Projects][8]. ### #10 GitHub wiki For an unstructured collection of pages — just like Wikipedia — the GitHub Wiki offering (which I will henceforth refer to as Gwiki) is great. For a structured collection of pages — for example, your documentation — not so much. There is no way to say “this page is a child of that page”, or have nice things like ‘Next section’ and ‘Previous section’ buttons. And Hansel and Gretel would be screwed, because there’s no breadcrumbs. (Side note, have you  _read_  that story? It’s brutal. The two jerk kids murder the poor hungry old woman by burning her to death in her  _own oven_ . No doubt leaving her to clean up the mess. I think this is why youths these days are so darn sensitive — bedtime stories nowadays don’t contain enough violence.) Moving on — to take Gwiki for a spin, I entered a few pages from the NodeJS docs as wiki pages, then created a custom sidebar so that I could emulate having some actual structure. The sidebar is there at all times, although it doesn’t highlight the page you are currently on. Links have to be manually maintained, but over all, I think it would work just fine. [Take a look][9] if you feel the need. ![](https://cdn-images-1.medium.com/max/1600/1*BSKQpkLmVQpUML0Je9WsLQ.png) It’s not going to compete with something like GitBook (that’s what the [Redux docs][10] use) or a bespoke website. But it’s a solid 80% and it’s all right there in your repo. I’m a fan. My suggestion: if you’ve outgrown a single `README.md` file and want a few different pages for user guides or more detailed documentation, then your next stop should be a Gwiki. If you start to feel the lack of structure/navigation is holding you back, move on to something else. ### #11 GitHub Pages (with Jekyll) You may already know that you can use GitHub Pages to host a static site. And if you didn’t now you do. However this section is specifically about using  _Jekyll_ to build out a site. At its very simplest, GitHub Pages + Jekyll will render your `README.md` in a pretty theme. For example, take a look at my readme page from [about-github][11]: ![](https://cdn-images-1.medium.com/max/2000/1*nU-vZfChZ0mZw9zO-6iJow.png) If I click the ‘settings’ tab for my site in GitHub, turn on GitHub Pages, and pick a Jekyll theme… ![](https://cdn-images-1.medium.com/max/1600/1*tT9AS7tNfEjbAcT3mkzgdw.png) I will get a [Jekyll-themed page][12]: ![](https://cdn-images-1.medium.com/max/2000/1*pIE2FMyWih7nFAdP-yGXtQ.png) From this point on I can build out a whole static site based mostly around markdown files that are easily editable, essentially turning GitHub into a CMS. I haven’t actually used it, but this is how the React and Bootstrap sites are made, so it can’t be terrible. Note, it requires Ruby to run locally (Windows users will exchange knowing glances and walk in the other direction. macOS users will be like “What’s the problem, where are you going? Ruby is a universal platform! GEMS!”) (It’s also worth adding here that “Violent or threatening content or activity” is not allowed on GitHub Pages, so you can’t go hosting your Hansel and Gretel reboot.) #### My opinion The more I looked into GitHub Pages + Jekyll (for this post), the more it seemed like there was something a bit strange about the whole thing. The idea of ‘taking all the complexity out of having your own web site’ is great. But you still need a build setup to work on it locally. And there’s an awful lot of CLI commands for something so ‘simple’. I just skimmed over the seven pages in the [Getting Started section][13], and I feel like  _I’m_  the only simple thing around here. And I haven’t even learnt the simple “Front Matter” syntax or the ins and outs of the simple “Liquid templating engine” yet. I’d rather just write a website. To be honest I’m a bit surprised Facebook use this for the React docs when they could probably build their help docs with React and [pre-render to static HTML files][14] in under a day. All they would need is some way to consume their existing markdown files as though they were coming from a CMS. I wonder if… ### #12 Using GitHub as a CMS Let’s say you have a website with some text in it, but you don’t want to store that text in the actual HTML markup. Instead, you want to store chunks of text somewhere so they can easily be edited by non-developers. Perhaps with some form of version control. Maybe even a review process. Here’s my suggestion: use markdown files stored in your repository to hold the text. Then have a component in your front end that fetches those chunks of text and renders them on the page. I’m a React guy, so here’s an example of a `<Markdown>` component that, given the path to some markdown, will fetch, parse and render it as HTML. (I’m using the [marked][1] npm package to parse the markdown into HTML.) That’s pointing to my example repo that has some markdown files in `[/text-snippets][2]`. (You could also use the GiHub API to [get the contents][15] — but I’m not sure why you would.) You would use such a component like so: So now GitHub is your CMS, sort of, for whatever chunks of text you want it to house. The above example only fetches the markdown after the component has mounted in the browser. If you want a static site then you’ll want to server-render this. Good news! There’s nothing stopping you from fetching all the markdown files on the server (coupled with whatever caching strategy works for you). If you go down that road you might want to look at the GitHub API to get a list of all the markdown files in a directory. ### Bonus round — GitHub tools! I’ve used the [Octotree Chrome extension][16] for a while now and I recommend it. Not wholeheartedly, but I recommend it nonetheless. It gives you a panel over on the left with a tree view of whatever repo you’re looking at. ![](https://cdn-images-1.medium.com/max/2000/1*-MgFq3TEjdys1coiF5-dCw.png) From [this video][17] I learned about [octobox][18], which so far seems pretty good. It’s an inbox for your GitHub issues. That’s all I have to say about that. Speaking of colors, I’ve taken all my screenshots above in the light theme so as not to startle you. But really, everything else I look at is dark themed, why must I endure a pallid GitHub? ![](https://cdn-images-1.medium.com/max/2000/1*SUdLeoaq8AtVQyE-dCw-Tg.png) That’s a combo of the [Stylish][19] Chrome extension (which can apply themes to any website) and the [GitHub Dark][20] style. And to complete the look, the dark theme of Chrome DevTools (which is built in, turn it on in settings) and the [Atom One Dark Theme][21] for Chrome. ### Bitbucket This doesn’t strictly fit anywhere in this post, but it wouldn’t be right if I didn’t give a shout-out to Bitbucket. Two years ago I was starting a project and spent half a day assessing which git host was best, and Bitbucket won by a considerable margin. Their code review flow was just so far ahead (this was long before GitHub even had the concept of assigning a reviewer). GitHub has since caught up in the review game, which is great. But sadly I haven’t had the chance to use Bitbucket in the last year — perhaps they’ve bounded ahead in some other way. So, I would urge anyone in the position of choosing a git host to check out Bitbucket too. ### Outro So that’s it! I hope there were at least three things in here that you didn’t know already, and also I hope that you have a nice day. Edit: there’s more tips in the comments; feel free to leave your own favourite. And seriously, I really do hope you have a nice day. -------------------------------------------------------------------------------- via: https://hackernoon.com/12-cool-things-you-can-do-with-github-f3e0424cf2f0 作者:[David Gilbertson][a] 译者:[译者ID](https://github.com/译者ID) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 [a]:https://hackernoon.com/@david.gilbertson [1]:https://www.npmjs.com/package/marked [2]:https://github.com/davidgilbertson/about-github/tree/master/text-snippets [3]:https://guides.github.com/features/mastering-markdown/ [4]:https://github.com/github/linguist/blob/fc1404985abb95d5bc33a0eba518724f1c3c252e/vendor/README.md [5]:https://help.github.com/articles/closing-issues-using-keywords/ [6]:https://help.github.com/articles/searching-issues-and-pull-requests/ [7]:https://www.zenhub.com/ [8]:https://help.github.com/articles/tracking-the-progress-of-your-work-with-project-boards/ [9]:https://github.com/davidgilbertson/about-github/wiki [10]:http://redux.js.org/ [11]:https://github.com/davidgilbertson/about-github [12]:https://davidgilbertson.github.io/about-github/ [13]:https://jekyllrb.com/docs/home/ [14]:https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#pre-rendering-into-static-html-files [15]:https://developer.github.com/v3/repos/contents/#get-contents [16]:https://chrome.google.com/webstore/detail/octotree/bkhaagjahfmjljalopjnoealnfndnagc?hl=en-US [17]:https://www.youtube.com/watch?v=NhlzMcSyQek&index=2&list=PLNYkxOF6rcIB3ci6nwNyLYNU6RDOU3YyL [18]:https://octobox.io/ [19]:https://chrome.google.com/webstore/detail/stylish-custom-themes-for/fjnbnpbmkenffdnngjfgmeleoegfcffe/related?hl=en [20]:https://userstyles.org/styles/37035/github-dark [21]:https://chrome.google.com/webstore/detail/atom-one-dark-theme/obfjhhknlilnfgfakanjeimidgocmkim?hl=en
Python
UTF-8
860
2.875
3
[]
no_license
import time import pprint import numpy as np from NeuralNetwork import * from Controler import * X = np.random.uniform(low=1.0, high=100.0, size=(100,1)) y = [] X_test = np.random.uniform(low=1.0, high=100.0, size=(100,1)) y_test = [] for sample in X: y.append((pow(sample, 0.5))/10) for sample in X_test: y_test.append((pow(sample, 0.5))/10) X = X/np.amax(X, axis=0) X_test = X_test/np.amax(X_test, axis=0) NN = Neural_Network() start_time = time.time() for i in range(10000): NN.loss.append(str(round(np.mean(np.square(y - NN.forward(X))),4))+ "\n") NN.train(X, y) training_time = time.time() - start_time FH = FileHandler(NN, round(training_time,3)) FH.SaveData() print("Loss: \n" + str(round(np.mean(np.square(y_test - NN.forward(X_test))),4))) print("INPUT: \n" + str(X_test*100)) print("PREDICTED OUTPUT: \n" + str(NN.forward(X_test)*10))
C++
GB18030
2,585
2.96875
3
[]
no_license
#include<opencv2/opencv.hpp> #include<iostream> #include<algorithm> #include<cmath> using namespace std; using namespace cv; void RGB2CMY(Mat& rgb, float k) { int height = rgb.rows; int width = rgb.cols; Mat cmy = rgb.clone(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float b = rgb.at<Vec3b>(i, j)[0];//OpenCvRGBͼǰBGR˳洢 float g = rgb.at<Vec3b>(i, j)[1]; float r = rgb.at<Vec3b>(i, j)[2]; float c, m, y; c = 255 - r; m = 255 - g; y = 255 - b; cmy.at<Vec3b>(i, j)[0] = (c * k + 255 * (1 - k)); cmy.at<Vec3b>(i, j)[1] = (m * k + 255 * (1 - k)); cmy.at<Vec3b>(i, j)[2] = (y * k + 255 * (1 - k)); } } imwrite("2CMY.jpg", cmy); return; } void RGB2HSI(Mat& rgb, float k) { int height = rgb.rows; int width = rgb.cols; Mat hsi = rgb.clone(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float b = rgb.at<Vec3b>(i, j)[0] / 255.0; float g = rgb.at<Vec3b>(i, j)[1] / 255.0; float r = rgb.at<Vec3b>(i, j)[2] / 255.0; float minRGB = min(min(r, g), b); float H, S, I; float temp1, temp2, radians, theta; temp1 = ((r - g) + (r - b)) / 2; temp2 = sqrt((r - g) * (r - g) + (r - b) * (g - b)); if (temp2 == 0) { H = 0; S = 0; } else { radians = acos(temp1 / temp2); theta = radians * 180.0 / 3.14; if (b > g) H = 360.0 - theta; else H = theta; } I = (r + g + b) / 3; if (I < 0.08) S = 0; else if (I > 0.92) S = 0; else S = 1.0 - (3.0 * minRGB) / (r + g + b); I *= 255; S *= 255; H = H / 360 * 255; hsi.at<Vec3b>(i, j)[0] = H; hsi.at<Vec3b>(i, j)[1] = S; hsi.at<Vec3b>(i, j)[2] = (I * k); } } imwrite("3HSI.jpg", hsi); return; } void Transform_RGB(Mat& rgb, float k) { int height = rgb.rows; int width = rgb.cols; Mat obj = rgb.clone(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float b = obj.at<Vec3b>(i, j)[0];//OpenCvRGBͼǰBGR˳洢 float g = obj.at<Vec3b>(i, j)[1]; float r = obj.at<Vec3b>(i, j)[2]; r = r * k; g = g * k; b = b * k; obj.at<Vec3b>(i, j)[0] = b; obj.at<Vec3b>(i, j)[1] = g; obj.at<Vec3b>(i, j)[2] = r; } } imwrite("1RGB.jpg", obj); return; } int main() { string imagepath("../pictures/0.jpg"); Mat image = imread(imagepath, IMREAD_COLOR); if (image.empty()) { cout << "Open image error" << endl; } float k = 0.7; RGB2CMY(image, k); RGB2HSI(image, k); Transform_RGB(image, k); waitKey(); return 0; }
Python
UTF-8
811
4.5
4
[]
no_license
""" Dada a classe TV abaixo, crie um objeto da classe TV, de 50 polegadas de tamanho, da marca Xingling, aumente o volume duas vezes utilizando os métodos fornecidos pela classe TV, e mostre mensagem informando a marca da TV e qual o volume do som atual. Não é necessário alterar a definição da classe TV. class TV: marca = None # marca da TV (string) polegadas = None # tamanho da TV em polegadas (inteiro) volume = None # volume atual do som (inteiro) def __init__(self, m, p, v): self.marca = m self.polegadas = p self.volume = v def soundUp (self): self.volume += 1 def soundDown (self): self.volume -= 1 """ tv = TV('Xingling', 50, 0) tv.soundUp() tv.soundUp() print("Marca %s \nVolume %s " % (tv.marca, tv.volume))
Markdown
UTF-8
738
2.5625
3
[]
no_license
--- weight: 40 bookFlatSection: true bookToc: false title: "Let's try to use" --- # Let's try to use The general flow for using this software is as follows. 1. Install timer software in advance. 2. Create a new profile. 3. Make initial settings. 4. Create a template image ([Tool]-> [Preview/Create template image]). 5. (Adjust the parameters in the table as needed.) 6. Execute image recognition processing. \ \ In "Let's try to use", we will explain on the premise of the following matters. - Use LiveSplit for timer software - Video capture method is "Screen Capture" - Target is OBS Studio's "windowed projector" (Because it is the software used by many RTA players and is compatible with any game.)
Java
UTF-8
8,240
3.125
3
[]
no_license
package com.example.martin.tugas2_pengcit; import java.util.ArrayList; import java.util.Collections; public class ConvolutionProcessor { private boolean isValid(int x, int y, int w, int h) { if (x < 0 || x >= w || y < 0 || y >= h) { return false; } return true; } public int[][] smoothing(int[][] givenImage, int w, int h) { int[] dx = {1, 1, 0, -1, -1, -1, 0, 1}; int[] dy = {0, 1, 1, 1, 0, -1, -1, -1}; int[][] new_matrix = new int[w][h]; ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { arr.clear(); arr.add(givenImage[i][j]); for (int k = 0; k < 8; k++) { if (isValid(i+dx[k], j+dy[k], w, h)) { arr.add(givenImage[i+dx[k]][j+dy[k]]); } } Collections.sort(arr); new_matrix[i][j] = arr.get(arr.size() / 2); } } return new_matrix; } public int[][] gradien(int[][] givenImage, int w, int h) { int[] dx1 = {1, 1, 1, 0}; int[] dy1 = {-1, 0, 1, 1}; int[] dx2 = {-1, -1, -1, 0}; int[] dy2 = {1, 0, -1, -1}; int[][] new_matrix = new int[w][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int max_difference = -1; for (int k = 0; k < 4; k++) { int pixel1 = isValid(i+dx1[k], j+dy1[k], w, h) ? givenImage[i+dx1[k]][j+dy1[k]] : 0; int pixel2 = isValid(i+dx2[k], j+dy2[k], w, h) ? givenImage[i+dx2[k]][j+dy2[k]] : 0; int delta = Math.abs(pixel1 - pixel2); if (max_difference == -1 || delta > max_difference) { max_difference = delta; } } new_matrix[i][j] = max_difference; } } return new_matrix; } public int[][] difference(int[][] givenImage, int w, int h) { int[] dx = {1, 1, 0, -1, -1, -1, 0, 1}; int[] dy = {0, 1, 1, 1, 0, -1, -1, -1}; int[][] new_matrix = new int[w][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int max_difference = -1; int current_pixel = givenImage[i][j]; for (int k = 0; k < 8; k++) { if (isValid(i+dx[k], j+dy[k], w ,h)) { int neighbour_pixel = givenImage[i+dx[k]][j+dy[k]]; int delta = Math.abs(neighbour_pixel - current_pixel); if (max_difference == -1 || delta > max_difference) { max_difference = delta; } } } new_matrix[i][j] = max_difference; } } return new_matrix; } public int[][] sobel(int[][] givenImage, int w, int h) { int[][] new_matrix = new int[w][h]; int[][] gx = { {-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}, }; int[][] gy = { {-1, -2, -1}, {0, 0, 0}, {1, 2, 1}, }; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int totalx = 0; int totaly = 0; for (int k = 0; k < gx.length; k++) { for (int l = 0; l < gx[0].length; l++) { if (isValid(i+k-1, j+l-1, w, h)) { int pixel = givenImage[i+k-1][j+l-1]; totalx += pixel * gx[k][l]; totaly += pixel * gy[k][l]; } } } new_matrix[i][j] = Math.min((int)Math.sqrt((double)totalx*totalx + totaly*totaly), 255); } } return new_matrix; } public int[][] prewitt(int[][] givenImage, int w, int h) { int[][] new_matrix = new int[w][h]; int[][] gx = { {-1, 0, 1}, {-1, 0, 1}, {-1, 0, 1}, }; int[][] gy = { {-1, -1, -1}, {0, 0, 0}, {1, 1, 1}, }; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int totalx = 0; int totaly = 0; for (int k = 0; k < gx.length; k++) { for (int l = 0; l < gx[0].length; l++) { if (isValid(i+k-1, j+l-1, w, h)) { int pixel = givenImage[i+k-1][j+l-1]; totalx += pixel * gx[k][l]; totaly += pixel * gy[k][l]; } } } new_matrix[i][j] = Math.min((int)Math.sqrt((double)totalx*totalx + totaly*totaly), 255); } } return new_matrix; } public int[][] roberts(int[][] givenImage, int w, int h) { int[][] new_matrix = new int[w][h]; int[][] gx = { {-1, 0}, {0, 1}, }; int[][] gy = { {0, -1}, {1, 0}, }; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int totalx = 0; int totaly = 0; for (int k = 0; k < gx.length; k++) { for (int l = 0; l < gx[0].length; l++) { if (isValid(i+k-1, j+l-1, w, h)) { int pixel = givenImage[i+k-1][j+l-1]; totalx += pixel * gx[k][l]; totaly += pixel * gy[k][l]; } } } new_matrix[i][j] = Math.min((int)Math.sqrt((double)totalx*totalx + totaly*totaly), 255); } } return new_matrix; } public int[][] frei_chen(int[][] givenImage, int w, int h) { int[][] new_matrix = new int[w][h]; double sqr = Math.sqrt(2); double[][] gx = { {-1, 0, 1}, {-sqr, 0, sqr}, {-1, 0, 1}, }; double[][] gy = { {-1, -sqr, -1}, {0, 0, 0}, {1, sqr, 1}, }; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { double totalx = 0; double totaly = 0; for (int k = 0; k < gx.length; k++) { for (int l = 0; l < gx[0].length; l++) { if (isValid(i+k-1, j+l-1, w, h)) { int pixel = givenImage[i+k-1][j+l-1]; totalx += pixel * gx[k][l]; totaly += pixel * gy[k][l]; } } } new_matrix[i][j] = Math.min((int)Math.sqrt(totalx*totalx + totaly*totaly), 255); } } return new_matrix; } public int[][] custom(int[][] givenImage, int w, int h, int[][] kernel) { int[][] new_matrix = new int[w][h]; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { int total = 0; for (int k = 0; k < kernel.length; k++) { for (int l = 0; l < kernel[0].length; l++) { if (isValid(i+k-1, j+l-1, w, h)) { int pixel = givenImage[i+k-1][j+l-1]; total += pixel * kernel[k][l]; } } } new_matrix[i][j] = Math.min(total, 255); } } return new_matrix; } }
Java
UTF-8
662
2.328125
2
[]
no_license
/* * 南京新网互联网络科技有效公司 * 预警平台1.0 */ package xwtec.alertor.thread; /** * * @author 张岩松 */ public interface RegistedTask extends AtomicTask, Runnable { /** * 获得注册的任务的名称 * * @return */ public abstract String getKey(); /** * 判断当前任务是否已经中断 * * @return */ public boolean isInterrupted(); /** * 中断任务 */ public void interrupt(); /** * 设置任务移除器 * * @param removeRegistedTask */ public void setRemoveRegistedTask(RemoveRegistedTask removeRegistedTask); }
Markdown
UTF-8
3,309
2.546875
3
[ "MIT" ]
permissive
--- title: Retrieve BitLocker keys shortcuts categories: - BitLocker tags: - PowerShell - BitLocker excerpt: Two quick ways to get BitLocker keys from AD accros the realm --- # Ups Some [time ago](https://www.mczerniawski.pl/bitlocker/retrieve-bitlocker-recovery-key) I've posted how to set AD environment for BitLocker and retrieve keys from AD. I've missed one spot though. For that to work you had to be: 1. AD User 2. Member of local adminstrators on your machine. I've updated that post with proper information how to [fix that](https://www.mczerniawski.pl/bitlocker/retrieve-bitlocker-recovery-key/#update-2019-04-23) - delegate proper permission to `SELF` object. # Some Goodies Today I'd like to share some `quick-dirty` scripts to automate even more: ## Backup ALL If you'd like to backup BitLocker key to both AD and AzureAD at the same time, here's a sample script. Just select only machines you need in the Out-GridView > Remember to Invoke (and retrieve BitLocker) to remote machine you require administrative permissions (or JEA with proper configuration)! ```powershell $ComputerName = Get-ADComputer -filter {OperatingSystem -like '*Windows*'} | Out-GridView -PassThru Invoke-command -ComputerName $ComputerName -ScriptBlock { $bitLockerVolume = Get-BitlockerVolume foreach ($Blv in $bitLockerVolume) { $keyProtectors = $blv.KeyProtector | Where-Object {$PSItem.KeyProtectorType -eq 'RecoveryPassword'} if ($KeyProtectors) { Write-Host "MountPoint {'$($blv.MountPoint)'} - KeyProtector {'$($keyProtectors.KeyProtectorID)'}" Write-Host " Backing up to AD" Backup-BitLockerKeyProtector -MountPoint $blv.MountPoint -KeyProtectorId $keyProtectors.KeyProtectorID Write-Host " Backing up to Azure AD" BackupToAAD-BitLockerKeyProtector -MountPoint $blv.MountPoint -KeyProtectorId $keyProtectors.KeyProtectorID } } } ``` ## See ALL And if You'd like to get all computers from AD with (and without) BitLocker information here's another one: > Remember the account you're running HAS to have proper AD permissions! ```powershell $computers = Get-ADcomputer -filter {OperatingSystem -like '*Windows*'} -Properties OperatingSystem,LastLogon $results = foreach ($computer in $computers) { $ComputerName = $computer $DNComputer = Get-ADComputer $computerName | Select-Object -ExpandProperty DistinguishedName $obj = Get-ADObject -Filter {objectclass -eq 'msFVE-RecoveryInformation'} -SearchBase $DNComputer -Properties 'msFVE-RecoveryPassword' | Select-Object Name,msFVE-RecoveryPassword if ($obj) { [pscustomobject]@{ ComputerName = $ComputerName RecoveryPassword = $obj.'msFVE-RecoveryPassword' Date = Get-Date -Date ($obj.Name ).Split('{')[0] KeyID = (($obj.Name ).Split('{')[1]).TrimEnd('}') LastLogon = [datetime]::FromFileTime($computer.LastLogon) } } else { [pscustomobject]@{ ComputerName = $ComputerName RecoveryPassword = $null Date = $Null KeyID = $null LastLogon = [datetime]::FromFileTime($computer.LastLogon) } } } ``` Now you can easily spot which computers are missing BitLocker keys stored in AD: ```powershell $empty = $results | where-object {$null -eq $PSItem.RecoveryPassword } ```
TypeScript
UTF-8
572
3.015625
3
[]
no_license
import { MenuActionTypes, MenuActions } from '../actions'; export interface MenuState { open: boolean; closed: boolean; } const initialState: MenuState = { open: false, closed: true }; export function menuReducer( state: MenuState = initialState, action: MenuActions ): MenuState { switch (action.type) { case MenuActionTypes.Open: return { ...state, open: true, closed: false }; case MenuActionTypes.Close: default: return { ...state, open: false, closed: true }; } }
TypeScript
UTF-8
1,060
2.828125
3
[ "MIT" ]
permissive
import { HEIGHT, gridSize, WIDTH } from '../../config'; export const neighbors = (map: any[], node:any) => { let dirs = [ {x: -gridSize, y: -gridSize}, {x: 0, y: -gridSize, distance: 10}, {x: gridSize, y: -gridSize}, {x: -gridSize, y: 0}, {x: gridSize, y: 0}, {x: -gridSize, y: gridSize}, {x: 0, y: gridSize}, {x: gridSize, y: gridSize} ]; let result = []; for(let dir of dirs) { let neighbor = { x: node.x + dir.x, y: node.y + dir.y } if(neighbor.x >= 0 && neighbor.x <= WIDTH && neighbor.y >= 0 && neighbor.y <= HEIGHT) { let finded:boolean = false; for(let node of map) { if(neighbor.x === node.x && neighbor.y === node.y) { finded = true; } } if(finded) { result.push({ x: neighbor.x, y: neighbor.y }); } } } return result; } export const addNeighbors = (map:any[]) => { for(let node of map) { let n = neighbors(map, node); node.neighbors = n; } }
Python
UTF-8
427
3.25
3
[]
no_license
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return 1 if not nums: return 0 index, dic = 0, {} for item in nums: if item not in dic: dic[item] = 1 nums[index] = item index += 1 return index
C++
UTF-8
563
2.890625
3
[]
no_license
#include <iostream> #include<math.h> #include <vector> #include <numeric> #include <algorithm> using namespace std; int abc103_b() { int N; cin >> N; string S, T; cin >> S >> T; long length = S.size(); for (int i = 0; i < length; ++i) { // 一個ずらす string first = S.substr(0, 1); string last = S.substr(length - 1, 1); S = S.substr(1, length - 1) + first; if (S == T) { cout << "Yes" << endl; return 0; } } cout << "No" << endl; return 0; }
Python
UTF-8
2,781
2.609375
3
[]
no_license
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS sonplays" user_table_drop = "DROP TABLE IF EXISTS users" song_table_drop = "DROP TABLE IF EXISTS songs" artist_table_drop = "DROP TABLE IF EXISTS artists" time_table_drop = "DROP TABLE IF EXISTS time" # CREATE TABLES songplay_table_create = ("""" CREATE TABLE IF NOT EXISTS songplays ( songplay_id SERIAL PRIMARY KEY, start_time timestamp NOT NULL, user_id varchar NOT NULL, level varchar, song_id varchar, artist_id varchar, session_id varchar NOT NULL, location varchar, user_agent varchar ) """) user_table_create = (""" CREATE TABLE IF NOT EXISTS users ( user_id varchar PRIMARY KEY, first_name varchar, last_name varchar, gender varchar, level varchar ) """) song_table_create = (""" CREATE TABLE IF NOT EXISTS songs ( song_id varchar PRIMARY KEY, title varchar, artist_id varchar NOT NULL, year int, duration int ) """) artist_table_create = (""" CREATE TABLE IF NOT EXISTS artists ( artist_id varchar PRIMARY KEY, name varchar, location varchar, latitude varchar, longitude varchar ) """) time_table_create = (""" CREATE TABLE IF NOT EXISTS time ( start_time timestamp PRIMARY KEY, hour int, day int, week int, month int, year int, weekday int ) """) # INSERT RECORDS songplay_table_insert = ("""" INSERT INTO songplays (start_time , user_id , level , song_id , artist_id , session_id , location , user_agent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (songplay_id) DO NOTHING """) user_table_insert = (""" INSERT INTO users (user_id, first_name, last_name, gender, level) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (user_id) DO UPDATE set level = EXCLUDED.level """) song_table_insert = (""" INSERT INTO songs (song_id, title, artist_id, year, duration) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (song_id) DO NOTHING """) artist_table_insert = (""" INSERT INTO artists (artist_id, name, location, latitude, longitude) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (artist_id) DO NOTHING """) time_table_insert = (""" INSERT INTO time (start_time, hour, day, week, month, year, weekday) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (start_time) DO NOTHING """) # FIND SONGS song_select = (""" SELECT songs.song_id, artists.artist_id FROM songs INNER JOIN artists ON songs.artist_id = artists.artist_id WHERE songs.title = %s AND artists.name = %s AND songs.duration = %s """) # QUERY LISTS create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
C#
UTF-8
385
3.171875
3
[]
no_license
using System; namespace Epam.Task_2._2._1.GAME { public class Tree : Barrier { public Tree(int _x, int _y) : base(_x, _y) { Name = "Tree"; } public override void MovedHero(Hero hero) { Console.WriteLine("Oh you hit a tree and it threw you 1 coordinate to the left!"); hero.Y--; } } }
C
UTF-8
15,219
2.921875
3
[]
no_license
/********************************************************************** * 版权所有 (C)2019, Zhou Zhaoxiong * * 文件名称:WriteLog.c * 文件标识:无 * 内容摘要:日志系统源代码文件 * 其它说明:无 * 当前版本:V1.0 * 作 者:Zhou Zhaoxiong * 完成日期:20190905 * **********************************************************************/ #include "WriteLog.h" // 全局变量 unsigned int g_iLogLevel = 0; // 日志等级 unsigned int g_iLogPosition = 0; // 日志位置 unsigned char g_szLogFile[100] = {0}; // 带路径的日志文件名 // 函数声明 void WriteLogFile(unsigned char *pszFileName, unsigned char *pszFunctionName, unsigned int iCodeLine, unsigned int iLogLevel, unsigned char *pszContent); unsigned char *LogLevel(unsigned int iLogLevel); void GetTime(unsigned char *pszTimeStr); void GetConfigValue(); void GetStringContentValue(FILE *fp, unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned char *pszOutput, unsigned int iOutputLen); void GetConfigFileStringValue(unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned char *pDefaultVal, unsigned char *pszOutput, unsigned int iOutputLen, unsigned char *pszConfigFileName); int GetConfigFileIntValue(unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned int iDefaultVal, unsigned char *pszConfigFileName); // 以下为函数具体实现 /********************************************************************** * 功能描述: 将内容写到日志文件中 * 输入参数: pszFileName-代码文件名 pszFunctionName-代码所在函数名 iCodeLine-代码行 iLogLevel-日志等级 pszContent-每条日志的具体内容 * 输出参数: 无 * 返 回 值: 无 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------- * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void WriteLogFile(unsigned char *pszFileName, unsigned char *pszFunctionName, unsigned int iCodeLine, unsigned int iLogLevel, unsigned char *pszContent) { FILE *fp = NULL; unsigned char szLogContent[2048] = {0}; unsigned char szTimeStr[128] = {0}; // 先对输入参数进行异常判断 if (pszFileName == NULL || pszContent == NULL) { return; } // 过滤日志等级 if (iLogLevel > g_iLogLevel) { return; } fp = fopen(g_szLogFile, "at+"); // 打开文件, 每次写入的时候在后面追加 if (fp == NULL) { return; } // 写入日志时间 GetTime(szTimeStr); fputs(szTimeStr, fp); // 写入日志内容 if (g_iLogPosition == 1) // 在日志信息中显示"文件名/函数名/代码行数"信息 { snprintf(szLogContent, sizeof(szLogContent)-1, "[%s][%s][%04d][%s]%s\n", pszFileName, pszFunctionName, iCodeLine, LogLevel(iLogLevel), pszContent); } else // 不用在日志信息中显示"文件名/代码行数"信息 { snprintf(szLogContent, sizeof(szLogContent)-1, "[%s]%s\n", LogLevel(iLogLevel), pszContent); } fputs(szLogContent, fp); fflush(fp); // 刷新文件 fclose(fp); // 关闭文件 fp = NULL; // 将文件指针置为空 return; } /********************************************************************** * 功能描述: 获取对应的日志等级 * 输入参数: iLogLevel-日志等级 * 输出参数: 无 * 返 回 值: 日志等级信息字符串 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------- * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ unsigned char *LogLevel(unsigned int iLogLevel) { switch (iLogLevel) { case LOG_FATAL: { return "FATAL"; } case LOG_ERROR: { return "ERROR"; } case LOG_WARN : { return "WARN"; } case LOG_INFO : { return "INFO"; } case LOG_TRACE: { return "TRACE"; } case LOG_DEBUG: { return "DEBUG"; } default: { return "OTHER"; } } } /********************************************************************** * 功能描述: 获取时间串 * 输入参数: pszTimeStr-时间串 * 输出参数: pszTimeStr-时间串 * 返 回 值: 无 * 其它说明: 时间串样式: YYYY.MM.DD HH:MIN:SS.Usec * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------- * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void GetTime(unsigned char *pszTimeStr) { struct tm tSysTime = {0}; struct timeval tTimeVal = {0}; time_t tCurrentTime = {0}; unsigned char szUsec[20] = {0}; // 微秒 unsigned char szMsec[20] = {0}; // 毫秒 // 先对输入参数进行异常判断 if (pszTimeStr == NULL) { return; } tCurrentTime = time(NULL); localtime_r(&tCurrentTime, &tSysTime); gettimeofday(&tTimeVal, NULL); sprintf(szUsec, "%06d", tTimeVal.tv_usec); // 获取微秒 strncpy(szMsec, szUsec, 3); // 微秒的前3位为毫秒(1毫秒=1000微秒) sprintf(pszTimeStr, "[%04d-%02d-%02d %02d:%02d:%02d.%3.3s]", tSysTime.tm_year+1900, tSysTime.tm_mon+1, tSysTime.tm_mday, tSysTime.tm_hour, tSysTime.tm_min, tSysTime.tm_sec, szMsec); } /********************************************************************** * 功能描述: 获取配置文件完整路径(包含文件名) * 输入参数: pszConfigFileName-配置文件名 pszWholePath-配置文件完整路径(包含文件名) * 输出参数: 无 * 返 回 值: 无 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------ * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void GetCompletePath(unsigned char *pszConfigFileName, unsigned char *pszWholePath) { unsigned char *pszHomePath = NULL; unsigned char szWholePath[256] = {0}; // 先对输入参数进行异常判断 if (pszConfigFileName == NULL || pszWholePath == NULL) { return; } pszHomePath = (unsigned char *)getenv("HOME"); // 获取当前用户所在的路径 if (pszHomePath == NULL) { return; } // 拼装配置文件路径 snprintf(szWholePath, sizeof(szWholePath)-1, "%s/test/WriteLog/%s", pszHomePath, pszConfigFileName); strncpy(pszWholePath, szWholePath, strlen(szWholePath)); } /********************************************************************** * 功能描述: 获取日志配置项的值 * 输入参数: 无 * 输出参数: 无 * 返 回 值: 无 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------- * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void GetConfigValue() { unsigned char szLogDir[256] = {0}; // 日志等级 g_iLogLevel = GetConfigFileIntValue("LOG", "LogLevel", 5, "Config.ini"); // 日志位置 g_iLogPosition = GetConfigFileIntValue("LOG", "LogPosition", 0, "Config.ini"); // 日志文件存放目录 GetConfigFileStringValue("LOG", "LogDir", "", szLogDir, sizeof(szLogDir), "Config.ini"); snprintf(g_szLogFile, sizeof(g_szLogFile)-1, "%s/WriteLog.log", szLogDir); } /********************************************************************** * 功能描述: 获取具体的字符串值 * 输入参数: fp-配置文件指针 pszSectionName-段名, 如: GENERAL pszKeyName-配置项名, 如: EmployeeName iOutputLen-输出缓存长度 * 输出参数: pszOutput-输出缓存 * 返 回 值: 无 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------ * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void GetStringContentValue(FILE *fp, unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned char *pszOutput, unsigned int iOutputLen) { unsigned char szSectionName[100] = {0}; unsigned char szKeyName[100] = {0}; unsigned char szContentLine[256] = {0}; unsigned char szContentLineBak[256] = {0}; unsigned int iContentLineLen = 0; unsigned int iPositionFlag = 0; // 先对输入参数进行异常判断 if (fp == NULL || pszSectionName == NULL || pszKeyName == NULL || pszOutput == NULL) { printf("GetStringContentValue: input parameter(s) is NULL!\n"); return; } sprintf(szSectionName, "[%s]", pszSectionName); strcpy(szKeyName, pszKeyName); while (feof(fp) == 0) { memset(szContentLine, 0x00, sizeof(szContentLine)); fgets(szContentLine, sizeof(szContentLine), fp); // 获取段名 // 判断是否是注释行(以;开头的行就是注释行)或以其他特殊字符开头的行 if (szContentLine[0] == ';' || szContentLine[0] == '\r' || szContentLine[0] == '\n' || szContentLine[0] == '\0') { continue; } // 匹配段名 if (strncasecmp(szSectionName, szContentLine, strlen(szSectionName)) == 0) { while (feof(fp) == 0) { memset(szContentLine, 0x00, sizeof(szContentLine)); memset(szContentLineBak, 0x00, sizeof(szContentLineBak)); fgets(szContentLine, sizeof(szContentLine), fp); // 获取字段值 // 判断是否是注释行(以;开头的行就是注释行) if (szContentLine[0] == ';') { continue; } memcpy(szContentLineBak, szContentLine, strlen(szContentLine)); // 匹配配置项名 if (strncasecmp(szKeyName, szContentLineBak, strlen(szKeyName)) == 0) { iContentLineLen = strlen(szContentLine); for (iPositionFlag = strlen(szKeyName); iPositionFlag <= iContentLineLen; iPositionFlag ++) { if (szContentLine[iPositionFlag] == ' ') { continue; } if (szContentLine[iPositionFlag] == '=') { break; } iPositionFlag = iContentLineLen + 1; break; } iPositionFlag = iPositionFlag + 1; // 跳过=的位置 if (iPositionFlag > iContentLineLen) { continue; } memset(szContentLine, 0x00, sizeof(szContentLine)); strcpy(szContentLine, szContentLineBak + iPositionFlag); // 去掉内容中的无关字符 for (iPositionFlag = 0; iPositionFlag < strlen(szContentLine); iPositionFlag ++) { if (szContentLine[iPositionFlag] == '\r' || szContentLine[iPositionFlag] == '\n' || szContentLine[iPositionFlag] == '\0') { szContentLine[iPositionFlag] = '\0'; break; } } // 将配置项内容拷贝到输出缓存中 strncpy(pszOutput, szContentLine, iOutputLen-1); break; } else if (szContentLine[0] == '[') { break; } } break; } } } /********************************************************************** * 功能描述: 从配置文件中获取字符串 * 输入参数: pszSectionName-段名, 如: GENERAL pszKeyName-配置项名, 如: EmployeeName pDefaultVal-默认值 iOutputLen-输出缓存长度 pszConfigFileName-配置文件名 * 输出参数: pszOutput-输出缓存 * 返 回 值: 无 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------ * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ void GetConfigFileStringValue(unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned char *pDefaultVal, unsigned char *pszOutput, unsigned int iOutputLen, unsigned char *pszConfigFileName) { FILE *fp = NULL; unsigned char szWholePath[256] = {0}; // 先对输入参数进行异常判断 if (pszSectionName == NULL || pszKeyName == NULL || pszOutput == NULL || pszConfigFileName == NULL) { printf("GetConfigFileStringValue: input parameter(s) is NULL!\n"); return; } // 获取默认值 if (pDefaultVal == NULL) { strcpy(pszOutput, ""); } else { strcpy(pszOutput, pDefaultVal); } // 打开配置文件 GetCompletePath(pszConfigFileName, szWholePath); fp = fopen(szWholePath, "r"); if (fp == NULL) { printf("GetConfigFileStringValue: open %s failed!\n", szWholePath); return; } // 调用函数用于获取具体配置项的值 GetStringContentValue(fp, pszSectionName, pszKeyName, pszOutput, iOutputLen); // 关闭文件 fclose(fp); fp = NULL; } /********************************************************************** * 功能描述: 从配置文件中获取整型变量 * 输入参数: pszSectionName-段名, 如: GENERAL pszKeyName-配置项名, 如: EmployeeName iDefaultVal-默认值 pszConfigFileName-配置文件名 * 输出参数: 无 * 返 回 值: iGetValue-获取到的整数值, -1-获取失败 * 其它说明: 无 * 修改日期 版本号 修改人 修改内容 * ------------------------------------------------------------------ * 20190905 V1.0 Zhou Zhaoxiong 创建 ********************************************************************/ int GetConfigFileIntValue(unsigned char *pszSectionName, unsigned char *pszKeyName, unsigned int iDefaultVal, unsigned char *pszConfigFileName) { unsigned char szGetValue[512] = {0}; int iGetValue = 0; // 先对输入参数进行异常判断 if (pszSectionName == NULL || pszKeyName == NULL || pszConfigFileName == NULL) { printf("GetConfigFileIntValue: input parameter(s) is NULL!\n"); return -1; } GetConfigFileStringValue(pszSectionName, pszKeyName, NULL, szGetValue, sizeof(szGetValue)-1, pszConfigFileName); // 先将获取的值存放在字符型缓存中 if (szGetValue[0] == '\0' || szGetValue[0] == ';') // 如果是结束符或分号, 则使用默认值 { iGetValue = iDefaultVal; } else { iGetValue = atoi(szGetValue); } return iGetValue; }
C++
UTF-8
3,005
3.28125
3
[]
no_license
/* Получавате като вход число N. Следват N числа които трябва да ги прочетете и съхраните в собственоръчно написан Свързан Списък. Следва число P. Следват P числа на нов ред. ( тях може да съхраните по начин който е най-удобен за вас ). От вас се изисква да върнете броя на различните двойки елементи ( (1,2) и (2,1) е една и съща двойка ) които се срещат в масива P и са съседи във вашият свръзан списък. Input Format Число N ( размер на вашият свързан списък ) Следват N числа. Число P. Следват P числа. Constraints N <= 1 000 000 Всеки един елемент е между 1 и 1234 ( включително ). P <= 3000 ( дължината на P ) Всяко едно число в масива P между 1 и 1 000 000 000. Output Format Число X: броят на двойките които удовлетворяват условието. Пример: 4 1 2 3 4 5 6 1 2 3 4 Изход: 3 Пояснение: 1->2->3->4 ( 1->2, 2->3, 3->4 като числата 1,2,3,4 се срещат в P ) */ #include <iostream> #include <vector> struct Node { int data; Node* next; }; Node* head = nullptr; void insert(int number) { Node* node = new Node; node->data = number; node->next = head; head = node; } int main() { std::ios_base::sync_with_stdio(false); int N = 0; std::cin >> N; for (int i = 0; i < N; i++) { int element = 0; std::cin >> element; insert(element); } int arr[1235] = { 0 }; int P = 0; std::cin >> P; for (int i = 0; i < P; i++) { int number = 0; std::cin >> number; if (number > 1234) { continue; } arr[number]++; } Node* current = head; std::vector<Node*> pairs; while (current && current->next != nullptr) { int first = current->data; int second = current->next->data; if (first > second) { int temp = second; second = first; first = temp; } bool pairAlreadyExist = false; for (int i = 0; i < pairs.size(); i++) { if ((pairs[i]->data == first && pairs[i]->next->data == second) || (pairs[i]->data == second && pairs[i]->next->data == first)) { pairAlreadyExist = true; break; } } if (!pairAlreadyExist && (arr[first] != 0 && arr[second] != 0)) { pairs.push_back(current); } current = current->next; } std::cout << pairs.size() << "\n"; return 0; }
C++
UTF-8
5,889
3.046875
3
[]
no_license
/* HJ2509 Hyun Soo Jeon */ #include <iostream> #include <vector> #include <iterator> #include <type_traits> #include <ctime> #include <algorithm> //#include <concepts> template<typename T> using Value_type = typename T::value_type; template<typename T> using Iterator_of = typename T::iterator; template <typename T, typename U> concept SameHelper = std::is_same_v<T,U>; template <typename T, typename U> concept Same_type = SameHelper<T,U> && SameHelper<U,T>; template <typename T> concept Less_than_comparable = requires (T a, T b) { { a < b } -> bool; { b < a } -> bool; }; template<typename T, typename U> concept Equality_comparable = requires(T a, U b) { { a == b } -> bool; { a != b } -> bool; { b == a } -> bool; { b != a } -> bool; { a == a } -> bool; { b == b } -> bool; }; template <typename T> concept Input_iterator = Equality_comparable<Value_type<T>,Value_type<T>> && std::is_copy_constructible<T>::value && std::is_copy_assignable<T>::value && std::is_destructible<T>::value && std::is_swappable<T>::value && requires (T t) { typename std::iterator_traits<T>::value_type; typename std::iterator_traits<T>::difference_type; typename std::iterator_traits<T>::pointer; typename std::iterator_traits<T>::reference; typename std::iterator_traits<T>::iterator_category; { ++t } -> T&; { *t } -> Value_type<T>; { *t++ } -> Value_type<T>; }; template <typename T> concept Random_access_iterator = requires(T t, T u) { { --t } -> T&; { ++t } -> T&; { t++ } -> T; { t-- } -> T; { *t-- } -> std::iterator_traits<T>::reference; { *t++ } -> std::iterator_traits<T>::reference; { t > u } -> bool; { t < u } -> bool; { t >= u } -> bool; { t <= u } -> bool; typename std::iterator_traits<T>::value_type; typename std::iterator_traits<T>::difference_type; typename std::iterator_traits<T>::reference; requires Input_iterator<T>; requires std::is_default_constructible<T>::value; }; template <typename T> concept Movable = std::is_object<T>::value && std::is_move_constructible<T>::value && std::is_assignable<T&, T>::value && std::is_swappable<T>::value; template <typename T> concept Boolean = Movable<std::remove_cvref_t<T>> && requires(const std::remove_reference_t<T>& b1, const std::remove_reference_t<T>& b2, const bool a) { { b1 } -> std::is_convertible<const std::remove_reference_t<T>&, bool>::value; { !b1 } -> std::is_convertible<const std::remove_reference_t<T>&, bool>::value; { b1 && b2 } -> Same_type<bool>; { b1 && a } -> Same_type<bool>; { b1 || b2 } -> Same_type<bool>; { b1 || a } -> Same_type<bool>; { a || b2 } -> Same_type<bool>; { b1 == a } -> bool; { a == b2 } -> bool; { b1 != b2 } -> bool; { b1 != a } -> bool; { a != b2 } -> bool; }; template <typename T> concept Sequence = requires(T t) { typename Value_type<T>; typename Iterator_of<T>; { begin(t) }-> Iterator_of<T>; { end(t) }-> Iterator_of<T>; requires Input_iterator<Iterator_of<T>>; requires Same_type<Value_type<T>, Value_type<Iterator_of<T>>>; }; template <typename T> concept Sortable = Sequence<T> && Less_than_comparable<Value_type<T>> && Random_access_iterator<Iterator_of<T>>; template <typename T, class... Args> concept bool Predicate = std::is_invocable<T(), Args...>::value;// && Boolean<std::invoke_result<T, Args...>::type>; template <typename S, typename T> requires Sequence<S> && Equality_comparable<Value_type<S>,T> Iterator_of<S> myfind(S& seq, const T& value) { return std::find(seq.begin(),seq.end(),value); } template <typename S, typename P> requires Sequence<S> && Predicate<P> Iterator_of<S> myfindIf(S& seq, P predicate) { return std::find_if(seq.begin(),seq.end(),predicate); } template <Sortable S, typename P = std::less<>> requires Predicate<P> void mysort(S& s, Predicate pred = P()) { std::sort(s.begin(),s.end(),pred); } template <Sequence Seq> void foo(Seq& s) { std::cout << "Foo!\n"; return; } int randGene(const int low, const int high) { return rand() % (high - low + 1) + low; } void display(const std::vector<int>& vect) { std::for_each(vect.begin(),vect.end(),[](const int x){std::cout << x << ' ';}); std::cout << '\n'; } // __referencebale // _Equality_comparable what are we checking for?_ //concept bool //range int main() { srand((unsigned)time(NULL)); const int SIZE = 100; auto comp = [](const int x, const int y){return x < y;}; auto isOdd = [](const int x){return x % 2 != 0;}; auto isEven = [](const int x){return x % 2 == 0;}; /* Populate the vect */ std::vector<int> vect; for(int i = 0; i < SIZE; ++i) vect.push_back(randGene(0,SIZE * 2)); std::cout << "Before sorting\n"; display(vect); /* mysort wraps std::sort */ mysort(vect,comp); std::cout << "\nAfter sorting\n"; display(vect); int target = randGene(0,SIZE * 2); /* myfind wraps std::find */ std::cout << "\nSearching for " << target << '\n'; auto it = myfind(vect,target); if(it != vect.end()) std::cout << *it << " found\n"; else std::cout << target << " cannot be found\n"; /* myfindIf wrap std::find_if */ std::cout << "\nSearching for the first odd number\n"; it = myfindIf(vect,isOdd); // odd number if(it != vect.end()) std::cout << *it << " is the first odd number\n"; else std::cout << "No odd number can be found\n"; std::cout << "\nSearching for the first even number\n"; it = myfindIf(vect,isEven); // even number if(it != vect.end()) std::cout << *it << " is the first even number\n"; else std::cout << "No even number can be found\n"; return 0; }
TypeScript
UTF-8
1,568
2.53125
3
[]
no_license
import { Component, ComponentFactoryResolver, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators, FormArray, FormControl } from '@angular/forms'; @Component({ selector: 'app-dynamics', templateUrl: './dynamics.component.html', styles: [ ] }) export class DynamicsComponent implements OnInit { myForm: FormGroup = this.formBuilder.group({ name: ['', [ Validators.required, Validators.minLength(3) ] ], favorites: this.formBuilder.array( [ [ 'Metal Gear', Validators.required ], [ 'Death Stranding', Validators.required ] ], Validators.required ) }); newFavorite: FormControl = this.formBuilder.control('', Validators.required); constructor( private formBuilder: FormBuilder) { } get favoritesArray() { return this.myForm.get('favorites') as FormArray; } ngOnInit(): void { } validField( field: string ) { return this.myForm.controls[field].errors && this.myForm.controls[field].touched; } save() { if( this.myForm.invalid ) { this.myForm.markAllAsTouched(); return; } console.log( this.myForm.value ); } addFavorite() { if( this.newFavorite.invalid ) { return; } // this.favoritesArray.push( new FormControl( this.newFavorite.value, Validators.required )); this.favoritesArray.push(this.formBuilder.control(this.newFavorite.value, [ Validators.required ])); this.newFavorite.reset(); } deleteFavorite( index: number ) { this.favoritesArray.removeAt(index); console.log(this.favoritesArray); } }
JavaScript
UTF-8
1,008
3.53125
4
[]
no_license
// Day 2 // Part 1: Car var paintColor = 'black'; console.log('paintColor:', paintColor); var make = 'Nissan'; console.log('make:', make); var model = 'Maxima'; console.log('model:', model); var year = 2021; console.log('year:', year); var isManualTransmission = false; console.log('isManualTransmission:', isManualTransmission); var seats = 5; console.log('seats:', seats); var mileage = 2000; console.log('mileage:', mileage); // Day 2 // Part 2: Passport/License const dateofBirth = 1985; const firstName = 'Alexander'; const lastName = 'King'; const streetAddress = '123 Washington Street' const city = 'Boston'; const state = 'Massachusetts'; const height = 75; const isOrganDonor = true; const licenseInfo = `My name is ${firstName} ${lastName} and I was born in ${dateofBirth} and I currently live at ${streetAddress} in ${city}, ${state} and I am ${Math.floor(height / 12)} feet ${height % 12} inches tall and it is ${isOrganDonor} that I am an organ donor.`; console.log(licenseInfo);
Python
UTF-8
1,090
2.5625
3
[ "Apache-2.0" ]
permissive
import json from pathlib import Path from typing import Optional from slack_notifications.user_api.message_type import SlackInstance class RunConfig: def __init__(self, path: Path): self._path = path self._data = {} def _reload(self): if not self._path.exists(): self._path.parent.mkdir(exist_ok=True, parents=True) self._rewrite() self._data = json.load(self._path.open("r")) def _rewrite(self): json.dump(self._data, self._path.open("w"), indent=4) @property def slack(self) -> SlackInstance: self._reload() return SlackInstance(self._data['slack']) if "slack" in self._data else None @slack.setter def slack(self, slack: SlackInstance): self._data['slack'] = slack.name self._rewrite() @property def secret(self) -> Optional[str]: self._reload() return self._data.get('secret') if "secret" in self._data else None @secret.setter def secret(self, secret: str): self._data['secret'] = secret self._rewrite()
C
UTF-8
2,498
4.0625
4
[]
no_license
#include "node.h" #include <stdio.h> #include <stdlib.h> void insert(Node **head, int data) { Node *temp = *head; if (*head == NULL) { Node *new = malloc(sizeof(Node)); if (new == NULL) { return; } new->data = data; new->left = NULL; new->right = NULL; *head = new; return; } if (temp->data >= data) { insert(&temp->left, data); } else { insert(&temp->right, data); } } Node* del(Node **head, int data) { Node *temp = *head; if (temp == NULL) { return NULL; } if (temp->data > data) { del(&temp->left, data); } else if(temp->data < data) { del(&temp->right, data); } else if (temp->data == data) { if (temp->left == NULL && temp->right == NULL) { free(temp); *head = NULL; } else if (temp->right == NULL) { Node* curr = NULL; curr = temp->left; temp->data = curr->data; temp->right = curr->right; temp->left = curr->left; free(curr); *head = temp; } else if (temp->left == NULL) { Node* curr = NULL; curr = temp->right; temp->data = curr->data; temp->left = curr->left; temp->right = curr->right; free(curr); *head = temp; } else { /* Find the successor */ Node *curr = temp->right; Node *prev = temp; while(curr->left != NULL) { prev = curr; curr = curr->left; } temp->data = curr->data; if (temp->right == curr) { temp->right = curr->right; free(curr); *head = temp; } else { prev->left = NULL; free(curr); *head = temp; } } } } void inorder(Node **head) { Node *temp = *head; if (temp == NULL) { return; } inorder(&temp->left); printf("%d\t", temp->data); inorder(&temp->right); } void tree_init(Node **head) { insert(head, 17); insert(head, 28); insert(head, 14); insert(head, 38); insert(head, 10); insert(head, 22); insert(head, 4); insert(head, 13); insert(head, 44); insert(head, 30); insert(head, 8); printf("Created tree:\n"); inorder(head); printf("\n"); }
Java
UTF-8
865
2.375
2
[]
no_license
package configuration.securityconfiguration; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { if (httpServletRequest.getRequestURI().equals("/")) { httpServletResponse.sendRedirect("login"); } else{ httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized to see that"); } } }
Java
UHC
680
2.046875
2
[]
no_license
package com.bit.pro.dao; import java.util.Map; import com.bit.pro.vo.JoinVo; public interface JoinDao { // Ǿ DB ̵ ̿ ش JoinVo selectUser(String userid) throws Exception; //Էµ DB int insertUser(JoinVo bean) throws Exception; //̵ ߺüũ int checkId(JoinVo bean) throws Exception; // void updateUser(JoinVo bean) throws Exception; int checkPw(JoinVo bean) throws Exception; int checkPwEdit(Map<String, String> map) throws Exception; int updatePw(Map<String, String> map) throws Exception; }
Java
UTF-8
1,024
2.859375
3
[]
no_license
package javanet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class ReadNetworkFileSock { public static void main(String[] args){ Socket soc=null; try{ soc = new Socket("www.este.ucam.ac.ma", 80); String req = "GET / HTTP/1.1\r\n"; req += "Host: www.este.ucam.ac.ma\r\n"; req += "\r\n"; BufferedOutputStream bos = new BufferedOutputStream(soc.getOutputStream()); bos.write(req.getBytes()); bos.flush(); BufferedInputStream bis = new BufferedInputStream(soc.getInputStream()); StringBuilder sb=new StringBuilder(); int n; while((n = bis.read()) != -1){ sb.append((char) n); } System.out.println(sb); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }