text:
[#]: subject: "How to use journalctl to View and Analyze Systemd Logs [With Examples]"
[#]: via: "https://www.debugpoint.com/systemd-journalctl/"
[#]: author: "Arindam https://www.debugpoint.com/author/admin1/"
[#]: collector: "lkxed"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "

How to use journalctl to View and Analyze Systemd Logs [With Examples]
======

**This guide explains the basics of the journalctl utility of [Systemd][1] and its various commands. You can use these commands for troubleshooting desktop and server logs in Linux. This is how you can use journalctl to view and analyze Systemd Logs with different examples.**

### Introduction

Many say that Systemd is not good, it is heavy on the system and it is a debated topic always. But you can not deny that it provides a well set of utilities to manage, troubleshoot a system. Imagine you end up with a broken system with no GUI. You probably messed up boot and GRUB as well. In those kinds of scenarios or in general – you can boot from a LIVE system, mount your Linux partition and explore the Systemd logs to find out about the problem.

Systemd has three basic components as follows –

- **systemd**: System and service manager for Linux operating systems.
- **systemctl**: Command to introspect and control the state of the systemd system and service manager.
- **systemd-analyze**: Provides system boot-up performance statistics and retrieve other state and tracing information from the system and service manager

Apart from these three, there are additional services that systemd provides such as – journald, logind, networkd, etc. In this guide we will talk about the journald service of systemd.

### journald – systemd journal daemon

By design, systemd provides a centralized way of handing all operating system logs from processes, applications, etc. All these logging events are handled by journald daemon of systemd. The journald daemon collects all logs from everywhere of the Linux operating systems and stores themes as binary data in files.

The advantages of centralized logging of events, system problems as binary data are many. For example, as the system logs are stored as binary and not text – you can translate in many ways such as text, JSON objects for various needs. Also, it is super easy to track down to a single event as the logs are stored sequentially via date/time manipulation of the logs.

Remember the log files that journald collects are in thousands of lines and it gets updated for every event, every boot. So if you have a long time running Linux operating system – the journal logs size should in GBs. As the logs are in thousands, it's better to filter with basic commands to find out more about the system problems.

#### The journald Configuration File

The configuration file of the journald is present in the below path. It contains various flags on how the logging happens. You can take a look at the file and make the changes necessary. But I would recommend not to modify this file unless you know what you are doing.

```
/etc/systemd/journald.conf
```

#### Where journald stores the binary log files

The journald stores the logs in binary format. They are stored inside a directory under this path.

```
/var/log/journal
```

For example, in the below path there is a directory that contains all the system logs to date.

![journalctl log file path][2]

Do not use cat command or use nano or vi to open these files. They would not be displayed properly.

### Use journalctl to View and Analyze Systemd Logs

#### Basic journald command

The basic command to view logs using journal daemon is –

```
journalctl
```

![journalctl][3]

This gives you all the journal entries including errors, warnings, etc from all applications and processes. It shows the list with the oldest log at the top and current logs at the bottom. You need to keep pressing ENTER to scroll through it line by line. You can also use PAGE UP and PAGE DOWN keys to scroll. Press q to exit from this view.

#### How to view journal entries for time zones

By default, the journalctl shows the log time in the current system time zone. However, you can easily provide the timezone in your command to convert the same log to a different time zone. For example, to view the logs in UTC, use the below command.

```
journalctl --utc
```

![journalctl --utc][4]

#### How to view only errors, warnings, etc in journal logs

The logs that a system generates have different priorities. Some logs may be a warning which can be ignored or some may be critical errors. You might want to look at only errors, not warnings. That is also possible using the below command.

To view emergency system messages use:

```
journalctl -p 0
```

![journalctl -p 0][5]

Error codes

```
0: emergency
1: alerts
2: critical
3: errors
4: warning
5: notice
6: info
7: debug
```

When you specify the error code, it shows all messages from that code and above. For example, if you specify the below command, it shows all messages with priority 2, 1 and 0

```
journalctl -p 2
```

#### How to view journal logs for a specific boot

When you are running the journalctl command it shows the information from the current boot that is from the current session which you are running. But it is also possible to view information about past boots as well.

Journal logs keep on updating in every reboot. The journald keeps track of the logs in different boots. To view, the boot-wise logs use the below command.

```
journalctl --list-boots
```

![journalctl list-boots][6]

- The first number shows the unique journald boot track number which you can use in the next command to analyze that specific boot.
- The second number the boot ID which also you can specify in the commands.
- The next two date, time combinations are the duration of the logs stored in the respective file. This is super handy if you want to find out a log or error from a specific date, time.

To view a specific boot number you the first number or the boot ID as below.

```
journalctl -b -45
```

```
journalctl -b 8bab42c7e82440f886a3f041a7c95b98
```

![journalctl -b 45][7]

You can also use `-x` switch which can add an explanation of the systemd error messages in your display. This is a lifesaver in certain situations.

```
journalctl -xb -p 3
```

![journalctl -xb][8]

#### How to view journal logs for a specific time, date duration

The journalctl is powerful enough to provide "english" like argument in the command itself for time and date manipulation.

You can use`--since` switch with a combination of `"yesterday", "today", "tomorrow", or "now".`

Some of the examples of different commands below. You can modify them as per your need. They are self-explanatory. The date, time format in the below commands are `"YYYY-MM-DD HH:MM:SS"`

```
journalctl --since "2020-12-04 06:00:00"
```

```
journalctl --since "2020-12-03" --until "2020-12-05 03:00:00"
```

```
journalctl --since yesterday
```

```
journalctl --since 09:00 --until "1 hour ago"
```

![journalctl --since 09:00 --until][9]

You can combine the above with the error level switches as well.

#### How to see Kernel specific journal logs

The Linux Kernel messages can be extracted from journal logs as well. To view the Kernel messages from the current boot only use the below command.

```
journalctl -k
```

#### How to see journal logs for a service, PID

You can filter out specific logs from a systemd service unit only from the journald logs. For example, to find out the logs from NetworkManager service use the below command.

```
journalctl -u NetworkManager.service
```

![journalctl NetworkManager service][10]

If you do not know the service name, you can use the below command to list the systemd services in your system.

```
systemctl list-units --type=service
```

#### How to view journal logs for a user, group

If you are analyzing server logs this command is helpful where multiple users are logged in. You can first find out about the user id using the below command from the user name. For example, to find out the id of user "`debugpoint`" –

```
id -u debugpoint
```

Then use that ID with `_UID` switch to view the logs generated by the user.

```
journalctl _UID=1000 --since today
```

![journalctl _UID][11]

Similarly use `_GID` switch to find out the same for user groups.

#### How to view journal logs for an executable

You can also find out journald logs of a specific program or executable. For example, if you want to find out the messages of gnome-shell, you can run the below command.

```
journalctl /usr/bin/gnome-shell --since today
```

![journalctl gnome-shell][12]

### Closing notes

I hope this guide helps you to use journalctl to view analyze systemd logs on your Linux desktop or server troubleshooting. The systemd journal management extremely powerful if you know how to use the commands, it makes your life a bit easy during debugging time. All major mainstream Linux distribution uses Systemd these days. Ubuntu, Debian, Fedora, Arch – they all use systemd for their default OS offerings. In case if you are wondering about systemd-free Linux distributions, you might want to check out [MX-Linux][13], Gentoo, Slackware, Void Linux.

--------------------------------------------------------------------------------

via: https://www.debugpoint.com/systemd-journalctl/

作者:[Arindam][a]
选题:[lkxed][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://www.debugpoint.com/author/admin1/
[b]: https://github.com/lkxed
[1]: https://freedesktop.org/wiki/Software/systemd/
[2]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-log-file-path.jpg
[3]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl.jpg
[4]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-utc.jpg
[5]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-p-0.jpg
[6]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-list-boots.jpg
[7]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-b-45.jpg
[8]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-xb.jpg
[9]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-since-0900-until.jpg
[10]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-NetworkManager-service.jpg
[11]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-_UID.jpg
[12]: https://www.debugpoint.com/wp-content/uploads/2020/12/journalctl-gnome-shell.jpg
[13]: https://www.debugpoint.com/tag/mx-linux


text:
package Objects;

import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Build;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;

import com.enrico.biella.gestione_ordinazioni.Camerieri;
import com.enrico.biella.gestione_ordinazioni.InserisciTavolo;
import com.enrico.biella.gestione_ordinazioni.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.concurrent.Callable;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

/**
 * Created by Enrico Biella on 05/01/2017.
 */

public class ConnessioneDB extends AsyncTask<Void, Void, Boolean>
{
    //170380
    //TODO: modificare l'ip! - 192.168.2.96
    private static final String ip = "172.17.2.126";
    //TODO: modificare l'utente: echo %username% - ranch
    private static final String username="enrico";
    //TODO: modificare la password - pluto
    private static final String password="Vivainter1";
    private static final String ENCODING = "windows-1252";
    private static final String ERRORE_FILE_NOT_EXISTS = "file_not_exists";
    public static final int DOWNLOAD_ARCHIVI = 0;
    public static final int DOWNLOAD_TAVOLI = 2;
    public static final int CONTROLLO_TAVOLI = 3;
    public static final int UPLOAD = 1;
    private static final String END_OF_FILE = "END OF FILE";
    private static String ERRORE = "";
    private static final String ERRORE_CONNESSIONE = "connessione";
    Callable<Integer> eseguiActivity;
    private ArrayList<Tavolo> elencoTavoli;
    private Context ctx;
    private ProgressDialog p;
    private SQLiteDatabase mydatabase;
    private File file;
    private CoordinatorLayout cl;
    private int downloadUpload;
    private Tavolo tavolo;
    Callable<Integer> refreshLista;
    Callable<Integer> downloadDB;

    /*
         Constructor
     */
    public ConnessioneDB(SQLiteDatabase mydatabase, CoordinatorLayout cl, Context ctx, Callable<Integer> refreshLista,
                         Callable<Integer> downloadDB, int downloadUpload, ProgressDialog p)
    {
        this.mydatabase=mydatabase;
        this.cl=cl;
        this.ctx=ctx;
        this.p=p;
        this.refreshLista=refreshLista;
        this.downloadDB=downloadDB;
        this.downloadUpload=downloadUpload;
    }
    public ConnessioneDB(ArrayList<Tavolo> elencoTavoli,CoordinatorLayout cl, Context ctx, Callable<Integer> refreshLista,
                         Callable<Integer> downloadDB, int downloadUpload,ProgressDialog p)
    {
        this.p=p;
        this.elencoTavoli=elencoTavoli;
        this.cl=cl;
        this.ctx=ctx;
        this.refreshLista=refreshLista;
        this.downloadDB=downloadDB;
        this.downloadUpload=downloadUpload;
    }
    public ConnessioneDB(Context ctx,Tavolo tavolo, int downloadUpload, Callable<Integer> eseguiActivity,ProgressDialog p)
    {
        this.p=p;
        this.eseguiActivity=eseguiActivity;
        this.ctx=ctx;
        this.tavolo=tavolo;
        this.downloadUpload=downloadUpload;
    }
    public ConnessioneDB(CoordinatorLayout cl, Context ctx,Tavolo tavolo,int downloadUpload,ProgressDialog p){
        this.cl=cl;
        this.p=p;
        this.ctx=ctx;
        this.tavolo=tavolo;
        this.downloadUpload=downloadUpload;
    }

    /*
        Runs on the UI thread before doInBackground
     */
    @Override
    protected void onPreExecute() {
        if (p == null) {
            if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR1){
                this.p=new ProgressDialog(ctx,R.style.AppTheme_MyDialog);
            } else{
                this.p=new ProgressDialog(ctx);
            }
            p.setMessage(ctx.getResources().getString(R.string.download_db));
            p.setIndeterminate(false);
            p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            p.setCancelable(false);
        }
        p.show();
    }

    /*
         This method to perform a computation on a background thread.
     */
    @Override
    protected Boolean doInBackground(Void... voids) {
        switch (downloadUpload){
            case ConnessioneDB.DOWNLOAD_ARCHIVI:
                mydatabase.execSQL("DROP TABLE IF EXISTS camerieri;");
                mydatabase.execSQL("DROP TABLE IF EXISTS prodotti;");
                mydatabase.execSQL("DROP TABLE IF EXISTS aggiunte;");
                mydatabase.execSQL("CREATE TABLE IF NOT EXISTS camerieri(codice mediumint(5) NOT NULL,nome VARCHAR(30));");
                mydatabase.execSQL("CREATE TABLE IF NOT EXISTS prodotti(codice mediumint(5) NOT NULL,descrizione VARCHAR(30), bottone VARCHAR(30));");
                mydatabase.execSQL("CREATE TABLE IF NOT EXISTS aggiunte(descrizione VARCHAR(30) NOT NULL,consenza VARCHAR(2));");
                try {
                    SmbFile file = getFileFromServer();
                    BufferedReader br = new BufferedReader(new InputStreamReader(new SmbFileInputStream(file), ENCODING));
                    String line;
                    while ((line = br.readLine()) != null) {
                        mydatabase.execSQL(line);
                    }
                    br.close();
                    return true;
                } catch (IOException e) {
                    Log.d("TAG",e.getMessage());
                    ERRORE = ERRORE_CONNESSIONE;
                    return false;
                }

            case ConnessioneDB.UPLOAD:
                try {
                    SmbFile file=CreateComanda();
                    BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new SmbFileOutputStream(file),ENCODING));
                    ArrayList<String> lista=tavolo.toComanda();
                    for (String s:lista) {
                        bw.write(s);
                        bw.write("\r\n");
                    }
                    bw.close();
                    return true;
                } catch (Exception e){return false;}
            case ConnessioneDB.DOWNLOAD_TAVOLI:
                try {
                    SmbFile file = getTavoliFromServer();
                    SmbFile[] files=file.listFiles();
                    String line;
                    for(SmbFile f:files){
                        BufferedReader br = new BufferedReader(new InputStreamReader(new SmbFileInputStream(f), ENCODING));
                        String[] h=f.getName().toUpperCase().split(" ");
                        Tavolo t=new Tavolo(h[2].replace(".DAT",""));
                        t.setCameriere(new Cameriere(h[1]));
                        int i=0;
                        while (((line = br.readLine()) != null)&&!line.equals(END_OF_FILE)) {
                            if(i==0){
                                String[] s=line.split(";");
                                t.setServizi(Integer.valueOf(s[1]));
                                //TODO: riparti da qui
                            }else{
                                String[] s=line.split(";");
                                Prodotto p=new Prodotto(s[0],s[2]);
                                p.setQuantità(Integer.valueOf(s[1]));
                                /*int k=6;
                                while(s.length>5&&k<s.length){
                                    String[] o=s[k].split(" ");
                                    p.addAggiunta(new Aggiunta(o[1],o[0]));
                                    k++;
                                }*/
                                t.inserisciProdotto(p);
                            }
                            i++;
                        }
                        elencoTavoli.add(t);
                        br.close();
                    }
                    return true;

                } catch (Exception e) {
                    Log.d("TAG",e.getMessage());
                    ERRORE = ERRORE_CONNESSIONE;
                    return false;
                }
            case ConnessioneDB.CONTROLLO_TAVOLI:
                try {
                    SmbFile file = getTavoliFromServer();
                    SmbFile[] files=file.listFiles();
                    ArrayList<String>nomiTavolo=new ArrayList<>();
                    String line;
                    for(SmbFile f:files){
                        BufferedReader br = new BufferedReader(new InputStreamReader(new SmbFileInputStream(f), ENCODING));
                        String[] h=f.getName().toUpperCase().split(" ");
                        nomiTavolo.add(h[2].replace(".DAT",""));
                        br.close();

                    }
                    if(nomiTavolo.contains(tavolo.getNomeTavolo())){// il nome del tavolo non esiste

                        int p=nomiTavolo.indexOf(tavolo.getNomeTavolo());
                        SmbFile f=files[p];
                        BufferedReader br = new BufferedReader(new InputStreamReader(new SmbFileInputStream(f), ENCODING));
                        String[] h=f.getName().toUpperCase().split(" ");
                        Tavolo t=new Tavolo(h[2].replace(".DAT",""));
                        t.setCameriere(new Cameriere(h[1]));
                        int i=0;
                        while (((line = br.readLine()) != null)&&!line.equals(END_OF_FILE)) {
                            if(i==0){
                                String[] s=line.split(";");
                                t.setServizi(Integer.valueOf(s[1]));
                            }else{
                                /*String[] s=line.split(";");
                                Prodotto pr=new Prodotto(s[0],s[5]);
                                pr.setQuantità(Integer.valueOf(s[1]));
                                int k=6;
                                while(s.length>5 && k<s.length){
                                    String[] o=s[k].split(" ");
                                    pr.addAggiunta(new Aggiunta(o[1],o[0]));
                                    k++;
                                }*/
                                String[] s=line.split(";");
                                Prodotto pr=new Prodotto(s[0],s[2]);
                                pr.setQuantità(Integer.valueOf(s[1]));
                                int k=6;
                                while(s.length>5&&k<s.length){
                                    String[] o=s[k].split(" ");
                                    pr.addAggiunta(new Aggiunta(o[1],o[0]));
                                    k++;
                                }
                                t.inserisciProdotto(pr);
                            }
                            i++;
                        }
                        tavolo=t;
                        br.close();
                        return true;
                    }
                    return false;

                } catch (Exception e) {
                    Log.d("TAG",e.getMessage());
                    ERRORE = ERRORE_CONNESSIONE;
                    return false;
                }
            default:
                return false;
        }
    }

    /*
        Runs on the UI thread after doInBackground
     */
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (p != null && p.isShowing()) {
            p.dismiss();
        }
        switch (downloadUpload){
            case ConnessioneDB.DOWNLOAD_ARCHIVI:
                if(result)
                {
                    Camerieri.AGGIORNA=false;
                    try {
                        refreshLista.call();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // Do something awesome here
                    Snackbar.make(cl,ctx.getResources().getText(R.string.elementi_inseriti),Snackbar.LENGTH_LONG).show();
                }
                else
                {
                    switch (ERRORE){
                        case ERRORE_CONNESSIONE:
                            Snackbar.make(cl,ctx.getResources().getText(R.string.errore_connesione),Snackbar.LENGTH_LONG)
                                    .setAction(ctx.getResources().getText(R.string.refresh), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            try {
                                                downloadDB.call();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).show();
                            break;
                        case ERRORE_FILE_NOT_EXISTS:
                            Snackbar.make(cl,ctx.getResources().getText(R.string.file_not_exists),Snackbar.LENGTH_LONG)
                                    .setAction(ctx.getResources().getText(R.string.refresh), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            try {
                                                downloadDB.call();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).show();
                            break;
                        default:
                            Snackbar.make(cl,ctx.getResources().getText(R.string.elementi_non_inseriti),Snackbar.LENGTH_LONG)
                                    .setAction(ctx.getResources().getText(R.string.refresh), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            try {
                                                downloadDB.call();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).show();
                    }
                }
                break;
            case ConnessioneDB.DOWNLOAD_TAVOLI:
                if(result)
                {
                    try {
                        refreshLista.call();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // Do something awesome here
                    Snackbar.make(cl,ctx.getResources().getText(R.string.elementi_inseriti),Snackbar.LENGTH_LONG).show();
                }else{
                    Snackbar.make(cl,ctx.getResources().getText(R.string.elementi_non_inseriti),Snackbar.LENGTH_LONG)
                            .setAction(ctx.getResources().getText(R.string.refresh), new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    try {
                                        downloadDB.call();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).show();
                }
                break;
            case ConnessioneDB.UPLOAD:
                if(result){
                    Snackbar.make(cl,ctx.getResources().getText(R.string.comanda_inviata),Snackbar.LENGTH_LONG).show();
                }else{
                    Snackbar.make(cl,ctx.getResources().getText(R.string.comanda_non_inviata),Snackbar.LENGTH_LONG).show();
                }
                break;
            case ConnessioneDB.CONTROLLO_TAVOLI:
                if(result) {
                    try {
                        tavolo.setControlloComanda(true);
                        tavolo.bloccaTavolo();
                        InserisciTavolo.tavolo=tavolo;
                        eseguiActivity.call();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // Do something awesome here
                }else{
                    try {
                        eseguiActivity.call();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    private SmbFile getFileFromServer() throws MalformedURLException {
        String user = username + ":" + password;
        //TODO: modificare il PATH
        String url = "smb://"+ip+"/Ranch/archivi.dat";
        SmbFile file;
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
        file = new SmbFile(url, auth);
        return file;
    }

    private SmbFile CreateComanda() throws MalformedURLException {
        String user = username + ":" + password;
        //TODO: modificare il PATH
        String url = "smb://"+ip+"/Ranch/"+"COM"+tavolo.getNomeTavolo()+"24"+".txt";
        SmbFile file;
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
        file = new SmbFile(url, auth);
        return file;
    }

    private SmbFile getTavoliFromServer() throws MalformedURLException {
        String user = username + ":" + password;
        //TODO: modificare il PATH
        String url = "smb://"+ip+"/Ranch/SYNCHRO/";
        SmbFile file;
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
        file = new SmbFile(url, auth);
        return file;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*************************************************************************/
/*  material_editor_plugin.cpp                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

// FIXME: Disabled as (according to reduz) users were complaining that it gets in the way
// Waiting for PropertyEditor rewrite (planned for 3.1) to be refactored.

#include "material_editor_plugin.h"

#if 0

#include "scene/main/viewport.h"

void MaterialEditor::_gui_input(InputEvent p_event) {

}

void MaterialEditor::_notification(int p_what) {

	if (p_what==NOTIFICATION_FIXED_PROCESS) {

	}

	if (p_what==NOTIFICATION_READY) {

		//get_scene()->connect("node_removed",this,"_node_removed");

		if (first_enter) {
			//it's in propertyeditor so.. could be moved around

			light_1_switch->set_normal_texture(get_icon("MaterialPreviewLight1","EditorIcons"));
			light_1_switch->set_pressed_texture(get_icon("MaterialPreviewLight1Off","EditorIcons"));
			light_2_switch->set_normal_texture(get_icon("MaterialPreviewLight2","EditorIcons"));
			light_2_switch->set_pressed_texture(get_icon("MaterialPreviewLight2Off","EditorIcons"));

			sphere_switch->set_normal_texture(get_icon("MaterialPreviewSphereOff","EditorIcons"));
			sphere_switch->set_pressed_texture(get_icon("MaterialPreviewSphere","EditorIcons"));
			box_switch->set_normal_texture(get_icon("MaterialPreviewCubeOff","EditorIcons"));
			box_switch->set_pressed_texture(get_icon("MaterialPreviewCube","EditorIcons"));

			first_enter=false;
		}

	}

	if (p_what==NOTIFICATION_DRAW) {

		Ref<Texture> checkerboard = get_icon("Checkerboard","EditorIcons");
		Size2 size = get_size();

		draw_texture_rect(checkerboard,Rect2(Point2(),size),true);

	}
}

void MaterialEditor::edit(Ref<Material> p_material) {

	material=p_material;

	if (!material.is_null()) {
		sphere_mesh->surface_set_material(0,material);
		box_mesh->surface_set_material(0,material);
	} else {

		hide();
	}

}

void MaterialEditor::_button_pressed(Node* p_button) {

	if (p_button==light_1_switch) {
		light1->set_enabled(!light_1_switch->is_pressed());
	}

	if (p_button==light_2_switch) {
		light2->set_enabled(!light_2_switch->is_pressed());
	}

	if (p_button==box_switch) {
		box_instance->show();
		sphere_instance->hide();
		box_switch->set_pressed(true);
		sphere_switch->set_pressed(false);
	}

	if (p_button==sphere_switch) {
		box_instance->hide();
		sphere_instance->show();
		box_switch->set_pressed(false);
		sphere_switch->set_pressed(true);
	}

}

void MaterialEditor::_bind_methods() {

	ClassDB::bind_method(D_METHOD("_gui_input"),&MaterialEditor::_gui_input);
	ClassDB::bind_method(D_METHOD("_button_pressed"),&MaterialEditor::_button_pressed);

}

MaterialEditor::MaterialEditor() {

	viewport = memnew( Viewport );
	Ref<World> world;
	world.instance();
	viewport->set_world(world); //use own world
	add_child(viewport);
	viewport->set_disable_input(true);

	camera = memnew( Camera );
	camera->set_transform(Transform(Matrix3(),Vector3(0,0,3)));
	camera->set_perspective(45,0.1,10);
	viewport->add_child(camera);

	light1 = memnew( DirectionalLight );
	light1->set_transform(Transform().looking_at(Vector3(-1,-1,-1),Vector3(0,1,0)));
	viewport->add_child(light1);

	light2 = memnew( DirectionalLight );
	light2->set_transform(Transform().looking_at(Vector3(0,1,0),Vector3(0,0,1)));
	light2->set_color(Light::COLOR_DIFFUSE,Color(0.7,0.7,0.7));
	light2->set_color(Light::COLOR_SPECULAR,Color(0.7,0.7,0.7));
	viewport->add_child(light2);

	sphere_instance = memnew( MeshInstance );
	viewport->add_child(sphere_instance);

	box_instance = memnew( MeshInstance );
	viewport->add_child(box_instance);

	Transform box_xform;
	box_xform.basis.rotate(Vector3(1,0,0),Math::deg2rad(25));
	box_xform.basis = box_xform.basis * Matrix3().rotated(Vector3(0,1,0),Math::deg2rad(25));
	box_xform.basis.scale(Vector3(0.8,0.8,0.8));
	box_instance->set_transform(box_xform);

	{

		sphere_mesh.instance();

		int lats=32;
		int lons=32;
		float radius=1.0;

		PoolVector<Vector3> vertices;
		PoolVector<Vector3> normals;
		PoolVector<Vector2> uvs;
		PoolVector<float> tangents;
		Matrix3 tt = Matrix3(Vector3(0,1,0),Math_PI*0.5);

		for(int i = 1; i <= lats; i++) {
			double lat0 = Math_PI * (-0.5 + (double) (i - 1) / lats);
			double z0  = Math::sin(lat0);
			double zr0 =  Math::cos(lat0);

			double lat1 = Math_PI * (-0.5 + (double) i / lats);
			double z1 = Math::sin(lat1);
			double zr1 = Math::cos(lat1);

			for(int j = lons; j >= 1; j--) {

				double lng0 = 2 * Math_PI * (double) (j - 1) / lons;
				double x0 = Math::cos(lng0);
				double y0 = Math::sin(lng0);

				double lng1 = 2 * Math_PI * (double) (j) / lons;
				double x1 = Math::cos(lng1);
				double y1 = Math::sin(lng1);

				Vector3 v[4]={
					Vector3(x1 * zr0, z0, y1 *zr0),
					Vector3(x1 * zr1, z1, y1 *zr1),
					Vector3(x0 * zr1, z1, y0 *zr1),
					Vector3(x0 * zr0, z0, y0 *zr0)
				};

#define ADD_POINT(m_idx)                                                                       \
	normals.push_back(v[m_idx]);                                                               \
	vertices.push_back(v[m_idx] * radius);                                                     \
	{                                                                                \
		Vector2 uv(Math::atan2(v[m_idx].x, v[m_idx].z), Math::atan2(-v[m_idx].y, v[m_idx].z)); \
		uv /= Math_PI;                                                                         \
		uv *= 4.0;                                                                             \
		uv = uv * 0.5 + Vector2(0.5, 0.5);                                                     \
		uvs.push_back(uv);                                                                     \
	}                                                                                \
	{                                                                                \
		Vector3 t = tt.xform(v[m_idx]);                                                        \
		tangents.push_back(t.x);                                                               \
		tangents.push_back(t.y);                                                               \
		tangents.push_back(t.z);                                                               \
		tangents.push_back(1.0);                                                               \
	}

				ADD_POINT(0);
				ADD_POINT(1);
				ADD_POINT(2);

				ADD_POINT(2);
				ADD_POINT(3);
				ADD_POINT(0);
			}
		}

		Array arr;
		arr.resize(VS::ARRAY_MAX);
		arr[VS::ARRAY_VERTEX]=vertices;
		arr[VS::ARRAY_NORMAL]=normals;
		arr[VS::ARRAY_TANGENT]=tangents;
		arr[VS::ARRAY_TEX_UV]=uvs;

		sphere_mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES,arr);

		sphere_instance->set_mesh(sphere_mesh);

	}
	{

		box_mesh.instance();

		PoolVector<Vector3> vertices;
		PoolVector<Vector3> normals;
		PoolVector<float> tangents;
		PoolVector<Vector3> uvs;

		int vtx_idx=0;
#define ADD_VTX(m_idx)                                                             \
	;                                                                              \
	vertices.push_back(face_points[m_idx]);                                        \
	normals.push_back(normal_points[m_idx]);                                       \
	tangents.push_back(normal_points[m_idx][1]);                                   \
	tangents.push_back(normal_points[m_idx][2]);                                   \
	tangents.push_back(normal_points[m_idx][0]);                                   \
	tangents.push_back(1.0);                                                       \
	uvs.push_back(Vector3(uv_points[m_idx * 2 + 0], uv_points[m_idx * 2 + 1], 0)); \
	vtx_idx++;\

		for (int i=0;i<6;i++) {

			Vector3 face_points[4];
			Vector3 normal_points[4];
			float uv_points[8]={0,0,0,1,1,1,1,0};

			for (int j=0;j<4;j++) {

				float v[3];
				v[0]=1.0;
				v[1]=1-2*((j>>1)&1);
				v[2]=v[1]*(1-2*(j&1));

				for (int k=0;k<3;k++) {

					if (i<3)
						face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1);
					else
						face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1);
				}
				normal_points[j]=Vector3();
				normal_points[j][i%3]=(i>=3?-1:1);
			}

		//tri 1
			ADD_VTX(0);
			ADD_VTX(1);
			ADD_VTX(2);
		//tri 2
			ADD_VTX(2);
			ADD_VTX(3);
			ADD_VTX(0);

		}

		Array d;
		d.resize(VS::ARRAY_MAX);
		d[VisualServer::ARRAY_NORMAL]= normals ;
		d[VisualServer::ARRAY_TANGENT]= tangents ;
		d[VisualServer::ARRAY_TEX_UV]= uvs ;
		d[VisualServer::ARRAY_VERTEX]= vertices ;

		PoolVector<int> indices;
		indices.resize(vertices.size());
		for(int i=0;i<vertices.size();i++)
			indices.set(i,i);
		d[VisualServer::ARRAY_INDEX]=indices;

		box_mesh->add_surface(Mesh::PRIMITIVE_TRIANGLES,d);
		box_instance->set_mesh(box_mesh);
		box_instance->hide();

	}

	set_custom_minimum_size(Size2(1,150)*EDSCALE);

	HBoxContainer *hb = memnew( HBoxContainer );
	add_child(hb);
	hb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2);

	VBoxContainer *vb_shape = memnew( VBoxContainer );
	hb->add_child(vb_shape);

	sphere_switch = memnew( TextureButton );
	sphere_switch->set_toggle_mode(true);
	sphere_switch->set_pressed(true);
	vb_shape->add_child(sphere_switch);
	sphere_switch->connect("pressed",this,"_button_pressed",varray(sphere_switch));

	box_switch = memnew( TextureButton );
	box_switch->set_toggle_mode(true);
	box_switch->set_pressed(false);
	vb_shape->add_child(box_switch);
	box_switch->connect("pressed",this,"_button_pressed",varray(box_switch));

	hb->add_spacer();

	VBoxContainer *vb_light = memnew( VBoxContainer );
	hb->add_child(vb_light);

	light_1_switch = memnew( TextureButton );
	light_1_switch->set_toggle_mode(true);
	vb_light->add_child(light_1_switch);
	light_1_switch->connect("pressed",this,"_button_pressed",varray(light_1_switch));

	light_2_switch = memnew( TextureButton );
	light_2_switch->set_toggle_mode(true);
	vb_light->add_child(light_2_switch);
	light_2_switch->connect("pressed",this,"_button_pressed",varray(light_2_switch));

	first_enter=true;

}

void MaterialEditorPlugin::edit(Object *p_object) {

	Material * s = Object::cast_to<Material>(p_object);
	if (!s)
		return;

	material_editor->edit(Ref<Material>(s));
}

bool MaterialEditorPlugin::handles(Object *p_object) const {

	return p_object->is_type("Material");
}

void MaterialEditorPlugin::make_visible(bool p_visible) {

	if (p_visible) {
		material_editor->show();
		//material_editor->set_process(true);
	} else {

		material_editor->hide();
		//material_editor->set_process(false);
	}

}

MaterialEditorPlugin::MaterialEditorPlugin(EditorNode *p_node) {

	editor=p_node;
	material_editor = memnew( MaterialEditor );
	add_control_to_container(CONTAINER_PROPERTY_EDITOR_BOTTOM,material_editor);
	material_editor->hide();

}

MaterialEditorPlugin::~MaterialEditorPlugin()
{
}

#endif

String SpatialMaterialConversionPlugin::converts_to() const {

	return "ShaderMaterial";
}
bool SpatialMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {

	Ref<SpatialMaterial> mat = p_resource;
	return mat.is_valid();
}
Ref<Resource> SpatialMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) {

	Ref<SpatialMaterial> mat = p_resource;
	ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());

	Ref<ShaderMaterial> smat;
	smat.instance();

	Ref<Shader> shader;
	shader.instance();

	String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());

	shader->set_code(code);

	smat->set_shader(shader);

	List<PropertyInfo> params;
	VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), &params);

	for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
		Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
		smat->set_shader_param(E->get().name, value);
	}

	smat->set_render_priority(mat->get_render_priority());
	return smat;
}


text:
#pragma once

#include "CompositeObj.hpp"
#include "system/System.hpp"
#include "Common.hpp"

/**
 \brief Helpers to export a Rendu scene.
 \ingroup ObjToScene
 */
namespace SceneExport {

/** \brief Contain exported texture infos for a given material.
	 */
struct Material {
	std::string colorName;		///< Color texture name.
	std::string normalName;		///< Normal map name.
	std::string roughMetAoName; ///< Roughness-metalness-ambient occlusion texture name.
	std::string depthName;		///< Optional depth map.
	bool hasAlpha = false;		///< Alpha mask.
};

/** Save a small colored texture.
	 \param outputPath the output image file path
	 \param color the color to store in the texture
	 \return an error code or 0
	 */
int saveColor(const std::string & outputPath, const glm::vec3 & color);

/** Save a material parameters as a series of textures.
	 \param baseName material base name
	 \param material the material to export
	 \param outputDirPath the output directory
	 \return the exported material information
	 */
Material saveMaterial(const std::string & baseName, const CompositeObj::Material & material, const std::string & outputDirPath);

/** Save a scene description, listing all objects with materials. The file can then be decoded by Codable objects.
	 \param objects the scene objects
	 \param materials the scene materials
	 \param outputPath the destination file
	 \return an error code or 0
	 */
int saveDescription(const std::vector<CompositeObj::Object> & objects, const std::unordered_map<std::string, Material> & materials, const std::string & outputPath);

}


text:
#!/usr/bin/env node

/*jshint multistr: true */

var doc = "\n\
Usage:\n\
    twitter-autoremove [-e EXCLUDE_LIST] [-d DELAY] [-fir]\n\
    twitter-autoremove -h | --help | --version\n\
\n\
Autoremove twitter friends according to certain conditions.\n\
You should provide a file listing list of friends who will\n\
NOT be removed no matter what via option -e\n\
Consumer secret and access token must be passed via environment\n\
variables like so:\n\
TWITTER_CONSUMER_KEY=xxx TWITTER_CONSUMER_SECRET=xxx\\\n\
TWITTER_ACCESS_TOKEN_KEY=xxx TWITTER_ACCESS_TOKEN_SECRET=xxx twitter-autoremove\n\
\n\
Options:\n\
    -e EXCLUDE_LIST   List of friends who will not be removed.\n\
    -d DELAY          Delay between removal in seconds. Set this\n\
                      carefully to avoid twitter API limit. [default: 100].\n\
    -f                Remove friends who are also followers.\n\
                      Default to false. [default: false].\n\
    -i                Output id instead of screen name [default: false]\n\
    -r                If this option is set, friends will be removed from\n\
                      the most recently added. Default to false so friends\n\
                      will be removed from the oldest.[default: false]\n\
    -h --help         Show this screen.\n\
    --version         Show version.\n\
";

var Twitter = require('twitter');
var async = require('async');
var docopt = require('docopt');
var parseInt = require('parse-int');
var lineReader = require('line-reader');
var _ = require('lodash');

var client = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});

var DELAY = 100;

function main(args) {
    async.auto({
        validateInputs: function(next, res) {
            var delay = parseInt(args['-d']);
            if (delay > 0) DELAY = delay;
            next();
        },
        excludedList: function(next, res) {
            var excludedFile = args['-e'];
            if (excludedFile) {
                var lines = [];
                lineReader.eachLine(excludedFile, function(line, last) {
                    lines.push(line);
                }, function(err) {
                    if (err) {
                        next('Cannot open ' + excludedFile);
                    } else next(null, lines);
                });
            } else next(null, []);
        },
        followerIds: function(next, res) {
            if (!args['-f']) {
                client.get('followers/ids', function(_error, _res) {
                    if (_error) {
                        next(_error);
                    } else next(null, _res.ids);
                });
            } else next(null, []);
        },
        friendIds: function(next, res) {
            client.get('friends/ids', function(_error, _res) {
                if (_error) {
                    next(_error);
                    return;
                } else next(null, _res.ids);
            });
        },
        sortedFriendIds: ['friendIds', function(next, res) {
            if (args['-r']) {
                next(null, _(res.friendIds).reverse().value());
            } else next(null, res.friendIds);
        }],
        friendNotFollower: ['sortedFriendIds', 'followerIds', function(next, res) {
            var result = res.sortedFriendIds;
            if (!args['-f']) {
                result = _.filter(result, function(e) {
                    return res.followerIds.indexOf(e) == -1;
                });
            }
            next(null, result);
        }],
        remove: ['friendNotFollower', function(next, res) {
            var toBeRemoved = res.friendNotFollower;

            async.whilst(
                function() {
                    return toBeRemoved.length > 0;
                },
                function(_next) {
                    async.waterfall([
                        function(__next) {
                            var e = toBeRemoved.pop();
                            client.get('users/lookup', {
                                user_id: String(e)
                            }, function(__error, __res) {
                                __next(__error, __res && __res[0]);
                            });
                        },
                        function(info, __next) {
                            if (res.excludedList.indexOf(info.screen_name) != -1) {
                                _next();
                                return;
                            }
                            client.post('friendships/destroy', {
                                user_id: info.id
                            }, function(__error, __res) {
                                if (__error) {
                                    __next(__error);
                                    return;
                                }
                                if (args['-i']) {
                                    console.log(__res.id);
                                } else console.log(__res.screen_name);
                                process.stderr.write("Removed " + __res.screen_name + ' ' + __res.id + "\n");
                                setTimeout(__next, DELAY * 1000);
                            });
                        }
                    ], _next);
                },
                next
            );
        }],
    }, function(err, res) {
        if (err) {
            process.stderr.write("Error: " + JSON.stringify(err) + "\n");
            process.exit(1);
        }
    });
}

if (require.main === module) {
    var kwargs = {
        name: "twitter-autoremove",
        version: "twitter-autoremove 0.1.6"
    };
    var args = docopt.docopt(doc, kwargs);
    main(args);
}


text:
using namespace shogun;

template <typename T>
class CDynamicArrayFixture : public ::testing::Test
{
protected:
	CDynamicArrayFixture()
	{
	}
	virtual void SetUp()
	{
		m_array = SG_MALLOC(T, 5);
		for (int32_t i = 0; i < 5; i++)
		{
			m_array[i] = (T)i;
		}
		wrapper_array = new CDynamicArray<T>(m_array, 5);
		SG_FREE(m_array);
	}
	virtual void TearDown()
	{
		SG_UNREF(wrapper_array);
	}
	virtual ~CDynamicArrayFixture()
	{
	}

	CDynamicArray<T>* wrapper_array;
	T* m_array;
};

SG_TYPED_TEST_CASE(CDynamicArrayFixture, sg_all_primitive_types, complex128_t);

TYPED_TEST(CDynamicArrayFixture, array_ctor)
{
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 5);
	EXPECT_EQ(this->wrapper_array->get_array_size(), 5);
	for (index_t i = 0; i < 5; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), (TypeParam)i);
	}
}

TYPED_TEST(CDynamicArrayFixture, resize_array)
{
	this->wrapper_array->resize_array(10);
	EXPECT_EQ(this->wrapper_array->get_array_size(), 15);
}

TYPED_TEST(CDynamicArrayFixture, set_array)
{
	int32_t seed = 12;
	std::mt19937_64 prng(seed);
	UniformIntDistribution<int32_t> uniform_int_dist;
	this->wrapper_array->reset_array();
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 0);
	TypeParam* array = SG_MALLOC(TypeParam, 5);
	for (int32_t i = 0; i < 5; i++)
	{
		array[i] = (TypeParam)uniform_int_dist(prng, {1, 10});
	}
	this->wrapper_array->set_array(array, 5);

	EXPECT_EQ(this->wrapper_array->get_num_elements(), 5);
	for (index_t i = 0; i < 5; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), array[i]);
	}
	SG_FREE(array);
}

TYPED_TEST(CDynamicArrayFixture, const_set_array)
{
	int32_t seed = 12;

	std::mt19937_64 prng(seed);
	UniformIntDistribution<int32_t> uniform_int_dist;
	TypeParam* array = SG_MALLOC(TypeParam, 5);
	for (int32_t i = 0; i < 5; i++)
	{
		array[i] = (TypeParam)uniform_int_dist(prng, {1, 10});
	}
	const TypeParam* const_array = array;
	this->wrapper_array->reset_array();

	// make sure array been reset
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 0);

	this->wrapper_array->set_array(const_array, 5);
	for (index_t i = 0; i < 5; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), const_array[i]);
	}
	SG_FREE(array);
}

TYPED_TEST(CDynamicArrayFixture, get_array)
{
	TypeParam* array = this->wrapper_array->get_array();

	for (index_t i = 0; i < 5; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), (TypeParam)array[i]);
	}
}

TYPED_TEST(CDynamicArrayFixture, push_array)
{
	this->wrapper_array->reset_array();
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 0);
	this->wrapper_array->push_back((TypeParam)0);
	this->wrapper_array->push_back((TypeParam)1);
	this->wrapper_array->push_back((TypeParam)2);
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 3);
	for (int32_t i = 0; i < 3; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), (TypeParam)i);
	}
}

TYPED_TEST(CDynamicArrayFixture, append_array)
{
	this->wrapper_array->reset_array();
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 0);
	this->wrapper_array->append_element((TypeParam)0);
	this->wrapper_array->append_element((TypeParam)1);
	this->wrapper_array->append_element((TypeParam)2);
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 3);
	for (int32_t i = 0; i < 3; i++)
	{
		EXPECT_EQ(this->wrapper_array->get_element(i), (TypeParam)i);
	}
}

TYPED_TEST(CDynamicArrayFixture, back_operation)
{
	EXPECT_EQ(this->wrapper_array->back(), (TypeParam)4);
}

TYPED_TEST(CDynamicArrayFixture, set_operation)
{
	this->wrapper_array->set_element(1, (TypeParam)4);
	EXPECT_EQ(this->wrapper_array->get_element(4), (TypeParam)1);
}

TYPED_TEST(CDynamicArrayFixture, pop_operation)
{
	this->wrapper_array->pop_back();
	EXPECT_EQ(this->wrapper_array->back(), (TypeParam)3);
}

TYPED_TEST(CDynamicArrayFixture, insert_operation)
{
	this->wrapper_array->insert_element((TypeParam)10, 2);
	EXPECT_EQ(this->wrapper_array->get_element(2), (TypeParam)10);
}

TYPED_TEST(CDynamicArrayFixture, append_array_bool)
{
	this->wrapper_array->reset_array();
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 0);
	this->wrapper_array->append_element((TypeParam)1);
	this->wrapper_array->append_element((TypeParam)0);
	this->wrapper_array->append_element((TypeParam)1);
	EXPECT_EQ(this->wrapper_array->get_num_elements(), 3);
	EXPECT_EQ(this->wrapper_array->get_element(0), (TypeParam)1);
	EXPECT_EQ(this->wrapper_array->get_element(1), (TypeParam)0);
	EXPECT_EQ(this->wrapper_array->get_element(2), (TypeParam)1);
}


text:
package com.ripariandata.timberwolf.conf4j;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a field as being a target for a ConfigFileParser to update with data
 * from a configuration file.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface ConfigEntry
{
    /** The key name in the configuration file for this entry. */
    String name();

    /** Short description of the entry, suitable for printing to the console. */
    String usage() default "";
}


text:
title: "Otimizar o desempenho"
description: "O desempenho é um recurso. Entregue seu conteúdo aos usuários o mais rápido possível. Quando eles estiverem no seu aplicativo, faça com que a interação e a renderização de páginas tenham a maior fluidez possível."
updated_on: 2014-04-28
---

{% comment %}
Guide list content will be output by the landing layout passed on the article collection matching page.id
{% endcomment %}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>CSA2Example - SQL Injection</title>

This is a safe link

<form method="post" action="http://localhost:8080/change.php">
    <input type="hidden" name="newusername" value="hacked">
    <input type="hidden" name="agb" value="1">
    <button class="link" type="submit">This a an unsafe link</button>
</form>


text:
// ==========================================================================
// Project:   Lebowski Framework - The SproutCore Test Automation Framework
// License:   Licensed under MIT license (see License.txt)
// ==========================================================================
/*globals TestApp */

TestApp.webViewsPage = SC.Page.design({

  mainView: SC.View.design({
    layout: { top: 20, bottom: 20, left: 20, right: 20 },
    childViews: 'firstWebView secondWebView counter'.w(),

    firstWebView: SC.View.design({
      layout: { width: 250, height: 150, left: 0, top: 0 },
      childViews: 'label webView'.w(),

      label: SC.LabelView.design({
        layout: { left: 0, right: 0, top: 0, height: 25 },
        value: 'First Web View',
        textAlign: SC.ALIGN_CENTER,
        backgroundColor: 'green'
      }),

      webView: SC.WebView.design({
        layout: { left: 0, right: 0, bottom: 0, top: 30 },
        layerId: 'first-web-view',
        value: '/basic'
      })
    }),

    secondWebView: SC.View.design({
      layout: { width: 250, height: 150, left: 260, top: 0 },
      childViews: 'label webView'.w(),

      label: SC.LabelView.design({
        layout: { left: 0, right: 0, top: 0, height: 25 },
        value: 'Second Web View',
        textAlign: SC.ALIGN_CENTER,
        backgroundColor: 'green'
      }),

      webView: SC.WebView.design({
        layout: { left: 0, right: 0, bottom: 0, top: 30 },
        layerId: 'second-web-view',
        value: '/basic'
      })
    }),

    counter: SC.View.design({
      layout: { left: 520, top: 0, right: 0, height: 150 },
      childViews: 'label incButton resetButton'.w(),

      label: SC.LabelView.design({
        layout: { left: 0, right: 0, top: 0, height: 23 },
        valueBinding: SC.Binding.transform(function(value) {
          return "Counter: %@".fmt(value);
        }).oneWay('TestApp.webViewControlsController.counter'),
        textAlign: SC.ALIGN_CENTER
      }),

      incButton: SC.ButtonView.design({
        layout: { centerX: -55, width: 100, height: 23, top: 50 },
        title: "Increment",
        action: "incrementCounter",
        target: TestApp.webViewControlsController
      }),

      resetButton: SC.ButtonView.design({
        layout: { centerX: 55, width: 100, height: 23, top: 50 },
        title: "Reset",
        action: "resetCounter",
        target: TestApp.webViewControlsController
      })
    })

  })

});


text:
using System.Windows.Controls;

namespace Microsoft.DataTransfer.Sql.Wpf.Source
{
    partial class SqlDataSourceAdapterConfigurationPage : UserControl
    {
        public SqlDataSourceAdapterConfigurationPage()
        {
            InitializeComponent();
        }
    }
}


text:
"""
Common Django settings for the project.

See the local, test, and production settings modules for the values used
in each environment.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
from django.core.exceptions import ImproperlyConfigured

import os

from dotenv import load_dotenv

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'not-so-secret'

ALLOWED_HOSTS = []

# Loading .env file automatically
load_dotenv(dotenv_path=os.path.join(BASE_DIR, '.env'))

# Twilio API credentials
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')

# Twilio number
TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER')

# TwiML Application SID
TWIML_APPLICATION_SID = os.environ.get('TWIML_APPLICATION_SID')

API_KEY = os.environ.get('API_KEY')
API_SECRET = os.environ.get('API_SECRET')

if not (TWILIO_ACCOUNT_SID and TWILIO_NUMBER and TWIML_APPLICATION_SID and API_KEY and API_SECRET):
    missing_config_values = \
    """
    You must set the TWILIO_ACCOUNT_SID, TWILIO_NUMBER, TWIML_APPLICATION_SID, API_KEY and API_SECRET environment variables to run this app.
    Consult the README for instructions on how to find them.
    """
    raise ImproperlyConfigured(missing_config_values)

# Application definition

DJANGO_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize'
)

THIRD_PARTY_APPS = (
    'bootstrap4',
)

LOCAL_APPS = (
    'browser_calls',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE = (
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'twilio_sample_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates/'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'twilio_sample_project.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'node_modules', 'twilio-client', 'dist'),
    os.path.join(BASE_DIR, 'node_modules', 'jquery', 'dist')
)

# STATIC_ROOT = BASE_DIR + '/staticfiles'

STATIC_URL = '/static/'

# Messages settings for Bootstrap 3

from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

# Redirect login to /support/dashboard
LOGIN_REDIRECT_URL = '/support/dashbaord'


text:
{% extends "base.html" %}

{% block body %}

Sell anywhere.Checkmate.

Make money for selling. Whether you're a music blogger or The New York Times, we give you 30% commission for a sale that comes from your site.

Sign up

Set you price

View details »

Sell anywhere

Sell anywhere on the Internet!

View details »

Incentivized sharing

Share books via social media.

View details »

Big data

View details »

Open api's

An open architecture means your content will be listed in more places.

View details »

Democracy

This virtual economy is run by voting.

View details »

No DRM

DRM is Evil.

View details »

Pay when you want

Different then pay what you want, you pay when you want. Sometimes you might never pay.

View details »

Democracy

This virtual economy is run by voting.

View details »

Read on any deviceAnywhere

With Futurepress there is no device lock in. Our technologies are all open source and based on open standards. Any device that supports epub or a modern browser will work. If you want to export your library you can.

Sell anywhere.Checkmate.

Make money for selling. Whether you're a music blogger or The New York Times, we give you 30% commission for a sale that comes from your site.

    {% include 'footer.html' %}

{% endblock %}


text:
package com.yudeyang.responsibilitychain;

class DirectorPPower extends PurchasePower {

    protected double getAllowable(){
        return BASE*20;
    }

    protected String getRole(){
        return "导演";
    }
}


text:
#ifndef BT_FIXED_CONSTRAINT_H
#define BT_FIXED_CONSTRAINT_H

#include "btGeneric6DofSpring2Constraint.h"

ATTRIBUTE_ALIGNED16(class)
btFixedConstraint : public btGeneric6DofSpring2Constraint
{
public:
	btFixedConstraint(btRigidBody & rbA, btRigidBody & rbB, const btTransform& frameInA, const btTransform& frameInB);

	virtual ~btFixedConstraint();
};

#endif  //BT_FIXED_CONSTRAINT_H


text:
namespace media_router {

TEST(MediaRouterTypeConvertersTest, ConvertMediaSink) {
  MediaSink expected_media_sink("sinkId1", "Sink 1");
  interfaces::MediaSinkPtr expected_mojo_sink(interfaces::MediaSink::New());
  expected_mojo_sink->sink_id = "sinkId1";
  expected_mojo_sink->name = "Sink 1";

  interfaces::MediaSinkPtr mojo_sink =
      mojo::TypeConverter<interfaces::MediaSinkPtr, MediaSink>::Convert(
          expected_media_sink);

  EXPECT_EQ(expected_mojo_sink, mojo_sink);

  MediaSink media_sink = mojo::TypeConverter<
      media_router::MediaSink,
      media_router::interfaces::MediaSinkPtr>::Convert(mojo_sink);

  // Convert MediaSink and back should result in identical object.
  EXPECT_EQ(expected_media_sink.name(), media_sink.name());
  EXPECT_EQ(expected_media_sink.id(), media_sink.id());
  EXPECT_TRUE(expected_media_sink.Equals(media_sink));
}

TEST(MediaRouterTypeConvertersTest, ConvertMediaRoute) {
  MediaSource expected_source(MediaSourceForTab(123));
  MediaRoute expected_media_route("routeId1", expected_source,
                                  MediaSink("sinkId", "sinkName"),
                                  "Description", false, "cast_view.html");
  interfaces::MediaRoutePtr expected_mojo_route(interfaces::MediaRoute::New());
  expected_mojo_route->media_route_id = "routeId1";
  expected_mojo_route->media_source = expected_source.id();
  expected_mojo_route->media_sink = interfaces::MediaSink::New();
  expected_mojo_route->media_sink->sink_id = "sinkId";
  expected_mojo_route->media_sink->name = "sinkName";
  expected_mojo_route->description = "Description";
  expected_mojo_route->is_local = false;
  expected_mojo_route->custom_controller_path = "cast_view.html";

  interfaces::MediaRoutePtr mojo_route = mojo::TypeConverter<
      media_router::interfaces::MediaRoutePtr,
      media_router::MediaRoute>::Convert(expected_media_route);
  EXPECT_EQ(expected_mojo_route, mojo_route);

  MediaRoute media_route = mojo_route.To<MediaRoute>();
  EXPECT_TRUE(expected_media_route.Equals(media_route));
  EXPECT_EQ(expected_media_route.media_sink().name(),
            media_route.media_sink().name());
  EXPECT_EQ(expected_media_route.media_sink().id(),
            media_route.media_sink().id());
  EXPECT_EQ(expected_media_route.description(), media_route.description());
  EXPECT_TRUE(
      expected_media_route.media_source().Equals(media_route.media_source()));
  EXPECT_EQ(expected_media_route.media_source().id(),
            media_route.media_source().id());
  EXPECT_EQ(expected_media_route.is_local(), media_route.is_local());
  EXPECT_EQ(expected_media_route.custom_controller_path(),
            media_route.custom_controller_path());
}

TEST(MediaRouterTypeConvertersTest, ConvertMediaRouteWithoutOptionalFields) {
  MediaRoute expected_media_route("routeId1", MediaSource(),
                                  MediaSink("sinkId", "sinkName"),
                                  "Description", false, "");
  interfaces::MediaRoutePtr expected_mojo_route(interfaces::MediaRoute::New());
  // MediaRoute::media_source is omitted.
  expected_mojo_route->media_route_id = "routeId1";
  expected_mojo_route->media_sink = interfaces::MediaSink::New();
  expected_mojo_route->media_sink->sink_id = "sinkId";
  expected_mojo_route->media_sink->name = "sinkName";
  expected_mojo_route->description = "Description";
  expected_mojo_route->is_local = false;

  interfaces::MediaRoutePtr mojo_route = mojo::TypeConverter<
      media_router::interfaces::MediaRoutePtr,
      media_router::MediaRoute>::Convert(expected_media_route);
  EXPECT_EQ(expected_mojo_route, mojo_route);

  MediaRoute media_route = mojo_route.To<MediaRoute>();
  EXPECT_TRUE(expected_media_route.Equals(media_route));
  EXPECT_EQ("sinkName", media_route.media_sink().name());
}

TEST(MediaRouterTypeConvertersTest, ConvertIssue) {
  interfaces::IssuePtr mojoIssue;
  mojoIssue = interfaces::Issue::New();
  mojoIssue->title = "title";
  mojoIssue->message = "msg";
  mojoIssue->route_id = "routeId";
  mojoIssue->default_action = interfaces::Issue::ActionType::ACTION_TYPE_OK;
  mojoIssue->secondary_actions =
      mojo::Array<interfaces::Issue::ActionType>::New(2);
  mojoIssue->secondary_actions[0] =
      interfaces::Issue::ActionType::ACTION_TYPE_CANCEL;
  mojoIssue->secondary_actions[1] =
      interfaces::Issue::ActionType::ACTION_TYPE_DISMISS;
  mojoIssue->severity = interfaces::Issue::Severity::SEVERITY_WARNING;
  mojoIssue->is_blocking = true;
  mojoIssue->help_url = "help_url";

  std::vector<IssueAction> secondary_actions;
  secondary_actions.push_back(IssueAction(IssueAction::TYPE_CANCEL));
  secondary_actions.push_back(IssueAction(IssueAction::TYPE_DISMISS));
  Issue expected_issue("title", "msg", IssueAction(IssueAction::TYPE_OK),
                       secondary_actions, "routeId", Issue::WARNING, true,
                       "help_url");
  Issue converted_issue = mojo::TypeConverter<
      media_router::Issue,
      media_router::interfaces::IssuePtr>::Convert(mojoIssue);

  EXPECT_EQ(expected_issue.title(), converted_issue.title());
  EXPECT_EQ(expected_issue.message(), converted_issue.message());
  EXPECT_EQ(expected_issue.default_action().type(),
            converted_issue.default_action().type());
  ASSERT_EQ(expected_issue.secondary_actions().size(),
            converted_issue.secondary_actions().size());
  for (size_t i = 0; i < expected_issue.secondary_actions().size(); ++i) {
    EXPECT_EQ(expected_issue.secondary_actions()[i].type(),
              converted_issue.secondary_actions()[i].type());
  }
  EXPECT_EQ(expected_issue.route_id(), converted_issue.route_id());
  EXPECT_EQ(expected_issue.severity(), converted_issue.severity());
  EXPECT_EQ(expected_issue.is_blocking(), converted_issue.is_blocking());
  EXPECT_EQ(expected_issue.help_url(), converted_issue.help_url());

  // Ensure that the internal Issue objects are considered distinct
  // (they possess different IDs.)
  EXPECT_FALSE(converted_issue.Equals(expected_issue));
}

TEST(MediaRouterTypeConvertersTest, ConvertIssueWithoutOptionalFields) {
  interfaces::IssuePtr mojoIssue;
  mojoIssue = interfaces::Issue::New();
  mojoIssue->title = "title";
  mojoIssue->default_action = interfaces::Issue::ActionType::ACTION_TYPE_OK;
  mojoIssue->severity = interfaces::Issue::Severity::SEVERITY_WARNING;
  mojoIssue->is_blocking = true;

  Issue expected_issue("title", "", IssueAction(IssueAction::TYPE_OK),
                       std::vector<IssueAction>(), "", Issue::WARNING, true,
                       "");

  Issue converted_issue = mojo::TypeConverter<
      media_router::Issue,
      media_router::interfaces::IssuePtr>::Convert(mojoIssue);

  EXPECT_EQ(expected_issue.title(), converted_issue.title());
  EXPECT_EQ(expected_issue.default_action().type(),
            converted_issue.default_action().type());
  EXPECT_EQ(0u, converted_issue.secondary_actions().size());
  EXPECT_EQ(expected_issue.severity(), converted_issue.severity());
  EXPECT_EQ(expected_issue.is_blocking(), converted_issue.is_blocking());

  // Ensure that the internal Issue objects are considered distinct
  // (they possess different IDs.)
  EXPECT_FALSE(converted_issue.Equals(expected_issue));
}

}  // namespace media_router


text:
using System;
using System.Reflection;

namespace CodeJam.Extensibility
{
	/// <summary>
	/// Extension manager contract.
	/// </summary>
	public interface IExtensionManager
	{
		/// <summary>
		/// Scan assembly.
		/// </summary>
		void Scan(IExtensionAttachmentStrategy strategy, params Assembly[] assemblies);

		/// <summary>
		/// Scan specific type.
		/// </summary>
		void Scan(IExtensionAttachmentStrategy strategy, params Type[] types);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using SourcePath;
using SourcePath.Roslyn;

namespace SharpLab.Server.Explanation.Internal {
    using IRoslynNodeKind = ISourceNodeKind<RoslynNodeContext>;

    public class CSharpExplanationPathDialect : ISourcePathDialect<RoslynNodeContext> {
        private static readonly IReadOnlyDictionary<string, IRoslynNodeKind> NodeKinds =
            EnumerateNodeKinds().ToDictionary(k => k.ToPathString(), k => k);

        private static IEnumerable<IRoslynNodeKind> EnumerateNodeKinds() {
            // Normally Enum.GetValues does not require Distinct, but there are some branches of Roslyn
            // that (temporarily?) have duplicate values, e.g. see
            // https://github.com/dotnet/roslyn/blob/7ea6fa4d1871175f5ad5445677c0e0dd1a7a597c/src/Compilers/Core/Portable/Operations/OperationKind.cs#L209-L212
            IEnumerable<T> GetEnumValues<T>() where T: Enum
                => Enum.GetValues(typeof(T)).Cast<T>().Distinct();

            foreach (var syntaxKind in GetEnumValues<SyntaxKind>()) {
                yield return new RoslynCSharpNodeKind(syntaxKind.ToString(), new HashSet<SyntaxKind> { syntaxKind });
            }

            foreach (var symbolKind in GetEnumValues<SymbolKind>()) {
                yield return new SymbolNodeKind(symbolKind);
            }

            foreach (var operationKind in GetEnumValues<OperationKind>()) {
                yield return new OperationNodeKind(operationKind);
            }

            yield return IsVerbatimNodeKind.Default;
            yield return StarNodeKind.Default;
        }

        public SourcePathDialectSupports Supports { get; } = new SourcePathDialectSupports {
            TopLevelAxis = false,
            TopLevelSegments = false,
            AxisSelf = false,
            AxisDescendant = false,
            AxisParent = false,
            AxisAncestor = false
        };

        public IRoslynNodeKind ResolveNodeKind(string nodeKindString) {
            Argument.NotNullOrEmpty(nameof(nodeKindString), nodeKindString);

            if (!NodeKinds.TryGetValue(nodeKindString, out var nodeKind))
                return UnknownNodeKind.Default;

            return nodeKind;
        }

        public class StarNodeKind : IRoslynNodeKind {
            public static StarNodeKind Default { get; } = new StarNodeKind();

            public bool Matches(RoslynNodeContext context) => true;
            public string ToPathString() => "*";
        }

        public class IsVerbatimNodeKind : IRoslynNodeKind {
            public static IsVerbatimNodeKind Default { get; } = new IsVerbatimNodeKind();

            public bool Matches(RoslynNodeContext context) {
                return context.IsToken
                    && context.AsToken().Text.StartsWith("@");
            }

            public string ToPathString() => "_IsVerbatim";
        }

        public class SymbolNodeKind : IRoslynNodeKind {
            private readonly SymbolKind _symbolKind;

            public SymbolNodeKind(SymbolKind symbolKind) {
                _symbolKind = symbolKind;
            }

            public bool Matches(RoslynNodeContext context) {
                var symbol = context.SemanticModel.GetSymbolInfo(context.AsNode());
                return symbol.Symbol?.Kind == _symbolKind;
            }

            public string ToPathString() => "SymbolKind:" + _symbolKind.ToString();
        }

        public class OperationNodeKind : IRoslynNodeKind {
            private readonly OperationKind _operationKind;

            public OperationNodeKind(OperationKind operationKind) {
                _operationKind = operationKind;
            }

            public bool Matches(RoslynNodeContext context) {
                var operation = context.SemanticModel.GetOperation(context.AsNode());
                return operation?.Kind == _operationKind;
            }

            public string ToPathString() => "OperationKind:" + _operationKind.ToString();
        }

        // Represents a value that's not in SyntaxKind enum -- likely because the
        // current branch is too old. It can't match anything, but it's still needed
        // so that Explanation file can be loaded without exceptions.
        private class UnknownNodeKind : IRoslynNodeKind {
            public static UnknownNodeKind Default { get; } = new UnknownNodeKind();

            public bool Matches(RoslynNodeContext context) => false;
            public string ToPathString() => "Unknown";
        }
    }
}


text:
<?php
/**
 * Delete topic action
 *
 */

$topic_guid = (int) get_input('guid');

$topic = get_entity($topic_guid);
if (!$topic || !$topic->getSubtype() == "groupforumtopic") {
	register_error(elgg_echo('discussion:error:notdeleted'));
	forward(REFERER);
}

if (!$topic->canEdit()) {
	register_error(elgg_echo('discussion:error:permissions'));
	forward(REFERER);
}

$container = $topic->getContainerEntity();

$result = $topic->delete();
if ($result) {
	system_message(elgg_echo('discussion:topic:deleted'));
} else {
	register_error(elgg_echo('discussion:error:notdeleted'));
}

forward("discussion/owner/$container->guid");


text:
package org.spongepowered.common.mixin.core.item.inventory;

import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryEnderChest;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.tileentity.TileEntityLockable;
import org.spongepowered.api.item.inventory.EmptyInventory;
import org.spongepowered.api.item.inventory.Inventory;
import org.spongepowered.api.item.inventory.Slot;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Intrinsic;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.common.item.inventory.EmptyInventoryImpl;
import org.spongepowered.common.item.inventory.adapter.impl.MinecraftInventoryAdapter;
import org.spongepowered.common.item.inventory.custom.CustomInventory;
import org.spongepowered.common.item.inventory.lens.SlotProvider;
import org.spongepowered.common.item.inventory.lens.impl.collections.SlotCollection;

import java.util.ArrayList;
import java.util.List;

@Mixin(value = {
        net.minecraft.inventory.Slot.class,
        InventoryPlayer.class,
        EntityVillager.class,
        Container.class,
        InventoryLargeChest.class,
        InventoryEnderChest.class,
        TileEntityLockable.class,
        CustomInventory.class
}, priority = 999)
@Implements(@Interface(iface = Inventory.class, prefix = "inventory$"))
public abstract class TraitInventoryAdapter implements MinecraftInventoryAdapter {

    protected EmptyInventory empty;
    protected Inventory parent;
    protected Inventory next;
    protected SlotCollection slots;
    protected List<Inventory> children = new ArrayList<Inventory>();
    protected Iterable<Slot> slotIterator;

    @Override
    public Inventory parent() {
        return this.parent == null ? this : this.parent();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends Inventory> T first() {
        return (T) this.iterator().next();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends Inventory> T next() {
        return (T) this.emptyInventory(); // TODO implement me
    }

    @Override
    public SlotProvider<IInventory, net.minecraft.item.ItemStack> getSlotProvider() {
        return this.slots;
    }

    @Override
    public Inventory getChild(int index) {
        if (index < 0 || index >= this.getRootLens().getChildren().size()) {
            throw new IndexOutOfBoundsException("No child at index: " + index);
        }
        while (index >= this.children.size()) {
            this.children.add(null);
        }
        Inventory child = this.children.get(index);
        if (child == null) {
            child = this.getRootLens().getChildren().get(index).getAdapter(this.getInventory(), this);
            this.children.set(index, child);
        }
        return child;
    }

    // TODO getChild with lens not implemented

    protected final EmptyInventory emptyInventory() {
        if (this.empty == null) {
            this.empty = new EmptyInventoryImpl(this);
        }
        return this.empty;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T extends Inventory> Iterable<T> slots() {
        if (this.slotIterator == null) {
            this.slotIterator = this.slots.getIterator(this);
        }
        return (Iterable<T>) this.slotIterator;
    }

    @Intrinsic
    public void inventory$clear() {
        this.getInventory().clear();
    }

}


text:
"""
Created on Sat Sep 03 12:38:45 2016

@author: DIP
"""

from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer

def build_feature_matrix(documents, feature_type='frequency'):

    feature_type = feature_type.lower().strip()

    if feature_type == 'binary':
        vectorizer = CountVectorizer(binary=True, min_df=1,
                                     ngram_range=(1, 1))
    elif feature_type == 'frequency':
        vectorizer = CountVectorizer(binary=False, min_df=1,
                                     ngram_range=(1, 1))
    elif feature_type == 'tfidf':
        vectorizer = TfidfVectorizer(min_df=1,
                                     ngram_range=(1, 1))
    else:
        raise Exception("Wrong feature type entered. Possible values: 'binary', 'frequency', 'tfidf'")

    feature_matrix = vectorizer.fit_transform(documents).astype(float)

    return vectorizer, feature_matrix

from scipy.sparse.linalg import svds

def low_rank_svd(matrix, singular_count=2):

    u, s, vt = svds(matrix, k=singular_count)
    return u, s, vt


text:
package Gemstone;

import org.apache.log4j.Logger;
import sagex.phoenix.vfs.IMediaResource;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Created by jusjoken on 2/20/2016.
 * Sorts a List of TV Episodes by the Season and Episode numbers
 * Converts these to a long value to aid in the sort
 */
public class SeasonEpisodeSorter implements Comparator<IMediaResource>, Serializable {
    static private final Logger LOG = Logger.getLogger(SeasonEpisodeSorter.class);
    private static final long serialVersionUID = 1L;

    public SeasonEpisodeSorter() {
    }

    public int compare(IMediaResource o1, IMediaResource o2) {
        //LOG.debug("Comparing '" + o1 + "' to '" + o2 + "'");
        if (o1 == null)
            return 1;
        if (o2 == null)
            return -1;

        long t1 = MetadataCalls.GetSeasonEpisodeForSort(o1);
        long t2 = MetadataCalls.GetSeasonEpisodeForSort(o2);
        //LOG.debug("Comparing t1 '" + t1 + "' to t2 '" + t2 + "'");

        if (t1 > t2)
            return 1;
        if (t1 < t2)
            return -1;

        return 0;
    }

}


text:
// Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.packages;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.syntax.Location;
import com.google.devtools.build.lib.syntax.StarlarkThread;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * A CallStack is an opaque immutable stack of Starlark call frames, outermost call first. Its
 * representation is highly optimized for space. Call {@link #toArray} to access the frames.
 *
 *
A CallStack cannot be constructed directly, but must be created by calling the {@code of}
 * method of a Builder, which should be shared across all the rules of a package.
 */
public final class CallStack {

  // A naive implementation using a simple array of CallStackEntry was
  // found to increase retained heap size for a large query by about 6%.
  // We reduce this using two optimizations:
  //
  // 1) entry compression
  // A CallStackEntry has size 2 (header) + 1 String + 1 Location = 4 words.
  // A Location has size 2 (header) + 1 String + 1 (file/loc) = 4 words.
  // By representing the two strings as small integers---indices into a shared
  // table---we can represent the payload using 4 ints = 2 words.
  // We reconstitute new Locations and CallStackEntries on request.
  // Eliminating Java object overheads reduces the marginal
  // space for an element by about a half.
  //
  // 2) prefix sharing
  // We share common stack prefixes between successive entries.
  // The stacks passed to successive of() calls display locality because
  // within a package, many rules are created by a single macro or stack
  // of macros. The Builder records the previous stack and creates a tree node
  // for each prefix. When it sees a new stack, it finds the common prefix
  // for the current and previous stacks, and only creates new nodes for
  // the suffix of different entries.
  // Avoiding storage of redundant prefixes reduces overall space by about
  // two thirds.
  //
  // This class intentionally does not implement List
  // because internally it is a linked list,
  // so accidentally using List.get for sequential access
  // would result in quadratic behavior.

  public static final CallStack EMPTY = new CallStack(ImmutableList.of(), 0, null);

  private final List<String> strings; // builder's string table, shared
  private final int size; // depth of stack
  @Nullable private final Node node; // tree node representing this stack

  private CallStack(List<String> strings, int size, @Nullable Node node) {
    this.strings = strings;
    this.size = size;
    this.node = node;
  }

  /** Returns the call stack as a list of frames, outermost call first. */
  public ImmutableList<StarlarkThread.CallStackEntry> toList() {
    return ImmutableList.copyOf(toArray());
  }

  /** Returns the call stack as a new array, outermost call first. */
  public StarlarkThread.CallStackEntry[] toArray() {
    StarlarkThread.CallStackEntry[] array = new StarlarkThread.CallStackEntry[size];
    int i = size;
    for (Node n = node; n != null; n = n.parent) {
      String file = strings.get(n.file);
      String name = strings.get(n.name);
      Location loc = Location.fromFileLineColumn(file, n.line, n.col);
      array[--i] = new StarlarkThread.CallStackEntry(name, loc);
    }
    return array;
  }

  // A Node is a node in a linked tree representing a prefix of the call stack.
  // file and line are indices of strings in the builder's shared table.
  private static class Node {
    Node(int name, int file, int line, int col, Node parent) {
      this.name = name;
      this.file = file;
      this.line = line;
      this.col = col;
      this.parent = parent;
    }

    final int name;
    final int file;
    final int line;
    final int col;
    @Nullable final Node parent;
  }

  /** A Builder is a stateful indexer of call stacks. */
  static final class Builder {

    // string table: strings[index[s]] == s
    private final Map<String, Integer> index = new HashMap<>();
    private final List<String> strings = new ArrayList<>();

    // nodes[0:depth] is the previously encountered call stack.
    // We avoid ArrayList because we need efficient truncation.
    private Node[] nodes = new Node[10];
    private int depth = 0;

    /**
     * Returns a compact representation of the specified call stack.

     * Space efficiency depends on the similarity of the list elements in successive calls.
     * Reversing the stack before calling this function destroys the optimization, for instance.
     */
    CallStack of(List<StarlarkThread.CallStackEntry> stack) {
      // We find and reuse the common ancestor node for the prefix common
      // to the current stack and the stack passed to the previous call,
      // then add child nodes for the different suffix, if any.

      // Loop invariant: parent == (i > 0 ? nodes[i-1] : null)
      Node parent = null;
      int n = stack.size();
      for (int i = 0; i < n; i++) {
        StarlarkThread.CallStackEntry entry = stack.get(i);

        int name = indexOf(entry.name);
        int file = indexOf(entry.location.file());
        int line = entry.location.line();
        int column = entry.location.column();
        if (i < depth
            && parent == nodes[i].parent
            && name == nodes[i].name
            && file == nodes[i].file
            && line == nodes[i].line
            && column == nodes[i].col) {
          parent = nodes[i];
          continue;
        }
        parent = new Node(name, file, line, column, parent);
        if (i == nodes.length) {
          nodes = Arrays.copyOf(nodes, nodes.length << 1); // grow by doubling
        }
        nodes[i] = parent;
      }
      this.depth = n; // truncate

      // Use the same node for all empty stacks, to avoid allocations.
      return parent != null ? new CallStack(strings, n, parent) : EMPTY;
    }

    private int indexOf(String s) {
      int i = index.size();
      Integer prev = index.putIfAbsent(s, i);
      if (prev != null) {
        i = prev;
      } else {
        strings.add(s);
      }
      return i;
    }
  }
}


text:
! { dg-do compile }
! Regression. ICE on valid code.
! The following worked with 4.1.3 and 4.2.2, but failed
! (segmentation fault) with 4.3.0 because the type comparison
! tried to comparethe types of the components of type(node), even
! though the only component is of type(node).
!
! Found using the Fortran Company Fortran 90 Test Suite (Lite),
! Version 1.4
!
! Reported by Tobias Burnus <burnus@gcc.gnu.org>
!
program error
  implicit none
  type node
    sequence
    type(node), pointer :: next
  end type
  type(node), pointer :: list

  interface
    subroutine insert(ptr)
      implicit none
      type node
        sequence
        type(node), pointer :: next
      end type
      type(node), pointer :: ptr
    end subroutine insert
  end interface
  allocate (list);
end program error


text:
module Wukong
  module Load

    # A base class for all syncers to subclass.
    class Syncer

      include Logging

      # Settings for this syncer.
      attr_accessor :settings

      # Name of this syncer.
      attr_accessor :name

      # Time taken to complete sync.
      attr_accessor :duration

      # Construct a new Syncer from the given `settings` for the given
      # `source` with the given `name`.
      #
      # @return [Syncer]
      def self.from_source settings, source, name
        raise NotImplementedError.new("Override the #{self}.from_source method")
      end

      # Create a new syncer.
      #
      # @param [Configliere::Param] settings
      def initialize settings
        self.settings = settings
        self.name     = settings[:name]
      end

      # Configure the given `settings` with more specific options.
      #
      # @param [Configliere::Param] settings
      def self.configure settings
      end

      # Run this syncer, performing validation, setting up, sycning,
      # and cleaning up.
      def run
        validate
        setup
        before_sync
        sync
        after_sync
      rescue => e
        on_error(e)
        raise e
      end

      # Validate this syncer.
      #
      # @return [true]
      def validate
        true
      end

      # Setup this syncer.
      def setup
      end

      # Perform the sync.
      def sync
        raise NotImplementedError.new("Override the #{self.class}#sync method")
      end

      module Hooks
        # Run before a sync.
        def before_sync
        end

        # Run after a successful sync.
        def after_sync
        end

        # Run when a sync fails for some reason.
        #
        # @param [Error] error the error that was thrown
        def on_error error
          log.error(error)
        end
      end
      include Hooks

    end
  end
end


text:
<?php
    /**
     * XPHP - PHP Framework
     *
     * This project is licensed
     * under MIT. Please use it
     * under the license and law.
     *
     * @category Framework
     * @package  XPHP
     * @author   Tianle Xu <xtl@xtlsoft.top>
     * @license  MIT
     * @link     https://github.com/xtlsoft/XPHP
     *
     */

    namespace X;

    use \Monolog\Logger;

    class Log implements \X\Interfaces\NeedApplication, \X\Interfaces\Bootable {

        public $logger = [];

        public function bootup() {

            $this->app->log = $this;

        }

        public function addLogger($name){

            $this->logger[$name] = new Logger($name);

            return $this;

        }

        public function pushHandler($name, $handler){

            $this->{$name}->pushHandler($handler);

            return $this;

        }

        public function mapEvent($event, $name, $method = "addInfo"){

            $logger = $this->{$name};

            $this->app->event->addListener($event, function($event, $log) use ($logger, $method){
                call_user_func([$logger, $method], $log);
            });

            return $this;

        }

        public function __get($name){

            return $this->logger[$name];

        }

    }


text:
import React, {ReactHTML, ComponentType, createElement, ReactNode} from "react"
import {jsx} from "@emotion/core"

type Args = Parameters<typeof jsx>
type Element = ReturnType<typeof jsx>

type Props
 = Omit<React.Attributes & P, "children">
type Children = Args[2]

function h(
  tag: keyof ReactHTML,
  propsOrChildren?: JSX.IntrinsicElements[typeof tag] | Children,
  children?: Children
): Element
function h
(
  comp: ComponentType
,
  propsOrChildren: Props
,
  children?: Children
): React.ReactElement

function h
(
  comp: ComponentType
,
  propsOrChildren?: Children
): React.ReactElement

function h
(comp: any, propsOrChildren?: any, children?: any): any {
  const secondIsArr = Array.isArray(propsOrChildren)
  if (!secondIsArr && typeof propsOrChildren === "object") {
    if (Array.isArray(children)) {
      return jsx(comp, propsOrChildren as P, ...children)
    } else {
      return jsx(comp, propsOrChildren as P, children)
    }
  } else {
    if (secondIsArr) {
      return jsx(comp, null, ...propsOrChildren)
    } else {
      return jsx(comp, null, propsOrChildren)
    }
  }
}

const hh = (tag: keyof ReactHTML) => (
  props?: JSX.IntrinsicElements[typeof tag] | Children,
  children?: Children
) => h(tag, props, children)

h.div = hh("div")
h.section = hh("section")
h.article = hh("article")
h.header = hh("header")
h.footer = hh("footer")
h.nav = hh("nav")
h.br = hh("br")
h.b = hh("b")
h.a = hh("a")
h.p = hh("p")
h.span = hh("span")
h.ul = hh("ul")
h.ol = hh("ol")
h.li = hh("li")
h.link = hh("link")
h.hr = hh("hr")
h.h1 = hh("h1")
h.h2 = hh("h2")
h.h3 = hh("h3")
h.h4 = hh("h4")
h.h5 = hh("h5")
h.i = hh("i")
h.b = hh("b")

h.frag = (...children: ReactNode[]) =>
  createElement(React.Fragment, null, ...children)

export default h

// Double paren version: h(elem)(props, children)

// function h(tag: keyof ReactHTML): (propsOrChildren?: JSX.IntrinsicElements[typeof tag] | Children, children?: Children) => Element
// function h
(comp: Component
): (propsOrChildren?: Props
 | Children, children?: Children) => Element
// function h
(comp: Component
): (propsOrChildren?: Children) => Element
// function h
(comp: any): (propsOrChildren?: any, children?: any) => any {
//   return function (propsOrChildren, children) {
//     const passesChildren = propsOrChildren && (Array.isArray(propsOrChildren) || typeof propsOrChildren !== "object") && !children
//     if (passesChildren) {
//       return jsx(comp, null, propsOrChildren)
//     } else {
//       return jsx(comp, propsOrChildren as P, children)
//     }
//   }
// }

// const makeElem = <Elem>(tag: keyof ReactHTML) => (
//   (props?: HTMLProps<Elem> | Children, children?: Children) => (
//     h<HTMLProps<Elem>>(tag)(props, children)
//   )
// )


text:
#pragma once
#ifndef CLEANUP_FILE_SYSTEM_BOOST_H
#define CLEANUP_FILE_SYSTEM_BOOST_H

#include <cleanup/Config.h>
#include <boost/filesystem.hpp>
#include <tbb/task.h>

CLEANUP_NAMESPACE_BEGIN

/// Boost based implementation of the FileSystem
class FileSystemBoost : tbb::task
{
    boost::filesystem::path path_;

public:
    /// Move Constructor
    FileSystemBoost(boost::filesystem::path&& curDir) : path_(curDir) {}

    /// Overrides virtual function task::execute
    tbb::task* execute() override;

    /// Analyze file system (root call)
    static void analyzeFilesystem(boost::filesystem::path root);
};

CLEANUP_NAMESPACE_END

#endif


text:
package com.github.rvesse.airline.parser.errors;

import com.github.rvesse.airline.utils.AirlineUtils;

import java.util.List;

/**
 * Exception that is thrown when a command receives unexpected arguments
 *
 */
public class ParseArgumentsUnexpectedException extends ParseRestrictionViolatedException {
    private static final long serialVersionUID = -3146629773738933406L;

    private final List<String> unparsedInput;

    public ParseArgumentsUnexpectedException(List<String> unparsedInput) {
        super("Found unexpected parameters: %s", unparsedInput);
        this.unparsedInput = AirlineUtils.unmodifiableListCopy(unparsedInput);
    }

    public List<String> getUnparsedInput() {
        return unparsedInput;
    }
}