text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
package telas;
import atributos.DetServicoEquipamento;
import atributos.Equipamento;
import funcoes.Conexao;
import funcoes.DetServicoEquipamentoDAO;
import funcoes.EquipamentoDAO;
import funcoes.TabelaZebrada;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class AdicionarDetServEquipamento extends javax.swing.JFrame {
private PreparedStatement pst;
private int idServico;
private DetalharServico telaDatalharServico;
private int codEquipamento;
private int codDetEquipamento;
private int codFabricanteEqui;
private int codModeloEqui;
private String modeloEqui;
private String fabricanteEqui;
private String equipamento;
/**
* Creates new form AdicionarDetServEquipamento
*/
public AdicionarDetServEquipamento() {
initComponents();
}
public AdicionarDetServEquipamento(int idServ, DetalharServico telaDetalharServ) {
this.idServico = idServ;
this.telaDatalharServico = telaDetalharServ;
initComponents();
ocultaTabela();
carregarComboEquipamento();
uJComboBoxEquipamento.getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
if (codEquipamento == 0 && uJComboBoxEquipamento.getSelectedIndex() != 0) {
JOptionPane.showMessageDialog(null, "Esse registro não encontra-se cadastrado na base de dados.");
uJComboBoxEquipamento.getEditor().getEditorComponent().requestFocus();
}
}
});
uJComboBoxEquipamento.setAutocompletar(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel4 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jBtnRemoveEquipamento = new javax.swing.JButton();
jBtbIncluirEquipamento = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTableEquipamento = new javax.swing.JTable();
jLabel37 = new javax.swing.JLabel();
jComboBoxModeloEquip = new javax.swing.JComboBox();
jLabel38 = new javax.swing.JLabel();
jComboBoxFabricanteEquip = new javax.swing.JComboBox();
jBtnInserirDetServEquipamento = new javax.swing.JButton();
uJComboBoxEquipamento = new componentes.UJComboBox();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jBtnCancelar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("ADICIONAR EQUIPAMENTO");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
});
jPanel4.setBackground(new java.awt.Color(223, 237, 253));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setText("Equipamento:");
jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 140, -1, -1));
jBtnRemoveEquipamento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/excluir.png"))); // NOI18N
jBtnRemoveEquipamento.setText("Remover");
jBtnRemoveEquipamento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnRemoveEquipamentoActionPerformed(evt);
}
});
jPanel4.add(jBtnRemoveEquipamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 430, 100, -1));
jBtbIncluirEquipamento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/add.png"))); // NOI18N
jBtbIncluirEquipamento.setText("Incluir Equipamento");
jBtbIncluirEquipamento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtbIncluirEquipamentoActionPerformed(evt);
}
});
jPanel4.add(jBtbIncluirEquipamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(500, 260, 150, -1));
jTableEquipamento.setBackground(new java.awt.Color(254, 254, 233));
jTableEquipamento.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Codigo", "Id modelo", "Id fabricante", "Equipamento", "Modelo", "Fabricante"
}
) {
boolean[] canEdit = new boolean [] {
false, false, true, false, false, true
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTableEquipamento.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTableEquipamento);
jPanel4.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 290, 620, 130));
jLabel37.setText("Modelo:");
jPanel4.add(jLabel37, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 180, -1, -1));
jComboBoxModeloEquip.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione o Modelo" }));
jComboBoxModeloEquip.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxModeloEquipItemStateChanged(evt);
}
});
jPanel4.add(jComboBoxModeloEquip, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 180, 320, -1));
jLabel38.setText("Fabricante:");
jPanel4.add(jLabel38, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 220, -1, -1));
jComboBoxFabricanteEquip.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione o Fabricante" }));
jComboBoxFabricanteEquip.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBoxFabricanteEquipActionPerformed(evt);
}
});
jPanel4.add(jComboBoxFabricanteEquip, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 220, 320, -1));
jBtnInserirDetServEquipamento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/salvar.png"))); // NOI18N
jBtnInserirDetServEquipamento.setText("Salvar");
jBtnInserirDetServEquipamento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnInserirDetServEquipamentoActionPerformed(evt);
}
});
jPanel4.add(jBtnInserirDetServEquipamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 490, 90, -1));
uJComboBoxEquipamento.setEditable(true);
uJComboBoxEquipamento.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
uJComboBoxEquipamentoItemStateChanged(evt);
}
});
uJComboBoxEquipamento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uJComboBoxEquipamentoActionPerformed(evt);
}
});
jPanel4.add(uJComboBoxEquipamento, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 140, 320, -1));
jLabel3.setFont(new java.awt.Font("Microsoft YaHei UI Light", 1, 24)); // NOI18N
jLabel3.setText("ADICIONAR EQUIPAMENTO");
jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/leiaute/img2.png"))); // NOI18N
jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 680, -1));
jBtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/cancelar.png"))); // NOI18N
jBtnCancelar.setText("Cancelar");
jBtnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnCancelarActionPerformed(evt);
}
});
jPanel4.add(jBtnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 490, -1, -1));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 532, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jBtnRemoveEquipamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRemoveEquipamentoActionPerformed
DefaultTableModel dtm = (DefaultTableModel) jTableEquipamento.getModel();
int linha = jTableEquipamento.getSelectedRow();
if(linha != -1) {
dtm.removeRow(linha);
}
}//GEN-LAST:event_jBtnRemoveEquipamentoActionPerformed
private void jBtbIncluirEquipamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtbIncluirEquipamentoActionPerformed
TabelaEquipamento();
}//GEN-LAST:event_jBtbIncluirEquipamentoActionPerformed
private void jComboBoxModeloEquipItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxModeloEquipItemStateChanged
jComboBoxFabricanteEquip.removeAllItems();
idModeloEquiComboBox();
populaComboBoxFabricanteEquip();
if (jComboBoxModeloEquip.getSelectedItem() != null) {
modeloEqui = jComboBoxModeloEquip.getSelectedItem().toString();
}
}//GEN-LAST:event_jComboBoxModeloEquipItemStateChanged
private void jComboBoxFabricanteEquipActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxFabricanteEquipActionPerformed
idFabricanteEquiComboBox();
if (jComboBoxFabricanteEquip.getSelectedItem() != null) {
fabricanteEqui = jComboBoxFabricanteEquip.getSelectedItem().toString();
}
}//GEN-LAST:event_jComboBoxFabricanteEquipActionPerformed
private void jBtnInserirDetServEquipamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnInserirDetServEquipamentoActionPerformed
DetServicoEquipamento dtServEqui = new DetServicoEquipamento();
for(int j=0; j < jTableEquipamento.getRowCount(); j++) {
dtServEqui.setCodServico(idServico);
dtServEqui.setCodDetEquipamento(Integer.parseInt(jTableEquipamento.getValueAt(j, 0).toString()));
DetServicoEquipamentoDAO.CadDetServEquipamento(dtServEqui);
}
telaDatalharServico.TabelaEquipamento("SELECT * FROM vw_detservequipamento where idservico = " + idServico +";");
verificaPagina();
this.dispose();
JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!");
}//GEN-LAST:event_jBtnInserirDetServEquipamentoActionPerformed
private void uJComboBoxEquipamentoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_uJComboBoxEquipamentoItemStateChanged
jComboBoxModeloEquip.removeAllItems();
jComboBoxFabricanteEquip.removeAllItems();
codModeloEqui = 0;
modeloEqui = null;
codFabricanteEqui = 0;
fabricanteEqui = null;
codEquipamento = 0;
idEquipamentoComboBox();
populaComboBoxModeloEqui();
equipamento = uJComboBoxEquipamento.getSelectedItem().toString();
}//GEN-LAST:event_uJComboBoxEquipamentoItemStateChanged
private void uJComboBoxEquipamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uJComboBoxEquipamentoActionPerformed
idEquipamentoComboBox();
if (uJComboBoxEquipamento.getSelectedItem() != null) {
equipamento = uJComboBoxEquipamento.getSelectedItem().toString();
}
}//GEN-LAST:event_uJComboBoxEquipamentoActionPerformed
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
verificaPagina();
}//GEN-LAST:event_formWindowClosed
private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelarActionPerformed
if (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja canselar? Os dados não serão salvos.", "Confirmar Cancelamento", JOptionPane.YES_NO_OPTION) == 0) {
verificaPagina();
this.dispose();
}
}//GEN-LAST:event_jBtnCancelarActionPerformed
public void TabelaEquipamento() {
codDetEquipamento = EquipamentoDAO.CodigoDetEquipamento(codEquipamento, codModeloEqui, codFabricanteEqui);
try {
DefaultTableModel dtm = (DefaultTableModel) jTableEquipamento.getModel();
dtm.addRow(new Object[] {codDetEquipamento,
codModeloEqui,
codFabricanteEqui,
equipamento,
modeloEqui,
fabricanteEqui});
TableCellRenderer renderer = new TabelaZebrada();
jTableEquipamento.setDefaultRenderer(Object.class, renderer);
} catch (Exception erro) {
Logger.getLogger(CadastrarCliente.class.getName()).log(Level.SEVERE, null, erro);
}
}
private void carregarComboEquipamento() {
// uJComboBoxEquipamento.clear();
ArrayList<Equipamento> equipamentos = new ArrayList<Equipamento>();
equipamentos = EquipamentoDAO.ListarEquipamentos();
uJComboBoxEquipamento.addItem("Selecione o equipamento");
for (Equipamento equi : equipamentos) {
uJComboBoxEquipamento.addItem(equi.getEquipamento(), equi);
}
}
private void idEquipamentoComboBox() {
Connection conexao = Conexao.getConnection();
ResultSet rs;
String sql = "select * from tabequipamento where equipamento = '" + uJComboBoxEquipamento.getSelectedItem()+ "';";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
codEquipamento = (rs.getInt("idEquipamento"));
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
private void populaComboBoxModeloEqui() {
Connection conexao = Conexao.getConnection();
ResultSet rs;
String sql = "select modelo " +
" from tabdetequipamento inner join " +
" tabequipamento inner join " +
" tabmodelo on tabmodelo_idtabModelo = idtabModelo and " +
" tabequipamento_idEquipamento = idEquipamento"
+ " where idEquipamento = " + codEquipamento + " group by modelo;";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
jComboBoxModeloEquip.addItem(rs.getString("modelo"));
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
private void idModeloEquiComboBox() {
Connection conexao = Conexao.getConnection();
ResultSet rs;
String sql = "select * from tabmodelo where modelo = '" + jComboBoxModeloEquip.getSelectedItem()+ "';";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
codModeloEqui = (rs.getInt("idtabModelo"));
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
private void populaComboBoxFabricanteEquip() {
Connection conexao = Conexao.getConnection();
ResultSet rs;
String sql = "SELECT * FROM vw_combofabricanteequipamento "
+ " WHERE idEquipamento = " + codEquipamento
+ " AND tabmodelo_idtabModelo = " + codModeloEqui + " group by fabricante;";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
jComboBoxFabricanteEquip.addItem(rs.getString("fabricante"));
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
private void idFabricanteEquiComboBox() {
Connection conexao = Conexao.getConnection();
ResultSet rs;
String sql = "select * from tabfabricante where fabricante = '" + jComboBoxFabricanteEquip.getSelectedItem()+ "';";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
codFabricanteEqui = (rs.getInt("idtabFabricante"));
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
private void ocultaTabela() {
jTableEquipamento.getColumnModel().getColumn(0).setMaxWidth(0);
jTableEquipamento.getColumnModel().getColumn(0).setMinWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0);
jTableEquipamento.getColumnModel().getColumn(1).setMaxWidth(0);
jTableEquipamento.getColumnModel().getColumn(1).setMinWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(1).setMaxWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(1).setMinWidth(0);
jTableEquipamento.getColumnModel().getColumn(2).setMaxWidth(0);
jTableEquipamento.getColumnModel().getColumn(2).setMinWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(2).setMaxWidth(0);
jTableEquipamento.getTableHeader().getColumnModel().getColumn(2).setMinWidth(0);
}
private void verificaPagina() {
if ((this.telaDatalharServico != null)) {
this.telaDatalharServico.setEnabled(true);
this.telaDatalharServico.toFront();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBtbIncluirEquipamento;
private javax.swing.JButton jBtnCancelar;
private javax.swing.JButton jBtnInserirDetServEquipamento;
private javax.swing.JButton jBtnRemoveEquipamento;
private javax.swing.JComboBox jComboBoxFabricanteEquip;
private javax.swing.JComboBox jComboBoxModeloEquip;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel38;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTableEquipamento;
private componentes.UJComboBox uJComboBoxEquipamento;
// End of variables declaration//GEN-END:variables
}
|
eb993f31f1ab4240d83cfcd8774cabcb89555818
|
{
"blob_id": "eb993f31f1ab4240d83cfcd8774cabcb89555818",
"branch_name": "refs/heads/master",
"committer_date": "2016-02-19T01:19:26",
"content_id": "8cd0461f9f2feabf78bc6210e3a302cf586844ba",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f4d66d5ffcbbfadacfbb4b2b65c5e129d989e7e4",
"extension": "java",
"filename": "AdicionarDetServEquipamento.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 51390973,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 20998,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/telas/AdicionarDetServEquipamento.java",
"provenance": "stack-edu-0023.json.gz:835216",
"repo_name": "PFC2Senai/PFC2ABatalhaFinal",
"revision_date": "2016-02-19T01:19:26",
"revision_id": "34156fff0525cec277f877892251d92400e2fdc9",
"snapshot_id": "097fa2baca5d2174a10b8aeb71afd4ff57e2e817",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PFC2Senai/PFC2ABatalhaFinal/34156fff0525cec277f877892251d92400e2fdc9/src/telas/AdicionarDetServEquipamento.java",
"visit_date": "2016-08-12T15:22:33.903475",
"added": "2024-11-19T00:42:26.925511+00:00",
"created": "2016-02-19T01:19:26",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
##Using Collections
This package uses and acknowledges the work done in the [ninsuo/symfony-collection](https://github.com/ninsuo/symfony-collection)
With the exception of instructions found below, the use of the collection package is found on [Symfony Collection jQuery Plugin](https://symfony-collection.fuz.org/symfony3/)
by [Alain Tiemblo](https://stackoverflow.com/users/731138/alain-tiemblo).
This collection strategy is defined for use with Doctrine entities, providing a sort, add and removal function within the
collection.
###Coding and Templating your Collection
####Forms
The colletion type provided by Symfony is replaced by CollectionType in the form package. An example of the form is:
```
<?php
namespace App\School\Form;
...
use Hillrange\Form\Type\CollectionType;
...
use Symfony\Component\Form\AbstractType;
...
class ExternalActivityType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
...
->add('tutors', CollectionType::class,
[
'entry_type' => ActivityTutorType::class,
'allow_add' => true,
'allow_delete' => true,
'allow_up' => true,
'allow_down' => true,
'sequence_manage' => true,
]
)
...
;
```
This is an example of the parent type, using all but the **unique_key** option, which defaults to **id**.
Calling the CollectionType add a couple of extra defaults to the options from the standard CollectionType. These are:
```
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'unique_key' => 'id',
'sort_manage' => false,
'allow_up' => false,
'allow_down' => false,
]
);
}
```
The defaults mirror some of the jquery collection options (allow_up, allow_dowm) and other are created to set the form
and code in the package.
* unique_key: Defaults to *id* which most entities use as a unique id in doctrine. You can use another unique key in
your entity by defining this option.
* sort_manage: Turn on the package sort options.
* allow_up: Allow an element to be moved up in the order.
* allow_down: Allow an element to be moved down in the order.
```
<?php
namespace App\School\Form;
use App\Core\Type\SettingChoiceType;
use App\Entity\Gibbon\Activity;
use App\Entity\Gibbon\ActivityTutor;
use App\Entity\Gibbon\Person;
use App\Entity\Gibbon\Student;
use Doctrine\ORM\EntityRepository;
use Hillrange\Form\Type\EntityType;
use Hillrange\Form\Type\HiddenEntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ActivityTutorType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('role', SettingChoiceType::class,
[
'label' => 'activity_tutor.role.label',
'help' => 'activity_tutor.role.help',
'placeholder' => 'activity_tutor.role.placeholder',
'setting_name' => 'tutor.type.list',
]
)
->add('activity', HiddenEntityType::class,
[
'class' => Activity::class,
]
)
->add('tutor', EntityType::class,
[
'class' => Person::class,
'choice_label' => 'fullName',
'label' => 'activity_tutor.tutor.label',
'help' => 'activity_tutor.tutor.help',
'placeholder' => 'activity_tutor.tutor.placeholder',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('p')
->where('p NOT INSTANCE OF :student')
->setParameter('student', Student::class)
->orderBy('p.surname')
->addOrderBy('p.firstName')
;
},
]
)
->add('sequence', HiddenType::class)
->add('id', HiddenType::class,
[
'attr' => [
'class' => 'removeElement',
],
]
)
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => ActivityTutor::class,
'translation_domain' => 'School',
]
);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'activity_tutor';
}
}
```
This is a full code base for the child form. Note the BlockPrefix.
####Templates and Controllers
The templates will first need to load the jquery files, and create an initial ajax call for the collection content. This
is done by ensuring that the following files are loaded as part of the page load.
* @HillrangeForm/FormTheme/jquery.collection.html.twig in the form_theme
* A form_theme you create for the collection element. in this case School/activity_tutor.html.twig
* @HillrangeForm/Script/collection_message.html.twig somewhere on the page content.
* @HillrangeForm/Script/jquery_collection.html.twig in the scripts
* A call to the manageCollection method for your collection. This should only be done once the document is ready.
```
...
{% form_theme form
<EMAIL_ADDRESS><EMAIL_ADDRESS> 'School/activity_tutor.html.twig'
%}
...
{% block contentContainer %}
{{ form_start(form, {attr: {id: 'saveForm'}}) }}
{% include<EMAIL_ADDRESS>%}
... // Ordinary form stuff
{% include 'external_activity_tutors.html.twig' %}
{{ form_end(form) }}
{% endblock contentContainer %}
{% block javascripts %}
{{ parent() }}
{% include<EMAIL_ADDRESS>%}
<script>
$(document).ready(function(){
var path = '{{ path('external_activity_tutor_manage', {id: app.request.get('id'), cid: 'ignore'}) }}';
var target = 'tutorCollection';
manageCollection(path, target, '');
});
</script>
{% endblock %}
```
The management of the collection relies on ajax calls, so the manageCollection jquery method will require a valid route,
as per the next code example for the controller. How the controller manages the removal of the the element is up to the
programmer. The removeTutor method in the activityManager handles this logic here, and sets details on status and
messaging. The jquery call always returns false, to stop the removal of the element by the jquery script, and allow
server processing and content update.
This response is ONLY for the collection element of the form, and in this case is passsed to the render as collection,
not form.
```
/**
* @param string $id
* @param string $cid
* @param ActivityManager $activityManager
* @return JsonResponse
* @Route("/school/activity/external/{id}/tutor/{cid}/manage/", name="external_activity_tutor_manage")
* @IsGranted("ROLE_PRINCIPAL")
*/
public function externalActivityTutorManage($id = 'Add', $cid = 'ignore', ActivityManager $activityManager, \Twig_Environment $twig)
{
//if cid != ignore, then remove cid from collection
$activity = $activityManager->setActivityType('external')->findActivity($id);
if (intval($cid) > 0)
$activityManager->removeTutor($cid);
$form = $this->createForm(ExternalActivityType::class, $activity);
return new JsonResponse(
[
'content' => $this->renderView("School/external_activity_collection.html.twig",
[
'collection' => $form->get('tutors')->createView(),
'route' => 'external_activity_tutor_manage',
'contentTarget' => 'tutorCollection',
]
),
'message' => $activityManager->getMessageManager()->renderView($twig),
'status' => $activityManager->getStatus(),
],
200
);
}
```
The response is return with the content generated by the followinf example. You must add the @HillrangeForm/Script/initiate_collection.html.twig
as an include to refresh the bind on the collection javascript.
```
{% form_theme collection
<EMAIL_ADDRESS><EMAIL_ADDRESS> 'School/activity_tutor.html.twig'
%}
{{ form_widget(collection) }}
{% include<EMAIL_ADDRESS>%}
```
and the element form theme, build by you to capture the element form (activity_tutor) details and render. (The template
uses a lot of addition features of the form package that are documented elsewhere.)
```
{% trans_default_domain "School" %}
{% block activity_tutor_label %}{% endblock %}
{% block activity_tutor_errors %}{% endblock %}
{% block activity_tutor_widget %}
{% spaceless %}
{% set h3Content = '<div class="collection-actions">' %}
{% set h3Content = h3Content ~ saveButton() %}
{% set h3Content = h3Content ~ deleteButton({title: 'activity.activity_tutor.remove.title', transDomain: 'Calendar', mergeClass: 'collection-remove collection-action'}) %}
{% set h3Content = h3Content ~ '<span style="float: right;"> </span>' %}
{% set h3Content = h3Content ~ upDownButton() %}
{% set h3Content = h3Content ~ '</div>' %}
<div class="container-fluid">
<div class="row">
<div class="col-5 card">
{{ form_widget(form.tutor, {value: transformData(form.tutor.vars)}) }}
{{ form_row(form.activity, {value: app.request.get('id')}) }}
{{ form_row(form.sequence) }}
</div>
<div class="col-3 card">
{{ form_widget(form.role) }}
</div>
<div class="col-4 card">
{{ h3Content|raw }}
{{ form_row(form.id) }}
</div>
</div>
</div>
{% endspaceless %}
{% endblock activity_tutor_widget %}
```
**NB:** The *sequence* and the *id* (as per the *unique_key*) MUST be set in this form. They are created by a listener
if you did not include them in your child element form. The deleteButton uses the before_remove of the jquery
collection to correctly call the manageCollection. The before_remove method of the calculates the child element
identifier to delete. **cid** Your controller must accept a **cid** value in the route, as the script assumes and sets
this value. A value of ignore is placed into the cid if the element is empty.
```
<!-- Initiate Collection -->
<script type="text/javascript" language="JavaScript">
$(".{{ collection.vars.id }}").collection({
name_prefix: '{{ collection.vars.full_name }}',
allow_up: {% if collection.vars.allow_up %}true{% else %}false{% endif %},
allow_down: {% if collection.vars.allow_down %}true{% else %}false{% endif %},
add: '{{ addButton({transDomain: collection.vars.translation_domain, title: collection.vars.id ~ '.add.title'})|raw }}',
remove: '{{ deleteButton({transDomain: collection.vars.translation_domain, title: collection.vars.id ~ '.remove.title', colour: 'warning'})|raw }}',
add_at_the_end: true,
before_remove: function (collection, element) {
var path = '{{ path(route, {id: app.request.get('id'), cid: '__cid__'}) }}';
if (element === '')
path = path.replace('__cid__', 'ignore');
var target = '{{ contentTarget }}';
manageCollection(path, target, element);
return false;
}
});
</script>
```
####Display the Collection

####Remove Element

|
6843ee9168da71b42cc7a3161ba21dba8bb98d73
|
{
"blob_id": "6843ee9168da71b42cc7a3161ba21dba8bb98d73",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-18T04:55:25",
"content_id": "13b5dda4eaaff6320ec51cfcfde374c31ec0a87c",
"detected_licenses": [
"MIT"
],
"directory_id": "b81346242b478942725fd5684e3534c11593515d",
"extension": "md",
"filename": "collection.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 120355377,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 12490,
"license": "MIT",
"license_type": "permissive",
"path": "/Resources/doc/collection.md",
"provenance": "stack-edu-markdown-0011.json.gz:169852",
"repo_name": "crayner/symfony-form",
"revision_date": "2019-05-18T04:55:25",
"revision_id": "9fb2c200b8ee9e9180cf81456afbfb8ba87757de",
"snapshot_id": "102131d9c10b5faf3ec222d62ffebd5f422421c9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/crayner/symfony-form/9fb2c200b8ee9e9180cf81456afbfb8ba87757de/Resources/doc/collection.md",
"visit_date": "2021-05-04T00:54:40.870314",
"added": "2024-11-18T23:07:50.419566+00:00",
"created": "2019-05-18T04:55:25",
"int_score": 4,
"score": 3.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0011.json.gz"
}
|
//
// PieChartProtocolExtentions.swift
//
//
// Created by Will Dale on 23/02/2021.
//
import SwiftUI
// MARK: - Extentions
extension CTPieDoughnutChartDataProtocol where Set == PieDataSet, DataPoint == PieChartDataPoint {
/**
Sets up the data points in a way that can be sent to renderer for drawing.
It configures each data point with startAngle and amount variables in radians.
*/
internal func makeDataPoints() {
let total = self.dataSets.dataPoints.reduce(0) { $0 + $1.value }
var startAngle = -Double.pi / 2
self.dataSets.dataPoints.indices.forEach { (point) in
let amount = .pi * 2 * (self.dataSets.dataPoints[point].value / total)
self.dataSets.dataPoints[point].amount = amount
self.dataSets.dataPoints[point].startAngle = startAngle
startAngle += amount
}
}
/**
Gets the number of degrees around the chart from 'north'.
# Reference
[Atan2](http://www.cplusplus.com/reference/cmath/atan2/)
[Rotate to north](https://stackoverflow.com/a/25398191)
- Parameters:
- touchLocation: Current location of the touch.
- rect: The size of the chart view as the parent view.
- Returns: Degrees around the chart.
*/
func degree(from touchLocation: CGPoint, in rect: CGRect) -> CGFloat {
let center = CGPoint(x: rect.midX, y: rect.midY)
let coordinates = CGPoint(x: touchLocation.x - center.x,
y: touchLocation.y - center.y)
// -90 is north
let degrees = atan2(-coordinates.x, -coordinates.y) * CGFloat(180 / Double.pi)
if (degrees > 0) {
return 270 - degrees
} else {
return -90 - degrees
}
}
}
extension CTPieDoughnutChartDataProtocol where Self.Set.DataPoint.ID == UUID,
Self.Set: CTSingleDataSetProtocol,
Self.Set.DataPoint: CTPieDataPoint {
internal func setupLegends() {
for data in dataSets.dataPoints {
if let legend = data.description {
self.legends.append(LegendData(id : data.id,
legend : legend,
colour : ColourStyle(colour: data.colour),
strokeStyle: nil,
prioity : 1,
chartType : .pie))
}
}
}
}
|
32c807bd88f6a71e3331f09f89c2786d648cf1d5
|
{
"blob_id": "32c807bd88f6a71e3331f09f89c2786d648cf1d5",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-29T21:05:15",
"content_id": "6e95257718f63737d61669f724e0458cea56d964",
"detected_licenses": [
"MIT"
],
"directory_id": "ded5b2a823d6e0b0af97e758fb46490a86d2e675",
"extension": "swift",
"filename": "PieChartProtocolsExtentions.swift",
"fork_events_count": 0,
"gha_created_at": "2021-03-29T20:26:59",
"gha_event_created_at": "2021-03-29T20:27:00",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 352775561,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 2647,
"license": "MIT",
"license_type": "permissive",
"path": "/Sources/SwiftUICharts/PieChart/Models/Protocols/PieChartProtocolsExtentions.swift",
"provenance": "stack-edu-0071.json.gz:382813",
"repo_name": "xremix/SwiftUICharts",
"revision_date": "2021-03-29T21:05:15",
"revision_id": "068f13afaa235c5f2336f34a6e9783535c84bbc1",
"snapshot_id": "5eaf815e937a4d440fd7f68197e9183eb1e9c209",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/xremix/SwiftUICharts/068f13afaa235c5f2336f34a6e9783535c84bbc1/Sources/SwiftUICharts/PieChart/Models/Protocols/PieChartProtocolsExtentions.swift",
"visit_date": "2023-03-15T10:14:47.327514",
"added": "2024-11-18T20:58:02.496637+00:00",
"created": "2021-03-29T21:05:15",
"int_score": 3,
"score": 3.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz"
}
|
package es.androidesverdesfritos.seguridad;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import es.androidesverdesfritos.seguridad.seguridad.Seguridad;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.firma_uno)).setText(Seguridad.getAppSignatureB(getApplicationContext()));
((TextView) findViewById(R.id.firma_larga)).setText(Seguridad.getAppSignatureA(getApplicationContext()));
}
}
|
dfcbffc6620719882a7d0c418b0d32a39e7ea500
|
{
"blob_id": "dfcbffc6620719882a7d0c418b0d32a39e7ea500",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-01T13:47:55",
"content_id": "827ed462e913bc1d563b76da0eafe32af2edfeb7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2052cb332a76ddb5f80eea67015132d2136f9773",
"extension": "java",
"filename": "MainActivity.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38373022,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 607,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/es/androidesverdesfritos/seguridad/MainActivity.java",
"provenance": "stack-edu-0031.json.gz:358674",
"repo_name": "androidesverdesfritos/SeguridadFirma",
"revision_date": "2015-07-01T13:47:55",
"revision_id": "8ba773c4621349e74d99f5a80db8c5b7cf76df85",
"snapshot_id": "a867d6ea146c5c4117ef04115c9f14eafd90ad9e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/androidesverdesfritos/SeguridadFirma/8ba773c4621349e74d99f5a80db8c5b7cf76df85/app/src/main/java/es/androidesverdesfritos/seguridad/MainActivity.java",
"visit_date": "2016-09-05T15:57:45.494949",
"added": "2024-11-18T21:30:19.791279+00:00",
"created": "2015-07-01T13:47:55",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
package com.gitenter.gitar;
import java.io.File;
import lombok.Getter;
public abstract class GitHistoricalPath implements GitPath {
@Getter
protected final String relativePath;
final GitCommit commit;
protected GitHistoricalPath(GitCommit commit, String relativePath) {
this.commit = commit;
this.relativePath = relativePath;
}
@Override
public String getName() {
/*
* Since what is provided is relative path rather than absolute
* path (but Java File is for absolute path), I don't know if
* there is a better way to do it.
*/
return new File(relativePath).getName();
}
}
|
15fba911dfe75455e02c09697ac867dbeae0ab38
|
{
"blob_id": "15fba911dfe75455e02c09697ac867dbeae0ab38",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-30T22:33:01",
"content_id": "e353f68bd7362ef4444f4c6c0d7e05a50d26df94",
"detected_licenses": [],
"directory_id": "11357fc026f7f0e55c82039120bb2814644b7667",
"extension": "java",
"filename": "GitHistoricalPath.java",
"fork_events_count": 0,
"gha_created_at": "2018-06-15T23:49:09",
"gha_event_created_at": "2021-04-26T17:55:52",
"gha_language": "Java",
"gha_license_id": "BSD-3-Clause",
"github_id": 137540681,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 610,
"license": "",
"license_type": "permissive",
"path": "/src/main/java/com/gitenter/gitar/GitHistoricalPath.java",
"provenance": "stack-edu-0024.json.gz:854669",
"repo_name": "gitenter/gitar",
"revision_date": "2019-10-30T22:33:01",
"revision_id": "67862be750a105f1b4a416c506e58ceedce85bc0",
"snapshot_id": "37e350a1d510e145f5bff3e70bcc3127d1b7ec62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gitenter/gitar/67862be750a105f1b4a416c506e58ceedce85bc0/src/main/java/com/gitenter/gitar/GitHistoricalPath.java",
"visit_date": "2021-06-06T00:55:19.078857",
"added": "2024-11-19T00:30:12.518330+00:00",
"created": "2019-10-30T22:33:01",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
#!/usr/bin/env python
#
# Lists all interfaces of all VMs run by a particular
# project. The project name can be provided as a paramater.
# If none is provided, all projects are listed.
#
# The tap interfaces can then be used to do a traffic
# capture locally using tcpdump
#
# v0.4 20-Jan-2016
# - added capability to select columns from table
# v0.3 02-Dec-2015
# - changed regex to work with webeditor topologies (w/o 6-digit random id)
# - added IP column for non-infrastructure ports
# - changed 'user' to 'project' because it is
# v0.2 02-Dec-2015
# adapted to Kilo release
# v0.1 24-Nov-2014
# initial release
#
# rschmied@cisco.com
#
import sys, re, os, prettytable, argparse
from neutronclient.v2_0 import client
from operator import itemgetter
# </guest/endpoint>-<triangle-ghU06c>-<iosv-2>-<guest>
# </guest/endpoint>-<trunk>-<lxc-2>-<iosvl2-1-to-lxc-2>
# </guest/endpoint>-<triangle-ghU06c>-<~mgmt-lxc>-<~lxc-flat>
# </guest/endpoint>-<jjj>-<~mgmt-lxc>-<~lxc-flat>
# </guest/endpoint>-<testAA-u6dRq3>-<lxc-1>-<guest>
def hyphen_range(s):
""" yield each integer from a complex range string like "1-9,12, 15-20,23"
http://code.activestate.com/recipes/577279-generate-list-of-numbers-from-hyphenated-and-comma/
>>> list(hyphen_range('1-9,12, 15-20,23'))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 19, 20, 23]
>>> list(hyphen_range('1-9,12, 15-20,2-3-4'))
Traceback (most recent call last):
...
ValueError: format error in 2-3-4
"""
for x in s.split(','):
elem = x.split('-')
if len(elem) == 1: # a number
yield int(elem[0])
elif len(elem) == 2: # a range inclusive
start, end = map(int, elem)
for i in xrange(start, end+1):
yield i
else: # more than one hyphen
raise ValueError('format error in %s' % x)
def list_taps(project, fields):
out = {}
nc = client.Client(username=os.environ['OS_USERNAME'], password=os.environ['OS_PASSWORD'],
tenant_name=os.environ['OS_TENANT_NAME'], auth_url=os.environ['OS_SERVICE_ENDPOINT'])
prog = re.compile(r'</('+project+')/endpoint>-<(.*)(?:-\w{6})?>-<(.*)>-<(.*)>')
ports = nc.list_ports()
for thisport in ports['ports']:
m = prog.match(thisport['name'])
if m:
project, topo, node, connection = m.group(1), m.group(2), m.group(3), m.group(4)
if not project in out:
out[project] = {}
if not topo in out[project]:
out[project][topo] = []
if connection == project:
tmp = 'Management Network'
else:
tmp = connection
ip = thisport['fixed_ips'][0]['ip_address']
if ip in ['10.255.255.1', '10.255.255.2']:
ip = ''
out[project][topo].append({'id': thisport['id'],
'from': node, 'to': tmp, 'mac': thisport['mac_address'], 'ip': ip})
pt = prettytable.PrettyTable(["Project", "Topology", "Node", "Link", "Interface", "MAC Address", "IP Address"])
pt.align = "l"
for project in out:
projectname = project
for topo in out[project]:
toponame = topo
out[project][topo].sort(key=itemgetter('from'))
for port in out[project][topo]:
pt.add_row([projectname, toponame, port['from'],
port['to'], "tap" + port['id'][0:11], port['mac'], port['ip']])
if len(toponame) > 0:
toponame = ""
projectname = ""
columns = pt.field_names
if fields:
columns = []
for i in list(hyphen_range(fields)):
columns.append(pt.field_names[i-1])
print pt.get_string(fields = columns)
return 0
def main():
parser = argparse.ArgumentParser()
parser.add_argument('project', default = '.*', nargs = '?',
help = "project name to list, all projects if ommited")
parser.add_argument('--columns', '-c',
help = "list of column numbers to print. like 1,2,4-7")
args = parser.parse_args()
return list_taps(args.project, args.columns)
if __name__ == '__main__':
sys.exit(main())
|
3b022675e46f3247ee09f67fe8826502de920e25
|
{
"blob_id": "3b022675e46f3247ee09f67fe8826502de920e25",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-15T15:52:34",
"content_id": "3a0c566ecd27a3a5e30e599d375abac685e0e07e",
"detected_licenses": [
"ISC"
],
"directory_id": "989c9130ec53242b8fa8d708b9662117a35e3860",
"extension": "py",
"filename": "list.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 48920777,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3937,
"license": "ISC",
"license_type": "permissive",
"path": "/virl-utils/list.py",
"provenance": "stack-edu-0060.json.gz:625644",
"repo_name": "rlaneyjr/VIRL_Projects",
"revision_date": "2020-03-15T15:52:34",
"revision_id": "547c36d3c323bcf539ec7a8a2bebcd30b77918cd",
"snapshot_id": "42fd9cb799f889e47fecc6744c86ffe08704d45d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rlaneyjr/VIRL_Projects/547c36d3c323bcf539ec7a8a2bebcd30b77918cd/virl-utils/list.py",
"visit_date": "2021-09-24T02:20:02.856449",
"added": "2024-11-19T01:21:39.461155+00:00",
"created": "2020-03-15T15:52:34",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
import {
FunctionSignatureAst,
IdentifierAst,
LambdaExpressionAst,
ValueSignatureAst,
createFunctionSignature,
createIdentifier,
createLambdaExpression,
createValueSignature,
foldTypeDeclaration,
TypeDeclarationAst,
} from "@/compiler/AST"
describe("Parser", () => {
describe("AST", () => {
describe("createIdentifier", () => {
it("returns an identifier ast", () => {
const ast = createIdentifier("number")
expect(ast).toEqual<IdentifierAst>({
text: "number",
type: "Identifier",
})
})
})
describe("createLambdaExpression", () => {
it("returns a lambda expression ast", () => {
const generics = [createIdentifier("a")]
const parameters = [createIdentifier("a"), createIdentifier("a")]
const result = createIdentifier("a")
const ast = createLambdaExpression(generics, parameters, result)
expect(ast).toEqual<LambdaExpressionAst>({
generics,
parameters,
result,
type: "LambdaExpression",
})
})
})
describe("createValueSignature", () => {
it("returns a value signature ast", () => {
const name = createIdentifier("count")
const value = createIdentifier("number")
const ast = createValueSignature(name, value)
expect(ast).toEqual<ValueSignatureAst>({
name,
type: "ValueSignature",
value,
})
})
})
describe("createFunctionSignature", () => {
it("returns a function signature ast", () => {
const name = createIdentifier("concat")
const generics = [createIdentifier("a")]
const parameters = [createIdentifier("a"), createIdentifier("a")]
const result = createIdentifier("a")
const body = createLambdaExpression(generics, parameters, result)
const ast = createFunctionSignature(name, body)
expect(ast).toEqual<FunctionSignatureAst>({
body,
name,
type: "FunctionSignature",
})
})
})
describe("foldTypeDeclaration", () => {
it("folds a function signature", () => {
const name = createIdentifier("concat")
const generics = [createIdentifier("a")]
const parameters = [createIdentifier("a"), createIdentifier("a")]
const result = createIdentifier("a")
const body = createLambdaExpression(generics, parameters, result)
const functionSignature = createFunctionSignature(name, body) as TypeDeclarationAst
const fold = foldTypeDeclaration({
Function: () => "This is a function!",
Value: () => "This is a value!",
})
expect(fold(functionSignature)).toBe("This is a function!")
})
it("folds a value signature", () => {
const name = createIdentifier("count")
const value = createIdentifier("number")
const valueSignature = createValueSignature(name, value) as TypeDeclarationAst
const fold = foldTypeDeclaration({
Function: () => "This is a function!",
Value: () => "This is a value!",
})
expect(fold(valueSignature)).toBe("This is a value!")
})
})
})
})
|
375c057e8502f9112d4f20e686d40ca0f0a01f80
|
{
"blob_id": "375c057e8502f9112d4f20e686d40ca0f0a01f80",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-01T18:12:52",
"content_id": "f8906f8e27715dfcb0d55c5cd62fa49be607f165",
"detected_licenses": [
"MIT"
],
"directory_id": "58cda9bf6716a42ccb62fede0b1404fd0580ea01",
"extension": "ts",
"filename": "AST.test.ts",
"fork_events_count": 0,
"gha_created_at": "2021-03-30T10:25:39",
"gha_event_created_at": "2021-04-01T18:00:29",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 352959885,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 3233,
"license": "MIT",
"license_type": "permissive",
"path": "/test/compiler/AST.test.ts",
"provenance": "stack-edu-0073.json.gz:556564",
"repo_name": "anthonypenna/hindley-milner-ts",
"revision_date": "2021-04-01T18:00:28",
"revision_id": "429108dd53631cffd9483a57e2c444462b736174",
"snapshot_id": "333ca06157071b8720e3d5b1ce7849af400a0ec1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/anthonypenna/hindley-milner-ts/429108dd53631cffd9483a57e2c444462b736174/test/compiler/AST.test.ts",
"visit_date": "2023-03-28T11:40:41.505067",
"added": "2024-11-19T02:23:46.193319+00:00",
"created": "2021-04-01T18:00:28",
"int_score": 3,
"score": 3.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
package com.ajjpj.acollections.mutable;
import com.ajjpj.acollections.AEntryIteratorTests;
import com.ajjpj.acollections.AIterator;
import com.ajjpj.acollections.AMap;
import java.util.Map;
public class AMutableMapWrapperIteratorTest implements AEntryIteratorTests {
@Override public AIterator<Map.Entry<Integer, Integer>> mkIterator (Integer... values) {
final AMap<Integer,Integer> result = AMutableMapWrapper.empty();
for (int v: values) result.put(v, 2*v+1);
return result.iterator();
}
}
|
9859f5906e2bea134f5a6bcbacaf0c6d47a7a39d
|
{
"blob_id": "9859f5906e2bea134f5a6bcbacaf0c6d47a7a39d",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-25T12:53:37",
"content_id": "aa3a84668f7928fd8190459e34d2a738a0eabdf7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "00aff9bcd320525420ca1067a8710345abae5fcf",
"extension": "java",
"filename": "AMutableMapWrapperIteratorTest.java",
"fork_events_count": 1,
"gha_created_at": "2018-10-11T16:00:18",
"gha_event_created_at": "2020-07-13T18:05:28",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 152618899,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 529,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/a-collections/src/test/java/com/ajjpj/acollections/mutable/AMutableMapWrapperIteratorTest.java",
"provenance": "stack-edu-0023.json.gz:285582",
"repo_name": "arnohaase/a-collections",
"revision_date": "2019-01-25T12:53:37",
"revision_id": "dde6c90468b47daa7b9ca4f9d92c0e90b8d7bedc",
"snapshot_id": "864851d52d7e3037078fa02ae13ff66f17379080",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/arnohaase/a-collections/dde6c90468b47daa7b9ca4f9d92c0e90b8d7bedc/a-collections/src/test/java/com/ajjpj/acollections/mutable/AMutableMapWrapperIteratorTest.java",
"visit_date": "2021-07-04T21:13:48.156605",
"added": "2024-11-18T23:12:51.550791+00:00",
"created": "2019-01-25T12:53:37",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { map } from 'lodash';
import SingleEntry from './SingleEntry';
let Entries = ({ entries }) => (
<span>
{ map(entries, entry =>
<SingleEntry title={entry.title} key={`${entry.title}_id`} content={entry.content} />
)}
</span>
);
Entries.propTypes = {
entries: PropTypes.array.isRequired,
};
const mapStateToProps = (state) => ({
entries: state.entities.posts.entries,
});
Entries = connect(mapStateToProps)(Entries);
export default Entries;
|
dc3459b2b427dbb051baed5fddcf70517353c58c
|
{
"blob_id": "dc3459b2b427dbb051baed5fddcf70517353c58c",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-21T19:53:02",
"content_id": "74bec479fb18af3c2a4297b984315a23c04f44f8",
"detected_licenses": [
"MIT"
],
"directory_id": "9461ce4db9f5fbcfbb5326b38b5980d20e2a49c4",
"extension": "js",
"filename": "Entries.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 556,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/views/Entries/Entries.js",
"provenance": "stack-edu-0037.json.gz:56007",
"repo_name": "elstr/react-redux-blog-seed",
"revision_date": "2016-09-21T19:53:02",
"revision_id": "a90231a7b0c250def986ec6330968a0217098627",
"snapshot_id": "e65e6a46b18b919995790dc5ad46627ccb2480c3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/elstr/react-redux-blog-seed/a90231a7b0c250def986ec6330968a0217098627/src/components/views/Entries/Entries.js",
"visit_date": "2020-03-07T07:47:05.825673",
"added": "2024-11-18T23:52:04.714275+00:00",
"created": "2016-09-21T19:53:02",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz"
}
|
package main
import (
"fmt"
"time"
)
type TaskA struct {
}
func (Task *TaskA) Init() bool {
fmt.Printf("TaskA Init\n")
return true
}
func (Task *TaskA) GetInitTimeout() int {
return 10
}
func (Task *TaskA) Work() int {
fmt.Printf("woker A Start : current time is %s\n", time.Now().UTC())
time.Sleep(time.Duration(10) * time.Second)
fmt.Printf("woker A End : current time is %s\n", time.Now().UTC())
return 10
}
|
1e8c66fe84d27ab581de2623fdc1f582c10b25ee
|
{
"blob_id": "1e8c66fe84d27ab581de2623fdc1f582c10b25ee",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-26T15:09:09",
"content_id": "9dbbbaabd6132bab1850ba1c38ef72c77bdf46ef",
"detected_licenses": [
"MIT"
],
"directory_id": "ed94984b0207a64f82f5e8551703778185d010d9",
"extension": "go",
"filename": "TaskA.go",
"fork_events_count": 0,
"gha_created_at": "2019-02-19T13:15:18",
"gha_event_created_at": "2023-03-12T13:28:38",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 171476378,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 427,
"license": "MIT",
"license_type": "permissive",
"path": "/Program/GO/signaltest/TaskA.go",
"provenance": "stack-edu-0015.json.gz:545080",
"repo_name": "gavinshark/stayHungryStayFoolish",
"revision_date": "2023-03-26T15:09:09",
"revision_id": "160556d6e22bbc5430999b94c68c32c7571e371e",
"snapshot_id": "b835e7a619ee6df97d7bdb75962ef22fca869bb2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gavinshark/stayHungryStayFoolish/160556d6e22bbc5430999b94c68c32c7571e371e/Program/GO/signaltest/TaskA.go",
"visit_date": "2023-03-31T13:42:11.748852",
"added": "2024-11-18T23:07:05.576904+00:00",
"created": "2023-03-26T15:09:09",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
from tkinter import *
from tkinter.ttk import *
import uPyExplorer.Terminal
import uPyExplorer.MicroPyTree
import uPyExplorer.UnixPyTree
class Screen(Frame):
def __init__(self, master, replCon,option, kw=None):
super().__init__(master, kw=kw)
self.option=option
self.replCon=replCon
self.master=master
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
# self.rowconfigure(0, weight=1)
self.rowconfigure(1, weight=2)
self.rowconfigure(3, weight=2)
self.terminal = uPyExplorer.Terminal.Terminal(self, replCon)
self.terminal.grid(row=3, column=0, sticky="NSEW", columnspan=2, padx=5, pady=5)
self.unixTree = uPyExplorer.UnixPyTree.UnixPyTree(self,replCon,self.option,self.terminal)
self.unixTree.grid(row=1, column=0, columnspan=1,sticky="NSEW", padx=5)
self.tree = uPyExplorer.MicroPyTree.MicroPyTree(self, self.replCon)
self.tree.grid(row=1, column=1, sticky="NSEW",columnspan=1, padx=5)
self.tree.setOtherTree(self.unixTree)
self.unixTree.setOtherTree(self.tree)
self.unixTree.frame.grid(row=0, sticky="W",column=0, padx=5)
self.tree.frame.grid(row=0, sticky="W",column=1, padx=5)
def focusIn(self):
self.terminal.startSerialRead()
self.unixTree.getPlatform()
self.tree.getPlatform()
def focusOut(self):
self.terminal.stopSerialRead()
|
aa38740179a9a7998882f7182bea7e9ee88ec83b
|
{
"blob_id": "aa38740179a9a7998882f7182bea7e9ee88ec83b",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-20T07:01:30",
"content_id": "8a2ff891f5f7cede2cf59c4f270d65c58fdfdc9e",
"detected_licenses": [
"MIT"
],
"directory_id": "5f7d64a5491cce2d8f0c65377171c0ee5ceae89e",
"extension": "py",
"filename": "Screen.py",
"fork_events_count": 1,
"gha_created_at": "2020-03-11T10:18:22",
"gha_event_created_at": "2020-03-11T10:18:23",
"gha_language": null,
"gha_license_id": null,
"github_id": 246539502,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1495,
"license": "MIT",
"license_type": "permissive",
"path": "/uPyExplorer/Screen.py",
"provenance": "stack-edu-0062.json.gz:612222",
"repo_name": "youxinweizhi/uPyExplorer",
"revision_date": "2022-02-20T07:01:30",
"revision_id": "539ea9834a40dcd3297f3abf567303f84bb2a938",
"snapshot_id": "e08f6b2df859873ac9c0cd0007333e755055cafd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/youxinweizhi/uPyExplorer/539ea9834a40dcd3297f3abf567303f84bb2a938/uPyExplorer/Screen.py",
"visit_date": "2022-07-10T16:07:04.608995",
"added": "2024-11-18T22:54:57.489956+00:00",
"created": "2022-02-20T07:01:30",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
<?php
declare(strict_types=1);
namespace NiR\GhDashboard\Behat\ApiExtension\Context;
use Http\Client\HttpClient;
use Http\Message\RequestFactory;
trait HttpClientAwareTrait
{
/** @var HttpClient|null */
private $client;
/** @var string|null */
private $baseUrl;
/** @var RequestFactory */
private $requestFactory;
public function setClient(HttpClient $client)
{
$this->client = $client;
}
public function setBaseUrl(string $baseUrl)
{
$this->baseUrl = $baseUrl;
}
public function setRequestFactory(RequestFactory $factory)
{
$this->requestFactory = $factory;
}
}
|
ea9050bc55c932d1203ba4c11fd5e91f0a49423f
|
{
"blob_id": "ea9050bc55c932d1203ba4c11fd5e91f0a49423f",
"branch_name": "refs/heads/master",
"committer_date": "2017-06-20T00:11:21",
"content_id": "107c0eaa860c1abb97d00541cb8e9a0f5741d85e",
"detected_licenses": [
"MIT"
],
"directory_id": "254d731e92139cc182847c95560180805fb57dec",
"extension": "php",
"filename": "HttpClientAwareTrait.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 656,
"license": "MIT",
"license_type": "permissive",
"path": "/features/ApiExtension/Context/HttpClientAwareTrait.php",
"provenance": "stack-edu-0053.json.gz:843898",
"repo_name": "akerouanton/github-dashboard",
"revision_date": "2017-06-20T00:03:52",
"revision_id": "cae6f140f411b01d19d296ec9ab4fc782fc271b6",
"snapshot_id": "aaf4b5a99191a895eaaf97f0c6527c3da5ceb34f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/akerouanton/github-dashboard/cae6f140f411b01d19d296ec9ab4fc782fc271b6/features/ApiExtension/Context/HttpClientAwareTrait.php",
"visit_date": "2021-06-17T18:57:46.491999",
"added": "2024-11-18T23:10:29.066827+00:00",
"created": "2017-06-20T00:03:52",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz"
}
|
# -*- coding: utf-8 -*-
from unittest import TestCase
import numpy as np
from sklearn.neural_network.multilayer_perceptron import MLPClassifier
from tests.estimator.classifier.Classifier import Classifier
from tests.language.JavaScript import JavaScript
class MLPClassifierJSTest(JavaScript, Classifier, TestCase):
def setUp(self):
super(MLPClassifierJSTest, self).setUp()
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=15,
max_iter=500, alpha=1e-4,
solver='sgd', tol=1e-4,
learning_rate_init=.1,
random_state=1, )
def tearDown(self):
super(MLPClassifierJSTest, self).tearDown()
def test_activation_fn_relu(self):
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_relu_w_mult_layers(self):
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_relu_w_binary_data(self):
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_relu_w_mult_layers_w_binary_data(self):
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_identity(self):
self.estimator = MLPClassifier(activation='identity',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_identity_w_mult_layers(self):
self.estimator = MLPClassifier(activation='identity',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_identity_w_binary_data(self):
self.estimator = MLPClassifier(activation='identity',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_identity_w_mult_layers_w_binary_data(self):
self.estimator = MLPClassifier(activation='identity',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_tanh(self):
self.estimator = MLPClassifier(activation='tanh',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_tanh_w_mult_layers(self):
self.estimator = MLPClassifier(activation='tanh',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_tanh_w_binary_data(self):
self.estimator = MLPClassifier(activation='tanh',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_tanh_w_mult_layers_w_binary_data(self):
self.estimator = MLPClassifier(activation='tanh',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_logistic(self):
self.estimator = MLPClassifier(activation='logistic',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_logistic_w_mult_layers(self):
self.estimator = MLPClassifier(activation='logistic',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_iris_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_logistic_w_binary_data(self):
self.estimator = MLPClassifier(activation='logistic',
hidden_layer_sizes=15,
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_logistic_w_mult_layers_w_binary_data(self):
self.estimator = MLPClassifier(activation='logistic',
hidden_layer_sizes=[15, 5],
learning_rate_init=.1)
self.load_binary_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_relu_w_multi_layers_w_image_data(self):
self.estimator = MLPClassifier(activation='relu',
hidden_layer_sizes=[15, 10, 5],
learning_rate_init=.1)
self.load_digits_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_tanh_w_multi_layers_w_image_data(self):
self.estimator = MLPClassifier(activation='tanh',
hidden_layer_sizes=[15, 10, 5],
learning_rate_init=.1)
self.load_digits_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_logistic_w_multi_layers_w_image_data(self):
self.estimator = MLPClassifier(activation='logistic',
hidden_layer_sizes=[15, 10, 5],
learning_rate_init=.1)
self.load_digits_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
def test_activation_fn_identity_w_multi_layers_w_image_data(self):
self.estimator = MLPClassifier(activation='identity',
hidden_layer_sizes=[15, 10, 5],
learning_rate_init=.1)
self.load_digits_data()
self._port_estimator()
amin = np.amin(self.X, axis=0)
amax = np.amax(self.X, axis=0)
preds, ground_truth = [], []
for _ in range(self.N_RANDOM_FEATURE_SETS):
x = np.random.uniform(amin, amax, self.n_features)
preds.append(self.pred_in_custom(x))
ground_truth.append(self.pred_in_py(x))
self._clear_estimator()
# noinspection PyUnresolvedReferences
self.assertListEqual(preds, ground_truth)
|
09bf8508ea108c8f3fc6683526afcf5511aec09b
|
{
"blob_id": "09bf8508ea108c8f3fc6683526afcf5511aec09b",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-21T23:32:44",
"content_id": "0ec2711b7a2c73bddfded7fc223f9d372bbb0922",
"detected_licenses": [
"MIT"
],
"directory_id": "b8518f30ab48d1dc1d538ba0ff0f31e3c3747a56",
"extension": "py",
"filename": "MLPClassifierJSTest.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16191,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/estimator/classifier/MLPClassifier/MLPClassifierJSTest.py",
"provenance": "stack-edu-0055.json.gz:171919",
"repo_name": "zhangqiking/sklearn-porter",
"revision_date": "2017-11-21T23:32:44",
"revision_id": "d0cff98080d02b0f30d74cc0c3ca6047748d3de3",
"snapshot_id": "cca7210f42572171c28852c5a8d30b3ac2726d62",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhangqiking/sklearn-porter/d0cff98080d02b0f30d74cc0c3ca6047748d3de3/tests/estimator/classifier/MLPClassifier/MLPClassifierJSTest.py",
"visit_date": "2021-08-26T06:41:31.664658",
"added": "2024-11-19T02:21:28.795980+00:00",
"created": "2017-11-21T23:32:44",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz"
}
|
$(document).ready(function() {
$('input[name=photo]').on('change', function () {
var formData = new FormData();
formData.append('archivo',document.getElementById("photo").files[0] );
formData.append('owner',localStorage.getItem("username"));
$.ajax({url:"http://socialcalendarplus.esy.es/filephp.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
document.getElementById("userImg").src = "http://socialcalendarplus.esy.es/imageGetter.php?id=" + data;
$('#imageId').val(data);
},
error: function(error){
console.log("ha fallado" + error);
}});
//document.getElementById("userImg").src = "http://socialcalendarplus.esy.es/imageGetter.php?id=" + $("#imageId").val();
});
$("#takePhoto").click(function (){
navigator.camera.getPicture(onSuccess, onFail, { quality: 40,
destinationType: Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA
});
});
function onSuccess(imageURI) {
document.getElementById("userImg").src = imageURI;
var win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + error.body);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "archivo";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://socialcalendarplus.esy.es/filephp.php"), win, fail, options);
}
function onFail(message) {
alert('Failed because: ' + message);
}
var myObject = {id : localStorage.getItem("username")}
var json = JSON.stringify(myObject);
$.post("http://socialcalendarplus.esy.es/profileGetter.php",{ par:json},null, "json")
.done(function( data, textStatus, jqXHR ) {
if ( data.success ) {
$('input[name=name]').val(data.name);
$('input[name=apellido]').val(data.lastname);
$('input[name=telefono]').val(data.tel);
$('input[name=correoe]').val(data.email);
$('#imageId').val(data.imageId);
if (data.imageId == 0){
document.getElementById("userImg").src = "img/standar-face.png";
} else {
document.getElementById("userImg").src = "http://socialcalendarplus.esy.es/imageGetter.php?id=" + data.imageId;
}
} else {
console.log("Error: " + data.message);
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if ( console && console.log ) {
console.log( "La solicitud a fallado: " + textStatus);
}
});
$("#send").click(function (){
var myObject3 = new Object();
myObject3.username = localStorage.getItem("username");
myObject3.name = $('input[name=name]').val();
myObject3.lastname = $('input[name=apellido]').val();
myObject3.email = $('input[name=correoe]').val();
myObject3.telephone = $('input[name=telefono]').val();
myObject3.imageId = $('#imageId').val();
console.log( $('#imageId').val());
myObject3.newusername = localStorage.getItem("username");
var json3 = JSON.stringify(myObject3);
console.log(json3);
$.post("http://socialcalendarplus.esy.es/profileSetter.php",{ par:json3},null, "json")
.done(function( data, textStatus, jqXHR ) {
if ( data.success ) {
} else {
console.log("Error: " + data);
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if ( console && console.log ) {
console.log( "La solicitud ha fallado: " + textStatus);
}
});
});
$("#discard").click(function (){
var myObject2 = {id : localStorage.getItem("username")}
var json2 = JSON.stringify(myObject2);
$.post("http://socialcalendarplus.esy.es/profileGetter.php",{ par:json2},null, "json")
.done(function( data, textStatus, jqXHR ) {
if ( data.success ) {
$('input[name=name]').val(data.name);
$('input[name=apellido]').val(data.lastname);
$('input[name=telefono]').val(data.tel);
$('input[name=correoe]').val(data.email);
$('#imageId').val(data.imageId);
} else {
console.log("Error: " + data.message);
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if ( console && console.log ) {
console.log( "La solicitud a fallado: " + textStatus);
}
});
});
});
|
ea36e190ea2f8ad8cc9d3f2d7ae2885e3353afbd
|
{
"blob_id": "ea36e190ea2f8ad8cc9d3f2d7ae2885e3353afbd",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-21T10:09:26",
"content_id": "46287761f53fa383101d6cd11e1cb2870518470f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "32674780633e082163f2555d13f4b68a96606e57",
"extension": "js",
"filename": "dbGetter.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 74047950,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4848,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/platforms/browser/www/js/dbGetter.js",
"provenance": "stack-edu-0041.json.gz:42348",
"repo_name": "alu0100825503/Proyecto-II",
"revision_date": "2017-01-21T10:09:26",
"revision_id": "9042a8eb469b485d4f8e6e8a9a8cd2b110f1c67e",
"snapshot_id": "c87217df6197246cf1bf9457a96c94208e7060fb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alu0100825503/Proyecto-II/9042a8eb469b485d4f8e6e8a9a8cd2b110f1c67e/platforms/browser/www/js/dbGetter.js",
"visit_date": "2020-07-06T09:50:19.708071",
"added": "2024-11-18T23:40:59.221654+00:00",
"created": "2017-01-21T10:09:26",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz"
}
|
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { NgxUiLoaderService } from 'ngx-ui-loader';
import { AuthService } from 'src/app/core/auth.service';
import { MOPHBalanceModel } from 'src/app/modules/orders/models/moph-balance.model';
import { TableButtonEnum } from 'src/app/modules/orders/models/planning-status.enum';
import { ResponseModel } from 'src/app/shared/models/api-response.model';
import { OrganizationEnum } from 'src/app/shared/models/organization.enum';
import { TableColumnModel } from 'src/app/shared/models/table-column.model';
import { DonationService } from '../../donation.service';
import { DonationRowModel } from '../../models/donation-row.model';
import { DonationStateEnum } from '../../models/donation-sate.enum';
import { DonationModel } from '../../models/donation.model';
import { DonateComponent } from '../dialogs/donate/donate.component';
@Component({
selector: 'app-donations',
templateUrl: './donations.component.html',
styleUrls: ['./donations.component.scss'],
})
export class DonationsComponent implements OnInit {
donations: ResponseModel<DonationModel>[] = [];
redeemedBalance: number = 0;
isDonor: boolean = false;
displayedColumns: TableColumnModel[] = [
new TableColumnModel('donationId', 'Donation ID'),
new TableColumnModel('donor', 'Donor ID'),
new TableColumnModel('amount', 'Amount',false,false,false,true,true),
new TableColumnModel('date', 'Donation Date'),
new TableColumnModel('button', '', false, true)
];
tableDataSource: MatTableDataSource<DonationRowModel> = new MatTableDataSource();
constructor(
public dialog: MatDialog,
private donationService: DonationService,
private authService: AuthService,
private ngxLoader: NgxUiLoaderService
) {
this.isDonor =
this.authService.getOrganizationType() == OrganizationEnum.Donor;
}
ngOnInit(): void {
this.getData();
}
getData() : void{
this.getDonations();
this.getAmountRedeemed();
}
getAmountRedeemed(){
if(!this.isDonor){
this.donationService.getFunds().subscribe((e)=>{
this.ngxLoader.stop();
this.redeemedBalance=e.response.redeemedAmount;
})
}
}
getDonations(): void {
if (!this.isDonor) {
this.donationService.getAllDonations().subscribe((result) => {
this.ngxLoader.stop();
this.donations = result.response
this.createDonations();
});
} else {
this.donationService.getDonationByUser().subscribe((result) => {
this.ngxLoader.stop();
this.donations = result.response;
this.createDonations();
});
}
}
redeemDonation(event: any) {
this.donationService.redeemDonation(event.item.donationId).subscribe(()=>{
this.ngxLoader.stop();
this.getData();
});
}
createDonations(): void {
const dataSource: any[] = [];
this.donations.forEach((e) => {
const row = new DonationRowModel(
e.Record.id,
e.Record.amount,
e.Record.issueDateTime,
e.Record.issuer,
!this.isDonor && e.Record.currentState == DonationStateEnum.ISSUED
? TableButtonEnum.REDEEM
: TableButtonEnum.NONE
);
dataSource.push(row);
});
this.tableDataSource = new MatTableDataSource(dataSource);
}
donate(): void {
const dialogRef = this.dialog.open(DonateComponent, {
panelClass: 'donate-dialog',
});
dialogRef.afterClosed().subscribe((result) => {
this.getData();
});
}
}
|
77623d9bdba7fa60cbb59f7b3f582bb73af008a0
|
{
"blob_id": "77623d9bdba7fa60cbb59f7b3f582bb73af008a0",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-26T20:41:58",
"content_id": "cb83e9dc1261ecb2d40a47293948b352e19bb77f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "56f924d46f1e5dc71ce51236b7cb09be51e80bad",
"extension": "ts",
"filename": "donations.component.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 3639,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/apps/vaccination-web/src/app/modules/donations/components/donations/donations.component.ts",
"provenance": "stack-edu-0075.json.gz:955556",
"repo_name": "Rima-ag/blockchain-vaccination-platform",
"revision_date": "2021-04-26T20:41:58",
"revision_id": "dfa9e78b9e8f0f3603291710360eaaa304176460",
"snapshot_id": "d70f42c71a34d2cc105b9cf5e5ad7d48e3f866c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Rima-ag/blockchain-vaccination-platform/dfa9e78b9e8f0f3603291710360eaaa304176460/apps/vaccination-web/src/app/modules/donations/components/donations/donations.component.ts",
"visit_date": "2023-04-17T01:32:06.197614",
"added": "2024-11-19T01:58:36.770889+00:00",
"created": "2021-04-26T20:41:58",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
// domReady event
window.onDomReady = DomReady;
function DomReady(fn){if(document.addEventListener){document.addEventListener("DOMContentLoaded", fn, false);}else{document.onreadystatechange = function(){readyState(fn);}}}
function readyState(fn){if(document.readyState == "interactive") fn();}
|
6e29029b9e0f3fe7c914911a1bbdc97fafb664b4
|
{
"blob_id": "6e29029b9e0f3fe7c914911a1bbdc97fafb664b4",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-24T04:14:11",
"content_id": "48b06f27127d6e07486fc849d8e1c5dbfb1a6e68",
"detected_licenses": [
"Unlicense"
],
"directory_id": "2633b9fc87a2922e357d4ed309ea860273209451",
"extension": "js",
"filename": "tfd.js",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1692877,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 294,
"license": "Unlicense",
"license_type": "permissive",
"path": "/public/js/tfd.js",
"provenance": "stack-edu-0044.json.gz:758620",
"repo_name": "mloberg/Tea-Fueled-Does",
"revision_date": "2015-09-24T04:14:11",
"revision_id": "1f70b1c9316f11e36193d4cc712057b3ff591b3e",
"snapshot_id": "680f7e81c02c4dcd29a167d46a28bc9efcdfe87b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mloberg/Tea-Fueled-Does/1f70b1c9316f11e36193d4cc712057b3ff591b3e/public/js/tfd.js",
"visit_date": "2021-01-20T06:51:01.607595",
"added": "2024-11-19T01:59:48.769146+00:00",
"created": "2015-09-24T04:14:11",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
package com.example.android.camera2basic;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.RelativeLayout;
import com.crashlytics.android.Crashlytics;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import static com.example.android.camera2basic.CameraVideoFragment.VIDEO_DIRECTORY_NAME;
public class CameraActivity2 extends AppCompatActivity {
RelativeLayout rl_pathhole;
Fragment photoFragment, videoFragment;
private FragmentTransaction transaction;
private static String TAG_FRAG_PHOTO = "ongoingFragment";
private static String TAG_FRAG_VIDEO = "pendingFragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera2);
//rl_pathhole = findViewById(R.id.rl_pathhole);
//
// rl_pathhole.setDrawingCacheEnabled(true);
//
// rl_pathhole.buildDrawingCache();
//
// Bitmap bm = rl_pathhole.getDrawingCache();
//
saveImageToInternalStorage(null);
loadLibrary();
photoFragment = Camera2BasicFragment2.newInstance();
videoFragment = Video2BasicFragment2.newInstance();
if (null == savedInstanceState) {
showFragment(TAG_FRAG_PHOTO);
/*getSupportFragmentManager().beginTransaction()
.replace(R.id.container, Camera2BasicFragment2.newInstance())
.commit();*/
}
}
public boolean saveImageToInternalStorage(Bitmap image) {
image = drawableToBitmap(getResources().getDrawable(R.drawable.round_pathhole2));
try {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
VIDEO_DIRECTORY_NAME);
// Create storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return false;
}
}
File directory = new File(Environment.getExternalStorageDirectory(),
VIDEO_DIRECTORY_NAME);
File mediaFile = new File((directory.getPath() + File.separator + "icon.png"));
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = new FileOutputStream(mediaFile);;
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
// Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(480, 720, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public void showPhotoFragment(){
if(videoFragment != null && videoFragment.isVisible()){
videoFragment.onPause();
showFragment(TAG_FRAG_PHOTO);
}
}
public void showVideoFragment(){
/// Crashlytics.getInstance().crash();
if(photoFragment != null && photoFragment.isVisible()){
photoFragment.onPause();
showFragment(TAG_FRAG_VIDEO);
}
}
private void showFragment(String selectedFragment){
if(selectedFragment.equals(TAG_FRAG_PHOTO)){
transaction = getSupportFragmentManager()
.beginTransaction();
if (photoFragment.isAdded()) { // if the fragment is already in container
transaction.show(photoFragment);
photoFragment.onResume();
} else { // fragment needs to be added to frame container
transaction.add(R.id.container, photoFragment, TAG_FRAG_PHOTO);
}
// Hide fragment B
if (videoFragment.isAdded()) {
transaction.hide(videoFragment);
/*
* in here we are clearing cached order numbers came via notification as because we already visited the
* pending fragment so that we already viewed the noti so we dont need this cache data anymore.
* */
}
}else if(selectedFragment.equals(TAG_FRAG_VIDEO)){
transaction = getSupportFragmentManager()
.beginTransaction();
if (videoFragment.isAdded()) { // if the fragment is already in container
transaction.show(videoFragment);
videoFragment.onResume();
// clearNotificationCounter();
} else { // fragment needs to be added to frame container
transaction.add(R.id.container, videoFragment, TAG_FRAG_VIDEO);
}
// Hide fragment B
if (photoFragment.isAdded()) {
transaction.hide(photoFragment);
}
}
transaction.commit();
// toggleBottomButtonColor(selectedFragment);
}
private void loadLibrary(){
FFmpeg ffmpeg = FFmpeg.getInstance(this);
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onStart() {}
@Override
public void onFailure() {}
@Override
public void onSuccess() {}
@Override
public void onFinish() {}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
}
}
}
|
1b0f9e460b1b95379a0f947a7f98fbbbc5bf4dec
|
{
"blob_id": "1b0f9e460b1b95379a0f947a7f98fbbbc5bf4dec",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-31T10:59:36",
"content_id": "6663ab5a527e06d09b8b0ad2c30804efe59581f1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f6705ddb634fdaab06b58935867a219b31346982",
"extension": "java",
"filename": "CameraActivity2.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 236810950,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 6950,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Application/src/main/java/com/example/android/camera2basic/CameraActivity2.java",
"provenance": "stack-edu-0028.json.gz:178963",
"repo_name": "jubayer23/android-Camera2Basic-master",
"revision_date": "2020-01-31T10:59:36",
"revision_id": "f3b652d6512a950b0456713b7f54497929bc6474",
"snapshot_id": "465a159b887cb130dae186161cefa7f235123413",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jubayer23/android-Camera2Basic-master/f3b652d6512a950b0456713b7f54497929bc6474/Application/src/main/java/com/example/android/camera2basic/CameraActivity2.java",
"visit_date": "2020-12-22T14:12:45.777972",
"added": "2024-11-18T21:09:15.122012+00:00",
"created": "2020-01-31T10:59:36",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
# Offers - v3.1.8 <!-- omit in toc -->
- [Overview](#overview)
- [Endpoints](#endpoints)
- [GET /accounts/{AccountId}/offers](#get-accountsaccountidoffers)
- [GET /offers](#get-offers)
- [Data Model](#data-model)
- [Resource Definition](#resource-definition)
- [UML Diagram](#uml-diagram)
- [Notes](#notes)
- [Permission Codes](#permission-codes)
- [Data Dictionary](#data-dictionary)
- [Usage Examples](#usage-examples)
- [Specific Account](#specific-account)
- [Get Offers Request](#get-offers-request)
- [Response: Get Offers Response](#response-get-offers-response)
- [Bulk](#bulk)
- [Request: Get Offers Request](#request-get-offers-request)
- [Response: Get Offers Response](#response-get-offers-response-1)
## Overview
The offers resource is used by an AISP to retrieve the offers available for a specific AccountId or to retrieve the offers detail in bulk for all accounts that the PSU has consented to.
This resource description should be read in conjunction with a compatible Account Information Services API Profile.
## Endpoints
Endpoints for the resource and available methods.
| |Resource |HTTP Operation |Endpoint |Mandatory? |Scope |Grant Type |Idempotency Key |Parameters |Request Object |Response Object |
| --- |--- |--- |--- |--- |--- |--- |--- |--- |--- |--- |
| 1 |offers |GET |GET /accounts/{AccountId}/offers |Conditional |accounts |Authorization Code |No | | |OBReadOffer1 |
| 2 |offers |GET |GET /offers |Optional |accounts |Authorization Code |No |Pagination | |OBReadOffer1 |
### GET /accounts/{AccountId}/offers
An AISP **may** retrieve the offers resource for a specific AccountId (which is retrieved in the call to GET /accounts).
### GET /offers
If an ASPSP has implemented the bulk retrieval endpoints, an AISP **may** optionally retrieve the offers in bulk.
This will retrieve the resources for all authorised accounts linked to the account-request.
## Data Model
The OBReadOffer1 object will be used for the call to:
* GET /accounts/{AccountId}/offers
* GET /offers
### Resource Definition
A resource that contains a set of elements that describes the list of offers available to a specific account (AccountId).
* Generic features (and pricing) for the account product will be not be available via the **offers** resources. These generic features will be available via the **product** resource.
* The outcome of any offer (or product feature) uptake will not be reported via the **offers** resource. The benefits, interest, cash-back for any account will be available via the **statements** resource (if this is available to PSUs in the existing ASPSP online channel).
An account (AccountId) may have no offers available, or may have multiple offers available.
### UML Diagram

### Notes
* Offers (or promotions) for a specific AccountId, which may be viewable in the ASPSP online banking interface, may have a complicated offer structure (which cannot be expressed using a flat Amount, Fee, Rate, or Value structure). In this case, the ASPSP must use the Description field to describe the nature of the offer in free-text
### Permission Codes
The resource requires the ReadOffers permission. The resource response payload does not differ depending on the permissions granted.
### Data Dictionary
| Name |Occurrence |XPath |EnhancedDefinition |Class |Codes |Pattern |
| --- |--- |--- |--- |--- |--- |--- |
| OBReadOffer1 | |OBReadOffer1 | |OBReadOffer1 | | |
| Data |1..1 |OBReadOffer1/Data | |OBReadDataOffer1 | | |
| Offer |0..n |OBReadOffer1/Data/Offer | |OBOffer1 | | |
| AccountId |1..1 |OBReadOffer1/Data/Offer/AccountId |A unique and immutable identifier used to identify the account resource. This identifier has no meaning to the account owner. |Max40Text | | |
| OfferId |0..1 |OBReadOffer1/Data/Offer/OfferId |A unique and immutable identifier used to identify the offer resource. This identifier has no meaning to the account owner. |Max40Text | | |
| OfferType |0..1 |OBReadOffer1/Data/Offer/OfferType |Offer type, in a coded form. |OBExternalOfferType1Code |BalanceTransfer LimitIncrease MoneyTransfer Other PromotionalRate | |
| Description |0..1 |OBReadOffer1/Data/Offer/Description |Further details of the offer. |Max500Text | | |
| StartDateTime |0..1 |OBReadOffer1/Data/Offer/StartDateTime |Date and time at which the offer starts. |ISODateTime | | |
| EndDateTime |0..1 |OBReadOffer1/Data/Offer/EndDateTime |Date and time at which the offer ends. |ISODateTime | | |
| Rate |0..1 |OBReadOffer1/Data/Offer/Rate |Rate associated with the offer type. |Max10Text | |^(-?\d{1,3}){1}(\.\d{1,4}){0,1}$ |
| Value |0..1 |OBReadOffer1/Data/Offer/Value |Value associated with the offer type. |Number | | |
| Term |0..1 |OBReadOffer1/Data/Offer/Term |Further details of the term of the offer. |Max500Text | | |
| URL |0..1 |OBReadOffer1/Data/Offer/URL |URL (Uniform Resource Locator) where documentation on the offer can be found |Max256Text | | |
| Amount |0..1 |OBReadOffer1/Data/Offer/Amount |Amount of money associated with the offer type. |OBActiveOrHistoricCurrencyAndAmount | | |
| Amount |1..1 |OBReadOffer1/Data/Offer/Amount/Amount |A number of monetary units specified in an active currency where the unit of currency is explicit and compliant with ISO 4217. |OBActiveCurrencyAndAmount_SimpleType | |`^\d{1,13}$\|^\d{1,13}\.\d{1,5}$` |
| Currency |1..1 |OBReadOffer1/Data/Offer/Amount/Currency |A code allocated to a currency by a Maintenance Agency under an international identification scheme, as described in the latest edition of the international standard ISO 4217 "Codes for the representation of currencies and funds". |ActiveOrHistoricCurrencyCode | |^[A-Z]{3,3}$ |
| Fee |0..1 |OBReadOffer1/Data/Offer/Fee |Fee associated with the offer type. |OBActiveOrHistoricCurrencyAndAmount | | |
| Amount |1..1 |OBReadOffer1/Data/Offer/Fee/Amount |A number of monetary units specified in an active currency where the unit of currency is explicit and compliant with ISO 4217. |OBActiveCurrencyAndAmount_SimpleType | |`^\d{1,13}$\|^\d{1,13}\.\d{1,5}$` |
| Currency |1..1 |OBReadOffer1/Data/Offer/Fee/Currency |A code allocated to a currency by a Maintenance Agency under an international identification scheme, as described in the latest edition of the international standard ISO 4217 "Codes for the representation of currencies and funds". |ActiveOrHistoricCurrencyCode | |^[A-Z]{3,3}$ |
## Usage Examples
### Specific Account
#### Get Offers Request
```
GET /accounts/22289/offers HTTP/1.1
Authorization: Bearer Az90SAOJklae
x-fapi-auth-date: Sun, 10 Sep 2017 19:43:31 GMT
x-fapi-customer-ip-address: <IP_ADDRESS>
x-fapi-interaction-id: 93bac548-d2de-4546-b106-880a5018460d
Accept: application/json
```
#### Response: Get Offers Response
```
HTTP/1.1 200 OK
x-fapi-interaction-id: 93bac548-d2de-4546-b106-880a5018460d
Content-Type: application/json
```
```json
{
"Data": {
"Offer": [
{
"AccountId": "22289",
"OfferId": "Offer1",
"OfferType": "LimitIncrease",
"Description": "Credit limit increase for the account up to £10000.00",
"Amount": {
"Amount": "10000.00",
"Currency": "GBP"
}
},
{
"AccountId": "22289",
"OfferId": "Offer2",
"OfferType": "BalanceTransfer",
"Description": "Balance transfer offer up to £2000",
"Amount": {
"Amount": "2000.00",
"Currency": "GBP"
}
}
]
},
"Links": {
"Self": "https://api.alphabank.com/open-banking/v3.1/aisp/accounts/22289/offers/"
},
"Meta": {
"TotalPages": 1
}
}
```
### Bulk
#### Request: Get Offers Request
```
GET /offers HTTP/1.1
Authorization: Bearer Az90SAOJklae
x-fapi-auth-date: Sun, 10 Sep 2017 19:43:31 GMT
x-fapi-customer-ip-address: <IP_ADDRESS>
x-fapi-interaction-id: 93bac548-d2de-4546-b106-880a5018460d
Accept: application/json
```
#### Response: Get Offers Response
```
HTTP/1.1 200 OK
x-fapi-interaction-id: 93bac548-d2de-4546-b106-880a5018460d
Content-Type: application/json
```
```json
{
"Data": {
"Offer": [
{
"AccountId": "22289",
"OfferId": "Offer1",
"OfferType": "LimitIncrease",
"Description": "Credit limit increase for the account up to £10000.00",
"Amount": {
"Amount": "10000.00",
"Currency": "GBP"
}
},
{
"AccountId": "22289",
"OfferId": "Offer2",
"OfferType": "BalanceTransfer",
"Description": "Balance transfer offer up to £2000",
"Amount": {
"Amount": "2000.00",
"Currency": "GBP"
}
},
{
"AccountId": "32515",
"OfferId": "Offer3",
"OfferType": "LimitIncrease",
"Description": "Credit limit increase for the account up to £50000.00",
"Amount": {
"Amount": "50000.00",
"Currency": "GBP"
}
}
]
},
"Links": {
"Self": "https://api.alphabank.com/open-banking/v3.1/aisp/offers/"
},
"Meta": {
"TotalPages": 1
}
}
```
|
040946cffdc83b53f7f10c319e771551551d7fa5
|
{
"blob_id": "040946cffdc83b53f7f10c319e771551551d7fa5",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-23T09:11:55",
"content_id": "19b942a9040667683be2dcb78d2e26ee0c6cad55",
"detected_licenses": [
"MIT"
],
"directory_id": "77871695b32f5dbc314e10ec05a45c05149c5836",
"extension": "md",
"filename": "Offers.md",
"fork_events_count": 11,
"gha_created_at": "2019-06-20T16:26:59",
"gha_event_created_at": "2023-08-21T14:58:33",
"gha_language": "Shell",
"gha_license_id": "MIT",
"github_id": 192953348,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 9130,
"license": "MIT",
"license_type": "permissive",
"path": "/docs/v3.1.8/resources-and-data-models/aisp/Offers.md",
"provenance": "stack-edu-markdown-0016.json.gz:44928",
"repo_name": "OpenBankingUK/read-write-api-docs-pub",
"revision_date": "2023-05-23T09:11:55",
"revision_id": "276d1667c53af78ce6ae5de0dd2c28377b467c01",
"snapshot_id": "00288288cb654829c9bdcf1d325a39d56d00e06c",
"src_encoding": "UTF-8",
"star_events_count": 16,
"url": "https://raw.githubusercontent.com/OpenBankingUK/read-write-api-docs-pub/276d1667c53af78ce6ae5de0dd2c28377b467c01/docs/v3.1.8/resources-and-data-models/aisp/Offers.md",
"visit_date": "2023-06-15T22:54:49.853157",
"added": "2024-11-19T03:29:40.231439+00:00",
"created": "2023-05-23T09:11:55",
"int_score": 4,
"score": 4.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0016.json.gz"
}
|
let {$, sleep} = require('./funcs');
module.exports = function(){
this.BeforeScenario(async function() {
await helpers.loadPage('http://localhost:3306/categories.html');
await sleep(3000);
});
this.Given(/^that there is (\d+) products in the cart$/, async function (numberOfProductsInCart) {
// never forget to convert string to number
numberOfProductsInCart = numberOfProductsInCart / 1;
/*let searchBar = await $('#myInput');
await searchBar.sendKeys("Renat");
await sleep(3000);*/
let add;
// continue to try to get the add buttons as long as we fail
// (dangerous could continue forever if they never show in the browser)
while(!add){
add = await $('.product-listing .product_cart');
await sleep(100);
}
//console.log("==> " + add.length);
for (let i = 0; i < numberOfProductsInCart; i++) {
//console.log("==>> " + add[i]);
//await sleep(3000);
await add[i].click();
}
});
this.When(/^i click on the empty\-cart button$/, async function () {
await helpers.loadPage('http://localhost:3306/cart.html');
await sleep(2000);
let emptyCartButton = await $('.button_clear');
assert.notEqual(emptyCartButton, null, 'could not find the emptycart button');
await emptyCartButton.click();
});
this.Then(/^It should empty the cart$/, async function () {
let cartItems = await $('.remove_button');
console.log("==>> " + cartItems);
assert(cartItems === null, "cart is not empty");
});
}
|
aa1488227da4ca593eccb7919b3d50e3f4714740
|
{
"blob_id": "aa1488227da4ca593eccb7919b3d50e3f4714740",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-01T08:49:36",
"content_id": "85ac4b4a896aa254cb5e8fa124e870c0ec66e9e3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3b7c7e03c784aae3a582f65ee07c43380ab8f354",
"extension": "js",
"filename": "emptycart.js",
"fork_events_count": 0,
"gha_created_at": "2019-04-17T11:19:08",
"gha_event_created_at": "2022-12-09T19:50:29",
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 181876045,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1481,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/step-definitions/emptycart.js",
"provenance": "stack-edu-0033.json.gz:274979",
"repo_name": "ehmadeli/systemBolaget-2019",
"revision_date": "2019-06-01T08:49:36",
"revision_id": "b78a7047119b2e7f8fefdd9de0c6d48c60df0571",
"snapshot_id": "28a30f65b8f358869d26159b60de068491030431",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ehmadeli/systemBolaget-2019/b78a7047119b2e7f8fefdd9de0c6d48c60df0571/step-definitions/emptycart.js",
"visit_date": "2022-12-13T06:47:31.827182",
"added": "2024-11-18T23:22:32.715531+00:00",
"created": "2019-06-01T08:49:36",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
import * as assert from 'assert'
import { none, some } from 'fp-ts/lib/Option'
import { failure, success } from 'fp-ts/lib/Validation'
import {
getClasses,
getFunctions,
getInterfaces,
getSourceFile,
getTypeAliases,
getConstants,
getModuleInfo,
getExports
} from '../src/parser'
describe('getInterfaces', () => {
it('should return no `Interface`s if the file is empty', () => {
const sourceFile = getSourceFile('test', '')
assert.deepStrictEqual(getInterfaces(sourceFile), success([]))
})
it('should return no `Interface`s if there are no exported interfaces', () => {
const sourceFile = getSourceFile('test', 'interface A {}')
assert.deepStrictEqual(getInterfaces(sourceFile), success([]))
})
it('should return an `Interface`', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a description...
* @since 1.0.0
* @deprecated
*/
export interface A {}`
)
assert.deepStrictEqual(
getInterfaces(sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'A',
signature: 'export interface A {}',
since: some('1.0.0'),
examples: []
}
])
)
})
})
describe('getFunctions', () => {
it('should raise an error if the function is anonymous', () => {
const sourceFile = getSourceFile('test', `export function(a: number, b: number): number { return a + b }`)
assert.deepStrictEqual(getFunctions('test', sourceFile), failure(['Missing function name in module test']))
})
it('should not return private function declarations', () => {
const sourceFile = getSourceFile('test', `function sum(a: number, b: number): number { return a + b }`)
assert.deepStrictEqual(getFunctions('test', sourceFile), success([]))
})
it('should not return internal function declarations', () => {
const sourceFile = getSourceFile(
'test',
`/** @internal */export function sum(a: number, b: number): number { return a + b }`
)
assert.deepStrictEqual(getFunctions('test', sourceFile), success([]))
})
it('should not return private variable declarations', () => {
const sourceFile = getSourceFile('test', `const sum = (a: number, b: number): number => a + b `)
assert.deepStrictEqual(getFunctions('test', sourceFile), success([]))
})
it('should not return internal variable declarations', () => {
const sourceFile = getSourceFile(
'test',
`/** @internal */export const sum = (a: number, b: number): number => a + b `
)
assert.deepStrictEqual(getFunctions('test', sourceFile), success([]))
})
it('should not return exported const declarations', () => {
const sourceFile = getSourceFile('test', `export const a = 1`)
assert.deepStrictEqual(getFunctions('test', sourceFile), success([]))
})
it('should handle a const function', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a description...
* @since 1.0.0
* @example
* assert.deeStrictEqual(f(1, 2), { a: 1, b: 2})
* @example
* assert.deeStrictEqual(f(3, 4), { a: 3, b: 4})
* @deprecated
*/
export const f = (a: number, b: number): { [key: string]: number } => ({ a, b })`
)
assert.deepStrictEqual(
getFunctions('test', sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'f',
signatures: ['export const f = (a: number, b: number): { [key: string]: number } => ...'],
since: some('1.0.0'),
examples: ['assert.deeStrictEqual(f(1, 2), { a: 1, b: 2})', 'assert.deeStrictEqual(f(3, 4), { a: 3, b: 4})']
}
])
)
})
it('should return a `Func` with a body', () => {
const sourceFile = getSourceFile(
'test',
`const a: number = 1
export function f(a: number, b: number): { [key: string]: number } { return { a, b } }`
)
assert.deepStrictEqual(
getFunctions('test', sourceFile),
success([
{
deprecated: false,
description: none,
name: 'f',
signatures: ['export function f(a: number, b: number): { [key: string]: number } { ... }'],
since: none,
examples: []
}
])
)
})
it('should return a `Func` with comments', () => {
const sourceFile = getSourceFile(
'test',
`const a: number = 1
/**
* a description...
* @since 1.0.0
* @deprecated
*/
export function f(a: number, b: number): { [key: string]: number } { return { a, b } }`
)
assert.deepStrictEqual(
getFunctions('test', sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'f',
signatures: ['export function f(a: number, b: number): { [key: string]: number } { ... }'],
since: some('1.0.0'),
examples: []
}
])
)
})
it('should handle overloadings', () => {
const sourceFile = getSourceFile(
'test',
`const a: number = 1
/**
* a description...
* @since 1.0.0
* @deprecated
*/
export function f(a: int, b: int): { [key: string]: number }
export function f(a: number, b: number): { [key: string]: number }
export function f(a: any, b: any): { [key: string]: number } { return { a, b } }`
)
assert.deepStrictEqual(
getFunctions('test', sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'f',
signatures: [
'export function f(a: int, b: int): { [key: string]: number }',
'export function f(a: number, b: number): { [key: string]: number } { ... }'
],
since: some('1.0.0'),
examples: []
}
])
)
})
})
describe('getTypeAliases', () => {
it('should return a `TypeAlias`', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a description...
* @since 1.0.0
* @deprecated
*/
export type Option<A> = None<A> | Some<A>`
)
assert.deepStrictEqual(
getTypeAliases(sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'Option',
signature: 'export type Option<A> = None<A> | Some<A>',
since: some('1.0.0'),
examples: []
}
])
)
})
})
describe('getConstants', () => {
it('should return a `Constant`', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a description...
* @since 1.0.0
* @deprecated
*/
export const setoidString: Setoid<string> = setoidStrict`
)
assert.deepStrictEqual(
getConstants(sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
name: 'setoidString',
signature: 'export const setoidString: Setoid<string> = ...',
since: some('1.0.0'),
examples: []
}
])
)
})
})
describe('getClasses', () => {
it('should raise an error if the class is anonymous', () => {
const sourceFile = getSourceFile('test', `export class {}`)
assert.deepStrictEqual(getClasses('test', sourceFile), failure(['Missing class name in module test']))
})
it('should skip the constructor body', () => {
const sourceFile = getSourceFile('test', `export class C { constructor() { ... } }`)
assert.deepStrictEqual(
getClasses('test', sourceFile),
success([
{
deprecated: false,
description: none,
examples: [],
methods: [],
name: 'C',
signature: 'export class C {\n constructor() { ... }\n ... \n}',
since: none,
staticMethods: []
}
])
)
})
it('should return a `Class`', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a class description...
* @since 1.0.0
* @deprecated
*/
export class Test {
/**
* a static method description...
* @since 1.1.0
* @deprecated
*/
static f() {}
constructor(readonly value: string) { }
/**
* a method description...
* @since 1.1.0
* @deprecated
*/
g(a: number, b: number): { [key: string]: number } {
return { a, b }
}
}`
)
assert.deepStrictEqual(
getClasses('test', sourceFile),
success([
{
deprecated: true,
description: some('a class description...'),
name: 'Test',
signature: 'export class Test {\n constructor(readonly value: string) { ... }\n ... \n}',
since: some('1.0.0'),
examples: [],
methods: [
{
deprecated: true,
description: some('a method description...'),
name: 'g',
signatures: ['g(a: number, b: number): { [key: string]: number } { ... }'],
since: some('1.1.0'),
examples: []
}
],
staticMethods: [
{
deprecated: true,
description: some('a static method description...'),
name: 'f',
signatures: ['static f() { ... }'],
since: some('1.1.0'),
examples: []
}
]
}
])
)
})
it('should handle method overloadings', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a class description...
* @since 1.0.0
* @deprecated
*/
export class Test<A> {
/**
* a static method description...
* @since 1.1.0
* @deprecated
*/
static f(x: number): number
static f(x: string): string
static f(x: any): any {}
constructor(readonly value: A) { }
/**
* a method description...
* @since 1.1.0
* @deprecated
*/
map(f: (a: number) => number): Test
map(f: (a: string) => string): Test
map(f: (a: any) => any): any {
return new Test(f(this.value))
}
}`
)
assert.deepStrictEqual(
getClasses('test', sourceFile),
success([
{
deprecated: true,
description: some('a class description...'),
name: 'Test',
signature: 'export class Test<A> {\n constructor(readonly value: A) { ... }\n ... \n}',
since: some('1.0.0'),
examples: [],
methods: [
{
deprecated: true,
description: some('a method description...'),
name: 'map',
signatures: ['map(f: (a: number) => number): Test', 'map(f: (a: string) => string): Test { ... }'],
since: some('1.1.0'),
examples: []
}
],
staticMethods: [
{
deprecated: true,
description: some('a static method description...'),
name: 'f',
signatures: ['static f(x: number): number', 'static f(x: string): string { ... }'],
since: some('1.1.0'),
examples: []
}
]
}
])
)
})
})
describe('getModuleInfo', () => {
it('should not return a file description if there is no @file tag', () => {
const sourceFile = getSourceFile(
'test',
`
/**
* @since 1.0.0
*/
export const a: number = 1
`
)
assert.deepStrictEqual(getModuleInfo(sourceFile), {
description: none,
deprecated: false
})
})
it('should return a description field and a deprecated field', () => {
const sourceFile = getSourceFile(
'test',
`
/**
* @file Manages the configuration settings for the widget
* @deprecated
*/
/**
* @since 1.0.0
*/
export const a: number = 1
`
)
assert.deepStrictEqual(getModuleInfo(sourceFile), {
description: some('Manages the configuration settings for the widget'),
deprecated: true
})
})
})
describe('getExports', () => {
it('should return no `Export`s if the file is empty', () => {
const sourceFile = getSourceFile('test', '')
assert.deepStrictEqual(getExports(sourceFile), success([]))
})
it('should skip if there are too many named exports', () => {
const sourceFile = getSourceFile('test', 'export { a, b }')
assert.deepStrictEqual(getExports(sourceFile), success([]))
})
it('should handle renamimg', () => {
const sourceFile = getSourceFile('test', 'export { a as b }')
assert.deepStrictEqual(
getExports(sourceFile),
success([
{
deprecated: false,
description: none,
examples: [],
name: 'b',
signature: 'export { a as b }',
since: none
}
])
)
})
it('should return an `Export`', () => {
const sourceFile = getSourceFile(
'test',
`/**
* a description...
* @since 1.0.0
* @deprecated
*/
export { a }`
)
assert.deepStrictEqual(
getExports(sourceFile),
success([
{
deprecated: true,
description: some('a description...'),
examples: [],
name: 'a',
signature: 'export { a }',
since: some('1.0.0')
}
])
)
})
})
|
4282b221feb15e6a78eb8098b808d27a8362b71e
|
{
"blob_id": "4282b221feb15e6a78eb8098b808d27a8362b71e",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-10T02:45:18",
"content_id": "80c4c5bcf451b6ebbf49452b94ca1a7f0b88c18b",
"detected_licenses": [
"MIT"
],
"directory_id": "7daf951b1d8e1dd7da05e77165c696c8020818b4",
"extension": "ts",
"filename": "parser.ts",
"fork_events_count": 0,
"gha_created_at": "2019-05-09T13:34:48",
"gha_event_created_at": "2019-05-09T13:34:49",
"gha_language": null,
"gha_license_id": null,
"github_id": 185805493,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 13153,
"license": "MIT",
"license_type": "permissive",
"path": "/test/parser.ts",
"provenance": "stack-edu-0076.json.gz:393646",
"repo_name": "rzeigler/docs-ts",
"revision_date": "2019-05-10T02:45:18",
"revision_id": "5ae3081185c1c41759e8cbe072b13809e45ee0de",
"snapshot_id": "1ecf5d9f4dfc72abb032e5d248debfaf17e92cd1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rzeigler/docs-ts/5ae3081185c1c41759e8cbe072b13809e45ee0de/test/parser.ts",
"visit_date": "2020-05-20T23:36:24.724662",
"added": "2024-11-19T02:35:40.796300+00:00",
"created": "2019-05-10T02:45:18",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz"
}
|
var t = require('u-test'),
assert = require('assert'),
wait = require('y-timers/wait'),
Setter = require('y-setter'),
Getter = Setter.Getter,
Hybrid = Setter.Hybrid,
Detacher = require('detacher'),
apply = require('../apply.js');
t('apply',function(){
t('Plain object',function(){
t('Simple',function(){
var obj = {};
obj[apply]({foo: 'bar'});
assert.strictEqual(obj.foo,'bar');
obj[apply]({foo: null});
assert.strictEqual(obj.foo,null);
});
t('Nested',function(){
var obj = {test: {}};
obj[apply]({test: {foo: 'bar'}});
assert.strictEqual(obj.test.foo,'bar');
});
t('Using a getter',function(){
var obj = {},
s = new Setter(),
g = s.getter,
c = new Detacher();
s.value = 'bar';
obj[apply]({foo: g},c);
assert.strictEqual(obj.foo,'bar');
s.value = 1;
assert.strictEqual(obj.foo,1);
c.detach();
s.value = 2;
assert.strictEqual(obj.foo,1);
s.value = 'bar';
obj[apply]({foo: g});
assert.strictEqual(obj.foo,'bar');
s.value = 1;
assert.strictEqual(obj.foo,1);
});
});
t('HTMLInputElement',function*(){
var i = document.createElement('input'),
h = new Hybrid(),
h2 = new Hybrid(),
c = new Detacher();
i.type = 'checkbox';
h.value = false;
document.body.appendChild(i);
i[apply]({checked: h});
assert.strictEqual(i.checked,false);
i.click();
assert.strictEqual(h.value,true);
h.value = false;
assert.strictEqual(i.checked,false);
h2.value = false;
i[apply]({checked: h2},c);
assert.strictEqual(i.checked,false);
h.value = true;
assert.strictEqual(i.checked,true);
h2.value = true;
assert.strictEqual(i.checked,true);
i.click();
assert.strictEqual(i.checked,false);
assert.strictEqual(h.value,false);
assert.strictEqual(h2.value,false);
c.detach();
h2.value = true;
assert.strictEqual(i.checked,false);
i[apply]({checked: h2, h: h});
assert.strictEqual(i.checked,true);
assert.strictEqual(i.h,true);
i.click();
assert.strictEqual(i.checked,false);
assert.strictEqual(h2.value,false);
assert.strictEqual(i.h,false);
h.value = false;
assert.strictEqual(i.h,false);
});
t('HTMLDivElement',function*(){
var span = document.createElement('span'),
width = new Hybrid(),
html = new Hybrid(),
children = new Hybrid(),
value = new Hybrid(),
scroll = new Hybrid(),
d = new Detacher(),
w1;
span[apply]({ offsetWidth: width, innerHTML: html, childElementCount: children, scrollTop: scroll, value }, d);
document.body.appendChild(span);
html.value = '<p>1</p><p>2</p>';
yield wait(100);
assert.strictEqual(children.value, 2);
html.value = '<p>1</p><p>2</p><p>3</p>';
yield wait(100);
assert.strictEqual(children.value, 3);
html.value = 'foo';
span = document.createElement('span');
span[apply]({ offsetWidth: width, innerHTML: html, childElementCount: children }, d);
document.body.appendChild(span);
yield wait(100);
assert.strictEqual(html.value, 'foo');
w1 = width.value;
span.textContent += 'bar';
yield wait(100);
assert.strictEqual(html.value, 'foobar');
assert(width.value > w1);
w1 = width.value;
d.detach();
span.textContent += 'bar';
yield wait(100);
assert.strictEqual(html.value, 'foobar');
assert.strictEqual(width.value,w1);
assert.strictEqual(value.value,undefined);
assert.strictEqual(scroll.value,0);
});
t('CSSStyleDeclaration',function(){
var div = document.createElement('div'),
h = new Hybrid(),
h2 = new Hybrid(),
c = new Detacher();
h.value = 'black';
div[apply]({style: {color: h}});
assert.strictEqual(div.style.color,'black');
h.value = 'red';
assert.strictEqual(div.style.color,'red');
h2.value = 'black';
div[apply]({style: {color: h2}},c);
assert.strictEqual(div.style.color,'black');
h.value = 'green';
assert.strictEqual(div.style.color,'green');
h2.value = 'red';
assert.strictEqual(div.style.color,'red');
c.detach();
h2.value = 'black';
assert.strictEqual(div.style.color,'red');
div[apply]({style: {color: null}});
assert.strictEqual(div.style.color,'');
div[apply]({style: {color: ['black','important']}});
assert.strictEqual(div.style.color,'black');
assert.strictEqual(div.style.getPropertyPriority('color'),'important');
});
});
|
3cfa3d6250ee6efd5c2ee5ba1cf483dbc02e4153
|
{
"blob_id": "3cfa3d6250ee6efd5c2ee5ba1cf483dbc02e4153",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-28T21:17:41",
"content_id": "e507513ecb0e157d76b25b46b1cd5e011b928ed0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9ffbf3732f16fae56ef1483c714db99f84762e1b",
"extension": "js",
"filename": "apply.br.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 30866430,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4659,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/apply.br.js",
"provenance": "stack-edu-0040.json.gz:201935",
"repo_name": "manvalls/u-proto",
"revision_date": "2017-08-28T21:17:41",
"revision_id": "0543d91f696224f1859f653006ff907c1913890d",
"snapshot_id": "7ad6645bdf938783a959eac0fdcb4c240aa64157",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/manvalls/u-proto/0543d91f696224f1859f653006ff907c1913890d/test/apply.br.js",
"visit_date": "2021-01-17T03:57:21.228950",
"added": "2024-11-19T00:49:38.970176+00:00",
"created": "2017-08-28T21:17:41",
"int_score": 3,
"score": 2.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz"
}
|
using System;
namespace Ncqrs.Eventing.Sourcing.Snapshotting.DynamicSnapshot
{
public static class ByteExtensions
{
public static int Find(this byte[] self, byte[] pattern)
{
int m = 0;
int i = 0;
var t = ComputeFailureTable(pattern);
while (m + i < self.Length)
{
if (pattern[i] == self[m + i])
{
if (i == pattern.Length - 1)
return m;
++i;
}
else
{
m += i - t[i];
i = (t[i] > -1) ? t[i] : 0;
}
}
return -1;
}
public static bool Replace(this byte[] self, byte[] patternToReplace, byte[] newPattern)
{
if (patternToReplace.Length != newPattern.Length)
return false;
int pos = Find(self, patternToReplace);
if (pos != -1)
{
newPattern.CopyTo(self, pos);
}
return (pos != -1);
}
private static int[] ComputeFailureTable(byte[] pattern)
{
int[] t = new int[pattern.Length];
t[0] = -1;
t[1] = 0;
int i = 2;
int j = 0;
while (i < pattern.Length)
{
if (pattern[i - 1] == pattern[j])
{
t[i++] = ++j;
}
else if (j > 0)
{
j = t[j];
}
else
{
t[i++] = 0;
}
}
return t;
}
}
}
|
330cc6183cea07641256ef5106ad51ecd560e6ed
|
{
"blob_id": "330cc6183cea07641256ef5106ad51ecd560e6ed",
"branch_name": "refs/heads/master",
"committer_date": "2014-10-12T19:35:36",
"content_id": "f9a73d1be1fef17526e85771726db179ad4ae9b6",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2e94c39cd0f91bca8094cbf46e202ca2b3dcaf79",
"extension": "cs",
"filename": "ByteExtensions.cs",
"fork_events_count": 0,
"gha_created_at": "2014-08-21T18:45:10",
"gha_event_created_at": "2021-08-20T05:13:08",
"gha_language": "C#",
"gha_license_id": "NOASSERTION",
"github_id": 23198857,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1835,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Extensions/src/Ncqrs.Eventing.Sourcing.Snapshotting.DynamicSnapshot/ByteExtensions.cs",
"provenance": "stack-edu-0013.json.gz:583502",
"repo_name": "galenp/ncqrs",
"revision_date": "2014-10-12T19:35:36",
"revision_id": "5094a62cd0871293f83465d6a393c2311ba519f3",
"snapshot_id": "f8a6a20efc9726cc2d0a589cf6fa3141da363714",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/galenp/ncqrs/5094a62cd0871293f83465d6a393c2311ba519f3/Extensions/src/Ncqrs.Eventing.Sourcing.Snapshotting.DynamicSnapshot/ByteExtensions.cs",
"visit_date": "2021-08-28T08:40:22.692806",
"added": "2024-11-19T01:50:38.657653+00:00",
"created": "2014-10-12T19:35:36",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
package grupp1.othello.view;
/*------------------------------------------------
* IMPORTS
*----------------------------------------------*/
import grupp1.othello.controller.GUIHumanPlayer;
import grupp1.othello.controller.GameManager;
import grupp1.othello.controller.Player;
import grupp1.othello.model.GameGrid;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.effect.*;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
/*------------------------------------------------
* CLASS
*----------------------------------------------*/
/**
* The GameBoard is the playfield
*
* @author Martin Bergqvist (S141564)
*/
public class GameBoard {
private GridPane board;
private GameManager gameManager;
private Circle[][] marker = new Circle[8][8];
/*------------------------------------------------
* PUBLIC METHODS
*----------------------------------------------*/
/**
* Creates the GameBoard, constructed with a GridPane of buttons
*
* @param gameManager
*/
public GameBoard(GameManager gameManager){
this.gameManager = gameManager;
gameManager.onDiskPlaced((player, diskPlacement) -> {
Platform.runLater(() -> updateGameBoard());
});
DropShadow shade = new DropShadow();
shade.setColor(Color.GREEN);
board = new GridPane();
board.setStyle("-fx-background-image: url(images/green.png);"
+ "-fx-background-repeat: stretch;"
+ "-fx-background-size: 480 480;"
+ "-fx-background-position: center center;");
board.setGridLinesVisible(true);
board.setEffect(shade);
board.setAlignment(Pos.CENTER);
int row, column;
for(row = 0; row < 8; row++){
for(column = 0; column < 8; column++){
Button tile = new Button();
tile.setMinSize(60,60);
tile.setMaxSize(60,60);
tile.setStyle("-fx-color: transparent;"
+ "-fx-border-color: white;"
+ "-fx-faint-focus-color: darkgreen;");
marker[column][row] = new Circle(20, Color.TRANSPARENT);
marker[column][row].setMouseTransparent(true);
GridPane.setRowIndex(tile, row);
GridPane.setColumnIndex(tile, column);
GridPane.setMargin(marker[column][row],new Insets(10));
board.add(marker[column][row], row, column);
tile.setFocusTraversable(true);
tile.setOnAction((ActionEvent e) -> {
setPlacing(GridPane.getColumnIndex(tile),
GridPane.getRowIndex(tile),
gameManager.getCurrentPlayer());
});
tile.setOnKeyPressed((KeyEvent event) -> {
Button temp = (Button)event.getSource();
if(event.getCode() == KeyCode.ENTER && temp.isFocused())
setPlacing(GridPane.getColumnIndex(tile),
GridPane.getRowIndex(tile),
gameManager.getCurrentPlayer());
});
board.getChildren().add(tile);
}
}
Platform.runLater(() -> updateGameBoard());
}
/**
*
* @return The GridPane representing the board
*/
public GridPane getGameBoard(){
return (board);
}
/*------------------------------------------------
* PRIVATE METHODS
*----------------------------------------------*/
private void setPlacing(int x, int y, Player player){
try{
((GUIHumanPlayer)player).setNextMove(x,y);
}
catch (Exception e) {} //Catches attempts to make move when it's not players turn
}
private void updateGameBoard(){
GameGrid updateGame;
updateGame = gameManager.getGameGrid();
int row, column;
for(row = 0; row < 8; row++){
for(column = 0; column < 8; column++){
if(updateGame.getCellData(row, column) == 1){
marker[column][row].setFill(Color.BLACK);
}
if(updateGame.getCellData(row, column) == 2){
marker[column][row].setFill(Color.WHITE);
}
}
}
}
}
|
4838d8613558810a3612e5292b7c7a14a21de9d8
|
{
"blob_id": "4838d8613558810a3612e5292b7c7a14a21de9d8",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-28T19:46:57",
"content_id": "bdd91f11177528af3624799c2927b2f61fe4ca72",
"detected_licenses": [
"MIT"
],
"directory_id": "d1296f031601c1aca445658d0e21ebb41747be5e",
"extension": "java",
"filename": "GameBoard.java",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43840816,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4315,
"license": "MIT",
"license_type": "permissive",
"path": "/oomj-lab2/src/grupp1/othello/view/GameBoard.java",
"provenance": "stack-edu-0021.json.gz:857608",
"repo_name": "philiparvidsson/Othello-3D-Game",
"revision_date": "2017-01-28T19:46:57",
"revision_id": "1823517ec855d9f45e756700c531083bc1336b10",
"snapshot_id": "f8efa235873bdd71e80d7e6f52f7f6e637d53da2",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/philiparvidsson/Othello-3D-Game/1823517ec855d9f45e756700c531083bc1336b10/oomj-lab2/src/grupp1/othello/view/GameBoard.java",
"visit_date": "2021-06-13T23:58:24.884108",
"added": "2024-11-19T01:45:12.242557+00:00",
"created": "2017-01-28T19:46:57",
"int_score": 3,
"score": 2.84375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
<?php
/**
* Copyright 2014 Jonathan Bouzekri. All rights reserved.
*
* @copyright Copyright 2014 Jonathan Bouzekri <jonathan.bouzekri@gmail.com>
* @license https://github.com/jbouzekri/FileUploaderBundle/blob/master/LICENSE
* @link https://github.com/jbouzekri/FileUploaderBundle
*/
namespace Jb\Bundle\FileUploaderBundle\Service\Validator;
use Jb\Bundle\FileUploaderBundle\Exception\ValidationException;
/**
* CropValidator
*
* @author jobou
*/
class CropValidator extends AbstractImageValidator
{
/**
* {@inheritdoc}
*/
protected function extractWidthHeight($value)
{
if (empty($value) || !isset($value['width']) || !isset($value['height'])) {
throw new ValidationException('Unable to determine size.');
}
return array(
'width' => (int) $value['width'],
'height' => (int) $value['height']
);
}
}
|
712bc9804c9cab546c79e4fbfc8041735fd5404f
|
{
"blob_id": "712bc9804c9cab546c79e4fbfc8041735fd5404f",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-16T06:18:49",
"content_id": "cbe8c5535577f27afc02977339dd5a5230f0f119",
"detected_licenses": [
"MIT"
],
"directory_id": "ba699d1608670a4032c0d35ab22fccf0f6b4b76b",
"extension": "php",
"filename": "CropValidator.php",
"fork_events_count": 0,
"gha_created_at": "2017-02-15T06:41:09",
"gha_event_created_at": "2017-02-15T06:41:09",
"gha_language": null,
"gha_license_id": null,
"github_id": 82028761,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 907,
"license": "MIT",
"license_type": "permissive",
"path": "/Service/Validator/CropValidator.php",
"provenance": "stack-edu-0052.json.gz:646686",
"repo_name": "bluntelk/FileUploaderBundle",
"revision_date": "2021-12-16T06:18:49",
"revision_id": "62c5e25690c98b207e4ba74efda35bb111079ece",
"snapshot_id": "122b3121d258f16f332aef2d531b429b0d743bb0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bluntelk/FileUploaderBundle/62c5e25690c98b207e4ba74efda35bb111079ece/Service/Validator/CropValidator.php",
"visit_date": "2022-01-01T02:41:43.017935",
"added": "2024-11-18T23:10:32.485804+00:00",
"created": "2021-12-16T06:18:49",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
# Tabular
This repo is a collection of useful code for automating processes within tabular modeling. All of these scripts are to be executed in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") so make sure to download and install it.
For addtional information on these scripts and more, check out my blog [Elegant BI](https://www.elegantbi.com "Elegant BI").
### [Auto Aggs](https://www.elegantbi.com/post/autoaggs "Auto Aggs")
Auto-generated aggregations supporting base fact tables in both import mode and direct query. Also check out the [Agg Wizard](https://github.com/m-kovalsky/AggWizard "Agg Wizard") which has additional functionalities and a supporting user interface.
### [Automated Data Dictionary](https://www.elegantbi.com/post/datadictionaryreinvented "Automated Data Dictionary")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") to create an automated data dictionary. This script works for Analysis Services, Azure Analysis Services, and Power BI Premium models ([XMLA R/W endpoints](https://docs.microsoft.com/en-us/power-bi/admin/service-premium-connect-tools#enable-xmla-read-write "XMLA R/W endpoints") enabled).
### [Automated Data Dictionary via Excel](https://www.elegantbi.com/post/datadictionaryexcel "Automated Data Dictionary via Excel")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") to create an automated data dictionary where the Data Dictionary table is stored in Excel. This script works for Analysis Services, Azure Analysis Services, and Power BI Premium models ([XMLA R/W endpoints](https://docs.microsoft.com/en-us/power-bi/admin/service-premium-connect-tools#enable-xmla-read-write "XMLA R/W endpoints") enabled).
### [Blank Row Finder](https://www.elegantbi.com/post/findblankrows "Blank Row Finder")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") against a live-connected model to quickly make a list of all relationships that contain a blank row in the 'to-table'. This has now been integrated into the Vertipaq Analyzer scripts [(see below)](https://github.com/m-kovalsky/Tabular#vertipaq-annotations) as well as the latest [Best Practice Rules](https://github.com/microsoft/Analysis-Services/tree/master/BestPracticeRules "Best Practice Rules").
### [Cancel Processing](https://www.elegantbi.com/post/canceldatarefreshte "Cancel Processing")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") against a live-connected model to cancel the data refresh of that model.
### [Data Preview - Table](https://www.elegantbi.com/post/datapreview "Data Preview")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") against a live-connected model while selecting a single table within the TOM (Object) Explorer. It will return a data preview of the table.
### [Data Preview - Columns](https://www.elegantbi.com/post/datapreview "Data Preview")
Run this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") against a live-connected model while selecting one or more columns from a table within the TOM (Object) Explorer. It will return a data preview of the columns (distinct values).
### [Descriptions](https://github.com/m-kovalsky/Tabular/tree/master/Descriptions "Descriptions")
Run the ExportDescriptions.cs script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") to export objects and existing descriptions in your tabular model to an Excel file.
Run the ImportDescriptions.cs script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") to import object descriptions back into your tabular model from the Excel file.
### [Export BPA Results](https://www.elegantbi.com/post/exportbparesults "Export BPA Results")
Running this script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") will run the [Best Practice Analyzer](https://docs.tabulareditor.com/Best-Practice-Analyzer.html "Best Practice Analyzer") and output the results. The output can easily be copied into Excel for further analysis.
### [Export Report Objects](https://www.elegantbi.com/post/exportreportobjects "Export Report Objects")
Run the ExportReportObjects.cs script in [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") to export the objects used in a Power BI report (or a collection of Power BI reports within a specified folder). Below shows the output:

* **Bookmarks**
* Report Name, Bookmark Name, Bookmark Id, Page Id
* **Connections**
* Report Name, Server Name, Database Name, Report Id, Connection Type
* **Custom Visuals**
* Report Name, Custom Visual Name
* **Page Filters**
* Report Name, Page Id, Page Name, Filter Name, Table Name, Object Name, Object Type, Filter Type
* **Pages**
* Report Name, Page Id, Page Name, Page Number, Page Width, Page Height, Page Hidden Flag, Visual Count
* **Report Filters**
* Report Name, Filter Name, Table Name, Object Name, Object Type, Filter Type
* **Unused Objects**
* Report Name, Table Name, Object Name, Object Type
* **Visual Filters**
* Report Name, Page Name, Visual Id, Table Name, Object Name, Object Type, Filter Type
* **Visuals Objects**
* Report Name, Page Name, Visual Id, Visual Type, Custom Visual Flag, Table Name, Object Name, Object Type, Source
* **Visuals**
* Report Name, Page Name, Visual Id, Visual Name, Visual Type, Custom Visual Flag, Visual Hidden Flag, X Coordinate, Y Cooridnate, Z Coordinate, Visual Width, Visual Height, Object Count
* **Visual Interactions**
* Report Name, Page Name, Source Visual ID, Target Visual ID, Type ID, Type
*Note: 'Source' within Visual Objects shows as 'Standard' for objects used within rows/columns etc. of visual itself. Objects used for conditional formatting or to set titles, backgrounds etc. will show as such within the 'Source' column.*
*Note: Unused Objects lists objects (measures, columns etc.) not used in the report and checks the dependencies listed below. This should be used in conjunction with the 'Remove Unnecessary Columns' [Best Practice Rule](https://github.com/microsoft/Analysis-Services/tree/master/BestPracticeRules) for the greatest efficacy.*
* Measures
* Relationships (key columns)
* Sort-by Columns
* Calculated Columns
* Hierarchies
* Calculation Groups
* Auto-date Tables
### [Master Model](https://www.elegantbi.com/post/mastermodel "Master Model")
### [Metadata Export](https://www.elegantbi.com/post/extractmodelmetadata "Metadata Export")
### Metadata Import - Perspectives
Run this script to automatically update the perspectives in your model (or add new perspectives). This script coordinates with the output text file from the Metadata Export script.
### Metadata Import - Translations
Run this script to automatically update the translations in your model (or add new translations). This script coordinates with the output text file from the Metadata Export script.
### [Perspective Editor](https://www.elegantbi.com/post/perspectiveeditor "Perspective Editor")
Running this script opens a program within [Tabular Editor](https://tabulareditor.com/ "Tabular Editor") that allows you to create or modify perspectives akin to the way it is done in SQL Server Development Tools (SSDT). It also gives you a tree-view of all the objects that are in a perspective relative to all the objects in the model.
### [Report-Level Measures](https://www.elegantbi.com/post/reportlevelmeasures "Report-Level Measures")
Want to migrate measures created within a Power BI Desktop report to your tabular model? This script does exactly that. Setting the 'createMeasures' parameter to 'true' will create the measures in the model file within Tabular Editor. Setting this paramter to 'false' will dynamically generate C# code which can be copied and executed in order to create the measures in a model.
### [Vertipaq Annotations](https://www.elegantbi.com/post/vertipaqintabulareditor "Vertipaq Annotations")
Run this script against a live-connected model to save [Vertipaq Analyzer](https://www.sqlbi.com/tools/vertipaq-analyzer/ "Vertipaq Analyzer") statistics as annotations on model objects. These annotations may be referenced to create Best Practice Analyzer rules for your model. See the link below for more info on [Tabular Editor](https://tabulareditor.com/ "Tabular Editor")'s [Best Practice Analyzer](https://docs.tabulareditor.com/Best-Practice-Analyzer.html "Best Practice Analyzer").
*Note: If running this script against a Power BI Desktop model (using Tabular Editor as an External Tool), you must select the following setting within Tabular Editor:*
File -> Preferences -> Features -> Allow Unsupported Power BI features (experimental)
* **Model:** Model Size
* **Tables:** Row Count; Table Size; Table Size as a Percentage of the Model Size
* **Partitions:** Record Count; Segment Count; Records Per Segment
* **Columns:** Cardinality; Column Hierarchy Size; Column Size; Data Size; Dictionary Size; Column Size as a Percentage of the Table Size; Column Size as a Percentage of the Model Size
* **Hierarchies:** User Hierarchy Size
* **Relationships:** Relationship Size; Max From Cardinality; Max To Cardinality; Referential Integrity Violation Invalid Rows
### [Vpax to Tabular Editor](https://www.elegantbi.com/post/vpaxtotabulareditor "Vpax to Tabular Editor")
This script creates the same annotations as the [Vertipaq Annotations](https://github.com/m-kovalsky/Tabular/blob/master/VertipaqAnnotations.cs "Vertipaq Annotations") script. The only difference is that this script loads the [Vertipaq Analyzer](https://www.sqlbi.com/tools/vertipaq-analyzer/ "Vertipaq Analyzer") data from a Vertipaq Analyzer (.vpax) file. The .vpax file can be generated by selecting 'View Metrics' within the 'Advanced' tab in [DAX Studio](https://daxstudio.org/ "DAX Studio").
|
f43a4925ae7ccddbb550d739032b8bf00d19d63b
|
{
"blob_id": "f43a4925ae7ccddbb550d739032b8bf00d19d63b",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-28T08:33:07",
"content_id": "1a1ff070abe822ffecba7c184349eb122a8fc435",
"detected_licenses": [
"MIT"
],
"directory_id": "7e1ded42418346b917c913f689366658cd949d17",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 9968,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0017.json.gz:316707",
"repo_name": "sureshpaulraj/Tabular",
"revision_date": "2021-10-28T08:33:07",
"revision_id": "4563ef7ec2ee3a8b8735123f5498c395d00127c8",
"snapshot_id": "a17c308580abfab9575ea5bd614014075ca92992",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sureshpaulraj/Tabular/4563ef7ec2ee3a8b8735123f5498c395d00127c8/README.md",
"visit_date": "2023-08-24T00:11:55.113793",
"added": "2024-11-18T23:37:36.575235+00:00",
"created": "2021-10-28T08:33:07",
"int_score": 3,
"score": 3.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0017.json.gz"
}
|
function Segment(x, y){
this.x = x;
this.y = y;
}
function Snake(grid){
Sprite.call(this);
this.grid = grid;
this.size = grid.cellSize;
var seg = new Sprite();
seg.image = Textures.load("images/bear.png");
seg.width = this.size;
seg.height = this.size;
seg.offsetX = -seg.width/2;
seg.offsetY = -seg.height/2;
this.seg = seg;
this.addChild(seg);
this.body = new List();
this.body.push(new Segment(grid.cols/2,grid.rows/2));
}
Snake.prototype = new Sprite();
Snake.prototype.speed = 0.1;
Snake.prototype.time = 0;
Snake.prototype.moveTime = 15;
Snake.prototype.dir = 0;
Snake.prototype.currenDir = 0;
Snake.prototype.dead = false;
//Adds some boolean values to the global input
gInput.addBool(39, "right");
gInput.addBool(40, "down");
gInput.addBool(37, "left");
gInput.addBool(38, "up");
Snake.prototype.draw = function(ctx){
var prev = null;
for(var node = this.body.head; node != null; node = node.link){
var current = node.item;
this.seg.x = current.x*this.size;
this.seg.y = current.y*this.size;
if(prev == null){
this.seg.rotation = DTR(this.currentDir*90);
}else{
var xd = prev.x-current.x;
var yd = prev.y-current.y;
var ang = Math.atan2(yd,xd);
this.seg.rotation = ang;
}
prev = current;
this.drawChildren(ctx);
}
}
Snake.prototype.update = function(d){
if(gInput.right){
if(this.currentDir != 2){
this.dir = 0;
}
}
if(gInput.down){
if(this.currentDir != 3){
this.dir = 1;
}
}
if(gInput.left){
if(this.currentDir != 0){
this.dir = 2;
}
}
if(gInput.up){
if(this.currentDir != 1){
this.dir = 3;
}
}
if(!this.dead){
this.time++;
if(this.time%this.moveTime == 0){
this.move();
}
}
}
Snake.prototype.move = function(){
//console.log("moving");
var head = this.body.head.item;
var headX = head.x;
var headY = head.y;
if(this.dir == 0){
headX += 1;
}else if(this.dir == 1){
headY += 1;
}else if(this.dir == 2){
headX -= 1;
}else if(this.dir == 3){
headY -= 1;
}
var newCell = this.grid.popCell(headX, headY);
if(newCell != "empty"){
if(newCell instanceof Food){
var newTail = new Segment(0,0);
this.body.push(newTail);
this.grid.pushCell(0, 0);
newCell.reposition();
}else if(newCell instanceof Segment){
this.dead = true;
}
}else{
this.dead = true;
}
var tail = this.body.tail.item;
this.body.remove(tail);
this.grid.popCell(tail.x, tail.y);
this.body.push_front(tail);
tail.x = headX;
tail.y = headY;
this.grid.pushCell(headX, headY, tail);
this.currentDir = this.dir;
}
|
04a83752436a7962339845bd6a75cdf6596ca7ad
|
{
"blob_id": "04a83752436a7962339845bd6a75cdf6596ca7ad",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-06T05:37:41",
"content_id": "5da5dbd9d2f9fbb596154a51ae6d1da42a4c8c90",
"detected_licenses": [
"MIT"
],
"directory_id": "1e6a2d5e501e3d53c415edacc48b4f147ce19e95",
"extension": "js",
"filename": "Snake.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 28845043,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2678,
"license": "MIT",
"license_type": "permissive",
"path": "/snake/Snake.js",
"provenance": "stack-edu-0043.json.gz:654166",
"repo_name": "Selkcip/brine",
"revision_date": "2015-01-06T05:37:41",
"revision_id": "fccfd76079580fb483aa127345d2fc9125a92c0d",
"snapshot_id": "466021d2eeaf8d555bd54ab671a2c528a014105a",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/Selkcip/brine/fccfd76079580fb483aa127345d2fc9125a92c0d/snake/Snake.js",
"visit_date": "2021-01-22T09:09:15.796048",
"added": "2024-11-19T01:52:07.439082+00:00",
"created": "2015-01-06T05:37:41",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\TransportadoraCusto;
/**
* TransportadoracustoSearch represents the model behind the search form about `app\models\TransportadoraCusto`.
*/
class TransportadoracustoSearch extends TransportadoraCusto
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'transportadora_id'], 'integer'],
[['custo_ar', 'custo_terra', 'custo_agua', 'custo_palete', 'custo_quilo'], 'number'],
[['searchTransportadora'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = TransportadoraCusto::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->joinWith('transportadora');
$dataProvider->setSort([
'attributes' => [
'custo_ar',
'custo_terra',
'custo_agua',
'custo_palete',
'custo_quilo',
'searchTransportadora'=> [
'asc' => ['transportadora.nome'=>SORT_ASC],
'desc' => ['transportadora.nome'=>SORT_DESC],
],
],
]);
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'custo_ar' => $this->custo_ar,
'custo_terra' => $this->custo_terra,
'custo_agua' => $this->custo_agua,
'custo_palete' => $this->custo_palete,
'custo_quilo' => $this->custo_quilo,
'transportadora_id' => $this->transportadora_id,
]);
$query->andFilterWhere(['like', 'transportadora.nome', $this->searchTransportadora]);
return $dataProvider;
}
}
|
39a85abeceddfd40f6c285df7331aa5961cc323d
|
{
"blob_id": "39a85abeceddfd40f6c285df7331aa5961cc323d",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-28T17:09:06",
"content_id": "d8554223e6b7af868699aae539c658a38bc01a48",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "213eecaf3578103cb3d20e9013bd8a23fb627b17",
"extension": "php",
"filename": "TransportadoracustoSearch.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 98627448,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2472,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/models/TransportadoracustoSearch.php",
"provenance": "stack-edu-0047.json.gz:628984",
"repo_name": "isaelanjos/itriad",
"revision_date": "2017-07-28T17:09:06",
"revision_id": "790d0dee0f7e4972452cae3057218c4752aee471",
"snapshot_id": "1ef247e7d0000abba81ab371d3a76d4a9b1f7f6f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/isaelanjos/itriad/790d0dee0f7e4972452cae3057218c4752aee471/models/TransportadoracustoSearch.php",
"visit_date": "2021-01-01T19:37:01.731479",
"added": "2024-11-19T03:21:58.622650+00:00",
"created": "2017-07-28T17:09:06",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LionFire.Valor;
using LionFire.Assets;
using LionFire.Templating;
namespace LionFire.Netrek
{
public class Torpedo : NetrekEntity<ProjectileState>
{
public override ITEntity Template
{
get
{
return LionFire.Valor.Packs.Nextrek.Vanilla.VanillaUnits.CA_Torp;
//return new HAsset<TUnit>(Team + "/Torpedo");
}
}
public Torpedo(Galaxy galaxy, int netrekId)
: base(galaxy, netrekId)
{
}
public override bool CanCreateEntity()
{
if (Status == TorpStatus.Free)
{
return false;
}
return base.CanCreateEntity();
}
public sbyte War { get; set; }
public TorpStatus Status
{
get { return status; }
set
{
if (status == value) return;
status = value;
switch (status)
{
case TorpStatus.Free:
if (Entity != null)
{
if (Entity.IsAlive) { Entity.Die(DieReason.Expired); }
Entity = null;
}
break;
case TorpStatus.Move:
TryCreateEntity(); // REVIEW - may be multiple unnecessary creates
break;
case TorpStatus.Explode:
if (Entity != null)
{
if (Entity.IsAlive) Entity.Die(DieReason.Detonated);
//Entity = null;
}
break;
case TorpStatus.Detonated:
if (Entity != null)
{
if (Entity.IsAlive) Entity.Die(DieReason.Abandoned);
//Entity = null;
}
break;
case TorpStatus.TOFF:
if (Entity != null)
{
if (Entity.IsAlive) Entity.Die(DieReason.Abandoned);
Entity = null;
}
l.Warn("Not implemented: TOFF torpedoes");
break;
case TorpStatus.TSTRAIGHT:
l.Warn("Not implemented: Straight torpedoes");
break;
default:
throw new UnreachableCodeException();
}
l.Trace(this.ToString() + " " + status);
}
}
private TorpStatus status = TorpStatus.Free;
private static ILogger l = Log.Get();
}
}
|
c016b1591dbb7c75a4996bcd237a8bf44f3f0f7e
|
{
"blob_id": "c016b1591dbb7c75a4996bcd237a8bf44f3f0f7e",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-01T08:41:25",
"content_id": "00738f0a031d4278a79a26407ca0843e3a10d84b",
"detected_licenses": [
"CC0-1.0",
"Unlicense"
],
"directory_id": "dce708f5dab50dfe16a5938662ab49bcf548d856",
"extension": "cs",
"filename": "Torpedo.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2968,
"license": "CC0-1.0,Unlicense",
"license_type": "permissive",
"path": "/DotNetrek/Model/Torpedo.cs",
"provenance": "stack-edu-0013.json.gz:875317",
"repo_name": "jaredthirsk/DotNetrek",
"revision_date": "2013-11-01T08:41:25",
"revision_id": "95b977fc79d0a72f421997be05f19104c1d62256",
"snapshot_id": "377193a79c28e0336d5675959dcb838417470726",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jaredthirsk/DotNetrek/95b977fc79d0a72f421997be05f19104c1d62256/DotNetrek/Model/Torpedo.cs",
"visit_date": "2020-04-25T23:47:20.863810",
"added": "2024-11-19T00:09:36.391010+00:00",
"created": "2013-11-01T08:41:25",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
package org.scut.ccnl.genomics;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.PeekableIterator;
import java.util.Iterator;
public class PeekableLastIterator<Object> extends PeekableIterator<Object> {
private Object last;
/** Constructs a new iterator that wraps the supplied iterator. */
public PeekableLastIterator(Iterator<Object> iterator) {
super(iterator);
}
/** Returns the next object and advances the iterator. */
@Override
public Object next() {
Object retval = super.next();
rememberLast(retval);
return retval;
}
private void rememberLast(Object retval){
last = retval;
}
public Object getLast(){
return last;
}
}
|
0a51f7724aa09c93465d6d6826b649c3b1ea67d4
|
{
"blob_id": "0a51f7724aa09c93465d6d6826b649c3b1ea67d4",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-21T16:29:36",
"content_id": "7d054ad63c2f945d6535789fe99d9805d0ff98d1",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "29badb7fb9eadc372729e1cdb814baa844f487fa",
"extension": "java",
"filename": "PeekableLastIterator.java",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 156668750,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 797,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/main/java/org/scut/ccnl/genomics/PeekableLastIterator.java",
"provenance": "stack-edu-0024.json.gz:314009",
"repo_name": "SCUT-CCNL/ADS-HCSpark",
"revision_date": "2018-11-21T16:29:36",
"revision_id": "53d560a1884dfe6627418a1e6e060bbd2da847e3",
"snapshot_id": "49bf480b2ea25f2663753273d5efe98d9ea56ed2",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/SCUT-CCNL/ADS-HCSpark/53d560a1884dfe6627418a1e6e060bbd2da847e3/src/main/java/org/scut/ccnl/genomics/PeekableLastIterator.java",
"visit_date": "2020-04-05T07:15:24.275591",
"added": "2024-11-18T23:52:44.176668+00:00",
"created": "2018-11-21T16:29:36",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package com.codefortomorrow.beginner.chapter7.solutions;
/*
* Create a program called Max,
* which prompts the user to
* enter 2 numbers.
*
* Use the ternary operator to
* assign a value to a variable
* max, and then print the max.
*/
import java.util.Scanner;
public class Max {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number 1: ");
double n1 = input.nextDouble();
System.out.print("Enter number 2: ");
double n2 = input.nextDouble();
input.close();
double max = (n1 > n2) ? n1 : n2; // real world: use Math.max(n1, n2)
System.out.println("The max of " + n1 + " and " + n2 + " is " + max);
}
}
|
95eb71f0e13e7351ab669ece6309998c075bd233
|
{
"blob_id": "95eb71f0e13e7351ab669ece6309998c075bd233",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-07T18:11:22",
"content_id": "11490d88b424d91c79a9a181222c2dbf71157d10",
"detected_licenses": [
"MIT"
],
"directory_id": "ce22eb7af8e449bb9fe8ae55771f4e5932067a3f",
"extension": "java",
"filename": "Max.java",
"fork_events_count": 6,
"gha_created_at": "2020-05-02T18:59:05",
"gha_event_created_at": "2021-07-07T18:11:23",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 260755337,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 745,
"license": "MIT",
"license_type": "permissive",
"path": "/src/com/codefortomorrow/beginner/chapter7/solutions/Max.java",
"provenance": "stack-edu-0031.json.gz:725701",
"repo_name": "code4tomorrow/java",
"revision_date": "2021-07-07T18:11:22",
"revision_id": "0b3b77394bdea71781b2ac25b14eb271362c233b",
"snapshot_id": "5e91dd91dbb760f47dc93663d3fc379ae6eb9556",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/code4tomorrow/java/0b3b77394bdea71781b2ac25b14eb271362c233b/src/com/codefortomorrow/beginner/chapter7/solutions/Max.java",
"visit_date": "2023-06-01T05:15:27.320613",
"added": "2024-11-18T21:21:58.081238+00:00",
"created": "2021-07-07T18:11:22",
"int_score": 5,
"score": 4.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
package com.maxzuo.printtemplate.api;
import com.github.pagehelper.PageInfo;
import com.maxzuo.printtemplate.model.ScOperationPrinterKitchen;
/**
* 出票口相关Service
* Created by zfh on 2019/01/09
*/
public interface IScOperationPrinterKitchenService {
/**
* 添加记录
* @param record {@link ScOperationPrinterKitchen}
* @return 自增主键
*/
Integer save(ScOperationPrinterKitchen record);
/**
* 根据主键查询
* @param id 主键
* @return {@link ScOperationPrinterKitchen}
*/
ScOperationPrinterKitchen getByPrimaryKey(Integer id);
/**
* 查询店铺下所有的出票口(未删除)
* @param shopId 店铺id
* @param page 页码
* @param rows 页条数
* @return {@link PageInfo}
*/
PageInfo<ScOperationPrinterKitchen> listPrinterKitchenByShopId (Integer shopId, Integer page, Integer rows);
/**
* 根据主键有选择性的更新
* @param record {@link ScOperationPrinterKitchen}
* @return 受影响的条数
*/
Integer updateByPrimaryKeySelective(ScOperationPrinterKitchen record);
}
|
7e165f41cf5fd4b988bd4eb10a8728e6a58b905d
|
{
"blob_id": "7e165f41cf5fd4b988bd4eb10a8728e6a58b905d",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-17T12:03:53",
"content_id": "7d40bce726d944fc2a9f10ca544edcb23a7bec75",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "6cae4a9688572f4351163aadaf3e0790a3a54d36",
"extension": "java",
"filename": "IScOperationPrinterKitchenService.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1141,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/print-template/src/main/java/com/maxzuo/printtemplate/api/IScOperationPrinterKitchenService.java",
"provenance": "stack-edu-0024.json.gz:494653",
"repo_name": "lweitao/bulb",
"revision_date": "2019-08-17T12:03:53",
"revision_id": "ecf3030724f3cc628c43378c33a509616f02eb02",
"snapshot_id": "2c643584cc749b207b5be51db31a883c4851aafc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lweitao/bulb/ecf3030724f3cc628c43378c33a509616f02eb02/print-template/src/main/java/com/maxzuo/printtemplate/api/IScOperationPrinterKitchenService.java",
"visit_date": "2020-07-07T07:31:38.108676",
"added": "2024-11-19T00:37:22.426146+00:00",
"created": "2019-08-17T12:03:53",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package cn.leancloud.im.v2;
import cn.leancloud.AVLogger;
import cn.leancloud.im.AVIMEventHandler;
import cn.leancloud.utils.LogUtil;
/**
*
* 用于处理Client相关的事件,包括网络连接断开和网络连接恢复
*/
public abstract class AVIMClientEventHandler extends AVIMEventHandler {
protected static final AVLogger LOGGER = LogUtil.getLogger(AVIMClientEventHandler.class);
private int prevOperation = Conversation.AVIMOperation.CONVERSATION_UNKNOWN.getCode();
/**
* 实现本方法以处理网络断开事件
*
* @param client client instance
* @since 3.0
*/
public abstract void onConnectionPaused(AVIMClient client);
/**
* 实现本方法以处理网络恢复事件
*
* @since 3.0
* @param client client instance
*/
public abstract void onConnectionResume(AVIMClient client);
/**
* 实现本方法以处理当前登录被踢下线的情况
*
*
* @param client client instance
* @param code 状态码说明被踢下线的具体原因
*/
public abstract void onClientOffline(AVIMClient client, int code);
@Override
protected final void processEvent0(int operation, Object operator, Object operand,
Object eventScene) {
if (prevOperation == operation) {
LOGGER.d("ignore duplicated operation: " + operation);
return;
}
prevOperation = operation;
switch (operation) {
case Conversation.STATUS_ON_CONNECTION_RESUMED:
onConnectionResume((AVIMClient) eventScene);
break;
case Conversation.STATUS_ON_CONNECTION_PAUSED:
onConnectionPaused((AVIMClient) eventScene);
break;
case Conversation.STATUS_ON_CLIENT_OFFLINE:
onClientOffline((AVIMClient) eventScene, (Integer) operand);
((AVIMClient) eventScene).close(null); // TODO: FIXME
break;
default:
LOGGER.d("ignore operation:" + operand);
}
}
}
|
33175facbfb1138a5c948aba98884ccef8b9c4fa
|
{
"blob_id": "33175facbfb1138a5c948aba98884ccef8b9c4fa",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-22T01:28:28",
"content_id": "b5d91f5e4629fdac1c488a0d1ff100fce3700cff",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b80eea6e56730144566e67ded030e364fbf9f042",
"extension": "java",
"filename": "AVIMClientEventHandler.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1942,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/realtime/src/main/java/cn/leancloud/im/v2/AVIMClientEventHandler.java",
"provenance": "stack-edu-0019.json.gz:364621",
"repo_name": "yin-haoran/java-unified-sdk",
"revision_date": "2021-04-22T01:28:28",
"revision_id": "34542bb4bf61e47ce3ea5f2df845c14a668217c6",
"snapshot_id": "1c64f43ee3c151cb2b1372f73ca45629f68c722e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yin-haoran/java-unified-sdk/34542bb4bf61e47ce3ea5f2df845c14a668217c6/realtime/src/main/java/cn/leancloud/im/v2/AVIMClientEventHandler.java",
"visit_date": "2023-04-10T05:05:08.714448",
"added": "2024-11-19T02:06:05.635786+00:00",
"created": "2021-04-22T01:28:28",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Utilities;
namespace Microsoft.Xna.Framework.Audio
{
/// <summary>Represents a collection of wave files.</summary>
public class WaveBank : IDisposable
{
#if !PORTABLE
private SoundEffect[] _sounds;
private string _bankName;
#endif
public bool IsDisposed { get; private set; }
#if !PORTABLE
struct Segment
{
public int Offset;
public int Length;
}
struct WaveBankEntry
{
public int Format;
public Segment PlayRegion;
public Segment LoopRegion;
public int FlagsAndDuration;
}
struct WaveBankHeader
{
public int Version;
public Segment[] Segments;
}
struct WaveBankData
{
public int Flags; // Bank flags
public int EntryCount; // Number of entries in the bank
public string BankName; // Bank friendly name
public int EntryMetaDataElementSize; // Size of each entry meta-data element, in bytes
public int EntryNameElementSize; // Size of each entry name element, in bytes
public int Alignment; // Entry alignment, in bytes
public int CompactFormat; // Format data for compact bank
public int BuildTime; // Build timestamp
}
private const int Flag_EntryNames = 0x00010000; // Bank includes entry names
private const int Flag_Compact = 0x00020000; // Bank uses compact format
private const int Flag_SyncDisabled = 0x00040000; // Bank is disabled for audition sync
private const int Flag_SeekTables = 0x00080000; // Bank includes seek tables.
private const int Flag_Mask = 0x000F0000;
private const int MiniFormatTag_PCM = 0x0;
private const int MiniFormatTag_XMA = 0x1;
private const int MiniFormatTag_ADPCM = 0x2;
private const int MiniForamtTag_WMA = 0x3;
#endif
/// <param name="audioEngine">Instance of the AudioEngine to associate this wave bank with.</param>
/// <param name="nonStreamingWaveBankFilename">Path to the .xwb file to load.</param>
/// <remarks>This constructor immediately loads all wave data into memory at once.</remarks>
public WaveBank(AudioEngine audioEngine, string nonStreamingWaveBankFilename)
{
#if PORTABLE
throw MonoGame.Portable.NotImplementedException;
#else
//XWB PARSING
//Adapted from MonoXNA
//Originally adaped from Luigi Auriemma's unxwb
WaveBankHeader wavebankheader;
WaveBankData wavebankdata;
WaveBankEntry wavebankentry;
wavebankdata.EntryNameElementSize = 0;
wavebankdata.CompactFormat = 0;
wavebankdata.Alignment = 0;
wavebankdata.BuildTime = 0;
wavebankentry.Format = 0;
wavebankentry.PlayRegion.Length = 0;
wavebankentry.PlayRegion.Offset = 0;
int wavebank_offset = 0;
nonStreamingWaveBankFilename = FileHelpers.NormalizeFilePathSeparators(nonStreamingWaveBankFilename);
#if !ANDROID
BinaryReader reader = new BinaryReader(TitleContainer.OpenStream(nonStreamingWaveBankFilename));
#else
Stream stream = Game.Activity.Assets.Open(nonStreamingWaveBankFilename);
MemoryStream ms = new MemoryStream();
stream.CopyTo( ms );
stream.Close();
ms.Position = 0;
BinaryReader reader = new BinaryReader(ms);
#endif
reader.ReadBytes(4);
wavebankheader.Version = reader.ReadInt32();
int last_segment = 4;
//if (wavebankheader.Version == 1) goto WAVEBANKDATA;
if (wavebankheader.Version <= 3) last_segment = 3;
if (wavebankheader.Version >= 42) reader.ReadInt32(); // skip HeaderVersion
wavebankheader.Segments = new Segment[5];
for (int i = 0; i <= last_segment; i++)
{
wavebankheader.Segments[i].Offset = reader.ReadInt32();
wavebankheader.Segments[i].Length = reader.ReadInt32();
}
reader.BaseStream.Seek(wavebankheader.Segments[0].Offset, SeekOrigin.Begin);
//WAVEBANKDATA:
wavebankdata.Flags = reader.ReadInt32();
wavebankdata.EntryCount = reader.ReadInt32();
if ((wavebankheader.Version == 2) || (wavebankheader.Version == 3))
{
wavebankdata.BankName = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(16),0,16).Replace("\0", "");
}
else
{
wavebankdata.BankName = System.Text.Encoding.UTF8.GetString(reader.ReadBytes(64),0,64).Replace("\0", "");
}
_bankName = wavebankdata.BankName;
if (wavebankheader.Version == 1)
{
//wavebank_offset = (int)ftell(fd) - file_offset;
wavebankdata.EntryMetaDataElementSize = 20;
}
else
{
wavebankdata.EntryMetaDataElementSize = reader.ReadInt32();
wavebankdata.EntryNameElementSize = reader.ReadInt32();
wavebankdata.Alignment = reader.ReadInt32();
wavebank_offset = wavebankheader.Segments[1].Offset; //METADATASEGMENT
}
if ((wavebankdata.Flags & Flag_Compact) != 0)
{
reader.ReadInt32(); // compact_format
}
int playregion_offset = wavebankheader.Segments[last_segment].Offset;
if (playregion_offset == 0)
{
playregion_offset =
wavebank_offset +
(wavebankdata.EntryCount * wavebankdata.EntryMetaDataElementSize);
}
int segidx_entry_name = 2;
if (wavebankheader.Version >= 42) segidx_entry_name = 3;
if ((wavebankheader.Segments[segidx_entry_name].Offset != 0) &&
(wavebankheader.Segments[segidx_entry_name].Length != 0))
{
if (wavebankdata.EntryNameElementSize == -1) wavebankdata.EntryNameElementSize = 0;
byte[] entry_name = new byte[wavebankdata.EntryNameElementSize + 1];
entry_name[wavebankdata.EntryNameElementSize] = 0;
}
_sounds = new SoundEffect[wavebankdata.EntryCount];
for (int current_entry = 0; current_entry < wavebankdata.EntryCount; current_entry++)
{
reader.BaseStream.Seek(wavebank_offset, SeekOrigin.Begin);
//SHOWFILEOFF;
//memset(&wavebankentry, 0, sizeof(wavebankentry));
wavebankentry.LoopRegion.Length = 0;
wavebankentry.LoopRegion.Offset = 0;
if ((wavebankdata.Flags & Flag_Compact) != 0)
{
int len = reader.ReadInt32();
wavebankentry.Format = wavebankdata.CompactFormat;
wavebankentry.PlayRegion.Offset = (len & ((1 << 21) - 1)) * wavebankdata.Alignment;
wavebankentry.PlayRegion.Length = (len >> 21) & ((1 << 11) - 1);
// workaround because I don't know how to handke the deviation length
reader.BaseStream.Seek(wavebank_offset + wavebankdata.EntryMetaDataElementSize, SeekOrigin.Begin);
//MYFSEEK(wavebank_offset + wavebankdata.dwEntryMetaDataElementSize); // seek to the next
if (current_entry == (wavebankdata.EntryCount - 1))
{ // the last track
len = wavebankheader.Segments[last_segment].Length;
}
else
{
len = ((reader.ReadInt32() & ((1 << 21) - 1)) * wavebankdata.Alignment);
}
wavebankentry.PlayRegion.Length =
len - // next offset
wavebankentry.PlayRegion.Offset; // current offset
goto wavebank_handle;
}
if (wavebankheader.Version == 1)
{
wavebankentry.Format = reader.ReadInt32();
wavebankentry.PlayRegion.Offset = reader.ReadInt32();
wavebankentry.PlayRegion.Length = reader.ReadInt32();
wavebankentry.LoopRegion.Offset = reader.ReadInt32();
wavebankentry.LoopRegion.Length = reader.ReadInt32();
}
else
{
if (wavebankdata.EntryMetaDataElementSize >= 4) wavebankentry.FlagsAndDuration = reader.ReadInt32();
if (wavebankdata.EntryMetaDataElementSize >= 8) wavebankentry.Format = reader.ReadInt32();
if (wavebankdata.EntryMetaDataElementSize >= 12) wavebankentry.PlayRegion.Offset = reader.ReadInt32();
if (wavebankdata.EntryMetaDataElementSize >= 16) wavebankentry.PlayRegion.Length = reader.ReadInt32();
if (wavebankdata.EntryMetaDataElementSize >= 20) wavebankentry.LoopRegion.Offset = reader.ReadInt32();
if (wavebankdata.EntryMetaDataElementSize >= 24) wavebankentry.LoopRegion.Length = reader.ReadInt32();
}
if (wavebankdata.EntryMetaDataElementSize < 24)
{ // work-around
if (wavebankentry.PlayRegion.Length != 0)
{
wavebankentry.PlayRegion.Length = wavebankheader.Segments[last_segment].Length;
}
}// else if(wavebankdata.EntryMetaDataElementSize > sizeof(WaveBankEntry)) { // skip unused fields
// MYFSEEK(wavebank_offset + wavebankdata.EntryMetaDataElementSize);
//}
wavebank_handle:
wavebank_offset += wavebankdata.EntryMetaDataElementSize;
wavebankentry.PlayRegion.Offset += playregion_offset;
// Parse WAVEBANKMINIWAVEFORMAT
int codec;
int chans;
int rate;
int align;
//int bits;
if (wavebankheader.Version == 1)
{ // I'm not 100% sure if the following is correct
// version 1:
// 1 00000000 000101011000100010 0 001 0
// | | | | | |
// | | | | | wFormatTag
// | | | | nChannels
// | | | ???
// | | nSamplesPerSec
// | wBlockAlign
// wBitsPerSample
codec = (wavebankentry.Format) & ((1 << 1) - 1);
chans = (wavebankentry.Format >> (1)) & ((1 << 3) - 1);
rate = (wavebankentry.Format >> (1 + 3 + 1)) & ((1 << 18) - 1);
align = (wavebankentry.Format >> (1 + 3 + 1 + 18)) & ((1 << 8) - 1);
//bits = (wavebankentry.Format >> (1 + 3 + 1 + 18 + 8)) & ((1 << 1) - 1);
/*} else if(wavebankheader.dwVersion == 23) { // I'm not 100% sure if the following is correct
// version 23:
// 1000000000 001011101110000000 001 1
// | | | | |
// | | | | ???
// | | | nChannels?
// | | nSamplesPerSec
// | ???
// !!!UNKNOWN FORMAT!!!
//codec = -1;
//chans = (wavebankentry.Format >> 1) & ((1 << 3) - 1);
//rate = (wavebankentry.Format >> 4) & ((1 << 18) - 1);
//bits = (wavebankentry.Format >> 31) & ((1 << 1) - 1);
codec = (wavebankentry.Format ) & ((1 << 1) - 1);
chans = (wavebankentry.Format >> (1) ) & ((1 << 3) - 1);
rate = (wavebankentry.Format >> (1 + 3) ) & ((1 << 18) - 1);
align = (wavebankentry.Format >> (1 + 3 + 18) ) & ((1 << 9) - 1);
bits = (wavebankentry.Format >> (1 + 3 + 18 + 9)) & ((1 << 1) - 1); */
}
else
{
// 0 00000000 000111110100000000 010 01
// | | | | |
// | | | | wFormatTag
// | | | nChannels
// | | nSamplesPerSec
// | wBlockAlign
// wBitsPerSample
codec = (wavebankentry.Format) & ((1 << 2) - 1);
chans = (wavebankentry.Format >> (2)) & ((1 << 3) - 1);
rate = (wavebankentry.Format >> (2 + 3)) & ((1 << 18) - 1);
align = (wavebankentry.Format >> (2 + 3 + 18)) & ((1 << 8) - 1);
//bits = (wavebankentry.Format >> (2 + 3 + 18 + 8)) & ((1 << 1) - 1);
}
reader.BaseStream.Seek(wavebankentry.PlayRegion.Offset, SeekOrigin.Begin);
byte[] audiodata = reader.ReadBytes(wavebankentry.PlayRegion.Length);
if (codec == MiniFormatTag_PCM) {
//write PCM data into a wav
#if DIRECTX
// TODO: Wouldn't storing a SoundEffectInstance like this
// result in the "parent" SoundEffect being garbage collected?
SharpDX.Multimedia.WaveFormat waveFormat = new SharpDX.Multimedia.WaveFormat(rate, chans);
var sfx = new SoundEffect(audiodata, 0, audiodata.Length, rate, (AudioChannels)chans, wavebankentry.LoopRegion.Offset, wavebankentry.LoopRegion.Length)
{
_format = waveFormat
};
_sounds[current_entry] = sfx;
#else
_sounds[current_entry] = new SoundEffect(audiodata, rate, (AudioChannels)chans);
#endif
} else if (codec == MiniForamtTag_WMA) { //WMA or xWMA (or XMA2)
byte[] wmaSig = {0x30, 0x26, 0xb2, 0x75, 0x8e, 0x66, 0xcf, 0x11, 0xa6, 0xd9, 0x0, 0xaa, 0x0, 0x62, 0xce, 0x6c};
bool isWma = true;
for (int i=0; i<wmaSig.Length; i++) {
if (wmaSig[i] != audiodata[i]) {
isWma = false;
break;
}
}
//Let's support m4a data as well for convenience
byte[][] m4aSigs = new byte[][] {
new byte[] {0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20, 0x00, 0x00, 0x02, 0x00},
new byte[] {0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41, 0x20, 0x00, 0x00, 0x00, 0x00}
};
bool isM4a = false;
for (int i=0; i<m4aSigs.Length; i++) {
byte[] sig = m4aSigs[i];
bool matches = true;
for (int j=0; j<sig.Length; j++) {
if (sig[j] != audiodata[j]) {
matches = false;
break;
}
}
if (matches) {
isM4a = true;
break;
}
}
if (isWma || isM4a) {
//WMA data can sometimes be played directly
#if DIRECTX
throw new NotImplementedException();
#elif !WINRT
//hack - NSSound can't play non-wav from data, we have to give a filename
string filename = Path.GetTempFileName();
if (isWma) {
filename = filename.Replace(".tmp", ".wma");
} else if (isM4a) {
filename = filename.Replace(".tmp", ".m4a");
}
using (var audioFile = File.Create(filename))
{
audioFile.Write(audiodata, 0, audiodata.Length);
audioFile.Seek(0, SeekOrigin.Begin);
_sounds[current_entry] = SoundEffect.FromStream(audioFile);
}
#else
throw new NotImplementedException();
#endif
} else {
//An xWMA or XMA2 file. Can't be played atm :(
throw new NotImplementedException();
}
}
else if (codec == MiniFormatTag_ADPCM)
{
#if DIRECTX
_sounds[current_entry] = new SoundEffect(audiodata, rate, (AudioChannels)chans)
{
_format = new SharpDX.Multimedia.WaveFormatAdpcm(rate, chans, align)
};
#else
using (var dataStream = new MemoryStream(audiodata)) {
using (var source = new BinaryReader(dataStream)) {
_sounds[current_entry] = new SoundEffect(
MSADPCMToPCM.MSADPCM_TO_PCM(source, (short) chans, (short) align),
rate,
(AudioChannels)chans
);
}
}
#endif
}
else {
throw new NotImplementedException();
}
}
audioEngine.Wavebanks[_bankName] = this;
#endif
}
/// <param name="audioEngine">Instance of the AudioEngine to associate this wave bank with.</param>
/// <param name="streamingWaveBankFilename">Path to the .xwb to stream from.</param>
/// <param name="offset">DVD sector-aligned offset within the wave bank data file.</param>
/// <param name="packetsize">Stream packet size, in sectors, to use for each stream. The minimum value is 2.</param>
/// <remarks>
/// <para>This constructor streams wave data as needed.</para>
/// <para>Note that packetsize is in sectors, which is 2048 bytes.</para>
/// <para>AudioEngine.Update() must be called at least once before using data from a streaming wave bank.</para>
/// </remarks>
public WaveBank(AudioEngine audioEngine, string streamingWaveBankFilename, int offset, short packetsize)
: this(audioEngine, streamingWaveBankFilename)
{
if (offset != 0) {
throw new NotImplementedException();
}
}
internal SoundEffect GetSoundEffect(int trackIndex)
{
#if PORTABLE
throw MonoGame.Portable.NotImplementedException;
#else
return _sounds[trackIndex];
#endif
}
#region IDisposable implementation
public void Dispose ()
{
if (IsDisposed)
return;
#if !PORTABLE
foreach (var s in _sounds)
s.Dispose();
#endif
IsDisposed = true;
}
#endregion
}
}
|
5a134dbecda2f279d86ec113bcff3830178979da
|
{
"blob_id": "5a134dbecda2f279d86ec113bcff3830178979da",
"branch_name": "refs/heads/DigitalRune",
"committer_date": "2016-06-04T18:29:16",
"content_id": "7aafc9ae31e11f05015d1d6dd81e7fd845629de4",
"detected_licenses": [
"MIT",
"MS-PL"
],
"directory_id": "e43cd556138a77c7c8bc086cb1202e8c453b510b",
"extension": "cs",
"filename": "WaveBank.cs",
"fork_events_count": 4,
"gha_created_at": "2013-02-08T11:07:30",
"gha_event_created_at": "2016-08-12T07:31:30",
"gha_language": "C#",
"gha_license_id": null,
"github_id": 8092119,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 20885,
"license": "MIT,MS-PL",
"license_type": "permissive",
"path": "/MonoGame.Framework/Audio/Xact/WaveBank.cs",
"provenance": "stack-edu-0015.json.gz:113971",
"repo_name": "DigitalRune/MonoGame",
"revision_date": "2016-06-04T18:29:16",
"revision_id": "366394d841fb53a7be8e96bb44db8733b8e7fed4",
"snapshot_id": "e4e0f26e5ca0e918326187f64e53347c28d14831",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/DigitalRune/MonoGame/366394d841fb53a7be8e96bb44db8733b8e7fed4/MonoGame.Framework/Audio/Xact/WaveBank.cs",
"visit_date": "2021-01-18T09:22:23.428895",
"added": "2024-11-19T01:01:10.464449+00:00",
"created": "2016-06-04T18:29:16",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(dead_code)]
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
// https://html.spec.whatwg.org/multipage/#beforeunloadevent
#[dom_struct]
pub struct BeforeUnloadEvent {
event: Event,
return_value: DomRefCell<DOMString>,
}
impl BeforeUnloadEvent {
fn new_inherited() -> BeforeUnloadEvent {
BeforeUnloadEvent {
event: Event::new_inherited(),
return_value: DomRefCell::new(DOMString::new()),
}
}
pub fn new_uninitialized(window: &Window) -> DomRoot<BeforeUnloadEvent> {
reflect_dom_object(box BeforeUnloadEvent::new_inherited(),
window,
BeforeUnloadEventBinding::Wrap)
}
pub fn new(window: &Window,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable) -> DomRoot<BeforeUnloadEvent> {
let ev = BeforeUnloadEvent::new_uninitialized(window);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bool::from(bubbles),
bool::from(cancelable));
}
ev
}
}
impl BeforeUnloadEventMethods for BeforeUnloadEvent {
// https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue
fn ReturnValue(&self) -> DOMString {
self.return_value.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-beforeunloadevent-returnvalue
fn SetReturnValue(&self, value: DOMString) {
*self.return_value.borrow_mut() = value;
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
5e596accacb9a659f8388524e57b84cd2d484e07
|
{
"blob_id": "5e596accacb9a659f8388524e57b84cd2d484e07",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-29T15:19:40",
"content_id": "ad1f3ee2a21a44fb59e7ae248cf1424c46130d59",
"detected_licenses": [
"MIT"
],
"directory_id": "d001de20f549b391534c058512cbe70170ba5030",
"extension": "rs",
"filename": "beforeunloadevent.rs",
"fork_events_count": 103,
"gha_created_at": "2015-02-22T02:04:12",
"gha_event_created_at": "2023-09-14T13:56:09",
"gha_language": "Rust",
"gha_license_id": null,
"github_id": 31149031,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 2388,
"license": "MIT",
"license_type": "permissive",
"path": "/collector/compile-benchmarks/style-servo/components/script/dom/beforeunloadevent.rs",
"provenance": "stack-edu-0068.json.gz:36957",
"repo_name": "rust-lang/rustc-perf",
"revision_date": "2023-08-29T15:19:40",
"revision_id": "1744325d2f0a41d5e2cacf568bc94cfd4516ff83",
"snapshot_id": "ae153f9c3c48bca5cafe91cd669c4fd0a383f52d",
"src_encoding": "UTF-8",
"star_events_count": 391,
"url": "https://raw.githubusercontent.com/rust-lang/rustc-perf/1744325d2f0a41d5e2cacf568bc94cfd4516ff83/collector/compile-benchmarks/style-servo/components/script/dom/beforeunloadevent.rs",
"visit_date": "2023-08-30T19:56:29.435255",
"added": "2024-11-18T21:47:26.714432+00:00",
"created": "2023-08-29T15:19:40",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.AI;
public class TankShooting : MonoBehaviour
{
public int m_PlayerNumber;
public GameObject enemy;
public GameObject direction;
public Rigidbody m_Shell;
public Transform m_FireTransform;
public Slider m_AimSlider;
public AudioSource m_ShootingAudio;
public AudioClip m_ChargingClip;
public AudioClip m_FireClip;
public float delay;
public float minDistance = 10;
public float midDistance = 15;
public float maxDistance = 20;
private float m_CurrentLaunchForce;
private bool canFire = true;
private float delayTimer;
private NavMeshHit hit;
private bool blocked = false;
private void Update()
{
if (enemy.activeSelf)
{
if (!canFire)
{
delayTimer += Time.deltaTime;
if (delayTimer >= delay)
canFire = true;
}
Vector3 origin = m_FireTransform.transform.position;
Vector3 destination = enemy.transform.position;
Vector3 tanksDistance = AbsoluteValue(destination - origin);
blocked = NavMesh.Raycast(origin, destination, out hit, NavMesh.AllAreas);
Debug.DrawLine(transform.position, enemy.transform.position, blocked ? Color.red : Color.green);
if (blocked)
{
canFire = false;
Debug.DrawRay(hit.position, Vector3.up, Color.red);
}
else if (!blocked && canFire)
Fire(EnemyClose(tanksDistance));
}
}
public void Fire(int charge)
{
if (charge != -1)
{
if (charge == 0)
m_CurrentLaunchForce = 15f;
else if (charge == 1)
m_CurrentLaunchForce = 17f;
else if (charge == 2)
m_CurrentLaunchForce = 22f;
Rigidbody shellInstance = Instantiate(m_Shell, m_FireTransform.transform.position, m_FireTransform.transform.rotation) as Rigidbody;
shellInstance.velocity = m_CurrentLaunchForce * m_FireTransform.forward;
canFire = false;
delayTimer = 0;
m_ShootingAudio.clip = m_FireClip;
m_ShootingAudio.Play();
m_CurrentLaunchForce = 15f;
}
}
private int EnemyClose(Vector3 distance)
{
int ret;
if (Mathf.Sqrt((distance.x * distance.x) + (distance.z * distance.z)) < minDistance) ret = 0;
else if (Mathf.Sqrt((distance.x * distance.x) + (distance.z * distance.z)) < midDistance) ret = 1;
else if (Mathf.Sqrt((distance.x * distance.x) + (distance.z * distance.z)) < maxDistance) ret = 2;
else ret = -1;
if ((ret == 2) && this.m_PlayerNumber == 2) ret = -1;
return ret;
}
private Vector3 AbsoluteValue(Vector3 vector)
{
if (vector.x < 0) vector.x = -vector.x;
if (vector.y < 0) vector.y = -vector.y;
if (vector.z < 0) vector.z = -vector.z;
return vector;
}
private Vector3 ProjectileMotion(float currentForce, Vector3 forward)
{
Vector3 ret = forward;
float initialVelocity = currentForce;
float gravity = 9.81f;
ret.y = FunctionImpact(initialVelocity, gravity, forward.x, forward.z, forward.y);
return ret;
}
private float FunctionImpact(float v, float g, float x, float y, float angleY)
{
float ret;
float sqrt = Mathf.Sqrt(v * v * v * v - g * (g * x * x + 2 * y * v * v));
float angle;
if (v * v - sqrt > 0)
{
angle = ((v * v - sqrt) / (g * x)) * Mathf.Rad2Deg;
angle = Mathf.Atan(angle);
ret = angle;
}
else if (v * v + sqrt > 0)
{
angle = ((v * v + sqrt) / (g * x)) * Mathf.Rad2Deg;
angle = Mathf.Atan(angle);
ret = angle;
}
else ret = angleY;
return ret;
}
}
|
66a7e7df20bd8f16d6f0ba6faf2b05ffbd725f93
|
{
"blob_id": "66a7e7df20bd8f16d6f0ba6faf2b05ffbd725f93",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-06T17:27:23",
"content_id": "60a8a4db3bace30f5753b4b6ed25f61ad4acbcb0",
"detected_licenses": [
"MIT"
],
"directory_id": "a3d7c2e92b900afd1a0db01c5eec48a21d0b9350",
"extension": "cs",
"filename": "TankShooting.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 302625222,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 4127,
"license": "MIT",
"license_type": "permissive",
"path": "/Tanks/Assets/Scripts/Tank/TankShooting.cs",
"provenance": "stack-edu-0013.json.gz:785424",
"repo_name": "Bullseye14/AI-Tanks",
"revision_date": "2020-12-06T17:27:23",
"revision_id": "76435a836d1bdd7eeea3c5fdcb63999904c2a1fc",
"snapshot_id": "d385588a8a85d1a27a10fe0c8c101fb8b01bf839",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Bullseye14/AI-Tanks/76435a836d1bdd7eeea3c5fdcb63999904c2a1fc/Tanks/Assets/Scripts/Tank/TankShooting.cs",
"visit_date": "2023-01-29T14:27:13.807169",
"added": "2024-11-19T00:09:18.625429+00:00",
"created": "2020-12-06T17:27:23",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
<?php
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
use App\TokenStore\TokenCache;
use App\TimeZones\TimeZones;
use App\ReservaSala;
use App\Reserva;
use App\VagaReserva;
use App\Convite;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
class CalendarController extends Controller
{ /**
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function calendar(Request $request)
{
if($request->dia == ''){
$dia = date('Y-m-d');
}else{
$dia = $request->dia;
}
$viewData = $this->loadViewData();
$graph = $this->getGraph();
// Get user's timezone
$timezone = TimeZones::getTzFromWindows($viewData['userTimeZone']);
// Get start and end of week
$startOfWeek = new \DateTimeImmutable('sunday -1 week', $timezone);
$endOfWeek = new \DateTimeImmutable('sunday', $timezone);
$viewData['dateRange'] = $startOfWeek->format('M j, Y').' - '.$endOfWeek->format('M j, Y');
$queryParams = array(
'startDateTime' => $startOfWeek->format(\DateTimeInterface::ISO8601),
'endDateTime' => $endOfWeek->format(\DateTimeInterface::ISO8601),
// Only request the properties used by the app
'$select' => 'subject,organizer,start,end',
// Sort them by start time
'$orderby' => 'start/dateTime',
// Limit results to 25
'$top' => 25
);
$bodyjson = '{
"attendees": [
{
"emailAddress": {
"address": "'.$request->sala.'",
"name": "'.$request->sala.'"
},
"type": "Required"
}
],
"timeConstraint": {
"timeslots": [
{
"start": {
"dateTime": "'.$dia.'T08:00:52",
"timeZone": "'.$viewData['userTimeZone'].'",
},
"end": {
"dateTime": "'.$dia.'T19:00:52",
"timeZone": "'.$viewData['userTimeZone'].'",
}
}
]
},
"locationConstraint": {
"isRequired": "false",
"suggestLocation": "true",
"locations": [
{
"displayName": "Conf Room 32/1368",
"locationEmailAddress": "conf32room1368@imgeek.onmicrosoft.com"
}
]
},
"meetingDuration": "PT1H"
}';
// Append query parameters to the '/me/calendarView' url
$getEventsUrl = '/me/findMeetingTimes';
//$getEventsUrl = '/users/reuniao1@kvminformatica.com.br/calendarView?'.http_build_query($queryParams);
$events = $graph->createRequest('POST', $getEventsUrl)->attachBody($bodyjson)
// Add the user's timezone to the Prefer header
->addHeaders(array(
'Prefer' => 'outlook.timezone="'.$viewData['userTimeZone'].'"'
))
->setReturnType(Model\Event::class)
->execute();
$viewData['events'] = $events;
//return view('calendar', $viewData);
$jsonObjt = json_encode($events);
$jsonString = json_decode($jsonObjt,true);
array_shift($jsonString);
//return view('calendar')->with(compact('valores',$jsonString));
return view('calendar')->with('valores',$jsonString)->with('sala',$request->sala);
}
// <getNewEventFormSnippet>
public function getNewEventForm()
{
return view('newevent');
}
public function createNewEvent(Request $request)
{
// Validate required fields
$request->validate([
'eventSubject' => 'nullable|string',
'eventAttendees' => 'nullable|string',
'eventStart' => 'required|date',
'eventEnd' => 'required|date',
'eventBody' => 'nullable|string'
]);
$viewData = $this->loadViewData();
$graph = $this->getGraph();
// Attendees from form are a semi-colon delimited list of
// email addresses
$attendeeAddresses = explode(';', $request->eventAttendees);
// The Attendee object in Graph is complex, so build the structure
$attendees = [];
foreach($attendeeAddresses as $attendeeAddress)
{
array_push($attendees, [
// Add the email address in the emailAddress property
'emailAddress' => [
'address' => $attendeeAddress
],
// Set the attendee type to required
'type' => 'required'
]);
}
// Build the event
$newEvent = [
'subject' => $request->eventSubject,
'attendees' => $attendees,
'start' => [
'dateTime' => $request->eventStart,
'timeZone' => $viewData['userTimeZone']
],
'end' => [
'dateTime' => $request->eventEnd,
'timeZone' => $viewData['userTimeZone']
],
'body' => [
'content' => $request->eventBody,
'contentType' => 'text'
]
];
// POST /me/events
$response = $graph->createRequest('POST', '/me/events')
->attachBody($newEvent)
->setReturnType(Model\Event::class)
->execute();
$novaReserva = new ReservaSala();
$novaReserva->id_user = session()->get('idusuario');
$novaReserva->id_empresa = session()->get('idempresa');
$novaReserva->sala = $request->nomesala;
$novaReserva->assunto = $request->eventSubject;
$novaReserva->data_inicio = $request->eventStart;
$novaReserva->hora_inicio = $request->eventStart;
$novaReserva->data_fim = $request->eventEnd;
$novaReserva->hora_fim = $request->eventEnd;
$novaReserva->participantes = $request->eventAttendees;
$novaReserva->save();
// pegando as reservas das posições e vagas
$idusuario = session()->get('idusuario');
$idempresa = session()->get('idempresa');
$data = date("Y-m-d",strtotime($request->eventStart));
$posicao = Reserva::where('usuario_idusuario',$idusuario)->where('empresa_idempresa',$idempresa)->where('data_reserva',$data)->count();
$estacionamento = VagaReserva::where('id_usuario',$idusuario)->where('id_empresa',$idempresa)->where('data_reserva',$data)->count();
return view('confirm.confirmsala')->with('agendado',"Sala Agendada!")->with('posicao',$posicao)->with('estacionamento',$estacionamento)->with('dia',$data);
}
// </createNewEventSnippet>
private function getGraph(): Graph
{
// Get the access token from the cache
$tokenCache = new TokenCache();
$accessToken = $tokenCache->getAccessToken();
// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
return $graph;
}
}
|
010dbf25d987e1191bd2f14700905a37aa983b38
|
{
"blob_id": "010dbf25d987e1191bd2f14700905a37aa983b38",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-24T16:56:43",
"content_id": "4cc07ea0b916e77bba184b950c26ac4a09feed50",
"detected_licenses": [
"MIT"
],
"directory_id": "83604bd2623f1a14e7e739024cb1db2439d0f279",
"extension": "php",
"filename": "CalendarController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 331388748,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 6820,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/CalendarController.php",
"provenance": "stack-edu-0046.json.gz:772511",
"repo_name": "clmartt/facilitiesCenter",
"revision_date": "2021-03-24T16:56:43",
"revision_id": "8e5a56742e971bf27b6fff816c965c46b76c8f96",
"snapshot_id": "b2d4c03ab52e2218682afddc8f4c8729ab50b101",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/clmartt/facilitiesCenter/8e5a56742e971bf27b6fff816c965c46b76c8f96/app/Http/Controllers/CalendarController.php",
"visit_date": "2023-03-26T01:35:38.065641",
"added": "2024-11-19T02:44:54.937165+00:00",
"created": "2021-03-24T16:56:43",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
<?php
/**
* UpdateViewer.php
*
* @since 29/05/15
* @author gseidel
*/
namespace Enhavo\Bundle\AppBundle\View\Type;
use Enhavo\Bundle\AppBundle\Action\ActionManager;
use Enhavo\Bundle\AppBundle\Grid\GridManager;
use Enhavo\Bundle\AppBundle\Resource\ResourceManager;
use Enhavo\Bundle\AppBundle\View\AbstractResourceFormType;
use Enhavo\Bundle\AppBundle\View\ViewUtil;
use Sylius\Bundle\ResourceBundle\Controller\EventDispatcherInterface;
use Sylius\Bundle\ResourceBundle\Controller\ResourceFormFactoryInterface;
use Sylius\Bundle\ResourceBundle\Controller\SingleResourceProviderInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\ResourceActions;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class UpdateViewType extends AbstractResourceFormType
{
public function __construct(
array $formThemes,
ActionManager $actionManager,
FlashBag $flashBag,
private ViewUtil $util,
RouterInterface $router,
TranslatorInterface $translator,
private ResourceManager $resourceManager,
GridManager $gridManager,
ResourceFormFactoryInterface $resourceFormFactory,
NormalizerInterface $normalizer,
EventDispatcherInterface $eventDispatcher,
private SingleResourceProviderInterface $singleResourceProvider,
) {
parent::__construct($formThemes, $actionManager, $flashBag, $util, $router, $translator, $resourceManager, $gridManager, $resourceFormFactory, $normalizer, $eventDispatcher);
}
public static function getName(): ?string
{
return 'update';
}
public function createResource($options) : ResourceInterface
{
$metadata = $this->getMetadata($options);
$configuration = $this->getRequestConfiguration($options);
$this->util->isGrantedOr403($configuration, ResourceActions::UPDATE);
$repository = $this->resourceManager->getRepository($metadata->getApplicationName(), $metadata->getName());
$resource = $this->singleResourceProvider->get($configuration, $repository);
if ($resource === null) {
throw new NotFoundHttpException();
}
return $resource;
}
protected function save($options)
{
$configuration = $this->getRequestConfiguration($options);
$event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $this->resource);
if ($event->isStopped()) {
if ($event->getResponse()) {
return $event->getResponse();
}
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
$this->resourceManager->update($this->resource, $configuration->getStateMachineTransition(), $configuration->getStateMachineGraph());
$event = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $this->resource);
if ($event->isStopped()) {
if ($event->getResponse()) {
return $event->getResponse();
}
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
}
protected function initialize($options)
{
$configuration = $this->getRequestConfiguration($options);
$event = $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE, $configuration, $this->resource);
if ($event->isStopped()) {
if ($event->getResponse()) {
return $event->getResponse();
}
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
}
public function configureOptions(OptionsResolver $optionsResolver)
{
parent::configureOptions($optionsResolver);
$optionsResolver->setDefaults([
'form_delete' => null,
'form_delete_parameters' => [],
'label' => 'label.edit',
]);
}
protected function getFormAction($options): string
{
$metadata = $this->getMetadata($options);
return sprintf('%s_%s_create', $metadata->getApplicationName(), $this->util->getUnderscoreName($metadata));
}
protected function getFormActionParameters($option): array
{
return ['id' => $this->resource->getId()];
}
protected function createSecondaryActions($options): array
{
$metadata = $this->getMetadata($options);
$requestConfiguration = $this->getRequestConfiguration($options);
$formDelete = $this->util->mergeConfig([
sprintf('%s_%s_delete', $metadata->getApplicationName(), $this->util->getUnderscoreName($metadata)),
$options['form_delete'],
$this->util->getViewerOption('form.delete', $requestConfiguration)
]);
$formDeleteParameters = $this->util->mergeConfigArray([
$options['form_delete_parameters'],
$this->util->getViewerOption('form.delete_parameters', $requestConfiguration)
]);
return [
'delete' => [
'type' => 'delete',
'route' => $formDelete,
'route_parameters' => $formDeleteParameters,
'permission' => $this->util->getRoleNameByResourceName($metadata->getApplicationName(), $this->util->getUnderscoreName($metadata), 'delete')
]
];
}
protected function getRedirectRoute($options): ?string
{
return null;
}
}
|
ed7accf322759d732b29df01fce269eae7ef837a
|
{
"blob_id": "ed7accf322759d732b29df01fce269eae7ef837a",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-25T09:38:31",
"content_id": "aac4dc29ebe963a76f56a21f63e5dfc030de68e6",
"detected_licenses": [
"MIT"
],
"directory_id": "50578ab807ea6cf7bb7aee182f3c6d7ea4f0ee47",
"extension": "php",
"filename": "UpdateViewType.php",
"fork_events_count": 40,
"gha_created_at": "2015-07-02T15:17:17",
"gha_event_created_at": "2023-09-14T20:40:08",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 38440204,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 5837,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Enhavo/Bundle/AppBundle/View/Type/UpdateViewType.php",
"provenance": "stack-edu-0049.json.gz:740391",
"repo_name": "enhavo/enhavo",
"revision_date": "2023-08-25T09:38:31",
"revision_id": "598cdf894378b7169831df332e04dd87058dc252",
"snapshot_id": "819cc5fe47fcd3ccdc920f96d8caf42582ef96ea",
"src_encoding": "UTF-8",
"star_events_count": 91,
"url": "https://raw.githubusercontent.com/enhavo/enhavo/598cdf894378b7169831df332e04dd87058dc252/src/Enhavo/Bundle/AppBundle/View/Type/UpdateViewType.php",
"visit_date": "2023-09-04T12:53:09.051560",
"added": "2024-11-19T00:52:10.077890+00:00",
"created": "2023-08-25T09:38:31",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
const webpack = require("webpack");
const dotenv = require("dotenv");
const fs = require("fs"); // to check if the file exists
const path = require("path");
module.exports = (env) => {
// Get the root path (assuming your webpack config is in the root of your project!)
const currentPath = path.join(__dirname);
// Create the fallback path (the production .env)
const basePath = currentPath + "/icast/.env";
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + "." + env.ENVIRONMENT;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
return {
entry: "./icast/frontend/src/index.js",
output: {
path: path.resolve(__dirname, "icast/frontend/static"),
filename: "main.js",
//publicPath: './licensepivot/frontend/static/'
},
plugins: [new webpack.DefinePlugin(envKeys)],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: ["style-loader", "css-loader", "sass-loader"],
},
{
test: /\.(ttf|eot|svg)$/,
use: {
loader: "file-loader",
options: {
name: "[hash].[ext]",
outputPath: "./css/fonts/",
publicPath: "static/css/fonts/",
},
},
},
{
test: /\.(woff|woff2)$/,
use: {
loader: "url-loader",
options: {
name: "[hash].[ext]",
outputPath: "./css/fonts/",
publicPath: "static/css/fonts/",
limit: 5000,
mimetype: "application/font-woff",
},
},
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
use: [
'file-loader',
{
loader: 'image-webpack-loader',
options: {
bypassOnDebug: true, // webpack@1.x
disable: true, // webpack@2.x and newer
},
},
],
}
],
},
resolve: {
extensions: ["*", ".js", ".jsx", ".scss"],
},
};
};
|
f1d5c982fb681cb61aed1813e9245df134e1befe
|
{
"blob_id": "f1d5c982fb681cb61aed1813e9245df134e1befe",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-18T09:58:03",
"content_id": "b04cf39dea7eb532e4f325fb00966a43de745e7d",
"detected_licenses": [
"Unlicense"
],
"directory_id": "c5149e54999c0f5bbb175263d081fa39333dbeec",
"extension": "js",
"filename": "webpack.config.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 286641292,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2706,
"license": "Unlicense",
"license_type": "permissive",
"path": "/webpack.config.js",
"provenance": "stack-edu-0032.json.gz:460741",
"repo_name": "wickylee/wwwicast",
"revision_date": "2020-11-18T09:58:03",
"revision_id": "c625f7d2ebcacfaf4431ea4987eee4313db9eef1",
"snapshot_id": "b6c1b9651de98a679184808d77ccdd7c530ef678",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wickylee/wwwicast/c625f7d2ebcacfaf4431ea4987eee4313db9eef1/webpack.config.js",
"visit_date": "2023-01-13T15:58:20.853407",
"added": "2024-11-19T01:21:35.500712+00:00",
"created": "2020-11-18T09:58:03",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz"
}
|
<?php
/**
* This file is part of the Cubiche package.
*
* Copyright (c) Cubiche
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cubiche\Core\Async\Tests\Units\Promise;
use Cubiche\Core\Delegate\Delegate;
use Cubiche\Core\Async\Promise\Promise;
use Cubiche\Core\Async\Promise\State;
/**
* Promise Tests class.
*
* @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
* @author Karel Osorio Ramírez <osorioramirez@gmail.com>
*/
class PromiseTests extends PromiseInterfaceTestCase
{
/**
* @var Delegate
*/
protected $resolve;
/**
* @var Delegate
*/
protected $reject;
/**
* @var Delegate
*/
protected $notify;
/**
* {@inheritdoc}
*/
protected function defaultConstructorArguments()
{
return array(
function (callable $callable) {
$this->resolve = new Delegate($callable);
},
function (callable $callable) {
$this->reject = new Delegate($callable);
},
function (callable $callable) {
$this->notify = new Delegate($callable);
},
);
}
/**
* {@inheritdoc}
*/
protected function resolve($value = null)
{
$this->resolve->__invoke($value);
}
/**
* {@inheritdoc}
*/
protected function reject($reason = null)
{
$this->reject->__invoke($reason);
}
/**
* {@inheritdoc}
*/
protected function notify($state = null)
{
$this->notify->__invoke($state);
}
/**
* Test __construct.
*/
public function testConstruct()
{
$this
->given(
$resolve = $this->delegateMock(),
$reject = $this->delegateMock(),
$notify = $this->delegateMock()
)
->when($this->newTestedInstance($resolve, $reject, $notify))
->then()
->delegateCall($resolve)
->once()
->delegateCall($reject)
->once()
->delegateCall($notify)
->once()
;
$this
/* @var \Cubiche\Core\Async\Promise\PromiseInterface $promise */
->given($promise = $this->newDefaultTestedInstance())
->then()
->boolean($promise->state()->equals(State::PENDING()))
->isTrue()
;
}
/**
* Test notify.
*/
public function testNotify()
{
$this
->given(
$promise = $this->newDefaultTestedInstance(),
$onNotify = $this->delegateMock()
)
->when(function () use ($promise, $onNotify) {
$promise->then(null, null, $onNotify);
$this->notify('foo');
})
->then()
->delegateCall($onNotify)
->withArguments('foo')
->once()
;
}
/**
* {@inheritdoc}
*/
protected function promiseDataProvider()
{
$pending = $this->newDefaultTestedInstance();
$fulfilled = $this->newDefaultTestedInstance();
$this->resolve($this->defaultResolveValue());
$rejected = $this->newDefaultTestedInstance();
$this->reject($this->defaultRejectReason());
return array(
'pending' => array($pending),
'fulfilled' => array($fulfilled),
'rejected' => array($rejected),
);
}
}
|
3f712c7d0feb18c2a92d3e02622a6d42426f0540
|
{
"blob_id": "3f712c7d0feb18c2a92d3e02622a6d42426f0540",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-25T15:25:45",
"content_id": "312640dec5dce96bcfee97697d084a398cc4a321",
"detected_licenses": [
"MIT"
],
"directory_id": "712e69981e6d3ffc6ee2279af5eb34ac927d8144",
"extension": "php",
"filename": "PromiseTests.php",
"fork_events_count": 2,
"gha_created_at": "2016-01-17T09:22:23",
"gha_event_created_at": "2018-04-17T17:12:53",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 49810591,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3654,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Cubiche/Core/Async/Tests/Units/Promise/PromiseTests.php",
"provenance": "stack-edu-0048.json.gz:614487",
"repo_name": "cubiche/cubiche",
"revision_date": "2018-09-25T15:25:45",
"revision_id": "9bbfd22db8a54a30fcc54bb295aa3652e64edce5",
"snapshot_id": "3e4b0a989cd20bae6c89462a9d0f4786d4a31f94",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/cubiche/cubiche/9bbfd22db8a54a30fcc54bb295aa3652e64edce5/src/Cubiche/Core/Async/Tests/Units/Promise/PromiseTests.php",
"visit_date": "2023-08-11T09:37:51.677479",
"added": "2024-11-19T00:52:11.654827+00:00",
"created": "2018-09-25T15:25:45",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
# Training models for object-detection and classification
## [Object Detection](training-object-detection.md)
Training a model for object-detection is quite a bit more convoluted than just classification.
But the advantage is knowing exactly where and what is in the image.
The process for training a model for object-detection is described in the file:
[training-object-detection](training-object-detection.md)
## Classification (WIP)
Todo..
I made a fairly good guide a while ago [in another repository.](https://github.com/HapsHapsHaps/Training-examples/tree/master/Classification/flower-image-classifier)
Just one one of these Docker containers instead:
**Using CPU**
```
docker run --rm -it -p 8001:8888 -p 6006:6006 -v $HOME/andet/training/docker-training-shared/object-training:/root/sharedfolder:Z jacobpeddk/tensorflow-improved:latest
```
**Using GPU**
```
nvidia-docker run --rm -it -p 8001:8888 -p 6006:6006 -v $HOME/andet/training/docker-training-shared/object-training:/root/sharedfolder:Z jacobpeddk/tensorflow-improved:latest-gpu
```
|
98df9d7ec1e62a2407d79575fa228f765e1f6f6d
|
{
"blob_id": "98df9d7ec1e62a2407d79575fa228f765e1f6f6d",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-16T19:06:55",
"content_id": "a22ff0af7146811641240c069af99c7def35c94c",
"detected_licenses": [
"MIT"
],
"directory_id": "0d5e16aa16a542d9268cdd41078ba07036262a04",
"extension": "md",
"filename": "README.md",
"fork_events_count": 1,
"gha_created_at": "2018-05-31T13:52:37",
"gha_event_created_at": "2018-07-16T19:06:56",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 135590241,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1062,
"license": "MIT",
"license_type": "permissive",
"path": "/training/README.md",
"provenance": "stack-edu-markdown-0013.json.gz:281586",
"repo_name": "HapsHapsHaps/machinelearning-subs",
"revision_date": "2018-07-16T19:06:55",
"revision_id": "6e3d01bf0e1911e6bc54f53eacfe1f956c2d521c",
"snapshot_id": "f0f5d9780a1382b9adb1aaca2c8b43de5399edc2",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/HapsHapsHaps/machinelearning-subs/6e3d01bf0e1911e6bc54f53eacfe1f956c2d521c/training/README.md",
"visit_date": "2020-03-19T02:00:26.122871",
"added": "2024-11-18T23:54:13.711348+00:00",
"created": "2018-07-16T19:06:55",
"int_score": 3,
"score": 3.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz"
}
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
namespace Microsoft.AzureStack.Commands
{
using System;
using System.Linq;
using System.Net;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure;
using Microsoft.AzureStack.Management;
/// <summary>
/// Base Admin API cmdlet class
/// </summary>
public abstract class AdminApiCmdlet : AzureRMCmdlet
{
protected const string SubscriptionApiVersion = "2015-11-01";
protected const string GalleryAdminApiVersion = "2015-04-01";
protected const string UsageApiVersion = "2015-06-01-preview";
/// <summary>
/// Gets or sets the API version. Not a parameter that is to bes passed from outside
/// </summary>
protected string ApiVersion { get; set; }
/// <summary>
/// Default constructor
/// </summary>
protected AdminApiCmdlet()
{
this.ApiVersion = SubscriptionApiVersion;
}
/// <summary>
/// Gets the current default context. overriding it here since DefaultContext could be null for Windows Auth/ADFS environments
/// </summary>
protected override IAzureContext DefaultContext
{
get
{
if (DefaultProfile == null)
{
return null;
}
return DefaultProfile.DefaultContext;
}
}
/// <summary>
/// Execute this cmdlet.
/// </summary>
/// <remarks>
/// Descendant classes must override this methods instead of Cmdlet.ProcessRecord, so
/// we can have a unique place where log all errors.
/// </remarks>
protected override void ProcessRecord()
{
var originalValidateCallback = ServicePointManager.ServerCertificateValidationCallback;
if (this.MyInvocation.BoundParameters.Keys.Contains("ResourceGroup", StringComparer.OrdinalIgnoreCase))
{
this.WriteWarning("The parameter alias ResourceGroup will be deprecated in a future release. Please use the parameter ResourceGroupName instead");
}
// Execute the API call(s) for the current cmdlet
this.ExecuteCore();
}
/// <summary>
/// Executes the API call(s) against Azure Resource Management API(s).
/// </summary>
protected abstract void ExecuteCore();
/// <summary>
/// Gets the Azure Stack management client.
/// </summary>
protected AzureStackClient GetAzureStackClient()
{
return GetAzureStackClientThruAzureSession();
}
private AzureStackClient GetAzureStackClientThruAzureSession()
{
var armUri = this.DefaultContext.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager);
var credentials = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(this.DefaultContext);
return AzureSession.Instance.ClientFactory.CreateCustomClient<AzureStackClient>(armUri, credentials, this.ApiVersion);
}
}
}
|
238a3cb9d193bef027379f3e5ad034bd54f95a00
|
{
"blob_id": "238a3cb9d193bef027379f3e5ad034bd54f95a00",
"branch_name": "refs/heads/dev",
"committer_date": "2017-12-20T23:25:38",
"content_id": "2c6e62f4b360e0654b238620ee6f5d27f5e276e8",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "b8ccd30279fc3b54364060f8cda0eb8c8d0c960b",
"extension": "cs",
"filename": "AdminApiCmdlet.cs",
"fork_events_count": 0,
"gha_created_at": "2015-06-08T21:04:49",
"gha_event_created_at": "2017-12-20T23:25:39",
"gha_language": "C#",
"gha_license_id": "Apache-2.0",
"github_id": 37092717,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 4113,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/src/StackAdmin/AzureStackAdmin/Commands.AzureStackAdmin/AdminApiCmdlet.cs",
"provenance": "stack-edu-0009.json.gz:345203",
"repo_name": "jeffersonezra/azure-powershell",
"revision_date": "2017-12-20T23:25:38",
"revision_id": "2b41b0cee5b7fb9537916a5fb47f6d5054166550",
"snapshot_id": "67aabc6a7c3e58e072d54f96aead88df5fde0174",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jeffersonezra/azure-powershell/2b41b0cee5b7fb9537916a5fb47f6d5054166550/src/StackAdmin/AzureStackAdmin/Commands.AzureStackAdmin/AdminApiCmdlet.cs",
"visit_date": "2021-01-17T17:12:49.457951",
"added": "2024-11-19T02:27:16.268307+00:00",
"created": "2017-12-20T23:25:38",
"int_score": 2,
"score": 2,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
package com.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.security.dataaccess.ApplicationUserDao;
@Service
public class UserService implements UserDetailsService {
@Autowired
private ApplicationUserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userDao.loadUserByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(String.format("Username %s not found", username)));
}
}
|
00c7c4a8b39ae743b8b10b1c264642e86faccff9
|
{
"blob_id": "00c7c4a8b39ae743b8b10b1c264642e86faccff9",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-28T18:07:52",
"content_id": "e904f2beef6006673ad9156ce50e3c3bc8ff7bfd",
"detected_licenses": [
"MIT"
],
"directory_id": "7b3fb56073a9df1a095b4f7d856f5f2a1a303ec7",
"extension": "java",
"filename": "UserService.java",
"fork_events_count": 0,
"gha_created_at": "2020-04-26T14:31:47",
"gha_event_created_at": "2021-03-31T22:05:05",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 259051715,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 789,
"license": "MIT",
"license_type": "permissive",
"path": "/jwt-based-authentication/spring-security/src/main/java/com/security/service/UserService.java",
"provenance": "stack-edu-0027.json.gz:470726",
"repo_name": "vsviveksharma100/spring-boot-security",
"revision_date": "2020-04-28T18:07:52",
"revision_id": "a129c55ec948ab2d931fec51e4bc3d111166a22b",
"snapshot_id": "b9005a3083a82f9e58775e0775f63ab40b24f80b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vsviveksharma100/spring-boot-security/a129c55ec948ab2d931fec51e4bc3d111166a22b/jwt-based-authentication/spring-security/src/main/java/com/security/service/UserService.java",
"visit_date": "2023-04-08T22:30:55.540099",
"added": "2024-11-18T23:36:36.845644+00:00",
"created": "2020-04-28T18:07:52",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz"
}
|
<?php
namespace Modules\Dynamicfield\Composers;
use Illuminate\Contracts\View\View;
//use Modules\Dynamicfield\Library\DynamicFields;
class DynamicfieldViewComposer
{
/**
* Assign dynamicField to view
*
* @param View $view
*/
public function compose(View $view)
{
$this->assignDynamicFieldsToPageObject($view);
}
/**
* Pass dynamicFields to view
*
* @param $view
* @return mixed
*/
private function assignDynamicFieldsToPageObject($view)
{
$entityDynamic = null;
$data = $view->getData();
//dd($data);
//TODO Fix with event
if (count($data)) {
$arrType = config('asgard.dynamicfield.config.entity-type');
$arrType = array_keys($arrType);
//dd($data, $arrType, $view);
// edit entity
foreach ($data as $item) {
if (is_object($item)) {
$className = get_class($item);
if (in_array($className, $arrType)) {
$entityDynamic = $item;
break;
}
}
}
}
//dd($entityDynamic);
// initial model data for create new;
if (is_null($entityDynamic)) {
$router = \Request::route()->getName();
//dd($router);
$arrCreateRouter = config('asgard.dynamicfield.config.router');
if (array_key_exists($router, $arrCreateRouter)) {
$entityDynamic = new $arrCreateRouter[$router];
}
}
//dd($entityDynamic);
$view->with('entityDynamic', $entityDynamic);
return $view;
}
}
|
f0b079d33182612933c4dc062ec0b7a86bec68c9
|
{
"blob_id": "f0b079d33182612933c4dc062ec0b7a86bec68c9",
"branch_name": "refs/heads/master",
"committer_date": "2017-10-12T07:42:49",
"content_id": "00080181854b0d341675b6cdb3f53a9b46af1ffa",
"detected_licenses": [
"MIT"
],
"directory_id": "d48a82d17dbea53808a747534f6f152200f92dce",
"extension": "php",
"filename": "DynamicfieldViewComposer.php",
"fork_events_count": 2,
"gha_created_at": "2017-04-26T04:20:45",
"gha_event_created_at": "2017-10-12T07:42:51",
"gha_language": "JavaScript",
"gha_license_id": null,
"github_id": 89437334,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1736,
"license": "MIT",
"license_type": "permissive",
"path": "/Composers/DynamicfieldViewComposer.php",
"provenance": "stack-edu-0046.json.gz:913125",
"repo_name": "oscarcao/Dynamicfield",
"revision_date": "2017-10-12T07:42:49",
"revision_id": "72076cbc4cf6f255da8edbae6b23234599bf4e31",
"snapshot_id": "b15617a2de699d6db354e0803ca7a3590d8ed015",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/oscarcao/Dynamicfield/72076cbc4cf6f255da8edbae6b23234599bf4e31/Composers/DynamicfieldViewComposer.php",
"visit_date": "2021-01-20T02:41:22.365471",
"added": "2024-11-18T21:00:06.883650+00:00",
"created": "2017-10-12T07:42:49",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
<?php
$username = $_POST["username"];
$password = $_POST["password"];
if($_POST["login"]){
if($username=="bcg-ma" && $password=="masonDixon"){
header("Location: regions/mid-atlantic/ma-emailMaker.php");
}else if($username=="bcg-s" && $password=="southernComfort"){
header("Location: regions/south/s-emailMaker.php");
}else if($username=="bcg-n" && $password=="patriotCountry"){
header("Location: regions/north/n-emailMaker.php");
}else if($username=="bcg-nw" && $password=="pacificRim"){
header("Location: regions/northwest/nw-emailMaker.php");
}else{
header("Location: loginError.html");
}
}
?>
|
1a538d0e713503895ffbc4aa8e63ee45063586ad
|
{
"blob_id": "1a538d0e713503895ffbc4aa8e63ee45063586ad",
"branch_name": "refs/heads/master",
"committer_date": "2015-08-09T01:35:24",
"content_id": "3295488d0810d2b7fed6ec43640fd01c5271280c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d20d948882fbec45b70112a420c1608fa21930b1",
"extension": "php",
"filename": "login.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 40421707,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 651,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/login.php",
"provenance": "stack-edu-0050.json.gz:274221",
"repo_name": "mauricedw22/sharpKayak2",
"revision_date": "2015-08-09T01:35:24",
"revision_id": "6e1de657be83f1cbf5f0139f525e3fb9c36b94b1",
"snapshot_id": "96ccb9b7c5051e8fe9ab0d31fbaba0ab48177534",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mauricedw22/sharpKayak2/6e1de657be83f1cbf5f0139f525e3fb9c36b94b1/login.php",
"visit_date": "2021-01-02T08:19:35.436641",
"added": "2024-11-18T23:10:11.148864+00:00",
"created": "2015-08-09T01:35:24",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0068.json.gz"
}
|
// edemote.c
inherit F_CLEAN_UP;
int in_use;
int main(object me, string arg)
{
mapping emote;
if( !arg ) return notify_fail("你要編輯什麼 emote?\n");
if( sscanf(arg, "-d %s", arg) ) {
write("刪除 emote:" + arg + "\n");
EMOTE_D->delete_emote(arg);
return 1;
}
if( sscanf(arg, "-p %s", arg) ) {
emote = EMOTE_D->query_emote(arg);
printf("上次修改:%s\n", emote["updated"]);
printf("—————————————\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
emote["myself"], emote["others"], emote["myself_self"],
emote["others_self"], emote["myself_target"], emote["target"],
emote["others_target"] );
return 1;
}
emote = EMOTE_D->query_emote(arg);
emote = (["updated":geteuid(me)]);
write("編輯 emote:" + arg + "\n");
write("訊息可以有好幾行,用 . 表示結束。\n");
write("訊息中可使用的參數有以下幾種:\n");
write(" $N 自己的名字。\n");
write(" $n 使用對象的名字。\n");
write(" $P 自己的人稱代名詞,如你、□、他、她、它、它。\n");
write(" $p 使用對象的人稱代名詞,如你、□、他、她、它、它。\n");
write("————————————————————————————————————\n");
write("不指定對象使用這個 emote 時,你自己看到的訊息:\n->");
input_to("get_msg_myself", emote, arg);
return 1;
}
int get_msg_myself(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["myself"]) ) emote["myself"] += "\n";
write("不指定對象使用這個 emote 時,其他人看到的訊息:\n->");
input_to("get_msg_others", emote, pattern);
return 1;
}
if( !undefinedp(emote["myself"]) )
emote["myself"] += msg + "\n";
else emote["myself"] = msg;
write("->");
input_to("get_msg_myself", emote, pattern);
return 1;
}
int get_msg_others(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["others"]) ) emote["others"] += "\n";
write("對自己使用這個 emote 時,自己看到的訊息:\n->");
input_to("get_msg_myself_self", emote, pattern);
return 1;
}
if( !undefinedp(emote["others"]) )
emote["others"] += msg + "\n";
else emote["others"] = msg;
write("->");
input_to("get_msg_others", emote, pattern);
return 1;
}
int get_msg_myself_self(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["myself_self"]) ) emote["myself_self"] += "\n";
write("對自己使用這個 emote 時,其他人看到的訊息:\n->");
input_to("get_msg_others_self", emote, pattern);
return 1;
}
if( !undefinedp(emote["myself_self"]) )
emote["myself_self"] += msg + "\n";
else emote["myself_self"] = msg;
write("->");
input_to("get_msg_myself_self", emote, pattern);
return 1;
}
int get_msg_others_self(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["others_self"]) ) emote["others_self"] += "\n";
write("對別人使用這個 emote 時,自己看到的訊息:\n->");
input_to("get_msg_myself_target", emote, pattern);
return 1;
}
if( !undefinedp(emote["others_self"]) )
emote["others_self"] += msg + "\n";
else emote["others_self"] = msg;
write("->");
input_to("get_msg_others_self", emote, pattern);
return 1;
}
int get_msg_myself_target(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["myself_target"]) ) emote["myself_target"] += "\n";
write("對別人使用這個 emote 時,使用對象看到的訊息:\n->");
input_to("get_msg_target", emote, pattern);
return 1;
}
if( !undefinedp(emote["myself_target"]) )
emote["myself_target"] += msg + "\n";
else emote["myself_target"] = msg;
write("->");
input_to("get_msg_myself_target", emote, pattern);
return 1;
}
int get_msg_target(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["target"]) ) emote["target"] += "\n";
write("對別人使用這個 emote 時,除你自己和使用對象外,其他人看到的訊息:\n->");
input_to("get_msg_others_target", emote, pattern);
return 1;
}
if( !undefinedp(emote["target"]) )
emote["target"] += msg + "\n";
else emote["target"] = msg;
write("->");
input_to("get_msg_target", emote, pattern);
return 1;
}
int get_msg_others_target(string msg, mapping emote, string pattern)
{
if (msg==".") {
if( !undefinedp(emote["others_target"]) ) emote["others_target"] += "\n";
EMOTE_D->set_emote(pattern, emote);
write("Emote 編輯結束。\n");
return 1;
}
if( !undefinedp(emote["others_target"]) )
emote["others_target"] += msg + "\n";
else emote["others_target"] = msg;
write("->");
input_to("get_msg_others_target", emote, pattern);
return 1;
}
int help(object me)
{
write(@HELP
指令格式 : edemote [-d|-p] <emote>
這個指令可以修改, 刪除 emote 或列出其內容. 加上 -d 參數會刪除
指定的 emote, -p 參數則會列出指定 emote 的內容. 列出的順序與編
輯 emote 時相同.
輸入 emote 訊息時有三個項目: 沒有目標, 指定目標或是對自己. 若
不想有某項訊息, 則直接在空白行輸入 '.' 跳過.
一個 emote 訊息可以有很多行, 在空白行輸入 '.' 結束輸入該項 emote.
編輯 emote 時可以用以下的符號來表示:
$N : 自己的名字.
$n : 目標的名字.
$P : 自己的人稱代名詞.
$p : 目標的人稱代名詞.
HELP
);
return 1;
}
|
c2edd09c8791d157848e82c9fdeb22def64f1a93
|
{
"blob_id": "c2edd09c8791d157848e82c9fdeb22def64f1a93",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-31T01:42:37",
"content_id": "7f67157f68eb6332925c504ffb2696c9fae1f1fd",
"detected_licenses": [
"MIT"
],
"directory_id": "e054e6e7eb5bf0df1242078ebf5293edb2dd79ad",
"extension": "c",
"filename": "edemote.c",
"fork_events_count": 0,
"gha_created_at": "2018-01-29T08:58:00",
"gha_event_created_at": "2018-01-29T08:58:00",
"gha_language": null,
"gha_license_id": null,
"github_id": 119357648,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 5463,
"license": "MIT",
"license_type": "permissive",
"path": "/mudlib/cmds/imm/edemote.c",
"provenance": "stack-edu-0000.json.gz:16004",
"repo_name": "ankion/es2-utf8",
"revision_date": "2018-01-31T01:42:37",
"revision_id": "87139379c00200ef4d533830ce383e808cc4906b",
"snapshot_id": "b406bb0799c3768b551df73f1cbe7bd3559069c4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ankion/es2-utf8/87139379c00200ef4d533830ce383e808cc4906b/mudlib/cmds/imm/edemote.c",
"visit_date": "2021-05-09T07:24:33.744167",
"added": "2024-11-19T00:51:26.497151+00:00",
"created": "2018-01-31T01:42:37",
"int_score": 3,
"score": 2.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
r"""Critic Network.
"""
import gin
import tensorflow as tf
import pdb
from tf_agents.networks import network
from tf_agents.networks import utils
import collections
@gin.configurable
class CriticNetwork(network.Network):
"""Creates a critic network."""
def __init__(self,
input_tensor_spec,
preprocessing_combiner=None,
observation_conv_layer_params=None,
observation_fc_layer_params=None,
observation_dropout_layer_params=None,
action_fc_layer_params=None,
action_dropout_layer_params=None,
joint_fc_layer_params=None,
joint_dropout_layer_params=None,
activation_fn=tf.nn.relu,
output_activation_fn=None,
mask_xy=False,
name='CriticNetwork'):
super(CriticNetwork, self).__init__(
input_tensor_spec=input_tensor_spec,
state_spec=(),
name=name)
self._mask_xy = mask_xy
observation_spec, action_spec = input_tensor_spec
flat_action_spec = tf.nest.flatten(action_spec)
if len(flat_action_spec) > 1:
raise ValueError(
'Only a single action is supported by this network')
self._single_action_spec = flat_action_spec[0]
self._observation_layers = utils.mlp_layers(
observation_conv_layer_params,
observation_fc_layer_params,
observation_dropout_layer_params,
activation_fn=activation_fn,
kernel_initializer=tf.compat.v1.keras.initializers.VarianceScaling(
scale=1. / 3., mode='fan_in', distribution='uniform'),
name='observation_encoding')
self._action_layers = utils.mlp_layers(
None,
action_fc_layer_params,
action_dropout_layer_params,
activation_fn=activation_fn,
kernel_initializer=tf.compat.v1.keras.initializers.VarianceScaling(
scale=1. / 3., mode='fan_in', distribution='uniform'),
name='action_encoding')
self._joint_layers = utils.mlp_layers(
None,
joint_fc_layer_params,
joint_dropout_layer_params,
activation_fn=activation_fn,
kernel_initializer=tf.compat.v1.keras.initializers.VarianceScaling(
scale=1. / 3., mode='fan_in', distribution='uniform'),
name='joint_mlp')
self._joint_layers.append(
tf.keras.layers.Dense(
1,
activation=output_activation_fn,
kernel_initializer=tf.keras.initializers.RandomUniform(
minval=-0.003, maxval=0.003),
name='value'))
self._preprocessing_combiner = preprocessing_combiner
def call(self, inputs, step_type=(), network_state=(), training=False):
observations, actions = inputs
if self._mask_xy:
if not isinstance(observations, collections.Mapping):
observations = observations[:, 2:]
elif not isinstance(observations["observation"], collections.Mapping):
observations["observation"] = observations["observation"][:, 2:]
else:
observations["observation"] = observations["observation"]["observation"][:, 2:]
# observations = observations
del step_type # unused.
if self._preprocessing_combiner is not None:
observations = self._preprocessing_combiner(observations)
observations = tf.cast(tf.nest.flatten(observations)[0], tf.float32)
for layer in self._observation_layers:
observations = layer(observations, training=training)
actions = tf.cast(tf.nest.flatten(actions)[0], tf.float32)
for layer in self._action_layers:
actions = layer(actions, training=training)
if observations.shape[-1] > 0:
joint = tf.concat([observations, actions], 1)
else:
joint = actions
for layer in self._joint_layers:
joint = layer(joint, training=training)
return tf.reshape(joint, [-1]), network_state
|
272abfc4ed044d9ed0de36f2208cd2bd873c535d
|
{
"blob_id": "272abfc4ed044d9ed0de36f2208cd2bd873c535d",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-04T19:21:32",
"content_id": "17aeaef1732c4d9f720b588529227154c23ceeb7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a522e109b81b49729b9f67749315a6889482318f",
"extension": "py",
"filename": "critic_network.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 377057139,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4267,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/networks/critic_network.py",
"provenance": "stack-edu-0060.json.gz:103158",
"repo_name": "ademiadeniji/lords",
"revision_date": "2021-08-04T19:21:32",
"revision_id": "75ce115ec7f950d857d0817eb0adf2cc2673ffdd",
"snapshot_id": "1b166ffdd0ad91e5261d5885fb694d502e722d17",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ademiadeniji/lords/75ce115ec7f950d857d0817eb0adf2cc2673ffdd/networks/critic_network.py",
"visit_date": "2023-06-29T15:46:58.396324",
"added": "2024-11-19T02:59:26.117951+00:00",
"created": "2021-08-04T19:21:32",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
package com.ppdai.das.strategy;
import org.apache.commons.codec.digest.DigestUtils;
import java.math.BigInteger;
public class HashModShardLocator extends ModShardLocator {
public HashModShardLocator(Integer mod) {
super(mod);
}
@Override
protected Long string2Long(String str) {
String md5 = DigestUtils.md5Hex(str);
BigInteger bigInteger = new BigInteger(md5, 16);
return bigInteger.longValue();
}
}
|
df89e637859d41c5c5e4c2db9591d567503b559b
|
{
"blob_id": "df89e637859d41c5c5e4c2db9591d567503b559b",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-21T03:00:34",
"content_id": "a899417c3d87ce2d335dd74ff2078a8cb17eba07",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d15f8431d25ba00ad6f7bbe71aefcfeb7ca3798d",
"extension": "java",
"filename": "HashModShardLocator.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 458,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/das-client/src/main/java/com/ppdai/das/strategy/HashModShardLocator.java",
"provenance": "stack-edu-0030.json.gz:702751",
"repo_name": "flylee85/das",
"revision_date": "2020-05-21T03:00:34",
"revision_id": "c0729a22b42f5553fd9b43f33caecd9776e6a7c7",
"snapshot_id": "90cf54fb968c9ceb12fd677b9b1df6a8f5742ddb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/flylee85/das/c0729a22b42f5553fd9b43f33caecd9776e6a7c7/das-client/src/main/java/com/ppdai/das/strategy/HashModShardLocator.java",
"visit_date": "2022-08-03T10:35:57.196821",
"added": "2024-11-18T21:06:42.406447+00:00",
"created": "2020-05-21T03:00:34",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz"
}
|
package com.shagihan.example.eventdrivensample.service;
import com.shagihan.example.eventdrivensample.model.OrderJMSMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private UserService userService;
public EmailService() {
System.out.println("---- Email service.create-----");
}
public void SendEmail(OrderJMSMessage orderJMSMessage) {
System.out.println("-------Sending email -------");
System.out.println("Order ID : " + orderJMSMessage.getOrderId());
System.out.println("User ID : " + orderJMSMessage.getUserId());
System.out.println("Sending email to : " + userService.getUser(orderJMSMessage.getUserId()).getEmail());
System.out.println("-------email sent -------");
}
}
|
600ecdfae285fba9320233dc9f4bae1066db2322
|
{
"blob_id": "600ecdfae285fba9320233dc9f4bae1066db2322",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-18T03:53:10",
"content_id": "22e13e87bf438342b3f59c79b47682664fe96dd7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0d8ada84bcaca11429140ec5e61885ee8fb30f5d",
"extension": "java",
"filename": "EmailService.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 397460765,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 870,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/com/shagihan/example/eventdrivensample/service/EmailService.java",
"provenance": "stack-edu-0020.json.gz:733844",
"repo_name": "shagihan/event-driven-sample",
"revision_date": "2021-08-18T03:53:10",
"revision_id": "bf2ad594ce2375ba64e5a3b29ca15b36447aa3df",
"snapshot_id": "58c740d21c1b4406ba28f3671f7cce3e68a5f42e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/shagihan/event-driven-sample/bf2ad594ce2375ba64e5a3b29ca15b36447aa3df/src/main/java/com/shagihan/example/eventdrivensample/service/EmailService.java",
"visit_date": "2023-07-12T03:11:58.374763",
"added": "2024-11-18T22:53:26.781091+00:00",
"created": "2021-08-18T03:53:10",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
package abstracts;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import dto.main.Respuesta;
import modelo.auth.usuarios.publicos.UsuarioPublico;
import steger.excepciones.controladas.ErrorInternoControlado;
@Scope(proxyMode = ScopedProxyMode.INTERFACES)
@Transactional
public abstract class ACrud<T extends Serializable, S> {
@PersistenceContext
EntityManager entityManager;
@SuppressWarnings("unchecked")
private Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
Logger logger = LoggerFactory.getLogger(clazz);
public Respuesta<T> obtener(final S id) {
final Respuesta<T> respuesta = new Respuesta<T>();
T objeto = entityManager.find(clazz, id);
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(objeto);
respuesta.setEstado(true);
respuesta.setMensaje("obtenido");
return respuesta;
}
@SuppressWarnings("unchecked")
public Respuesta<List<T>> obtenerTodos() {
final Respuesta<List<T>> respuesta = new Respuesta<List<T>>();
List<T> datos = entityManager.createQuery("from " + clazz.getName()).getResultList();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(datos);
respuesta.setEstado(true);
respuesta.setMensaje("obtenidos");
return respuesta;
}
public Respuesta<T> crear(final T objeto) {
final Respuesta<T> respuesta = new Respuesta<T>();
entityManager.persist(objeto);
entityManager.flush();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(objeto);
respuesta.setEstado(true);
respuesta.setMensaje("creado");
return respuesta;
}
public Respuesta<T> actualizar(final T objeto) {
final Respuesta<T> respuesta = new Respuesta<T>();
entityManager.merge(objeto);
entityManager.flush();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(objeto);
respuesta.setEstado(true);
respuesta.setMensaje("actualizado");
return respuesta;
}
public Respuesta<Boolean> eliminar(final S id) {
final Respuesta<Boolean> respuesta = new Respuesta<Boolean>();
T objeto = entityManager.find(clazz, id);
entityManager.remove(objeto);
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(true);
respuesta.setEstado(true);
respuesta.setMensaje("eliminado");
return respuesta;
}
@SuppressWarnings("unchecked")
public Respuesta<T> obtenerPorUsuario(OAuth2Authentication auth, final S id) {
final Respuesta<T> respuesta = new Respuesta<T>();
for (Field field : clazz.getDeclaredFields()) {
if (field.getType().equals(UsuarioPublico.class)) {
T datos = (T) entityManager
.createQuery("from " + clazz.getName() + " class " + "INNER JOIN class." + field.getName()
+ " usuario " + " WHERE usuario.username =:usuario AND class.id =:idClass")
.setParameter("usuario", auth.getPrincipal().toString()).setParameter("idClass", id)
.getSingleResult();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(datos);
respuesta.setEstado(true);
respuesta.setMensaje("obtenido");
return respuesta;
}
}
respuesta.setCodigo(400);
respuesta.setCodigoHttp(400);
respuesta.setCuerpo(null);
respuesta.setEstado(true);
respuesta.setMensaje("El modelo no cuenta con la estructura mapeada de UsuarioPublico");
return respuesta;
}
@SuppressWarnings("unchecked")
public Respuesta<List<T>> obtenerTodosPorUsuario(OAuth2Authentication auth) {
final Respuesta<List<T>> respuesta = new Respuesta<List<T>>();
try {
for (Field field : clazz.getDeclaredFields()) {
if (field.getType().equals(UsuarioPublico.class)) {
List<T> datos = entityManager
.createQuery("from " + clazz.getName() + " class " + "INNER JOIN class." + field.getName()
+ " usuario " + "WHERE usuario.username =:usuario ")
.setParameter("usuario", auth.getPrincipal().toString()).getResultList();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(datos);
respuesta.setEstado(true);
respuesta.setMensaje("obtenidos");
return respuesta;
}
}
respuesta.setCodigo(400);
respuesta.setCodigoHttp(400);
respuesta.setCuerpo(null);
respuesta.setEstado(true);
respuesta.setMensaje("El modelo no cuenta con la estructura mapeada de UsuarioPublico");
return respuesta;
} catch (Exception ex) {
return ErrorInternoControlado.error(ex.getMessage());
}
}
public Respuesta<T> crearPorUsuario(OAuth2Authentication auth, final T objeto) {
logger.info("CLASE ===>" + objeto.getClass().getName());
String usuario = validaUsuario(objeto);
final Respuesta<T> respuesta = new Respuesta<T>();
respuesta.setCodigo(400);
respuesta.setCodigoHttp(400);
respuesta.setCuerpo(objeto);
respuesta.setEstado(false);
if (usuario == null) { // SI ENCONTRO EL USUARIO DENTRO DEL OBJETO
respuesta.setMensaje("EL usuario no existe o no tiene mapeada la clase de usuario publico");
return respuesta;
}
if (usuario.equals(auth.getPrincipal().toString())) { // SI SON LOS MISMOS
entityManager.persist(objeto);
entityManager.flush();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(objeto);
respuesta.setEstado(true);
respuesta.setMensaje("creado");
return respuesta;
}
respuesta.setMensaje("EL usuario no tiene permitido crear comentarios que no son suyos");
return respuesta;
}
public Respuesta<T> actualizarPorUsuario(OAuth2Authentication auth, final T objeto) {
logger.info("CLASE ===>" + objeto.getClass().getName());
String usuario = validaUsuario(objeto);
final Respuesta<T> respuesta = new Respuesta<T>();
respuesta.setCodigo(400);
respuesta.setCodigoHttp(400);
respuesta.setCuerpo(objeto);
respuesta.setEstado(false);
if (usuario == null) { // SI ENCONTRO EL USUARIO DENTRO DEL OBJETO
respuesta.setMensaje("EL usuario no existe o no tiene mapeada la clase de usuario publico");
return respuesta;
}
if (usuario.equals(auth.getPrincipal().toString())) { // SI SON LOS MISMOS
entityManager.merge(objeto);
entityManager.flush();
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(objeto);
respuesta.setEstado(true);
respuesta.setMensaje("actualizado");
return respuesta;
}
respuesta.setMensaje("EL usuario no tiene permitido actualizar comentarios que no son suyos");
return respuesta;
}
public Respuesta<Boolean> eliminarPorUsuario(OAuth2Authentication auth, final S id) {
T objeto = entityManager.find(clazz, id);
logger.info("CLASE ===>" + objeto.getClass().getName());
String usuario = validaUsuario(objeto);
final Respuesta<Boolean> respuesta = new Respuesta<Boolean>();
respuesta.setCodigo(400);
respuesta.setCodigoHttp(400);
respuesta.setCuerpo(false);
respuesta.setEstado(false);
if (usuario == null) { // SI ENCONTRO EL USUARIO DENTRO DEL OBJETO
respuesta.setMensaje("EL usuario no existe o no tiene mapeada la clase de usuario publico");
return respuesta;
}
if (usuario.equals(auth.getPrincipal().toString())) { // SI SON LOS MISMOS
entityManager.remove(objeto);
respuesta.setCodigo(200);
respuesta.setCodigoHttp(200);
respuesta.setCuerpo(true);
respuesta.setEstado(true);
respuesta.setMensaje("eliminado");
return respuesta;
}
respuesta.setMensaje("EL usuario no tiene permitido eliminar comentarios que no son suyos");
return respuesta;
}
private String validaUsuario(T objeto) {
String usuario = null;
try {
for (Field field : objeto.getClass().getDeclaredFields()) {
if (field.getType().equals(UsuarioPublico.class)) {
Field usuarioPublicoField = null;
Field usernameField = null;
try {
usuarioPublicoField = objeto.getClass().getDeclaredField(field.getName());
if (usuarioPublicoField != null) {
usuarioPublicoField.setAccessible(true);
UsuarioPublico usuarioPublico2 = (UsuarioPublico) usuarioPublicoField.get(objeto);
if (usuarioPublico2 != null) {
usernameField = usuarioPublico2.getClass().getDeclaredField("username");
if (usernameField != null) {
usernameField.setAccessible(true);
usuario = (String) usernameField.get(usuarioPublico2);
logger.info("username ===>" + usuario);
usernameField.setAccessible(false);
}
}
usuarioPublicoField.setAccessible(false);
}
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException
| IllegalAccessException e) {
e.printStackTrace();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return usuario;
}
}
|
5b20d78cf736d065fadfc2ab904d3efb80d0231c
|
{
"blob_id": "5b20d78cf736d065fadfc2ab904d3efb80d0231c",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-24T17:43:15",
"content_id": "a194963acd92b2397dc090bd769428fa3879e44a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "80a0ecc396a41005edd1c4a0caec7603fb15f7fc",
"extension": "java",
"filename": "ACrud.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 9179,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Stegeriluminacion/interfaces/src/main/java/abstracts/ACrud.java",
"provenance": "stack-edu-0027.json.gz:346560",
"repo_name": "nirangasandaruwan/TheUltimateMicroServicesTemplate",
"revision_date": "2019-12-24T17:43:15",
"revision_id": "ccca3b877b988ff5aed28940d53bfe178fbb5779",
"snapshot_id": "b2c11bf74a4989c3233b9ec4f8b8b7f5ddc97a16",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nirangasandaruwan/TheUltimateMicroServicesTemplate/ccca3b877b988ff5aed28940d53bfe178fbb5779/Stegeriluminacion/interfaces/src/main/java/abstracts/ACrud.java",
"visit_date": "2020-12-11T08:47:11.301452",
"added": "2024-11-19T03:41:47.711483+00:00",
"created": "2019-12-24T17:43:15",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz"
}
|
import time
import grpc
from concurrent import futures
import mutual_tls_auth_pb2 as serializer
import mutual_tls_auth_pb2_grpc as grpc_lib
from utils import secrets, config
class GatewayServicer(grpc_lib.GatewayServicer):
def loan_orders(self, request, context):
point = serializer.LoanPoint(
rate='0.010000',
amount='5.250',
range_min=2,
range_max=2
)
orders = serializer.Orders(
offers=[point, point, point],
demands=[point]
)
return orders
def serve(cfg):
# Client will verify the server using server cert and the server
# will verify the client using client cert.
server_credentials = grpc.ssl_server_credentials(
[(secrets.load(cfg['credentials']['server']['key']),
secrets.load(cfg['credentials']['server']['cert']))],
root_certificates=secrets.load(cfg['credentials']['client']['cert']),
require_client_auth=True
)
# this statement needs to be tested:
# it's okay to have multiple threads because poloniex api call uses thread lock
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
grpc_lib.add_GatewayServicer_to_server(GatewayServicer(), server)
server.add_secure_port('[::]:50051', server_credentials)
server.start()
try:
while True:
time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve(config.invoke_config())
|
804c8b5a61a007e1eba0f61da9bb594508e363c3
|
{
"blob_id": "804c8b5a61a007e1eba0f61da9bb594508e363c3",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-09T08:21:10",
"content_id": "acfc0f931a981c1fa44f448223546383bc058c22",
"detected_licenses": [
"MIT"
],
"directory_id": "689563b8a41044eed4864f970ee4a2d9ce098a71",
"extension": "py",
"filename": "server.py",
"fork_events_count": 4,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 151419967,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1520,
"license": "MIT",
"license_type": "permissive",
"path": "/python_grpc_mutual_tls_auth/server.py",
"provenance": "stack-edu-0059.json.gz:636938",
"repo_name": "nikolskiy/python-grpc-mutual-tls-auth",
"revision_date": "2018-10-09T08:21:10",
"revision_id": "a347085162bbd23034d9cc8fb5b71cfb931e7d99",
"snapshot_id": "7701d9ccc9c8a907d39792489a5227d337af0b00",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/nikolskiy/python-grpc-mutual-tls-auth/a347085162bbd23034d9cc8fb5b71cfb931e7d99/python_grpc_mutual_tls_auth/server.py",
"visit_date": "2020-03-30T16:39:37.935207",
"added": "2024-11-19T02:43:39.125634+00:00",
"created": "2018-10-09T08:21:10",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Duration } from '../../shared/models/duration.model';
@Component({
selector: 'app-timeduration',
templateUrl: './timeduration.component.html',
styleUrls: ['./timeduration.component.scss']
})
export class TimedurationComponent implements OnInit {
@Output() selection_change = new EventEmitter();
duration: Duration;
constructor() { }
ngOnInit() {
}
keys(): Array<string> {
const keys = Object.values(Duration);
return keys.slice(keys.length / 2);
}
selectionchange(value: number) {
if (this.selection_change) {
this.selection_change.emit(value);
}
}
}
|
02a6d47d96c3dfb49601acae04f11d79b36725a1
|
{
"blob_id": "02a6d47d96c3dfb49601acae04f11d79b36725a1",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-07T20:35:42",
"content_id": "ccac30c85e6ae8928958da69e382d5b409eb7347",
"detected_licenses": [
"MIT"
],
"directory_id": "6bf05a5372ff06b08c886f0a0d4137f2585f1777",
"extension": "ts",
"filename": "timeduration.component.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147513830,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 704,
"license": "MIT",
"license_type": "permissive",
"path": "/src/booking/timeduration/timeduration.component.ts",
"provenance": "stack-edu-0075.json.gz:820513",
"repo_name": "code-karen-muradyan/Booking.Calendar.Client",
"revision_date": "2018-09-07T20:35:42",
"revision_id": "77bafbedbba19cc56198b7a78a6613f24a293295",
"snapshot_id": "0669376cbd987016755c6f24e4816f8e303ad718",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/code-karen-muradyan/Booking.Calendar.Client/77bafbedbba19cc56198b7a78a6613f24a293295/src/booking/timeduration/timeduration.component.ts",
"visit_date": "2020-03-28T01:33:53.376967",
"added": "2024-11-19T01:58:05.442432+00:00",
"created": "2018-09-07T20:35:42",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
<?php
namespace Armincms\Advertise;
use Illuminate\Support\ServiceProvider;
use Laravel\Nova\Nova as LaravelNova;
class ToolServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
LaravelNova::serving([$this, 'servingNova']);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
public function servingNova()
{
LaravelNova::resources([
Nova\Advertise::class,
Nova\Category::class,
Nova\Tag::class,
]);
}
}
|
265eca77a327242fea849ff40c79ff681337ca90
|
{
"blob_id": "265eca77a327242fea849ff40c79ff681337ca90",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-16T07:23:46",
"content_id": "ec8375a6fe663aec7b2ba62432d46f50ff43b8f3",
"detected_licenses": [
"MIT"
],
"directory_id": "5cca3efddb10a12a9655fc3d8f1cfd5e77e08e43",
"extension": "php",
"filename": "ToolServiceProvider.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 256139966,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 685,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ToolServiceProvider.php",
"provenance": "stack-edu-0047.json.gz:85001",
"repo_name": "armincms/advertise",
"revision_date": "2020-04-16T07:23:46",
"revision_id": "cac2eb03d5bba9aa41337187fbe3d3b7d7eae532",
"snapshot_id": "cfc87b8343f2d88a447c073f30ca410c2e147890",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/armincms/advertise/cac2eb03d5bba9aa41337187fbe3d3b7d7eae532/src/ToolServiceProvider.php",
"visit_date": "2022-04-16T12:55:05.074879",
"added": "2024-11-18T23:22:56.330040+00:00",
"created": "2020-04-16T07:23:46",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
function User(data) {
this.id = data.id;
this.name = data.name;
this.color1 = data.color1;
this.color2 = data.color2;
this.message = data.message;
this.me = false;
this.lastTimeScene = Date.now();
this.screenPosition = { x: 0, y: 0 };
this.normalizedScreenPos = { x: 0, y: 0 };
this.oScreenPosition = { x: 0, y: 0 };
this.mousePosition = { x: 0, y: 0, z: 0 };
this.cameraPosition = { x: 0, y: 0, z: 0 };
this.cameraRotation = { x: 0, y: 0, z: 0, w: 0 };
this.screenSize = { x: 0, y: 0 };
this.primaryColor = { x: 0, y: 0, z: 0 };
this.secondaryColor = { x: 0, y: 0, z: 0 };
this.cameraTargetPosition = new Vector3();
this.cameraTargetRotation = new Quaternion();
this.mouseTargetPosition = new Vector3();
this.screenDistance = 1;
this.mouseDown = 0;
this.testDiv = document.createElement("div");
this.testDiv.className = "miniDiv";
this.testDiv.innerHTML = this.name;
this.testDiv.style.top = Math.random() * 200 + "px";
this.testDiv.style.left = Math.random() * 400 + "px";
this.testDiv.style.pointerEvents = "none";
this.geo = new THREE.BoxGeometry(1, 1, 1);
this.mat = new THREE.MeshNormalMaterial();
console.log( parseInt(this.id));
this.uniforms = {
dT: G.uniforms.dt,
time: G.uniforms.time,
t_audio: G.uniforms.t_audio,
t_matcap: G.uniforms.t_matcap,
t_normal: G.uniforms.t_normal,
c_primaryColor: {type:"c",value:new THREE.Color(0xffff00)},
c_secondaryColor: {type:"c",value:new THREE.Color(0x00ff00)},
id: { type:"f", value: parseInt(this.id) * .3}
}
this.bodyMat = new THREE.ShaderMaterial({
vertexShader: G.shaders.vs.face,
fragmentShader: G.shaders.fs.face,
blending: THREE.AdditiveBlending,
uniforms: this.uniforms
});
console.log( G.s)
this.eyeMat = new THREE.ShaderMaterial({
vertexShader: G.shaders.vs.eyes,
fragmentShader: G.shaders.fs.eyes,
uniforms: this.uniforms
});
this.cameraRep = new THREE.Object3D();
var geometry = new THREE.IcosahedronGeometry( .2,2 );
var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
this.body = new THREE.Mesh(this.geo,material);
this.eyeL = new THREE.Mesh(this.geo, this.eyeMat);
this.eyeR = new THREE.Mesh(this.geo, this.eyeMat);
this.cone = new THREE.Mesh( geometry, this.bodyMat );
this.cone.rotation.x = Math.PI/2;
this.cone.position.z = .4;
this.cone.rotation.y = Math.PI/4;
this.body.scale.set( .2 , .2 , .3);
this.mouseRep = new THREE.Mesh(this.geo, this.bodyMat);
// dont add representations IF its ourselves!
if (this.id == SERVER.myID) {
this.me = true;
this.updateName( this.name );
}else{
this.eyeL.position.set(0.25, 0, -1);
this.eyeR.position.set(-0.25, 0, -1);
this.eyeL.scale.set(.3,.3,.3)
this.eyeR.scale.set(.3,.3,.3)
//this.cameraRep.add(this.body);
this.cameraRep.add(this.cone);
// this.cameraRep.add(this.eyeL);
//this.cameraRep.add(this.eyeR);
this.updateName( this.name );
this.updateColor1( this.color1 );
this.updateColor2( this.color2 );
}
}
User.prototype.Add = function() {
// if( !this.me ) scene.add(this.nameMesh);
scene.add(this.cameraRep);
// scene.add(this.mouseRep);
//document.body.appendChild(this.testDiv);
};
User.prototype.Remove = function() {
scene.remove(this.cameraRep);
scene.remove(this.mouseRep);
//scene.remove(this.nameMesh);
//this.testDiv.remove();
};
User.prototype.GetData = function() {
return {
name: this.name,
id: this.id,
lastTimeScene: Date.now(),
mousePosition: this.mousePosition,
screenPosition: this.screenPosition,
screenSize: this.screenSize,
cameraPosition: this.cameraPosition,
cameraRotation: this.cameraRotation,
color1: this.color1,
color2: this.color2,
message: this.message
};
};
User.prototype.emitData = function() {
//TODO: only emit if something has changed
// or if we need to send heartbeat to stay alive
socket.emit("new user data", this.GetData());
};
User.prototype.updateData = function(data) {
if (data.name != this.name) this.updateName(data.name);
if (data.color1 != this.color1) this.updateColor1(data.color1);
if (data.color2 != this.color2) this.updateColor2(data.color2);
if (data.message != this.message) this.updateMessage(data.message);
this.testDiv.style.top = data.screenPosition.y + "px";
this.testDiv.style.left = data.screenPosition.x + "px";
this.lastTimeScene = data.lastTimeScene;
//this.cameraRep.scale.set(1, data.screenSize.y / data.screenSize.x, 0.1);
if( !this.me ){
this.cameraTargetPosition.copy(data.cameraPosition);
this.cameraTargetRotation.copy(data.cameraRotation);
this.mouseTargetPosition.copy(data.mousePosition);
this.mouseRep.scale.set(0.1, 0.1, 0.1);
}else{
this.mouseRep.scale.set(0.04, 0.04, 0.04);
}
};
User.prototype.lerpValues = function(){
this.cameraRep.position.lerp( this.cameraTargetPosition , .2 );
this.cameraRep.quaternion.slerp( this.cameraTargetRotation, .2 );
this.mouseRep.position.lerp( this.mouseTargetPosition ,.2)
this.mouseRep.quaternion.slerp( this.cameraTargetRotation,.2)
v1.copy(this.cameraRep.position);
v2.set(0,.5,0);
v1.add(v2);
this.nameMesh.position.copy( v1 );
this.nameMesh.lookAt( camera.position );
}
User.prototype.selfUpdate = function() {
this.cameraPosition.x = camera.position.x;
this.cameraPosition.y = camera.position.y;
this.cameraPosition.z = camera.position.z;
this.cameraRotation.x = camera.quaternion.x;
this.cameraRotation.y = camera.quaternion.y;
this.cameraRotation.z = camera.quaternion.z;
this.cameraRotation.w = camera.quaternion.w;
this.screenSize.x = window.innerWidth;
this.screenSize.y = window.innerHeight;
v1.set(
(this.screenPosition.x / window.innerWidth) * 2 - 1,
-(this.screenPosition.y / window.innerHeight) * 2 + 1,
0.5
);
this.normalizedScreenPos.x = v1.x;
this.normalizedScreenPos.y = v1.y;
//console.log( v1 );
v1.unproject(camera);
v1.sub(camera.position).normalize();
v2.copy(camera.position).add(v1.multiplyScalar(this.screenDistance));
this.mousePosition.x = v2.x;
this.mousePosition.y = v2.y;
this.mousePosition.z = v2.z;
this.mouseRep.position.copy(this.mousePosition);
this.mouseRep.quaternion.copy(this.cameraRotation)
};
// Right now we are just booting a user
// if we haven't seen them in 5 seconds!
User.prototype.Update = function() {
if (this.me != true) {
if (Date.now() - this.lastTimeScene > 5000) {
SERVER.RemoveUser(this.GetData());
}
this.lerpValues()
} else {
this.selfUpdate();
this.updateData(this.GetData());
}
};
User.prototype.updateName = function(name) {
if( this.nameMesh ){scene.remove(this.nameMesh)}
this.nameMesh = textMaker.createMesh(name);
this.nameMesh.scale.set(.3,.3,.3)
this.nameMesh.position.copy( this.cameraRep.position )
// if( !this.me ) scene.add( this.nameMesh );
this.name = name;
this.testDiv.innerHTML = this.name;
};
User.prototype.updateColor1 = function(color1) {
this.color1 = color1;
this.uniforms.c_primaryColor.value.set(color1);
};
User.prototype.updateColor2 = function(color2) {
this.color2 = color2;
this.uniforms.c_secondaryColor.value.set(color2);
};
User.prototype.updateMessage = function(message) {
this.message = message;
};
|
b8ab6aab451a445e2f69a8736b09c9bcaccc0c12
|
{
"blob_id": "b8ab6aab451a445e2f69a8736b09c9bcaccc0c12",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-28T19:24:10",
"content_id": "010a7bc33cec39660dc6c5b36b01c32c5ab9ba1e",
"detected_licenses": [
"MIT"
],
"directory_id": "3403662abc181fd5f1d26d68f08a6a1fd6c26601",
"extension": "js",
"filename": "User.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 7497,
"license": "MIT",
"license_type": "permissive",
"path": "/public/scripts/User.js",
"provenance": "stack-edu-0044.json.gz:401550",
"repo_name": "technologyarts/SWAMP",
"revision_date": "2021-06-28T19:24:10",
"revision_id": "549c4f002cbbe8af9e0bec6758c3d904f0b2a7ce",
"snapshot_id": "cbae4e17c3e064859f54abf4ae8133756a9fea0a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/technologyarts/SWAMP/549c4f002cbbe8af9e0bec6758c3d904f0b2a7ce/public/scripts/User.js",
"visit_date": "2023-06-02T16:35:01.597970",
"added": "2024-11-19T00:39:04.421911+00:00",
"created": "2021-06-28T19:24:10",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
import time
import os
import sys
import rclpy
from rclpy.node import Node
from std_msgs.msg import Int8MultiArray
class RemoPublisher(Node):
def __init__(self):
super().__init__('remo_publisher')
self.publisher_ = self.create_publisher(Int8MultiArray, 'drive', 10)
#timer_period = 0.5 # seconds
#self.timer = self.create_timer(timer_period, self.timer_callback)
def send_ints(self, data):
msg = Int8MultiArray()
msg.data = data
self.publisher_.publish(msg)
self.get_logger().info('Publishing: "%s"' % msg.data)
rclpy.init()
remo_publisher = RemoPublisher()
def setup(robot_config):
# your hardware setup code goes here
print("initializing ROS node")
return
def move(args):
command = args['button']['command']
print(args)
print (command)
try:
if command == 'F' or command == 'f' :
# your hardware movement code for forward goes here
remo_publisher.send_ints([10,10])
return
elif command == 'B' or command == 'b':
# your hardware movement code for backwards goes here
remo_publisher.send_ints([-10,-10])
return
elif command == 'L' or command == 'l':
# your hardware movement code for left goes here
remo_publisher.send_ints([-10,10])
return
elif command == 'R' or command == 'r':
# your hardware movement code for right goes here
remo_publisher.send_ints([10,-10])
return
elif command == 'S' or command == 's':
remo_publisher.send_ints([0,0])
return
except:
import traceback
print(traceback.format_exc())
return
|
b03033ff331cddf20cde9fbda2da6dedbe3e0d59
|
{
"blob_id": "b03033ff331cddf20cde9fbda2da6dedbe3e0d59",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-17T09:05:19",
"content_id": "383d68ebd16b70a4b0389a5f9a95bb5413378b5d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "3ad6a835d52eaa37b2fb77200694a20144aafc96",
"extension": "py",
"filename": "rvrros.py",
"fork_events_count": 0,
"gha_created_at": "2020-09-16T22:42:34",
"gha_event_created_at": "2020-09-16T22:42:35",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 296163043,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1812,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hardware/rvrros.py",
"provenance": "stack-edu-0058.json.gz:162325",
"repo_name": "Yoruio/controller",
"revision_date": "2020-10-17T09:00:32",
"revision_id": "6cb12f24f3d239281e32d76cb44984ac89a97e50",
"snapshot_id": "422aaa5bf2122dd9030bc31629911476ddfc321f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Yoruio/controller/6cb12f24f3d239281e32d76cb44984ac89a97e50/hardware/rvrros.py",
"visit_date": "2022-12-28T06:34:21.411663",
"added": "2024-11-19T01:37:35.799516+00:00",
"created": "2020-10-17T09:00:32",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz"
}
|
/*
* Copyright 2021 Allette Systems (Australia)
* http://www.allette.com.au
*
* 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 org.pageseeder.ox.core;
import org.pageseeder.ox.api.Result;
import org.pageseeder.ox.core.JobStatus.STATUS;
import org.pageseeder.ox.util.ISO8601;
import org.pageseeder.xmlwriter.XMLWritable;
import org.pageseeder.xmlwriter.XMLWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A simple java object to represent a Job for each Pipeline.
*
* @author Ciber Cai
* @since 07 November 2014
*/
public final class PipelineJob implements XMLWritable, Serializable {
/** the serial version. */
private static final long serialVersionUID = -3028660547170793478L;
/** The max inactive time allowed. */
private long maxInactiveTimeAllowed = StepJob.DEFAULT_MAX_INACTIVE_TIME_MS;
/** The job id. */
private final String _id;
/** Time the job was started. */
private final long _startTime;
/** The data package;. */
private final PackageData _package;
/** The pipeline needs to process. */
private final Pipeline _pipeline;
/** The status of job. */
private final JobStatus status;
/** The file to download. */
private String download;
/** The job result. */
private List<Result> results;
/** to indicate the job is in slow land. */
private boolean isSlow = false;
/**
* Instantiates a new pipeline job.
*
* @param pipeline The {@link Pipeline }
* @param pack The {@link PackageData }
*/
public PipelineJob(Pipeline pipeline, PackageData pack) {
if (pipeline == null) { throw new NullPointerException("pipeline is null."); }
if (pack == null) { throw new NullPointerException("pack is null."); }
this._id = "c" + System.nanoTime() + "f" + new Random(System.currentTimeMillis()).nextInt(100);
this._startTime = System.currentTimeMillis();
this._pipeline = pipeline;
this._package = pack;
this.status = new JobStatus();
this.results = new ArrayList<>();
}
/**
* Gets the id.
*
* @return the job id.
*/
public String getId() {
return this._id;
}
/**
* Gets the pipeline.
*
* @return the pipeline
*/
public Pipeline getPipeline() {
return this._pipeline;
}
/**
* Gets the package data.
*
* @return the package data
*/
public PackageData getPackageData() {
return this._package;
}
/**
* Gets the download.
*
* @return the download path
*/
public String getDownload() {
return this.download;
}
/**
* Gets the status.
*
* @return the status of the job
*/
public JobStatus getStatus() {
return this.status;
}
/**
* Gets the max inactive time allowed.
*
* @return the max inactive time allowed
*/
public long getMaxInactiveTimeAllowed() {
return maxInactiveTimeAllowed;
}
/**
* Sets the max inactive time allowed.
*
* @param maxInactiveTimeAllowed the new max inactive time allowed
*/
public void setMaxInactiveTimeAllowed(long maxInactiveTimeAllowed) {
if (maxInactiveTimeAllowed > 0) {
this.maxInactiveTimeAllowed = maxInactiveTimeAllowed;
}
}
/**
* Indicates whether this job is considered inactive.
*
* <p>An job is considered inactive if the job have have created longer than a specified time
* since it is created.
*
* @return status of the job.
*/
public boolean isInactive() {
return System.currentTimeMillis() - this._startTime > getMaxInactiveTimeAllowed() ? true : false;
}
/**
* Checks if is slow job.
*
* @return whether the job is slow job.
*/
public boolean isSlowJob() {
return this.isSlow;
}
/**
* Set the job to complete status.
*/
public void started() {
this.status.setJobStatus(STATUS.PROCESSING);
this.status.setPercentage(1);
}
/**
* Set the job to complete status.
*/
public void completed() {
this.status.setJobStatus(STATUS.COMPLETED);
this.status.setPercentage(100);
}
/**
* Set the job to error status.
*/
public void failed() {
this.status.setJobStatus(STATUS.ERROR);
}
/**
* Sets the download.
*
* @param download set the download path
*/
public void setDownload(String download) {
this.download = download;
}
/**
* Sets the slow mode.
*
* @param slow to indicate that the job is to run on slow mode.
*/
public void setSlowMode(boolean slow) {
this.isSlow = slow;
}
/**
* Adds the step result.
*
* @param result the result
*/
public void addStepResult (Result result) {
if (result != null) this.results.add(result);
}
/* (non-Javadoc)
* @see org.pageseeder.xmlwriter.XMLWritable#toXML(org.pageseeder.xmlwriter.XMLWriter)
*/
@Override
public void toXML(XMLWriter xml) throws IOException {
xml.openElement("job");
xml.attribute("id", this._id);
xml.attribute("start", ISO8601.DATETIME.format(this._startTime));
xml.attribute("status", this.status.toString());
xml.attribute("input", this._package.getOriginal().getName());
xml.attribute("mode", this.isSlow ? "slow" : "normal");
if (this.download != null) {
xml.attribute("path", this.download);
}
xml.openElement("results");
for (Result result:results) {
result.toXML(xml);
}
xml.closeElement();//results
xml.closeElement();
}
}
|
5a08fed5b8d612342c06df5ce9a991911393a258
|
{
"blob_id": "5a08fed5b8d612342c06df5ce9a991911393a258",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-28T15:11:40",
"content_id": "3f8d50a7fe8afb3cc0d26d832b8bb8b677950d86",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "977c74913c46e8ad6608e04224da830038db9d03",
"extension": "java",
"filename": "PipelineJob.java",
"fork_events_count": 0,
"gha_created_at": "2016-11-18T00:18:31",
"gha_event_created_at": "2021-05-03T11:12:23",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 74079110,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5985,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/pso-ox-core/src/main/java/org/pageseeder/ox/core/PipelineJob.java",
"provenance": "stack-edu-0026.json.gz:553321",
"repo_name": "pageseeder/ox",
"revision_date": "2023-02-28T15:11:40",
"revision_id": "cf93d2dc0b5e95d6dd4a49f4ad3522e069999eb7",
"snapshot_id": "d61636fe2c1ed8ea09a728fddce34bfc082b1aec",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pageseeder/ox/cf93d2dc0b5e95d6dd4a49f4ad3522e069999eb7/pso-ox-core/src/main/java/org/pageseeder/ox/core/PipelineJob.java",
"visit_date": "2023-07-10T22:45:45.128923",
"added": "2024-11-18T22:24:48.159642+00:00",
"created": "2023-02-28T15:11:40",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
from abc import ABC
from dataclasses import dataclass, asdict
from typing import Set, Dict
@dataclass
class Mixin(ABC):
pass
@dataclass
class AsDictMixin(Mixin):
def as_dict(self, exclude: Set["str"]) -> Dict:
entity_dict = asdict(self)
for key in exclude:
del entity_dict[key]
return entity_dict
|
b843e958836a6fce9c21e3d9f1abc28678cdf13b
|
{
"blob_id": "b843e958836a6fce9c21e3d9f1abc28678cdf13b",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-24T18:57:59",
"content_id": "f7a73d80d47bf0e384e927f7b59851ebf203a2a5",
"detected_licenses": [
"MIT"
],
"directory_id": "6b7e31dd8a982b75eabb45c7dbe7fdaa50910f10",
"extension": "py",
"filename": "mixins.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291758561,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 348,
"license": "MIT",
"license_type": "permissive",
"path": "/memrise/core/mixins.py",
"provenance": "stack-edu-0062.json.gz:363446",
"repo_name": "kolesnikov-bn/django-memrise-scraper",
"revision_date": "2021-01-24T18:57:59",
"revision_id": "00dddb53f04ce2f794fe3611ea97190ef8265079",
"snapshot_id": "dbd1e2c3976f29702e397ce47df1416f0bf73be1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kolesnikov-bn/django-memrise-scraper/00dddb53f04ce2f794fe3611ea97190ef8265079/memrise/core/mixins.py",
"visit_date": "2023-03-02T10:37:10.610551",
"added": "2024-11-18T20:48:53.270829+00:00",
"created": "2021-01-24T18:57:59",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
package util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageSaver implements Runnable
{
Logger logger = LoggerFactory.getLogger(ImageSaver.class);
BufferedImage img;
File file;
public ImageSaver(BufferedImage img, File file)
{
this.img = img;
this.file = file;
}
@Override
public void run()
{
try {
ImageIO.write(img, "png", file);
} catch (IOException e) {
logger.error("Can't write image", e);
}
}
}
|
7d73a460d2e4a484269ee92bd77b850c416e5fc1
|
{
"blob_id": "7d73a460d2e4a484269ee92bd77b850c416e5fc1",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-01T11:49:03",
"content_id": "9bb5eb9eaabc40ed60b9defc395bef1708a052a5",
"detected_licenses": [
"MIT"
],
"directory_id": "82d2b7b3c1438a16ba6a9605a9649dc133440450",
"extension": "java",
"filename": "ImageSaver.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 578,
"license": "MIT",
"license_type": "permissive",
"path": "/src/util/ImageSaver.java",
"provenance": "stack-edu-0024.json.gz:428340",
"repo_name": "bbo-lab/CalGraph3D",
"revision_date": "2021-07-01T11:48:49",
"revision_id": "aa1172f228a58539064b816d5a01b4af5772c547",
"snapshot_id": "9489542902b27565bd282b9e0cab0be35bf62d35",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bbo-lab/CalGraph3D/aa1172f228a58539064b816d5a01b4af5772c547/src/util/ImageSaver.java",
"visit_date": "2023-06-12T16:40:58.463388",
"added": "2024-11-19T02:48:27.728197+00:00",
"created": "2021-07-01T11:48:49",
"int_score": 3,
"score": 3.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
import datetime
birthdays = [
datetime.datetime(2012, 4, 29),
datetime.datetime(2006, 8, 9),
datetime.datetime(1978, 5, 16),
datetime.datetime(1981, 8, 15),
datetime.datetime(2001, 7, 4),
datetime.datetime(1999, 12, 30)
]
today = datetime.datetime.today()
# Create a function named is_over_13 that takes a datetime and returns
# whether or not the difference between that datetime and today is 4745 days or more.
def is_over_13(adatetime):
return abs((adatetime - datetime.datetime.today()).days) >= 13*365
# Now create a function named date_string that takes a datetime and returns
# a string like "May 20" using strftime. The format string is "%B %d".
def date_string(adatetime):
return adatetime.strftime("%B %d, %Y")
# Finally, make a variable named birth_dates. Use map() and filter(),
# along with your two functions, to create date strings for every datetime in birthdays
# so long as the datetime is more than 13 years old.
birth_dates = map(date_string, filter(is_over_13, birthdays))
print(list(birth_dates))
|
a80e9e979b9350613d8035413f421ffa2921e7b4
|
{
"blob_id": "a80e9e979b9350613d8035413f421ffa2921e7b4",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-13T15:51:51",
"content_id": "f05831b732819e85dc6359019b95408a678a4bea",
"detected_licenses": [
"Unlicense"
],
"directory_id": "b4fbc2aa91027db96292e0c351305fc2746c6527",
"extension": "py",
"filename": "birthdays.py",
"fork_events_count": 0,
"gha_created_at": "2016-12-22T20:11:36",
"gha_event_created_at": "2021-04-16T20:17:59",
"gha_language": "C#",
"gha_license_id": "Unlicense",
"github_id": 77172849,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1059,
"license": "Unlicense",
"license_type": "permissive",
"path": "/python/python-scripts/functional python/challenges/birthdays.py",
"provenance": "stack-edu-0054.json.gz:620523",
"repo_name": "davejlin/treehouse",
"revision_date": "2020-10-13T15:51:51",
"revision_id": "0842c1e0515d6d629b02579e189ca7b1afe6918b",
"snapshot_id": "ae45b33977caf5d4e7d604cf8e046f6206d5adca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/davejlin/treehouse/0842c1e0515d6d629b02579e189ca7b1afe6918b/python/python-scripts/functional python/challenges/birthdays.py",
"visit_date": "2021-07-03T13:03:42.285468",
"added": "2024-11-19T02:31:20.994886+00:00",
"created": "2020-10-13T15:51:51",
"int_score": 4,
"score": 4,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
import torch
import os
from collections import OrderedDict, defaultdict
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import time
import sys
import csv
from torch.distributions.kl import kl_divergence
from . import __version__, util
from .distributions import Empirical
from .graph import Graph
from .trace import Trace
def _address_stats(trace_dist, use_address_base=True, reuse_ids_from_address_stats=None):
addresses = {}
address_id_to_variable = {}
if reuse_ids_from_address_stats is not None:
address_ids = reuse_ids_from_address_stats['address_ids']
address_base_ids = reuse_ids_from_address_stats['address_base_ids']
else:
address_ids = {}
address_base_ids = {}
for i in range(trace_dist.length):
trace = trace_dist._get_value(i)
trace_weight = float(trace_dist._get_weight(i))
for variable in trace.variables:
address_base = variable.address_base
address = variable.address
key = address_base if use_address_base else address
if key in addresses:
addresses[key]['count'] += 1
addresses[key]['weight'] += trace_weight
else:
if key in address_ids:
address_id = address_ids[key]
else:
if use_address_base:
if address_base.startswith('__A'):
address_id = address_base[2:]
else:
address_id = 'A' + str(len(address_ids) + 1)
else:
if address_base.startswith('__A'):
address_id = address[2:]
else:
if address_base not in address_base_ids:
address_base_id = 'A' + str(len(address_base_ids) + 1)
address_base_ids[address_base] = address_base_id
address_id = address_base_ids[address_base] + '__' + str(variable.instance)
address_ids[key] = address_id
addresses[key] = {'count': 1, 'weight': trace_weight, 'address_id': address_id, 'variable': variable}
address_id_to_variable[address_id] = variable
addresses = OrderedDict(sorted(addresses.items(), key=lambda v: util.address_id_to_int(v[1]['address_id'])))
addresses_extra = OrderedDict()
addresses_extra['pyprob_version'] = __version__
addresses_extra['torch_version'] = torch.__version__
addresses_extra['num_distribution_elements'] = len(trace_dist)
addresses_extra['addresses'] = len(addresses)
addresses_extra['addresses_controlled'] = len([1 for value in list(addresses.values()) if value['variable'].control])
addresses_extra['addresses_replaced'] = len([1 for value in list(addresses.values()) if not value['variable'].accepted])
addresses_extra['addresses_observable'] = len([1 for value in list(addresses.values()) if value['variable'].observable])
addresses_extra['addresses_observed'] = len([1 for value in list(addresses.values()) if value['variable'].observed])
addresses_extra['addresses_tagged'] = len([1 for value in list(addresses.values()) if value['variable'].tagged])
return {'addresses': addresses, 'addresses_extra': addresses_extra, 'address_base_ids': address_base_ids, 'address_ids': address_ids, 'address_id_to_variable': address_id_to_variable}
def _trace_stats(trace_dist, use_address_base=True,
reuse_ids_from_address_stats=None, reuse_ids_from_trace_stats=None):
address_stats = _address_stats(trace_dist,
use_address_base=use_address_base,
reuse_ids_from_address_stats=reuse_ids_from_address_stats)
addresses = address_stats['addresses']
traces = {}
if reuse_ids_from_trace_stats is not None:
trace_ids = reuse_ids_from_trace_stats['trace_ids']
else:
trace_ids = {}
for i in range(trace_dist.length):
trace = trace_dist._get_value(i)
trace_weight = float(trace_dist._get_weight(i))
trace_str = ''.join([variable.address_base if use_address_base else variable.address for variable in trace.variables])
if trace_str not in traces:
if trace_str in trace_ids:
trace_id = trace_ids[trace_str]
else:
trace_id = 'T' + str(len(trace_ids) + 1)
trace_ids[trace_str] = trace_id
address_id_sequence = ['START'] + [addresses[variable.address_base if use_address_base else variable.address]['address_id'] for variable in trace.variables] + ['END']
traces[trace_str] = {'count': 1, 'weight': trace_weight, 'trace_id': trace_id, 'trace': trace, 'address_id_sequence': address_id_sequence}
else:
traces[trace_str]['count'] += 1
traces[trace_str]['weight'] += trace_weight
traces = OrderedDict(sorted(traces.items(), key=lambda v: v[1]['count'], reverse=True))
address_ids = [i for i in range(len(addresses))]
address_weights = []
for key, value in addresses.items():
address_weights.append(value['count'])
address_id_dist = Empirical(address_ids, weights=address_weights, name='Address ID')
unique_trace_ids = [i for i in range(len(traces))]
trace_weights = []
for _, value in traces.items():
trace_weights.append(value['count'])
trace_id_dist = Empirical(unique_trace_ids, weights=unique_trace_ids, name='Unique trace ID')
trace_length_dist = trace_dist.map(lambda trace: trace.length).unweighted().rename('Trace length (all)')
trace_length_controlled_dist = trace_dist.map(lambda trace: trace.length_controlled).unweighted().rename('Trace length (controlled)')
trace_execution_time_dist = trace_dist.map(lambda trace: trace.execution_time_sec).unweighted().rename('Trace execution time (s)')
traces_extra = OrderedDict()
traces_extra['trace_types'] = len(traces)
traces_extra['trace_length_min'] = float(trace_length_dist.min)
traces_extra['trace_length_max'] = float(trace_length_dist.max)
traces_extra['trace_length_mean'] = float(trace_length_dist.mean)
traces_extra['trace_length_stddev'] = float(trace_length_dist.stddev)
traces_extra['trace_length_controlled_min'] = float(trace_length_controlled_dist.min)
traces_extra['trace_length_controlled_max'] = float(trace_length_controlled_dist.max)
traces_extra['trace_length_controlled_mean'] = float(trace_length_controlled_dist.mean)
traces_extra['trace_length_controlled_stddev'] = float(trace_length_controlled_dist.stddev)
traces_extra['trace_execution_time_min'] = float(trace_execution_time_dist.min)
traces_extra['trace_execution_time_max'] = float(trace_execution_time_dist.max)
traces_extra['trace_execution_time_mean'] = float(trace_execution_time_dist.mean)
traces_extra['trace_execution_time_stddev'] = float(trace_execution_time_dist.stddev)
return {'traces': traces, 'traces_extra': traces_extra, 'trace_ids': trace_ids, 'address_stats': address_stats, 'trace_id_dist': trace_id_dist, 'trace_length_dist': trace_length_dist, 'trace_length_controlled_dist': trace_length_controlled_dist, 'trace_execution_time_dist': trace_execution_time_dist, 'address_id_dist': address_id_dist}
def trace_histograms(trace_dist, use_address_base=True, figsize=(10, 5), bins=30, plot=False, plot_show=True, file_name=None):
trace_stats = _trace_stats(trace_dist, use_address_base=use_address_base)
traces = trace_stats['traces']
traces_extra = trace_stats['traces_extra']
if plot:
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
# mpl.rcParams['font.size'] = 4
fig, ax = plt.subplots(2, 2, figsize=figsize)
values = trace_stats['trace_length_dist'].values_numpy()
weights = trace_stats['trace_length_dist'].weights_numpy()
name = trace_stats['trace_length_dist'].name
ax[0, 0].hist(values, weights=weights, density=1, bins=bins)
ax[0, 0].set_xlabel(name)
ax[0, 0].set_ylabel('Frequency')
ax[0, 0].set_yscale('log', nonposy='clip')
values = trace_stats['trace_length_controlled_dist'].values_numpy()
weights = trace_stats['trace_length_controlled_dist'].weights_numpy()
name = trace_stats['trace_length_controlled_dist'].name
ax[0, 1].hist(values, weights=weights, density=1, bins=bins)
ax[0, 1].set_xlabel(name)
# ax[0, 1].set_ylabel('Frequency')
ax[0, 1].set_yscale('log', nonposy='clip')
values = trace_stats['address_id_dist'].values_numpy()
weights = trace_stats['address_id_dist'].weights_numpy()
name = trace_stats['address_id_dist'].name
ax[1, 0].hist(values, weights=weights, density=1, bins=len(values))
ax[1, 0].set_xlabel(name)
ax[1, 0].set_ylabel('Frequency')
ax[1, 0].set_yscale('log', nonposy='clip')
values = trace_stats['trace_execution_time_dist'].values_numpy()
weights = trace_stats['trace_execution_time_dist'].weights_numpy()
name = trace_stats['trace_execution_time_dist'].name
ax[1, 1].hist(values, weights=weights, density=1, bins=bins)
ax[1, 1].set_xlabel(name)
# ax[1, 1].set_ylabel('Frequency')
ax[1, 1].set_yscale('log', nonposy='clip')
plt.suptitle(trace_dist.name, x=0.0, y=.99, horizontalalignment='left', verticalalignment='top', fontsize=10)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
if file_name is not None:
plot_file_name = file_name + '.pdf'
print('Plotting to file: {}'.format(plot_file_name))
plt.savefig(plot_file_name)
report_file_name = file_name + '.txt'
print('Saving trace report to file: {}'.format(report_file_name))
with open(report_file_name, 'w') as file:
file.write('pyprob diagnostics\n')
for key, value in traces_extra.items():
file.write('{}: {}\n'.format(key, value))
traces_file_name = file_name + '.csv'
print('Saving traces to file: {}'.format(traces_file_name))
with open(traces_file_name, 'w') as file:
file.write('trace_id, count, length, length_controlled, address_id_sequence\n')
for key, value in traces.items():
file.write('{}, {}, {}, {}, {}\n'.format(value['trace_id'], value['count'], len(value['trace'].variables), len(value['trace'].variables_controlled), ' '.join(value['address_id_sequence'])))
if plot_show:
plt.show()
def address_histograms(trace_dists, ground_truth_trace=None, figsize=(15, 12), bins=30, use_address_base=True, plot=False, plot_show=True, file_name=None):
if not isinstance(trace_dists, list):
trace_dists = [trace_dists]
dists = {}
address_stats = None
address_stats_combined = {}
for trace_dist in trace_dists:
print('Collecting values for distribution: {}'.format(trace_dist.name))
address_stats = _address_stats(trace_dist, use_address_base=use_address_base, reuse_ids_from_address_stats=address_stats)
addresses = address_stats['addresses']
for key, val in addresses.items():
if key in address_stats_combined:
address_stats_combined[key]['count'] += val['count']
else:
address_stats_combined[key] = val
addresses_extra = address_stats['addresses_extra']
i = 0
util.progress_bar_init('Collecting values', len(addresses), 'Addresses')
for key, value in addresses.items():
util.progress_bar_update(i)
i += 1
address_id = value['address_id']
variable = value['variable']
can_render = True
try:
if use_address_base:
address_base = variable.address_base
dist = trace_dist.filter(lambda trace: address_base in trace.variables_dict_address_base).map(lambda trace: util.to_tensor(trace.variables_dict_address_base[address_base].value)).filter(lambda v: torch.is_tensor(v)).filter(lambda v: v.nelement() == 1)
else:
address = variable.address
dist = trace_dist.filter(lambda trace: address in trace.variables_dict_address).map(lambda trace: util.to_tensor(trace.variables_dict_address[address].value)).filter(lambda v: torch.is_tensor(v)).filter(lambda v: v.nelement() == 1)
dist.rename(address_id + '' if variable.name is None else '{} ({})'.format(address_id, variable.name))
if dist.length == 0:
can_render = False
except Exception:
can_render = False
if can_render:
if key not in dists:
dists[key] = {}
dists[key][trace_dist.name] = dist, variable
util.progress_bar_end()
if plot:
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
mpl.rcParams['font.size'] = 4
rows, cols = util.tile_rows_cols(len(dists))
fig, ax = plt.subplots(rows, cols, figsize=figsize)
ax = ax.flatten()
i = 0
hist_color_cycle = list(reversed(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', 'b', 'k']))
hist_colors = {}
util.progress_bar_init('Plotting histograms', len(dists), 'Histograms')
for key, value in dists.items():
util.progress_bar_update(i)
for trace_dist_name, v in value.items():
dist = v[0]
variable = v[1]
values = dist.values_numpy()
weights = dist.weights_numpy()
if trace_dist_name in hist_colors:
label = None
color = hist_colors[trace_dist_name]
else:
label = trace_dist_name
color = hist_color_cycle.pop()
hist_colors[trace_dist_name] = color
if hasattr(variable.distribution, 'low'):
range = (float(variable.distribution.low), float(variable.distribution.high))
else:
range = None
ax[i].hist(values, weights=weights, density=1, bins=bins, color=color, label=label, alpha=0.75, range=range)
ax[i].set_title(dist.name, fontsize=4, y=0.95)
ax[i].tick_params(pad=0., length=2)
# ax[i].set_aspect(aspect='equal', adjustable='box-forced')
if ground_truth_trace is not None:
vline_x = None
if use_address_base:
address_base = variable.address_base
if address_base in ground_truth_trace.variables_dict_address_base:
vline_x = float(ground_truth_trace.variables_dict_address_base[address_base].value)
else:
address = variable.address
if address in ground_truth_trace.variables_dict_address:
vline_x = float(ground_truth_trace.variables_dict_address[address].value)
if vline_x is not None:
ax[i].axvline(x=vline_x, linestyle='dashed', color='gray', linewidth=0.75)
i += 1
util.progress_bar_end()
fig.legend()
# plt.tight_layout()
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, hspace=1.5, wspace=0.85)
if file_name is not None:
plot_file_name = file_name + '.pdf'
print('Plotting to file: {}'.format(plot_file_name))
plt.savefig(plot_file_name)
report_file_name = file_name + '.txt'
print('Saving address report to file: {}'.format(report_file_name))
with open(report_file_name, 'w') as file:
file.write('pyprob diagnostics\n')
file.write(('aggregated ' if use_address_base else '') + 'address report\n')
for key, value in addresses_extra.items():
file.write('{}: {}\n'.format(key, value))
addresses_file_name = file_name + '.csv'
print('Saving addresses to file: {}'.format(addresses_file_name))
with open(addresses_file_name, 'w') as file:
file.write('address_id, count, name, controlled, rejected, observable, observed, {}\n'.format('address_base' if use_address_base else 'address'))
for key, value in address_stats_combined.items():
name = '' if value['variable'].name is None else value['variable'].name
file.write('{}, {}, {}, {}, {}, {}, {}, {}\n'.format(value['address_id'], value['count'], name, value['variable'].control, not value['variable'].accepted, value['variable'].observable, value['variable'].observed, key))
if plot_show:
plt.show()
def network(inference_network, save_dir=None):
train_iter_per_sec = inference_network._total_train_iterations / inference_network._total_train_seconds
train_traces_per_sec = inference_network._total_train_traces / inference_network._total_train_seconds
train_traces_per_iter = inference_network._total_train_traces / inference_network._total_train_iterations
train_loss_initial = inference_network._history_train_loss[0]
train_loss_final = inference_network._history_train_loss[-1]
train_loss_change = train_loss_final - train_loss_initial
train_loss_change_per_sec = train_loss_change / inference_network._total_train_seconds
train_loss_change_per_iter = train_loss_change / inference_network._total_train_iterations
train_loss_change_per_trace = train_loss_change / inference_network._total_train_traces
if len(inference_network._history_valid_loss) > 0:
valid_loss_initial = inference_network._history_valid_loss[0]
valid_loss_final = inference_network._history_valid_loss[-1]
valid_loss_change = valid_loss_final - valid_loss_initial
valid_loss_change_per_sec = valid_loss_change / inference_network._total_train_seconds
valid_loss_change_per_iter = valid_loss_change / inference_network._total_train_iterations
valid_loss_change_per_trace = valid_loss_change / inference_network._total_train_traces
stats = OrderedDict()
stats['pyprob version'] = __version__
stats['torch version'] = torch.__version__
stats['network type'] = inference_network._network_type
stats['number of parameters'] = inference_network._history_num_params[-1]
stats['pre-generated layers'] = inference_network._layers_pre_generated
stats['modified'] = inference_network._modified
stats['updates'] = inference_network._updates
stats['trained on device'] = str(inference_network._device)
stats['distributed training'] = inference_network._distributed_backend is not None
stats['distributed backend'] = inference_network._distributed_backend
stats['distributed world size'] = inference_network._distributed_world_size
stats['optimizer'] = str(inference_network._optimizer_type)
stats['learning rate'] = inference_network._learning_rate
stats['momentum'] = inference_network._momentum
stats['batch size'] = inference_network._batch_size
stats['total train. seconds'] = inference_network._total_train_seconds
stats['total train. traces'] = inference_network._total_train_traces
stats['total train. iterations'] = inference_network._total_train_iterations
stats['train. iter. per second'] = train_iter_per_sec
stats['train. traces per second'] = train_traces_per_sec
stats['train. traces per iter.'] = train_traces_per_iter
stats['train. loss initial'] = train_loss_initial
stats['train. loss final'] = train_loss_final
stats['train. loss change per second'] = train_loss_change_per_sec
stats['train. loss change per iter.'] = train_loss_change_per_iter
stats['train. loss change per trace'] = train_loss_change_per_trace
if len(inference_network._history_valid_loss) > 0:
stats['valid. loss initial'] = valid_loss_initial
stats['valid. loss final'] = valid_loss_final
stats['valid. loss change per second'] = valid_loss_change_per_sec
stats['valid. loss change per iter.'] = valid_loss_change_per_iter
stats['valid. loss change per trace'] = valid_loss_change_per_trace
if save_dir is not None:
if not os.path.exists(save_dir):
print('Directory does not exist, creating: {}'.format(save_dir))
os.makedirs(save_dir)
file_name_stats = os.path.join(save_dir, 'inference_network_stats.txt')
print('Saving diagnostics information to {} '.format(file_name_stats))
with open(file_name_stats, 'w') as file:
file.write('pyprob diagnostics report\n')
for key, value in stats.items():
file.write('{}: {}\n'.format(key, value))
file.write('architecture:\n')
file.write(str(next(inference_network.modules())))
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
file_name_loss = os.path.join(save_dir, 'loss.pdf')
print('Plotting loss to file: {}'.format(file_name_loss))
fig = plt.figure(figsize=(10, 7))
ax = plt.subplot(111)
ax.plot(inference_network._history_train_loss_trace, inference_network._history_train_loss, label='Training')
ax.plot(inference_network._history_valid_loss_trace, inference_network._history_valid_loss, label='Validation')
ax.legend()
plt.xlabel('Training traces')
plt.ylabel('Loss')
plt.grid()
fig.tight_layout()
plt.savefig(file_name_loss)
file_name_num_params = os.path.join(save_dir, 'num_params.pdf')
print('Plotting number of parameters to file: {} '.format(file_name_num_params))
fig = plt.figure(figsize=(10, 7))
ax = plt.subplot(111)
ax.plot(inference_network._history_num_params_trace, inference_network._history_num_params, label='Training')
plt.xlabel('Training traces')
plt.ylabel('Number of parameters')
plt.grid()
fig.tight_layout()
plt.savefig(file_name_num_params)
save_dir_params = os.path.join(save_dir, 'params')
if not os.path.exists(save_dir_params):
print('Directory does not exist, creating: {}'.format(save_dir_params))
os.makedirs(save_dir_params)
file_name_params = os.path.join(save_dir_params, 'params.csv')
with open(file_name_params, 'w') as file:
file.write('file_name, param_name\n')
num_params = len(list(inference_network.named_parameters()))
util.progress_bar_init('Plotting inference network parameters', num_params, 'Parameters')
for index, param in enumerate(inference_network.named_parameters()):
util.progress_bar_update(index+1)
print()
file_name_param = os.path.join(save_dir_params, 'param_{}.png'.format(index))
param_name = param[0]
file.write('{}, {}\n'.format(os.path.basename(file_name_param), param_name))
print('Plotting to file: {} parameter: {}'.format(file_name_param, param_name))
param_val = param[1].cpu().detach().numpy()
if param_val.ndim == 1:
param_val = np.expand_dims(param_val, 1)
elif param_val.ndim > 2:
print('Warning: reshaping parameter {} to 2D for plotting.'.format(param_name, param_val.ndim))
c = param_val.shape[0]
param_val = np.reshape(param_val, (c, -1))
fig = plt.figure(figsize=(10, 7))
ax = plt.subplot(111)
heatmap = ax.pcolor(param_val, cmap=plt.cm.jet)
ax.invert_yaxis()
plt.xlabel('{} {}'.format(param_name, param_val.shape))
plt.colorbar(heatmap)
# fig.tight_layout()
plt.savefig(file_name_param)
plt.close()
util.progress_bar_end()
return stats
def graph(trace_dist, use_address_base=True, n_most_frequent=None,
base_graph=None, file_name=None, normalize_weights=True):
graph = Graph(trace_dist=trace_dist, use_address_base=use_address_base,
n_most_frequent=n_most_frequent, base_graph=base_graph,
normalize_weights=normalize_weights)
if file_name is not None:
graph.render_to_file(file_name, background_graph=base_graph)
for trace_id, trace_graph in graph.trace_graphs():
trace_graph.render_to_file('{}_{}'.format(file_name, trace_id), background_graph=(graph if base_graph is None else base_graph))
return graph
def address_dictionary(address_dictionary, file_name):
print('Saving address_id, address pairs to {}'.format(file_name))
util.create_path(file_name)
with open(file_name, 'w') as file:
file.write('address_id, address\n')
for key, value in address_dictionary._shelf.items():
if key.startswith('__id__'):
address_id = key.replace('__id__', '')
address = value
file.write('{}, {}\n'.format(address_id, address))
def log_prob(trace_dists, resolution=1000, names=None, figsize=(10, 5), xlabel="Iteration", ylabel='Log probability', xticks=None, yticks=None, log_xscale=False, log_yscale=False, plot=False, plot_show=True, file_name=None, min_index=None, max_index=None, *args, **kwargs):
if type(trace_dists) != list:
raise TypeError('Expecting a list of posterior trace distributions, each from a call to a Model\'s posterior_traces.')
if min_index is None:
min_i = 0
iters = []
log_probs = []
for j in range(len(trace_dists)):
if type(trace_dists[j][0]) != Trace:
raise TypeError('Expecting a list of posterior trace distributions, each from a call to a Model\'s posterior_traces.')
if max_index is None:
max_i = trace_dists[j].length
else:
max_i = min(trace_dists[j].length, max_index)
num_traces = max_i - min_i
iters.append(list(range(min_i, max_i, max(1, int(num_traces / resolution)))))
time_start = time.time()
prev_duration = 0
len_str_num_traces = len(str(num_traces))
print('Loading trace log-probabilities to memory')
print('Time spent | Time remain.| Progress | {} | Traces/sec'.format('Trace'.ljust(len_str_num_traces * 2 + 1)))
vals = []
for i in iters[j]:
vals.append(trace_dists[j]._get_value(i).log_prob)
duration = time.time() - time_start
if (duration - prev_duration > util._print_refresh_rate) or (i == num_traces - 1):
prev_duration = duration
traces_per_second = (i + 1) / duration
print('{} | {} | {} | {}/{} | {:,.2f} '.format(util.days_hours_mins_secs_str(duration), util.days_hours_mins_secs_str((num_traces - i) / traces_per_second), util.progress_bar(i+1, num_traces), str(i+1).rjust(len_str_num_traces), num_traces, traces_per_second), end='\r')
sys.stdout.flush()
print()
log_probs.append(vals)
if plot:
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
fig = plt.figure(figsize=figsize)
if names is None:
names = ['{}'.format(trace_dists[i].name) for i in range(len(log_probs))]
for i in range(len(log_probs)):
plt.plot(iters[i], log_probs[i], *args, **kwargs, label=names[i])
if log_xscale:
plt.xscale('log')
if log_yscale:
plt.yscale('log', nonposy='clip')
if xticks is not None:
plt.xticks(xticks)
if yticks is not None:
plt.xticks(yticks)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.legend(loc='best')
fig.tight_layout()
if file_name is not None:
print('Plotting to file: {}'.format(file_name))
plt.savefig(file_name)
if plot_show:
plt.show()
return np.array(iters), np.array(log_probs)
def _n_most_frequent_addresses(trace_dist, n_most_frequent, num_traces=None):
address_counts = defaultdict(int)
if num_traces is None:
num_traces = trace_dist.length
util.progress_bar_init('Collecting most frequent addresses', num_traces, 'Traces')
for i in range(num_traces):
trace = trace_dist._get_value(i)
util.progress_bar_update(i)
for variable in trace.variables:
if variable.value.nelement() == 1:
address_counts[variable.address] += 1
util.progress_bar_end()
address_counts = {k: v for k, v in address_counts.items() if v >= num_traces}
address_counts = OrderedDict(sorted(address_counts.items(), key=lambda x: x[1], reverse=True))
ret = []
for i, address in enumerate(address_counts):
ret.append(address)
if i + 1 == n_most_frequent:
break
return ret
def _variable_values(trace_dist, names=None, n_most_frequent=None, num_traces=None):
if num_traces is None:
num_traces = trace_dist.length
if names is None:
name_counts = defaultdict(int)
for i in range(num_traces):
trace = trace_dist._get_value(i)
for name in trace.named_variables.keys():
name_counts[name] += 1
names = [name for name in name_counts if name_counts[name] == num_traces] # Names of named variables that are found in all traces
variable_values = {}
# Select named variables to process
for name in names:
variable = trace_dist[0].named_variables[name]
if variable.value.nelement() == 1:
if variable.address not in variable_values:
variable_values[variable.address] = {'variable': None, 'values': np.ones(num_traces) * np.nan}
variable_values[variable.address]['variable'] = variable
# Select most frequent variables to process (either named or not named)
if n_most_frequent is not None:
addresses = _n_most_frequent_addresses(trace_dist, n_most_frequent, num_traces)
for address in addresses:
variable = trace_dist[0].variables_dict_address[address]
if variable.value.nelement() == 1:
if variable.address not in variable_values:
variable_values[variable.address] = {'variable': None, 'values': np.ones(num_traces) * np.nan}
variable_values[variable.address]['variable'] = variable
if len(variable_values) == 0:
raise RuntimeError('No variables with scalar value.')
util.progress_bar_init('Loading selected variables to memory', num_traces, 'Traces')
for i in range(num_traces):
trace = trace_dist._get_value(i)
util.progress_bar_update(i)
for address, v in variable_values.items():
v['values'][i] = float(trace.variables_dict_address[address].value)
util.progress_bar_end()
return variable_values
def autocorrelation(trace_dist, names=None, lags=None, n_most_frequent=None, figsize=(10, 5), xticks=None, yticks=None, log_xscale=True, plot=False, plot_show=True, file_name=None, *args, **kwargs):
if type(trace_dist) != Empirical:
raise TypeError('Expecting a trace distribution.')
if type(trace_dist[0]) != Trace:
raise TypeError('Expecting a trace distribution.')
def _autocorrelation(values, lags):
ret = np.array([1. if lag == 0 else np.corrcoef(values[lag:], values[:-lag])[0][1] for lag in lags])
# nan is encountered when there is no variance in the values, the foloowing might be used to assign autocorrelation of 1 to such cases
# ret[np.isnan(ret)] = 1.
return ret
num_traces = trace_dist.length
if lags is None:
lags = np.unique(np.logspace(0, np.log10(num_traces/2)).astype(int))
variable_values = _variable_values(trace_dist, names, n_most_frequent)
for i, (address, v) in enumerate(variable_values.items()):
print('Computing autocorrelation for variable address: {}, name: {} ({} of {})'.format(v['variable'].address, v['variable'].name, i + 1, len(variable_values)))
v['autocorrelation'] = _autocorrelation(v['values'], lags)
if plot:
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
fig = plt.figure(figsize=figsize)
plt.axhline(y=0, linewidth=1, color='black')
other_legend_added = False
for address, v in variable_values.items():
name = v['variable'].name
autocorrelation = v['autocorrelation']
if name is None:
label = None
if not other_legend_added:
label = '{} most frequent addresses'.format(len(variable_values))
other_legend_added = True
plt.plot(lags, autocorrelation, *args, **kwargs, linewidth=1, color='gray', label=label)
else:
plt.plot(lags, autocorrelation, *args, **kwargs, label=v['variable'].name)
if log_xscale:
plt.xscale('log')
if xticks is not None:
plt.xticks(xticks)
if yticks is not None:
plt.xticks(yticks)
plt.xlabel('Lag')
plt.ylabel('Autocorrelation')
plt.legend(loc='best')
fig.tight_layout()
if file_name is not None:
print('Plotting to file: {}'.format(file_name))
plt.savefig(file_name)
if plot_show:
plt.show()
return lags, variable_values
def gelman_rubin(trace_dists, names=None, iters=None, n_most_frequent=50, figsize=(10, 5), xticks=None, yticks=None, log_xscale=False, log_yscale=False, plot=False, plot_show=True, file_name=None, *args, **kwargs):
def _r_hat(values):
m, n = values.shape[0], values.shape[1] # m: number of chains, n: length of chains
if m < 2:
raise ValueError('Gelman-Rubin diagnostic requires at least two chains')
b = n * np.var(np.mean(values, axis=1), axis=0, ddof=1) # Between-chain variance
w = np.mean(np.var(values, axis=1, ddof=1), axis=0) # Within-chain variance
v_hat = ((n-1) / n) * w + b / n # Estimate of marginal posterior variance
r_hat = np.sqrt(v_hat / w)
return r_hat
def _r_hats(values, iters):
ret = np.zeros_like(iters, dtype=float)
for i, iter in enumerate(iters):
ret[i] = _r_hat(values[:, :iter])
return ret
trace_lengths = [trace.length for trace in trace_dists]
num_traces = min(trace_lengths)
if max(trace_lengths) != num_traces:
print('Distributions have unequal length, setting the length to minimum: {}'.format(num_traces))
if iters is None:
iters = np.unique(np.logspace(0, np.log10(num_traces)).astype(int))
variable_values = {}
for trace_dist in trace_dists:
vv = _variable_values(trace_dist, names, n_most_frequent, num_traces)
for address, v in vv.items():
if address in variable_values:
variable_values[address]['values'] = np.vstack((variable_values[address]['values'], v['values']))
else:
variable_values[address] = v
for i, (address, v) in enumerate(variable_values.items()):
print('Computing R-hat for variable address: {}, name: {} ({} of {})'.format(v['variable'].address, v['variable'].name, i + 1, len(variable_values)))
v['rhat'] = _r_hats(v['values'], iters)
if plot:
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
fig = plt.figure(figsize=figsize)
plt.axhline(y=1, linewidth=1, color='black')
other_legend_added = False
for address, v in variable_values.items():
name = v['variable'].name
rhat = v['rhat']
if name is None:
label = None
if not other_legend_added:
label = '{} most frequent addresses'.format(len(variable_values))
other_legend_added = True
plt.plot(iters, rhat, *args, **kwargs, linewidth=1, color='gray', label=label)
else:
plt.plot(iters, rhat, *args, **kwargs, label=v['variable'].name)
if log_xscale:
plt.xscale('log')
if log_yscale:
plt.yscale('log', nonposy='clip')
if xticks is not None:
plt.xticks(xticks)
if yticks is not None:
plt.xticks(yticks)
plt.xlabel('Iteration')
plt.ylabel('R-hat')
plt.legend(loc='best')
fig.tight_layout()
if file_name is not None:
print('Plotting to file: {}'.format(file_name))
plt.savefig(file_name)
if plot_show:
plt.show()
return iters, variable_values
def jensen_shannon(trace_dist_p, trace_dist_q, names=None, n_most_frequent=50,
use_address_base=False,
figsize=(10, 5), bins=30, xticks=None, yticks=None, log_xscale=False, log_yscale=True, plot=False, plot_show=True, file_name=None,
posterior_flag=False):
def plot_func(variable_info, address_stats_combined,
figsize, bins, xticks, yticks, log_xscale, log_yscale, plot_show, file_name):
if not plot_show:
mpl.rcParams['axes.unicode_minus'] = False
plt.switch_backend('agg')
mpl.rcParams['font.size'] = 4
hist_color_cycle = list(reversed(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', 'b', 'k']))
# Plot Jensen–Shannon histogram
fig, ax1 = plt.subplots(figsize=figsize)
ax1.set_ylabel('#')
ax1.set_xlabel('Jensen–Shannon')
ax1.hist([v['divergence'] for v in variable_info.values()], alpha=0.75, color=hist_color_cycle[-1])
plt.tight_layout()
if file_name is not None:
plot_file_name = file_name + '_divergence_hist.pdf'
print('Plotting to file: {}'.format(plot_file_name))
plt.savefig(plot_file_name)
if plot_show:
plt.show()
# Plot address histograms
hist_color_cycle = list(reversed(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf', 'b', 'k']))
rows, cols = util.tile_rows_cols(len(variable_info))
fig, ax = plt.subplots(rows, cols, figsize=figsize)
ax = ax.flatten()
i = 0
hist_colors = {}
util.progress_bar_init('Plotting histograms', len(variable_info), 'Histograms')
for address_id, v in variable_info.items():
util.progress_bar_update(i)
for dist_label, values in v['values'].items():
# dist_label is the main trace distribution name
if dist_label in hist_colors:
label = None
color = hist_colors[dist_label]
else:
label = dist_label
color = hist_color_cycle.pop()
hist_colors[dist_label] = color
range_ = (np.min(values), np.max(values))
ax[i].hist(values, density=1, bins=bins, color=color, label=label, alpha=0.75, range=range_)
ax[i].set_title('{} / {:.2f}'.format(variable_info[address_id]['dist'].name, v['divergence']), fontsize=4, y=0.95)
ax[i].tick_params(pad=0., length=2)
# ax[i].set_aspect(aspect='equal', adjustable='box-forced')
i += 1
util.progress_bar_end()
fig.legend()
# plt.tight_layout()
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, hspace=1.5, wspace=0.85)
if file_name is not None:
plot_file_name = file_name + '_address.pdf'
print('Plotting to file: {}'.format(plot_file_name))
plt.savefig(plot_file_name)
if plot_show:
plt.show()
def _shrink(empirical_dist, final_size, posterior_flag):
'''
Given an empirical distribution, shrinks it to final_size.
If final size is bigger than the current size, it will be unchanged
If it has unifrom weights, we assume it comes from some sort of MCMC, therefore it will be thinned.
Otherwise, it will be resampled.
'''
if empirical_dist._uniform_weights:
# Samples are supposedly from MCMC => should thin
if final_size != len(empirical_dist):
return empirical_dist.thin(final_size)
else:
# No need for thinning if the size is exactly the same
return empirical_dist
else:
# Weighted samples => should resample
# Even if the size is exactly the same as expected, resampling is needed to make weights uniform
if posterior_flag:
# Resample according to proposal sample weights, in order to get a posterior approximation.
return empirical_dist.resample(final_size)
else:
# Randomly choose from the proposal samples and remove the weights.
return Empirical(np.random.choice(empirical_dist, final_size, replace=False))
def generate_variable_empiricals(trace_dist, chosen_addresses, use_address_base):
'''
Arguments
---------
trace_dist Empirical distribution over traces
chosen_addresses List of chosen addresses (could be address bases, depending on use_address_base)
num_traces length of the empirical distribution to consider
use_address_base If True, uses address base as variable identifier.
Returns
-------
A dictionary of the same addresses (could be a subset of addresses, if no sample exist for that variable)
to another dictionary:
'variable' -> variable information for the variable at the address
'dist' -> Empirical distribution over this single variable
'''
variable_info = defaultdict(lambda: {'variable': None, 'values': [], 'log_weights': []})
num_traces = trace_dist.length
util.progress_bar_init('Loading selected variables to memory', num_traces, 'Traces')
for i in range(num_traces):
trace = trace_dist._get_value(i)
util.progress_bar_update(i)
trace_weight = trace_dist._get_log_weight(i)
for address in chosen_addresses:
# Set the trace dictionary too look for address in. Depending on use_address_base, it could be variables_dict_address or variables_dict_address_base.
if use_address_base:
trace_variables_dict = trace.variables_dict_address_base
else:
trace_variables_dict = trace.variables_dict_address
if address in trace_variables_dict:
if trace_variables_dict[address].value.nelement() == 1:
if variable_info[address]['variable'] is None:
variable_info[address]['variable'] = trace_variables_dict[address]
variable_info[address]['values'].append(trace_variables_dict[address].value)
variable_info[address]['log_weights'].append(trace_weight)
ret_val = {address: {'variable': info['variable'],
'dist': Empirical(info['values'], log_weights=info['log_weights'])}
for address, info in variable_info.items() if info['variable'] is not None and len(info['values']) > 0}
util.progress_bar_end()
return ret_val
def _n_most_frequent_from_stats(address_stats, n):
addresses = address_stats['addresses']
ordered_addresses = OrderedDict(sorted(addresses.items(), key=lambda x: x[1]['count'], reverse=True))
res = []
i = 0
for candidate_address, variable_info in ordered_addresses.items():
# variable_info is the value associated with 'addresses' key in address_stats (has ['count', 'weight', 'address_id', 'variable'] as keys)
if len(res) >= n:
break
if variable_info['variable'].value.nelement() == 1:
# Ignore multi-dimensional random variables
res.append(candidate_address)
return res
def get_renamed_variable_empiricals(trace_dists, names, n_most_frequent, use_address_base):
'''
Arguments
---------
trace_dists List of trace distributions
names List of chosen variable names (if any)
n_most_frequent Number of most frequent variables to include in the result
use_address_base If True, uses address base as variable identifier.
Returns
-------
variable_empiricals A dictionary from variable address_id to:
A dictionary with the keys ['dist', 'variable']
The value associated with 'dist' is the distribution over
the corresponding variable, renamed to be used as plot title
address_stats Combined address_stats for trace distributions in the given trace_dists.
'''
variable_empiricals = []
address_stats = None
for trace_dist in trace_dists:
print('Computing address stats for {}'.format(trace_dist.name))
address_stats = _address_stats(trace_dist, use_address_base=use_address_base, reuse_ids_from_address_stats=address_stats)
chosen_addresses = _n_most_frequent_from_stats(address_stats, n_most_frequent)
variable_empirical = generate_variable_empiricals(trace_dist, chosen_addresses, use_address_base)
# Rename variable_empirical keys from address (or address_base) to address_id:
keys = list(variable_empirical.keys())
for k in keys:
new_key = address_stats['address_ids'][k]
variable_empirical[new_key] = variable_empirical.pop(k)
# Rename the distributions based on their assigned address_id:
for address_id, variable_info in variable_empirical.items():
# variable_info is a dictionary with ['variable', 'dist'] as keys
variable = variable_info['variable']
variable_info['dist'].rename(address_id + '' if variable.name is None else '{} ({})'.format(address_id, variable.name))
variable_empiricals.append(variable_empirical)
return variable_empiricals, address_stats
'''
Arguments
---------
posterior_flag If true, will calculate Jensen–Shannon divergence with the approximated posterior
rather than the proposal. It is done by resampling proposal samples.
Returns
-------
variable_info A dictionary of sample address_ids to their analysis.
The analysis itself is a dictronary with the
following specifications: (key -> value)
'variable' -> an object of type Variable containing
the random variable specifications.
'values' -> A dictionary from trace name (has input trace names as keys)
to numpy array of sampled values in P distribution
(shape: nxd, where n is the number of samples and d is the size of each sampled value)
'divergence' -> The Jensen–Shannon divergence.
'''
assert isinstance(bins, int)
[variable_empirical_p, variable_empirical_q], address_stats_combined = get_renamed_variable_empiricals([trace_dist_p, trace_dist_q], names, n_most_frequent, use_address_base)
variable_info = {} # Will contain the output i.e. divergence and sample values for all addresses.
common_address_ids = set(variable_empirical_p.keys()) & set(variable_empirical_q.keys()) #address_id_to_variable
util.progress_bar_init('Computing Jensen-Shannon divergence', len(common_address_ids), 'Variables')
for i, address_id in enumerate(common_address_ids):
util.progress_bar_update(i)
variable_info_log = 'address: {}, name: {} ({} of {})'.format(variable_empirical_p[address_id]['variable'].address, variable_empirical_p[address_id]['variable'].name, i + 1, len(common_address_ids))
var_dist_p = variable_empirical_p[address_id]['dist']
var_dist_q = variable_empirical_q[address_id]['dist'] # Get the distribution for the same variable from the other distribution
num_samples = min(len(var_dist_p), len(var_dist_q))
if num_samples < 10:
print('\nToo few samples for {} ({}). Skipping...'.format(address_id, num_samples))
continue
'''
# There is no need for having the same number of samples to compute Jensen–Shannon.
var_dist_p = _shrink(var_dist_p, num_samples, posterior_flag)
var_dist_q = _shrink(var_dist_q, num_samples, posterior_flag)
assert var_dist_p._uniform_weights
assert var_dist_q._uniform_weights
'''
v_p = var_dist_p.values_numpy()
v_q = var_dist_q.values_numpy()
range_ = (min(np.min(v_p), np.min(v_q)), max(np.max(v_p), np.max(v_q)))
bins_seq = np.linspace(*range_, bins)
bin_width = bins_seq[1] - bins_seq[0]
p_probs = np.histogram(v_p, bins=bins, density=True)[0]
q_probs = np.histogram(v_q, bins=bins, density=True)[0]
# add a small amount to all porbs so that nothing is zero. It avoids problems in computing Jensen–Shannon.
p_probs += 1e-20 / bins
q_probs += 1e-20 / bins
p_categorical = torch.distributions.categorical.Categorical(probs=util.to_tensor(p_probs))
q_categorical = torch.distributions.categorical.Categorical(probs=util.to_tensor(q_probs))
kl_pq = kl_divergence(p_categorical, q_categorical).item()
kl_qp = kl_divergence(q_categorical, p_categorical).item()
divergence = (kl_pq + kl_qp) / 2
# Aggregate info about P and Q in "variable info"
v = {}
v['divergence'] = divergence
for vv_key in variable_empirical_p[address_id]:
if vv_key != 'values':
v[vv_key] = variable_empirical_p[address_id][vv_key]
v['values'] = {}
v['values'][trace_dist_p.name] = v_p
v['values'][trace_dist_q.name] = v_q
v['bin_width'] = bin_width
variable_info[address_id] = v
util.progress_bar_end()
if plot:
plot_func(variable_info, address_stats_combined,
figsize, bins, xticks, yticks, log_xscale, log_yscale, plot_show, file_name)
if file_name is not None:
divergence_info_csv = file_name + '_info.csv'
print('Saving Jensen–Shannon diagnostic info to CSV: {}'.format(divergence_info_csv))
with open(divergence_info_csv, 'w') as csvfile:
csv_titles = ['Name', 'ID', 'Address', 'Divergence', 'sample-size', 'bin width']
csv_writer = csv.DictWriter(csvfile, fieldnames=csv_titles)
csv_writer.writeheader()
for k, v in variable_info.items():
info = {}
info['Name'] = v['variable'].name
info['ID'] = k
info['Address'] = v['variable'].address
info['Divergence'] = v['divergence']
info['sample-size'] = len(v['values'][next(iter(v['values']))])
info['bin width'] = v['bin_width']
csv_writer.writerow(info)
divergence_values = [v['divergence'] for v in variable_info.values()]
divergence_mean = np.mean(divergence_values)
divergence_var = np.var(divergence_values)
csv_writer.writerow({csv_titles[0]: 'Number of bins', csv_titles[1]: bins})
csv_writer.writerow({csv_titles[0]: 'Jensen–Shannon mean', csv_titles[1]: divergence_mean})
csv_writer.writerow({csv_titles[0]: 'Jensen–Shannon variance', csv_titles[1]: divergence_var})
print('Jensen–Shannon mean = {}, Jensen–Shannon variance = {}'.format(divergence_mean, divergence_var))
return variable_info
|
f53f8eee66ed9307800b64c750ba8c23ccefb4da
|
{
"blob_id": "f53f8eee66ed9307800b64c750ba8c23ccefb4da",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-07T21:07:37",
"content_id": "d99e66aa3ba92e7aae54d977a912850241cb184a",
"detected_licenses": [
"BSD-2-Clause",
"BSD-3-Clause"
],
"directory_id": "7e2ac6f7fc32711d34d9716ffe008f7d1bc2ded0",
"extension": "py",
"filename": "diagnostics.py",
"fork_events_count": 0,
"gha_created_at": "2018-11-04T21:26:31",
"gha_event_created_at": "2023-02-02T19:28:38",
"gha_language": "Python",
"gha_license_id": "BSD-2-Clause",
"github_id": 156126659,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 53235,
"license": "BSD-2-Clause,BSD-3-Clause",
"license_type": "permissive",
"path": "/pyprob/diagnostics.py",
"provenance": "stack-edu-0063.json.gz:394325",
"repo_name": "ammunk/pyprob",
"revision_date": "2022-07-07T21:07:37",
"revision_id": "dd71451b8ed6d07fe894beb4cbad7c59a01e9a3b",
"snapshot_id": "7e13c682481af7dd70b0339f79ec7c90f83af92f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/ammunk/pyprob/dd71451b8ed6d07fe894beb4cbad7c59a01e9a3b/pyprob/diagnostics.py",
"visit_date": "2023-07-06T22:00:47.873548",
"added": "2024-11-19T02:33:40.400588+00:00",
"created": "2022-07-07T21:07:37",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Org.OpenAPITools.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class ComDayCqWcmCoreImplVariantsPageVariantsProviderImplProperties {
/// <summary>
/// Gets or Sets DefaultExternalizerDomain
/// </summary>
[DataMember(Name="default.externalizer.domain", EmitDefaultValue=false)]
[JsonProperty(PropertyName = "default.externalizer.domain")]
public ConfigNodePropertyString DefaultExternalizerDomain { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class ComDayCqWcmCoreImplVariantsPageVariantsProviderImplProperties {\n");
sb.Append(" DefaultExternalizerDomain: ").Append(DefaultExternalizerDomain).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
}
|
775758a02e3468d32b0f18312e4233f0e7e6bbd1
|
{
"blob_id": "775758a02e3468d32b0f18312e4233f0e7e6bbd1",
"branch_name": "refs/heads/master",
"committer_date": "2021-04-09T07:46:03",
"content_id": "3fd8debc3907b2e64628c2c9ced7a50d20323d60",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5ec06dab1409d790496ce082dacb321392b32fe9",
"extension": "cs",
"filename": "ComDayCqWcmCoreImplVariantsPageVariantsProviderImplProperties.cs",
"fork_events_count": 3,
"gha_created_at": "2019-06-04T14:23:28",
"gha_event_created_at": "2022-10-05T03:26:20",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 190217155,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1369,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/clients/csharp-dotnet2/generated/src/main/CsharpDotNet2/Org/OpenAPITools/Model/ComDayCqWcmCoreImplVariantsPageVariantsProviderImplProperties.cs",
"provenance": "stack-edu-0011.json.gz:498557",
"repo_name": "shinesolutions/swagger-aem-osgi",
"revision_date": "2021-04-09T07:46:03",
"revision_id": "c2f6e076971d2592c1cbd3f70695c679e807396b",
"snapshot_id": "e9d2385f44bee70e5bbdc0d577e99a9f2525266f",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/shinesolutions/swagger-aem-osgi/c2f6e076971d2592c1cbd3f70695c679e807396b/clients/csharp-dotnet2/generated/src/main/CsharpDotNet2/Org/OpenAPITools/Model/ComDayCqWcmCoreImplVariantsPageVariantsProviderImplProperties.cs",
"visit_date": "2022-10-29T13:07:40.422092",
"added": "2024-11-18T22:09:24.031757+00:00",
"created": "2021-04-09T07:46:03",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
<?php
namespace App\Http\Controllers\Core;
use App\Category;
use App\Http\Controllers\Controller;
use App\Transformers\CoreCategoryTransformer;
/**
* Class AccountController
*
* @package App\Http\Controllers
*/
class ListCategoriesController extends Controller
{
public function index()
{
$categories = Category::orderBy('code')->get();
return $this->collection($categories, new CoreCategoryTransformer);
}
}
|
82061f616a1fdc607dfdd9838932898c584741b0
|
{
"blob_id": "82061f616a1fdc607dfdd9838932898c584741b0",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-26T09:23:04",
"content_id": "2d755289fb3a283ba8768be0342a447e7cf29d18",
"detected_licenses": [
"MIT"
],
"directory_id": "7358996f05826c57de4180bc122e0f1f25d455d3",
"extension": "php",
"filename": "ListCategoriesController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 169206410,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 447,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/Core/ListCategoriesController.php",
"provenance": "stack-edu-0046.json.gz:679094",
"repo_name": "Tapklik/tapklik-api",
"revision_date": "2018-12-25T21:01:01",
"revision_id": "41c30163340617130977495373a931c4fab5c7cd",
"snapshot_id": "40ab495d9d8be938f09652b58ff93073b521298d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tapklik/tapklik-api/41c30163340617130977495373a931c4fab5c7cd/app/Http/Controllers/Core/ListCategoriesController.php",
"visit_date": "2020-04-21T00:47:15.458563",
"added": "2024-11-18T21:46:46.209250+00:00",
"created": "2018-12-25T21:01:01",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
export function scrollIntoView(
selector: string,
options: Options | undefined,
): boolean {
let doc: Document | undefined;
const timeout =
options !== undefined && options.timeout ? options.timeout : 0;
if (options !== undefined && options.document !== undefined) {
doc = options.document;
} else if (document !== undefined) {
doc = document;
} else {
return false;
}
try {
const element = doc.querySelector(selector);
if (element) {
setTimeout((): void => {
element.scrollIntoView();
}, timeout);
}
} catch (error) {
return false;
}
return true;
}
export async function asyncScrollIntoView(
selector: string,
options?: Options | undefined,
): Promise<boolean> {
return scrollIntoView(selector, options);
}
class Options {
public document?: Document | undefined;
public timeout?: number | undefined;
}
export async function asyncQuerySelector(
selector: string,
): Promise<Element | null> {
return document.querySelector(selector);
}
export async function asyncScrollTop(
selector: string,
top: number = 0,
): Promise<void> {
const element = await asyncQuerySelector(selector);
if (element) {
element.scrollTop = top;
}
}
|
081064b66ac4d27aba98c67566cd144bf8dc0c45
|
{
"blob_id": "081064b66ac4d27aba98c67566cd144bf8dc0c45",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-15T15:34:31",
"content_id": "101416ac740e7f46e218c3142c8abf796b1ef488",
"detected_licenses": [
"Apache-2.0",
"MIT"
],
"directory_id": "efbf177b07ad126e489e469ff46f2f87fc0b8c71",
"extension": "ts",
"filename": "scroll-into-view.ts",
"fork_events_count": 0,
"gha_created_at": "2019-06-01T04:09:27",
"gha_event_created_at": "2023-01-05T02:52:57",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 189688986,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1232,
"license": "Apache-2.0,MIT",
"license_type": "permissive",
"path": "/OneInThineHand.org/src/app/scroll-into-view.ts",
"provenance": "stack-edu-0072.json.gz:338721",
"repo_name": "one-in-thine-hand/OneInThineHand.org",
"revision_date": "2019-06-15T15:34:31",
"revision_id": "189aee9c4491042217ae51a47a24b97fca8e8dc6",
"snapshot_id": "61847734b65411bf934a65041dc8820338357fa4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/one-in-thine-hand/OneInThineHand.org/189aee9c4491042217ae51a47a24b97fca8e8dc6/OneInThineHand.org/src/app/scroll-into-view.ts",
"visit_date": "2023-01-20T23:42:08.345556",
"added": "2024-11-19T03:12:01.141901+00:00",
"created": "2019-06-15T15:34:31",
"int_score": 3,
"score": 2.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
'use strict';
var fs = require('fs');
var streamBuffers = require('stream-buffers');
module.exports = function readFd(fd, cb) {
if (!(fd && cb)) {
return;
}
var bufferStream = new streamBuffers.WritableStreamBuffer();
var fileStream = fs.createReadStream(null, {fd: fd});
bufferStream.on('error', cb);
fileStream.on('error', cb);
fileStream.pipe(bufferStream).on('finish', function () {
cb(null, bufferStream.getContents());
});
};
|
50274dc304e97d4762de8ed471cce5475a3d06dd
|
{
"blob_id": "50274dc304e97d4762de8ed471cce5475a3d06dd",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-28T01:48:11",
"content_id": "682f5d5f2612c88a5a097aecefb8a3a67824e647",
"detected_licenses": [
"MIT"
],
"directory_id": "2f17e2bb966decc29ab64d8d84323bc586270fc1",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 39807307,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 461,
"license": "MIT",
"license_type": "permissive",
"path": "/index.js",
"provenance": "stack-edu-0035.json.gz:601386",
"repo_name": "Qix-/node-read-fd",
"revision_date": "2015-07-28T01:48:11",
"revision_id": "12a8b803cfb9a59a22068d32eef827e988d83bb8",
"snapshot_id": "d24359d4707baea1bfeb3de0c8c1f4d42b23f534",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Qix-/node-read-fd/12a8b803cfb9a59a22068d32eef827e988d83bb8/index.js",
"visit_date": "2021-01-20T11:31:47.652027",
"added": "2024-11-19T03:11:14.805849+00:00",
"created": "2015-07-28T01:48:11",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
<?php
namespace App\Console\Commands;
use App\Models\Task;
use App\Models\User;
use Illuminate\Console\Command;
class StatsTasks extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'stats:tasks';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Get stats for tasks.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$headers = ['Description', 'Value'];
$data = [
[
'Tasks count',
Task::count()
],
[
'User count',
User::count()
],
[
'Avarage tasks per user',
User::withCount('tasks')->pluck('tasks_count')->average()
],
[
'New tasks last week',
Task::where('created_at', '>=', now()->subWeek())->count()
],
[
'New tasks last month',
Task::where('created_at', '>=', now()->subMonth())->count()
],
[
'New tasks last year',
Task::where('created_at', '>=', now()->subYear())->count()
],
[
'Tasks with due_at date',
Task::whereNotNull('due_at')->count()
],
[
'Tasks without due_at date',
Task::whereNull('due_at')->count()
],
[
'Tasks completed',
Task::completed()->count()
],
[
'Tasks not completed',
Task::whereIsCompleted(false)->count()
]
];
$this->table($headers, $data);
}
}
|
021a2439c98d883de661e9bcdc97f10948aa8bfa
|
{
"blob_id": "021a2439c98d883de661e9bcdc97f10948aa8bfa",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-14T13:20:43",
"content_id": "e60874de59e4edeacb8353b7f6fa5f0ef39d97a6",
"detected_licenses": [
"MIT"
],
"directory_id": "4cb9b9c48dd8906e0f91e7d547dc3610dcf40132",
"extension": "php",
"filename": "StatsTasks.php",
"fork_events_count": 0,
"gha_created_at": "2018-05-29T10:09:46",
"gha_event_created_at": "2020-03-14T13:20:44",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 135277836,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2056,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Console/Commands/StatsTasks.php",
"provenance": "stack-edu-0049.json.gz:211933",
"repo_name": "fernandez-fabien/todolist-backend-laravel",
"revision_date": "2020-03-14T13:20:43",
"revision_id": "39e363da1bfbb4615c7c53cba6dc805915875223",
"snapshot_id": "25eed7a4f8811c5f28051695095acde913d4bba5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fernandez-fabien/todolist-backend-laravel/39e363da1bfbb4615c7c53cba6dc805915875223/app/Console/Commands/StatsTasks.php",
"visit_date": "2020-03-18T21:23:06.911512",
"added": "2024-11-18T21:46:11.963955+00:00",
"created": "2020-03-14T13:20:43",
"int_score": 3,
"score": 2.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
#!/bin/sh
#
# Shell script to start the server application, with debug enabled.
#
# Get the current version...
source ./version.sh
cd testDeploy
QVCS_HOME=`pwd`;
# Port 9889 is default client port; port 9890 is default admin port; port 9080 is web server (http) port.
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -Xmx512m -Xms512m -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -Xloggc:$HOME/qvcse-server-gc.log -XX:+PrintGCDetails -XX:+PrintGCDateStamps -jar qvcse-server-$QVCS_VERSION.jar "$QVCS_HOME" 9889 9890 9080
cd ..
|
77e3bcac5f0846acf226f8ff5d0a450938ea5d39
|
{
"blob_id": "77e3bcac5f0846acf226f8ff5d0a450938ea5d39",
"branch_name": "refs/heads/master",
"committer_date": "2014-04-15T00:45:53",
"content_id": "635750dcb78b3be7dcc0019690e7951b6cd7c046",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2292fede67397ba1a99d5f74f9e3c0882f1b857a",
"extension": "sh",
"filename": "server.sh",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 545,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/testenterprise/server.sh",
"provenance": "stack-edu-0069.json.gz:711828",
"repo_name": "joshualambert/qvcsos",
"revision_date": "2014-04-15T00:45:53",
"revision_id": "a3529b44c97ac0b2104a5a60650dd3305262891a",
"snapshot_id": "cbc294942c7edeb2ac9552ea8a01e55ce5c677b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/joshualambert/qvcsos/a3529b44c97ac0b2104a5a60650dd3305262891a/testenterprise/server.sh",
"visit_date": "2021-01-18T08:42:53.467413",
"added": "2024-11-19T02:31:43.732731+00:00",
"created": "2014-04-15T00:45:53",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
using Microsoft.AspNetCore.Mvc;
using SquidGame.Interfaces;
using SquidGame.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SquidGame.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class GamesController : ControllerBase
{
private IGameService _gameService;
public GamesController(IGameService gameService)
{
_gameService = gameService;
}
[HttpGet]
public async Task<ActionResult<ICollection<GameListItem>>> GetGamesList()
{
var games = await _gameService.GetGameList();
return Ok(games);
}
}
}
|
2e980caab43e4d4b453ddd8c86916d4860e1603b
|
{
"blob_id": "2e980caab43e4d4b453ddd8c86916d4860e1603b",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-22T15:54:40",
"content_id": "7b059f884fbda7f153eee4cd2746af784445bb07",
"detected_licenses": [
"MIT"
],
"directory_id": "5876c2e9c7b8f1ec6b57efbb729da40416a26270",
"extension": "cs",
"filename": "GamesController.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 430740609,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 675,
"license": "MIT",
"license_type": "permissive",
"path": "/SquidGame.Api/Controllers/GamesController.cs",
"provenance": "stack-edu-0009.json.gz:208902",
"repo_name": "CAgorski/squid-game",
"revision_date": "2021-11-22T15:54:40",
"revision_id": "597b9bb98bb42a95f0099d8ecc1957921b02438d",
"snapshot_id": "21aa479d7a7fcec14acf97c8587683ec5071d122",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CAgorski/squid-game/597b9bb98bb42a95f0099d8ecc1957921b02438d/SquidGame.Api/Controllers/GamesController.cs",
"visit_date": "2023-09-03T13:45:22.788176",
"added": "2024-11-19T02:16:40.727944+00:00",
"created": "2021-11-22T15:54:40",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
<?php
function print_help()
{
echo "Program uses standard input to read IPPCode19 source file, performs lexical and syntactic checks and creates XML output\n";
}
function print_stats($STATP, $mask, $file)
{
$openFile = fopen($file, "w");
foreach($mask as $stat)
{
fwrite($openFile, $STATP[$stat]."\n");
}
fclose($openFile);
}
function parse_command_line_args($argv)
{
if(count($argv) == 1)
{
return;
}
elseif (count($argv) == 2)
{
if ($argv[1] == "--help")
{
print_help();
exit(0);
}
else
{
echo "ERROR: Invalid argument\n";
exit(10);
}
}
elseif (count($argv) > 1 and strpos($argv[1], '--stats=') === 0) #argument starts with stats
{
$file = explode('=', $argv[1])[1];
$mask = [];
foreach(array_slice($argv, 2) as $key)
{
if(in_array($key, ["--loc", "--comments", "--jumps", "--labels"]))
{
array_push($mask, $key);
}
else
{
echo "ERROR: Invalid argument\n";
exit(10);
}
}
return ["file" => $file,
"mask" => $mask];
}
else
{
echo "Invalid number of arguments\n";
exit(10);
}
}
function parse_line($line, &$lineNumber, $xmlDoc, &$STATP)
{
$line = trim($line);
if($line === '')
{
return;
}
elseif($line[0] == '#')
{
$STATP["--comments"]++;
return;
}
elseif(strlen(trim($line)) == 0)
{
return;
}
elseif(strpos($line, '#'))
{
$line = explode('#', $line)[0];
$line = rtrim($line);
$STATP["--comments"]++;
}
$STATP["--loc"]++;
xmlwriter_start_element($xmlDoc, 'instruction'); #Generate instruction element
$line_array = explode(" ", $line, 2);
$expectedArgs = parse_opcode($line_array[0], $xmlDoc, $STATP, $lineNumber);
parse_arguments($xmlDoc, $line_array, $expectedArgs);
xmlwriter_end_element($xmlDoc);
}
function parse_string($inputString)
{
$escapeArray = [];
$escapeInt = 0;
preg_match_all('/\\\\\d\d\d/', $inputString, $escapeArray);
foreach($escapeArray[0] as $escapeSequence)
{
$escapeInt = intval(substr($escapeSequence, 1));
if(in_array(chr($escapeInt), ['<', '>', '&']))
$inputString = str_replace($escapeSequence, chr($escapeInt), $inputString, $i);
}
if(empty($escapeArray[0]) and preg_match('/\\\\/', $inputString) === 1)
{
exit(23);
}
return $inputString;
}
function parse_opcode($opcode, $xmlDoc, &$STATP, &$lineNumber)
{
if($opcode[strlen($opcode)-1] == "\n")
{
$opcode = substr($opcode, 0, -1);
}
$arr_opcodes = ["MOVE" => ["var", "symb"],
"CREATEFRAME" => NULL,
"PUSHFRAME" => NULL,
"POPFRAME" => NULL,
"DEFVAR" => ["var"],
"CALL" => ["label"],
"RETURN" => NULL,
"PUSHS" => ["symb"],
"POPS" => ["var"],
"ADD" => ["var", "symb", "symb"],
"SUB" => ["var", "symb", "symb"],
"MUL" => ["var", "symb", "symb"],
"IDIV" => ["var", "symb", "symb"],
"LT" => ["var", "symb", "symb"],
"GT" => ["var", "symb", "symb"],
"EQ" => ["var", "symb", "symb"],
"AND" => ["var", "symb", "symb"],
"OR" => ["var", "symb", "symb"],
"NOT" => ["var", "symb"],
"INT2CHAR" => ["var", "symb"],
"STRI2INT" => ["var", "symb", "symb"],
"READ" => ["var", "type"],
"WRITE" => ["symb"],
"CONCAT" => ["var", "symb", "symb"],
"STRLEN" => ["var", "symb"],
"GETCHAR" => ["var", "symb", "symb"],
"SETCHAR" => ["var", "symb", "symb"],
"TYPE" => ["var", "symb"],
"LABEL" => ["label"],
"JUMP" => ["label"],
"JUMPIFEQ" => ["label", "symb", "symb"],
"JUMPIFNEQ" => ["label", "symb", "symb"],
"EXIT" => ["symb"],
"DPRINT" => ["symb"],
"BREAK" => NULL];
if(!array_key_exists(strtoupper($opcode), $arr_opcodes))
{
#echo("Invalid opcode: ".$opcode."\n");
exit(22);
}
else
{
if(in_array(strtoupper($opcode), ["JUMP", "JUMPIFEQ", "JUMPIFNEQ"]))
{
$STATP["--jumps"]++;
}
elseif(strtoupper($opcode) == "LABEL")
{
$STATP["--labels"]++;
}
xmlwriter_start_attribute($xmlDoc, 'order');
xmlwriter_text($xmlDoc, $lineNumber);
$lineNumber++;
xmlwriter_end_attribute($xmlDoc);
xmlwriter_start_attribute($xmlDoc, 'opcode');
xmlwriter_text($xmlDoc, strtoupper($opcode));
xmlwriter_end_attribute($xmlDoc);
#echo $opcode."\n";
return $arr_opcodes[strtoupper($opcode)];
}
}
function parse_arguments($xmlDoc, $argString, $expectedArgs)
{
if(!array_key_exists(1, $argString) && $expectedArgs != NULL)
{
#echo "No arguments specified\n";
exit(23);
}
elseif(array_key_exists(1, $argString) && $expectedArgs == NULL)
{
if($argString[1][0] == '#')
{
return;
}
#echo "Unexpected argument\n";
exit(23);
}
elseif(!array_key_exists(1, $argString) && $expectedArgs == NULL)
{
return;
}
#$argString[1] = rtrim($argString[1]);
$argArray = explode(" ", $argString[1]);
#Match patterns
$patterns = [
"variable" => '/(GF|LF|TF)@([A-Za-z]|[-_\$&%\*!\?])([A-Za-z0-9-\$&%\*!\?]*)/',
"integer" => '/int@\S*/',
"boolean" => '/bool@(true|false)/',
"string" => '/string@[\S^#]*/',
"nil" => '/nil@nil/',
"type" => '/(int|bool|string|nil)/',
"label" => '/([A-Za-z]|[-\$&%\*!\?])([A-Za-z0-9-\$&%\*!\?]*)/'
];
$match = [];
$expectedArgCount = count($expectedArgs);
$argCount = 1;
$value = "";
foreach($argArray as $item)
{
if($argCount > $expectedArgCount)
{
#echo "Invalid argument count\n";
exit(23);
}
xmlwriter_start_element($xmlDoc, 'arg'.$argCount); #Start element argx
xmlwriter_start_attribute($xmlDoc, 'type'); #Start attribute type
if(preg_match($patterns["variable"], $item, $match))
{
#echo 'Found variable '.$match[0]."\n";
if($expectedArgs[$argCount-1] == "var" || $expectedArgs[$argCount-1] == "symb")
{
xmlwriter_text($xmlDoc, 'var');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $match[0]);
#echo 'arg'.$argCount;
}
else
{
echo "Unexpected variable\n";
exit(23);
}
}
#Match integer literal
elseif(preg_match($patterns["integer"], $item, $match))
{
if($expectedArgs[$argCount-1] == "symb")
{
$value = explode('@', $match[0])[1];
xmlwriter_text($xmlDoc, 'int');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $value);
#echo 'Found integer '.$match[0]."\n";
}
else
{
#echo "Unexpected integer literal\n";
exit(23);
}
}
#Match boolean literal
elseif(preg_match($patterns["boolean"], $item, $match))
{
if($expectedArgs[$argCount-1] == "symb")
{
$value = explode('@', $match[0])[1];
xmlwriter_text($xmlDoc, 'bool');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $value);
#echo 'Found boolean '.$match[0]."\n";
}
else
{
echo "Unexpected boolean literal\n";
exit(23);
}
}
#Match string
elseif(preg_match($patterns["string"], $item, $match))
{
if($expectedArgs[$argCount-1] == "symb")
{
$value = explode('@', $match[0], 2)[1];
xmlwriter_text($xmlDoc, 'string');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, parse_string($value));
#echo 'Found string '.$match[0]."\n";
}
else
{
#echo "Unexpected string literal\n";
exit(23);
}
}
#Match nil
elseif(preg_match($patterns["nil"], $item, $match))
{
if($expectedArgs[$argCount-1] == "symb")
{
$value = explode('@', $match[0])[1];
xmlwriter_text($xmlDoc, 'nil');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $value);
#echo 'Found nil '.$match[0]."\n";
}
else
{
#echo "Unexpected nil value\n";
exit(23);
}
}
#Match type
elseif(preg_match($patterns["type"], $item, $match))
{
if($expectedArgs[$argCount-1] == "type")
{
xmlwriter_text($xmlDoc, 'type');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $match[0]);
#echo 'Found type '.$match[0]."\n";
}
else
{
#echo "Unexpected type\n";
exit(23);
}
}
#Match label
elseif(preg_match($patterns["label"], $item, $match))
{
if($expectedArgs[$argCount-1] == "label")
{
xmlwriter_text($xmlDoc, 'label');
xmlwriter_end_attribute($xmlDoc); #end attribute type
xmlwriter_text($xmlDoc, $match[0]);
#echo 'Found label '.$match[0]."\n";
}
else
{
#echo "Unexpected label\n";
exit(23);
}
}
$argCount++;
xmlwriter_end_element($xmlDoc); #End element argx
}
}
function parse_header($xmlDoc)
{
$header = fgets(STDIN);
$header = rtrim(explode('#', $header)[0]);
if(strtolower($header) != ".ippcode19")
{
#echo("Invalid or missing header\n");
exit(21);
}
}
$extras = parse_command_line_args($argv);
$STATP = [
"--loc" => 0,
"--comments" => 0,
"--labels" => 0,
"--jumps" => 0
];
$xw = xmlwriter_open_memory();
xmlwriter_set_indent($xw, 1);
$res = xmlwriter_set_indent_string($xw, ' ');
xmlwriter_start_document($xw, '1.0', 'UTF-8'); #Generate XML header
xmlwriter_start_element($xw, 'program'); #Generate element program with attribute language=IPPcode19
xmlwriter_start_attribute($xw, 'language');
xmlwriter_text($xw, 'IPPcode19');
xmlwriter_end_attribute($xw);
parse_header($xw);
$lineNumber = 1;
while(!feof(STDIN))
{
$line = fgets(STDIN);
parse_line($line, $lineNumber, $xw, $STATP);
}
xmlwriter_end_element($xw);
xmlwriter_end_document($xw);
echo(xmlwriter_output_memory($xw));
if($extras != NULL)
{
print_stats($STATP, $extras["mask"], $extras["file"]);
}
?>
|
501b8996053e29bb694b957a1b1ef9b17115d217
|
{
"blob_id": "501b8996053e29bb694b957a1b1ef9b17115d217",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-08T10:24:09",
"content_id": "833e0c39363489266025e0b0896ab708fa2b4ba5",
"detected_licenses": [
"MIT"
],
"directory_id": "94b7c9202280eff6b5f6b7e635742370e42687e0",
"extension": "php",
"filename": "parse.php",
"fork_events_count": 0,
"gha_created_at": "2019-03-12T20:27:05",
"gha_event_created_at": "2019-06-08T10:24:11",
"gha_language": "C",
"gha_license_id": null,
"github_id": 175291194,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 12439,
"license": "MIT",
"license_type": "permissive",
"path": "/ipp/parse.php",
"provenance": "stack-edu-0048.json.gz:247229",
"repo_name": "DrGumby/FIT-VUT",
"revision_date": "2019-06-08T10:24:09",
"revision_id": "867a73b0787c97a25bc59d2a270f67ffd5738e1d",
"snapshot_id": "be61a97488a219e13f277be4ff5d0848aab3484f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DrGumby/FIT-VUT/867a73b0787c97a25bc59d2a270f67ffd5738e1d/ipp/parse.php",
"visit_date": "2020-04-28T12:53:49.287313",
"added": "2024-11-19T03:08:58.857109+00:00",
"created": "2019-06-08T10:24:09",
"int_score": 3,
"score": 2.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
package commands
import (
"strings"
"github.com/Jac0bDeal/pikamon/internal/pikamon/constants"
"github.com/Jac0bDeal/pikamon/internal/pikamon/models"
"github.com/bwmarrin/discordgo"
log "github.com/sirupsen/logrus"
)
func (h *Handler) list(s *discordgo.Session, m *discordgo.MessageCreate) {
trainerID := m.Author.ID
// check if trainer is registered, and return register suggestion if not
registered, err := h.isRegistered(trainerID)
if err != nil {
log.WithField("trainer", trainerID).Error("Error checking if trainer is registered")
}
if !registered {
publishTrainerNotRegistered(s, m)
return
}
pokemon, err := h.store.GetAllPokemon(trainerID)
if err != nil {
log.WithField("trainer", trainerID).Errorf("Failed to get all list for trainer: %v", err)
}
publishPokemonInfo(pokemon, s, m)
}
func publishPokemonInfo(pokemon []*models.Pokemon, s *discordgo.Session, m *discordgo.MessageCreate) {
pokemonInfo := make([]string, len(pokemon))
for idx, p := range pokemon {
pokemonInfo[idx] = p.ListingInfo()
}
msg := &discordgo.MessageEmbed{
Title: "Your pokémon:",
Description: strings.Join(pokemonInfo, "\n"),
Color: constants.MessageColor,
}
_, err := s.ChannelMessageSendEmbed(m.ChannelID, msg)
if err != nil {
log.Error(err)
}
}
|
63361cdb3ae46bd07a77e5d214b24aca6b5d30c4
|
{
"blob_id": "63361cdb3ae46bd07a77e5d214b24aca6b5d30c4",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-12T00:33:20",
"content_id": "668b63c8181445f259c61107032f8f1ae64b46c3",
"detected_licenses": [
"MIT"
],
"directory_id": "70f73b107f1ea7e2283ac3d6c91828fd77515428",
"extension": "go",
"filename": "list.go",
"fork_events_count": 0,
"gha_created_at": "2020-06-01T22:35:33",
"gha_event_created_at": "2021-08-12T00:33:21",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 268647317,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1289,
"license": "MIT",
"license_type": "permissive",
"path": "/internal/pikamon/commands/list.go",
"provenance": "stack-edu-0016.json.gz:68078",
"repo_name": "Jac0bDeal/pikamon",
"revision_date": "2021-08-11T23:20:10",
"revision_id": "520b4f75bee899a36748b0478e76c925dc2c05ea",
"snapshot_id": "baa491204cb96dcf6387c49da33aabfe8ccac9c0",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/Jac0bDeal/pikamon/520b4f75bee899a36748b0478e76c925dc2c05ea/internal/pikamon/commands/list.go",
"visit_date": "2023-07-07T13:45:37.405606",
"added": "2024-11-18T20:27:25.180994+00:00",
"created": "2021-08-11T23:20:10",
"int_score": 3,
"score": 2.515625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="UShareSoft"
from progressbar import AnimatedMarker, Bar, BouncingBar, Counter, ETA, \
FileTransferSpeed, FormatLabel, Percentage, \
ProgressBar, ReverseBar, RotatingMarker, \
SimpleProgress, Timer
class Download():
def __init__(self, name='Status: '):
#widgets = ['Status: ', Percentage(), ' ', Bar('>'), ' ', ETA(), ' ', FileTransferSpeed()]
widgets = [name, Percentage(), ' ', Bar('>'), ' ', ETA()]
self.pbar = ProgressBar(widgets=widgets, maxval=100).start()
def progress_update(self, count, blockSize, totalSize):
percent=None
if totalSize-blockSize<=0:
percent=50
else:
if totalSize-(count*blockSize)>=0:
percent = int(count*blockSize*100/totalSize)
if percent is not None:
self.pbar.update(percent)
def progress_finish(self):
self.pbar.finish()
|
842cdf38817549d582c60cac19106c629a245768
|
{
"blob_id": "842cdf38817549d582c60cac19106c629a245768",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-16T10:03:30",
"content_id": "9d5675e23ce87989263b493570981d12d8a0f855",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c91c9716e0b0fe3affab9807ee98e6f1f3fdc57f",
"extension": "py",
"filename": "download_utils.py",
"fork_events_count": 3,
"gha_created_at": "2015-07-16T08:03:27",
"gha_event_created_at": "2017-11-08T12:52:41",
"gha_language": "Python",
"gha_license_id": null,
"github_id": 39184600,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1256,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/ussclicore/utils/download_utils.py",
"provenance": "stack-edu-0055.json.gz:543958",
"repo_name": "jbremond/ussclicore",
"revision_date": "2015-07-16T10:03:30",
"revision_id": "4a5f30e612c1d8681b2d787dfee6bd85537ac6b3",
"snapshot_id": "38f29793ff35c58a82122ee7aeafe7d7db3b283d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jbremond/ussclicore/4a5f30e612c1d8681b2d787dfee6bd85537ac6b3/src/ussclicore/utils/download_utils.py",
"visit_date": "2021-01-21T05:04:44.745868",
"added": "2024-11-18T22:36:42.737447+00:00",
"created": "2015-07-16T10:03:30",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz"
}
|
export default class Bar {
constructor() {
this.init()
}
init() {
this.items = []
for(let i = 0; i < 10; i++) {
this.items.push(i)
}
}
print() {
this.items.map((item) => {
console.log(item)
})
}
}
|
5e98c1f0c9fe16d4912ef13427d2c31d35f9d5fb
|
{
"blob_id": "5e98c1f0c9fe16d4912ef13427d2c31d35f9d5fb",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-25T16:26:51",
"content_id": "9291be6017c92ff18a73762753006675aa710c79",
"detected_licenses": [
"MIT"
],
"directory_id": "f6287376fd93cd065b9af5cce12d88d34fa96865",
"extension": "js",
"filename": "bar.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 71864578,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 292,
"license": "MIT",
"license_type": "permissive",
"path": "/src/bar.js",
"provenance": "stack-edu-0037.json.gz:495876",
"repo_name": "jellyfishgh/es6-demo",
"revision_date": "2016-10-25T16:26:51",
"revision_id": "7a0d3c59ba7b15315ba97e2fb3fe59719f6c7f3a",
"snapshot_id": "3f3e91b481baa1d2486cce8d41da0ec4e685b057",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jellyfishgh/es6-demo/7a0d3c59ba7b15315ba97e2fb3fe59719f6c7f3a/src/bar.js",
"visit_date": "2021-01-12T15:42:42.991589",
"added": "2024-11-19T01:46:48.413511+00:00",
"created": "2016-10-25T16:26:51",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0055.json.gz"
}
|
from crystals import Crystal
import numpy as np
def eqPoints(POINT):
"""
Get point and make all combinations of ones and zeros by addding numbers in binary
"""
zera = np.where(POINT == 0)[0]
ilepow = 2**zera.size
mylist = np.empty((ilepow-1,3))
for n in range(1,ilepow):
val = f"{n:b}"
jkl = zera.size - len(val)
if jkl:
val = '0'*jkl + val
NP = POINT.copy()
for indexV, indexP in enumerate(zera):
if int(val[indexV]):
NP[indexP] += 1
mylist[n-1] = NP
return mylist
def allEqPoints(CELL):
"""
Find all points with zeros and add their equivalent to make whole cell
From [0,0,0] to [1,1,1]
"""
CELLwith0s = CELL[~CELL.all(axis=1)]
for point in CELLwith0s:
CELL = np.append(CELL,eqPoints(point),axis =0)
return np.unique(CELL,axis=0)
def millerORweber(ITN):
"""
Determine which kind of coordinates to use
"""
if ITN > 194 or ITN < 143:
return "m" #"rest"
return "w" #"hP, hR"
def getSCell(func, filename, size):
"""
Get cell from cod/cif/else.
Expand it to supercell size.
Place points between -1 and less than 1
Add missing walls of a cell.
"""
file = func(filename)
basetype = millerORweber(file.symmetry()['international_number'])
points = file.supercell(size,size,size).itersorted()
if size%2:
cell = np.array([1,1,1])
else:
cell = points.__next__().coords_fractional/(size/2)-1
for el in points:
cell = np.vstack((cell,el.coords_fractional/(size/2)-1))
return allEqPoints(cell), basetype
|
8bb1a827773703c812f64bd94b9ffc876e58f01c
|
{
"blob_id": "8bb1a827773703c812f64bd94b9ffc876e58f01c",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-05T14:35:31",
"content_id": "083a8a53bd926ceba9f28a1a70f0c127f1d7b556",
"detected_licenses": [
"MIT"
],
"directory_id": "f27116e50d62672fe9bb9dbaed60ce9b079d7121",
"extension": "py",
"filename": "cif_parsing.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 181493505,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1673,
"license": "MIT",
"license_type": "permissive",
"path": "/krysztalki/cif_parsing.py",
"provenance": "stack-edu-0063.json.gz:212587",
"repo_name": "woblob/Crystal_Symmetry",
"revision_date": "2020-09-05T14:35:31",
"revision_id": "be2984b4487d6075986ef60822a347d0b0e6b885",
"snapshot_id": "288032093e10a51cb868c368c8093c3a6bd74f72",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/woblob/Crystal_Symmetry/be2984b4487d6075986ef60822a347d0b0e6b885/krysztalki/cif_parsing.py",
"visit_date": "2021-07-07T21:31:09.188504",
"added": "2024-11-19T01:17:58.255864+00:00",
"created": "2020-09-05T14:35:31",
"int_score": 3,
"score": 2.890625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
---
hrs_structure:
division: '1'
volume: '3'
title: '10'
chapter: '138'
section: 138-7
type: hrs_section
tags:
- Government
menu:
hrs:
identifier: HRS_0138-0007
parent: HRS0138
name: 138-7 Audits
weight: 32035
title: Audits
full_title: 138-7 Audits
---
**§138-7 Audits.** (a) During any period in which an enhanced 911 surcharge is imposed upon customers, the board may request an audited report prepared by an independent certified public accountant that demonstrates that the request for cost recovery from public safety answering points and communications service providers recovers only costs and expenses directly related to the provision of enhanced 911 service as authorized by this chapter. The cost of the audited reports shall be considered expenses of the board. The board shall prevent public disclosure of proprietary information contained in the audited report, unless required by court order or appropriate administrative agency decision.
(b) The board shall select an independent third party to audit the fund every two years to determine whether the fund is being managed in accordance with this chapter. The board may use the audit to determine whether the amount of the surcharge assessed on each communications service connection is required to be adjusted. The costs of the audit shall be an administrative cost of the board recoverable from the fund. [L 2004, c 159, pt of §2; am L 2011, c 168, pt of §1]
|
60e0b46ac78fd686d9dfbec45e61e58fdf1d9ffc
|
{
"blob_id": "60e0b46ac78fd686d9dfbec45e61e58fdf1d9ffc",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-18T05:53:22",
"content_id": "bd29f2cf9a2150ec2281a8a5176e50f01efdb7f5",
"detected_licenses": [
"MIT"
],
"directory_id": "f61c38eafa0627ff34d51381df43e1fec7a10224",
"extension": "md",
"filename": "section-138-7.md",
"fork_events_count": 0,
"gha_created_at": "2017-09-15T00:11:35",
"gha_event_created_at": "2017-09-15T00:11:35",
"gha_language": null,
"gha_license_id": null,
"github_id": 103594169,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1456,
"license": "MIT",
"license_type": "permissive",
"path": "/web/content/title-10/chapter-138/section-138-7.md",
"provenance": "stack-edu-markdown-0015.json.gz:12344",
"repo_name": "SamMade/BlueAndKrabby",
"revision_date": "2017-09-18T05:53:22",
"revision_id": "18abdc95d05874245e951c6f33b37e02ff11c29a",
"snapshot_id": "a229efd627a45a3b75469d2a04dc792b1be44713",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SamMade/BlueAndKrabby/18abdc95d05874245e951c6f33b37e02ff11c29a/web/content/title-10/chapter-138/section-138-7.md",
"visit_date": "2021-07-01T12:51:41.871997",
"added": "2024-11-18T23:13:33.531316+00:00",
"created": "2017-09-18T05:53:22",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0015.json.gz"
}
|
#include <Python.h>
#include <string.h>
#include "stream.h"
#include "lzss.h"
#include "pixel.h"
#define MAGIC "TLG5.0\x00raw\x1A"
#define MAGIC_SIZE 11
typedef struct
{
uint8_t channel_count;
uint32_t image_width;
uint32_t image_height;
uint32_t block_height;
} Tlg5Header;
typedef struct
{
unsigned char *data;
size_t data_size;
} Tlg5BlockInfo;
static Tlg5BlockInfo *tlg5_block_info_create_empty(void)
{
Tlg5BlockInfo *block_info = PyMem_RawMalloc(sizeof(Tlg5BlockInfo));
if (!block_info)
{
PyErr_SetNone(PyExc_MemoryError);
return NULL;
}
block_info->data = NULL;
block_info->data_size = 0;
return block_info;
}
static Tlg5BlockInfo *tlg5_block_info_create_for_data(const size_t data_size)
{
Tlg5BlockInfo *block_info = PyMem_RawMalloc(sizeof(Tlg5BlockInfo));
if (!block_info)
{
PyErr_SetNone(PyExc_MemoryError);
return NULL;
}
block_info->data = PyMem_RawMalloc(data_size);
if (!block_info->data)
{
PyMem_RawFree(block_info);
PyErr_SetNone(PyExc_MemoryError);
return NULL;
}
block_info->data_size = data_size;
return block_info;
}
static void tlg5_block_info_destroy(Tlg5BlockInfo *block_info)
{
assert(block_info);
PyMem_RawFree(block_info->data);
PyMem_RawFree(block_info);
}
static int tlg5_block_info_read(
Tlg5BlockInfo *block_info,
Stream *stream,
const Tlg5Header *header,
uint8_t *dict,
size_t *dict_pos)
{
assert(block_info);
assert(stream);
assert(header);
assert(dict);
assert(dict_pos);
uint8_t mark;
uint32_t data_comp_size;
unsigned char *data_comp = NULL;
unsigned char *data_orig = NULL;
int ret = 0;
const size_t data_orig_size = header->image_width * header->block_height;
if (!stream_read_u8(stream, &mark))
goto end;
if (!stream_read_u32_le(stream, &data_comp_size))
goto end;
if (mark == 0)
{
data_comp = PyMem_RawMalloc(data_comp_size);
if (!data_comp)
{
PyErr_SetNone(PyExc_MemoryError);
goto end;
}
if (!stream_read_data(stream, data_comp, data_comp_size))
goto end;
data_orig = lzss_decompress(
data_comp, data_comp_size, data_orig_size, dict, dict_pos);
if (!data_orig)
goto end;
}
else
{
data_orig = PyMem_RawMalloc(data_comp_size);
if (!data_orig)
{
PyErr_SetNone(PyExc_MemoryError);
goto end;
}
if (!stream_read_data(stream, data_orig, data_orig_size))
goto end;
}
block_info->data = data_orig;
block_info->data_size = data_orig_size;
ret = 1;
end:
if (data_comp)
PyMem_RawFree(data_comp);
return ret;
}
static int tlg5_block_info_write(
Tlg5BlockInfo *block_info,
Stream *stream,
const Tlg5Header *header,
uint8_t *dict,
size_t *dict_pos)
{
assert(block_info);
assert(stream);
assert(header);
assert(dict);
assert(dict_pos);
int ret = 0;
const unsigned char *data_orig = block_info->data;
const size_t data_orig_size = block_info->data_size;
unsigned char *data_comp = NULL;
size_t data_comp_size = 0;
data_comp = lzss_compress(
block_info->data,
block_info->data_size,
&data_comp_size,
dict,
dict_pos);
// for some reason, even though the dummy lzss compression seems to work
// correctly, the game crashes... therefore we'll stick to raw mode
if (0 && data_comp_size < data_orig_size)
{
if (!data_comp) goto end;
if (!stream_write_u8(stream, 0)) goto end;
if (!stream_write_u32_le(stream, data_comp_size)) goto end;
if (!stream_write_data(stream, data_comp, data_comp_size)) goto end;
}
else
{
if (!stream_write_u8(stream, 1)) goto end;
if (!stream_write_u32_le(stream, data_orig_size)) goto end;
if (!stream_write_data(stream, data_orig, data_orig_size)) goto end;
}
ret = 1;
end:
if (data_comp)
PyMem_RawFree(data_comp);
return ret;
}
static int tlg5_header_read(Stream *stream, Tlg5Header *header)
{
assert(stream);
assert(header);
if (!stream_read_u8(stream, &header->channel_count)) return 0;
if (!stream_read_u32_le(stream, &header->image_width)) return 0;
if (!stream_read_u32_le(stream, &header->image_height)) return 0;
if (!stream_read_u32_le(stream, &header->block_height)) return 0;
return 1;
}
static int tlg5_header_write(Stream *stream, Tlg5Header *header)
{
assert(stream);
assert(header);
if (!stream_write_u8(stream, header->channel_count)) return 0;
if (!stream_write_u32_le(stream, header->image_width)) return 0;
if (!stream_write_u32_le(stream, header->image_height)) return 0;
if (!stream_write_u32_le(stream, header->block_height)) return 0;
return 1;
}
static int tlg5_load_pixel_block_row(
Pixel *image_data,
const size_t image_data_size,
Tlg5BlockInfo **block_data,
const Tlg5Header *header,
size_t block_y)
{
size_t max_y = block_y + header->block_height;
if (max_y > header->image_height)
max_y = header->image_height;
int use_alpha = header->channel_count == 4;
for (size_t y = block_y; y < max_y; y++)
{
size_t block_y_shift = (y - block_y) * header->image_width;
Pixel prev_pixel = {0, 0, 0, 0};
for (size_t x = 0; x < header->image_width; x++)
{
Pixel pixel;
pixel.b = block_data[0]->data[block_y_shift + x];
pixel.g = block_data[1]->data[block_y_shift + x];
pixel.r = block_data[2]->data[block_y_shift + x];
pixel.a = use_alpha
? block_data[3]->data[block_y_shift + x]
: 0xFF;
pixel.b += pixel.g;
pixel.r += pixel.g;
prev_pixel.r += pixel.r;
prev_pixel.g += pixel.g;
prev_pixel.b += pixel.b;
prev_pixel.a += pixel.a;
Pixel *target_pixel = image_data + y * header->image_width + x;
if (target_pixel >= image_data + image_data_size/sizeof(Pixel))
{
PyErr_SetString(PyExc_ValueError, "Corrupt data");
return 0;
}
target_pixel->r = prev_pixel.r;
target_pixel->g = prev_pixel.g;
target_pixel->b = prev_pixel.b;
target_pixel->a = prev_pixel.a;
if (y > 0)
{
Pixel *top_pixel = target_pixel - header->image_width;
target_pixel->r += top_pixel->r;
target_pixel->g += top_pixel->g;
target_pixel->b += top_pixel->b;
target_pixel->a += top_pixel->a;
}
if (!use_alpha)
image_data[y * header->image_width + x].a = 0xFF;
}
}
return 1;
}
static int tlg5_save_pixel_block_row(
const Pixel *image_data,
const size_t image_data_size,
Tlg5BlockInfo **block_data,
const Tlg5Header *header,
size_t block_y)
{
size_t max_y = block_y + header->block_height;
if (max_y > header->image_height)
max_y = header->image_height;
for (size_t y = block_y; y < max_y; y++)
{
size_t block_y_shift = (y - block_y) * header->image_width;
Pixel prev_pixel = {0, 0, 0, 0};
for (size_t x = 0; x < header->image_width; x++)
{
const Pixel *source_pixel =
image_data + y * header->image_width + x;
if (source_pixel >= image_data + image_data_size/sizeof(Pixel))
{
PyErr_SetString(PyExc_ValueError, "Corrupt data");
return 0;
}
Pixel pixel = *source_pixel;
if (y > 0)
{
const Pixel *top_pixel = source_pixel - header->image_width;
pixel.r -= top_pixel->r;
pixel.g -= top_pixel->g;
pixel.b -= top_pixel->b;
pixel.a -= top_pixel->a;
}
pixel.r -= prev_pixel.r;
pixel.g -= prev_pixel.g;
pixel.b -= prev_pixel.b;
pixel.a -= prev_pixel.a;
prev_pixel.r += pixel.r;
prev_pixel.g += pixel.g;
prev_pixel.b += pixel.b;
prev_pixel.a += pixel.a;
pixel.b -= pixel.g;
pixel.r -= pixel.g;
block_data[0]->data[block_y_shift + x] = pixel.b;
block_data[1]->data[block_y_shift + x] = pixel.g;
block_data[2]->data[block_y_shift + x] = pixel.r;
block_data[3]->data[block_y_shift + x] = pixel.a;
}
}
return 1;
}
static PyObject *tlg5_decode(PyObject *self, PyObject *args)
{
Stream *stream = NULL;
Pixel *image_data = NULL;
Py_buffer input = {0};
PyObject *output = NULL;
Tlg5Header header;
Tlg5BlockInfo *block_info[4] = {NULL, NULL, NULL, NULL};
if (!PyArg_ParseTuple(args, "y*", &input))
goto end;
stream = stream_create_for_data(input.buf, input.len);
if (!stream)
goto end;
if (memcmp(stream->data, MAGIC, MAGIC_SIZE))
{
PyErr_SetString(PyExc_ValueError, "Not a TLG5 image");
goto end;
}
stream->pos += MAGIC_SIZE;
if (!tlg5_header_read(stream, &header))
goto end;
if (header.channel_count != 3 && header.channel_count != 4)
{
PyErr_SetString(PyExc_ValueError, "Unsupported channel count");
goto end;
}
const size_t image_data_size =
header.image_height * header.image_width * 4;
image_data = PyMem_RawMalloc(image_data_size);
if (!image_data)
{
PyErr_SetNone(PyExc_MemoryError);
goto end;
}
// ignore block sizes
size_t block_count = (header.image_height - 1) / header.block_height + 1;
stream->pos += 4 * block_count;
for (int channel = 0; channel < 4; channel++)
{
block_info[channel] = tlg5_block_info_create_empty();
if (!block_info[channel])
goto end;
}
unsigned char dict[4096] = {0};
size_t dict_pos = 0;
for (size_t y = 0; y < header.image_height; y += header.block_height)
{
for (int channel = 0; channel < header.channel_count; channel++)
{
if (!tlg5_block_info_read(
block_info[channel], stream, &header, dict, &dict_pos))
{
goto end;
}
}
if (!tlg5_load_pixel_block_row(
image_data, image_data_size, block_info, &header, y))
{
goto end;
}
}
for (int channel = 0; channel < 4; channel++)
{
tlg5_block_info_destroy(block_info[channel]);
block_info[channel] = NULL;
}
PyObject *output_image_width = PyLong_FromLong(header.image_width);
PyObject *output_image_height = PyLong_FromLong(header.image_height);
PyObject *output_image_data = PyBytes_FromStringAndSize(
(char*)image_data, image_data_size);
output = PyTuple_Pack(
3,
output_image_width,
output_image_height,
output_image_data);
Py_DECREF(output_image_width);
Py_DECREF(output_image_height);
Py_DECREF(output_image_data);
end:
for (int channel = 0; channel < 4; channel++)
if (block_info[channel])
tlg5_block_info_destroy(block_info[channel]);
if (image_data) PyMem_RawFree(image_data);
if (stream) stream_destroy(stream);
PyBuffer_Release(&input);
return output;
}
static PyObject *tlg5_encode(PyObject *self, PyObject *args)
{
Tlg5BlockInfo *block_info[4] = {NULL, NULL, NULL, NULL};
int input_image_width;
int input_image_height;
Py_buffer input_image_data = {0};
Stream *stream = NULL;
PyObject *output = NULL;
if (!PyArg_ParseTuple(
args,
"iiy*",
&input_image_width,
&input_image_height,
&input_image_data))
{
goto end;
}
if (input_image_data.len != input_image_width * input_image_height * 4)
{
PyErr_SetString(PyExc_ValueError, "Invalid data size");
goto end;
}
stream = stream_create_empty();
if (!stream)
goto end;
if (!stream_write_data(stream, (unsigned char*)MAGIC, MAGIC_SIZE))
goto end;
Tlg5Header header;
header.channel_count = 4;
header.image_width = input_image_width;
header.image_height = input_image_height;
header.block_height = 16;
if (!tlg5_header_write(stream, &header))
goto end;
size_t block_sizes_offset = stream->pos;
size_t block_count = (header.image_height - 1) / header.block_height + 1;
for (size_t i = 0; i < block_count; i++)
if (!stream_write_u32_le(stream, 0))
goto end;
for (int channel = 0; channel < 4; channel++)
{
block_info[channel] = tlg5_block_info_create_for_data(
header.image_width * header.block_height);
if (!block_info[channel])
goto end;
}
unsigned char dict[4096] = {0};
size_t dict_pos = 0;
for (size_t y = 0; y < header.image_height; y += header.block_height)
{
size_t old_pos = stream->pos;
for (int channel = 0; channel < header.channel_count; channel++)
{
if (!tlg5_save_pixel_block_row(
input_image_data.buf,
input_image_data.len,
block_info,
&header,
y))
{
goto end;
}
if (!tlg5_block_info_write(
block_info[channel],
stream,
&header,
dict,
&dict_pos))
{
goto end;
}
}
size_t collective_size = stream->pos - old_pos;
old_pos = stream->pos;
stream->pos = block_sizes_offset + 4 * y / header.block_height;
if (!stream_write_u32_le(stream, collective_size))
goto end;
stream->pos = old_pos;
}
for (int channel = 0; channel < 4; channel++)
{
tlg5_block_info_destroy(block_info[channel]);
block_info[channel] = NULL;
}
output = PyBytes_FromStringAndSize(
(char*)stream->data, stream->size);
end:
for (int channel = 0; channel < 4; channel++)
if (block_info[channel])
tlg5_block_info_destroy(block_info[channel]);
if (stream)
stream_destroy(stream);
PyBuffer_Release(&input_image_data);
return output;
}
static PyMethodDef Methods[] = {
{"decode_tlg_5", tlg5_decode, METH_VARARGS, "Decode a tlg5 image"},
{"encode_tlg_5", tlg5_encode, METH_VARARGS, "Encode a tlg5 image"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT, "lib.tlg.tlg5", NULL, -1, Methods,
};
PyMODINIT_FUNC PyInit_tlg5(void)
{
PyObject *magic_key = Py_BuildValue("s", "MAGIC");
PyObject *magic_value = Py_BuildValue("y#", MAGIC, MAGIC_SIZE);
PyObject *module = PyModule_Create(&module_definition);
PyObject_SetAttr(module, magic_key, magic_value);
return module;
}
|
5376e499984a9d91e805de7c81c9439ee7d1df6e
|
{
"blob_id": "5376e499984a9d91e805de7c81c9439ee7d1df6e",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-03T18:04:29",
"content_id": "bb7c528498a7fefe714bb742a65e833744fed9e8",
"detected_licenses": [
"MIT"
],
"directory_id": "2dfc5264d092e9e7c61e17ff3ec5dbec1f168cd8",
"extension": "c",
"filename": "tlg5.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87466901,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 15332,
"license": "MIT",
"license_type": "permissive",
"path": "/ext/tlg5.c",
"provenance": "stack-edu-0001.json.gz:431595",
"repo_name": "rr-/tsujidou",
"revision_date": "2019-02-03T18:04:29",
"revision_id": "82cc2da7c36931e01db0d6d4d3939a2bdb364b4d",
"snapshot_id": "1a196f2c12755198819db902c39631d6f5861be8",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/rr-/tsujidou/82cc2da7c36931e01db0d6d4d3939a2bdb364b4d/ext/tlg5.c",
"visit_date": "2021-01-19T06:29:26.079518",
"added": "2024-11-18T18:23:05.530317+00:00",
"created": "2019-02-03T18:04:29",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz"
}
|
<?php
namespace Smartdiary\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection,
Symfony\Component\Security\Core\User\UserInterface,
Symfony\Component\Validator\ExecutionContextInterface;
/**
* Smartdiary\UserBundle\Entity\User
*
* @ORM\Entity(repositoryClass="Smartdiary\UserBundle\Entity\UserRepository")
* @ORM\Table(name="user")
*/
class User implements UserInterface, \Serializable {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string $name
*
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @var string $surname
*
* @ORM\Column(type="string", length=255)
*/
private $surname;
/**
* @var string $school
*
* @ORM\Column(type="string", length=255)
*/
private $school;
/**
* @var string $birthDate
*
* @ORM\Column(name="birth_date", type="date")
*/
private $birthDate;
/**
* @var string $sex
*
* @ORM\Column(type="boolean")
*/
private $sex;
/**
* @var string $username
*
* @ORM\Column(type="string", length=255, unique=true)
*/
private $username;
/**
* @var string $slug
*
* @ORM\Column(type="string", length=255, unique=true)
* @Gedmo\Slug(fields={"username"})
*/
private $slug;
/**
* @var string $salt
*
* @ORM\Column(name="salt", type="string", length=40)
*/
private $salt;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* @var string $password
*
* @ORM\Column(type="string", length=255)
*/
private $password;
/**
* @var string $email
*
* @ORM\Column(type="string", length=255, unique=true)
*/
private $email;
/**
* @var int $roleId
*
* @ORM\Column(name="role_id", type="integer", nullable=false)
*/
private $roleId;
/**
* @var string $teacherEmail
*
* @ORM\Column(name="teacher_email", type="string", length=255, nullable=true)
*/
private $teacher_email;
/**
* @var datetime $createdAt
*
* @ORM\Column(name="created_at", type="datetime", nullable=true)
* @Gedmo\Timestampable(on="create")
*
*/
private $createdAt;
/**
* @var datetime $updatedAt
*
* @ORM\Column(name="updated_at", type="datetime", nullable=true)
* @Gedmo\Timestampable(on="update")
*/
private $updatedAt;
/**
* @var Role
*
* @ORM\ManyToOne(targetEntity="Role", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="role_id", referencedColumnName="id")
*/
private $role;
/**
* @ORM\OneToMany(targetEntity="\Smartdiary\SmartdiaryBundle\Entity\UserProblematicSituation", mappedBy="user")
*/
private $userProblematicSituations;
public function __construct()
{
$this->isActive = true;
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
$this->userProblematicSituations = new ArrayCollection();
}
/**
* @return string
*/
public function getBirthDate()
{
return $this->birthDate;
}
public function eraseCredentials()
{
}
/**
* @return \Smartdiary\UserBundle\Entity\datetime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @return \Smartdiary\UserBundle\Entity\Role
*/
public function getRole()
{
return $this->role;
}
public function getRoles()
{
return array($this->getRole()->getRole());
}
/**
* @return int
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* @return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* @return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* @return \Smartdiary\UserBundle\Entity\datetime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getSchool()
{
return $this->school;
}
/**
* @return string
*/
public function getSex()
{
return $this->sex;
}
/**
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* @return string
*/
public function getTeacherEmail()
{
return $this->teacher_email;
}
public function hasTeacherEmail(ExecutionContextInterface $context)
{
if($this->getRole()->getId()==2 && !$this->getTeacherEmail())
{
$context->addViolationAt(
'teacher_email',
'Email non valida',
array(),
null
);
}
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* @param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* @param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @param \Smartdiary\UserBundle\Entity\Role $role
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* @param int $roleId
*/
public function setRoleId($roleId)
{
$this->roleId = $roleId;
}
/**
* @param string $salt
*/
public function setSalt($salt)
{
$this->salt = $salt;
}
/**
* @param string $slug
*/
public function setSlug($slug)
{
$this->slug = $slug;
}
/**
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @param string $birthDate
*/
public function setBirthDate($birthDate)
{
$this->birthDate = \DateTime::createFromFormat('d/m/Y', $birthDate);
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @param string $school
*/
public function setSchool($school)
{
$this->school = $school;
}
/**
* @param string $sex
*/
public function setSex($sex)
{
$this->sex = $sex;
}
/**
* @param string $surname
*/
public function setSurname($surname)
{
$this->surname = $surname;
}
/**
* @param string $teacher_email
*/
public function setTeacherEmail($teacher_email)
{
$this->teacher_email = $teacher_email;
}
/**
* Serialize the User object
* @see Serializable::serialize()
*/
public function serialize()
{
return serialize(array($this->id, $this->username, $this->password));
}
/**
* Unserialize the User object
* @see Serializable::unserialize()
*/
public function unserialize($serialized)
{
list($this->id, $this->username, $this->password) = unserialize($serialized);
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
* @return User
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Add userProblematicSituations
*
* @param \Smartdiary\SmartdiaryBundle\Entity\UserProblematicSituation $userProblematicSituations
* @return User
*/
public function addUserProblematicSituation(\Smartdiary\SmartdiaryBundle\Entity\UserProblematicSituation $userProblematicSituations)
{
$this->userProblematicSituations[] = $userProblematicSituations;
return $this;
}
/**
* Remove userProblematicSituations
*
* @param \Smartdiary\SmartdiaryBundle\Entity\UserProblematicSituation $userProblematicSituations
*/
public function removeUserProblematicSituation(\Smartdiary\SmartdiaryBundle\Entity\UserProblematicSituation $userProblematicSituations)
{
$this->userProblematicSituations->removeElement($userProblematicSituations);
}
/**
* Get userProblematicSituations
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUserProblematicSituations()
{
return $this->userProblematicSituations;
}
}
|
a0cff362d5e37afa9f52c4df9b385395db0f6982
|
{
"blob_id": "a0cff362d5e37afa9f52c4df9b385395db0f6982",
"branch_name": "refs/heads/master",
"committer_date": "2014-02-25T09:00:37",
"content_id": "e687377aa4f31f8a96b6143209a57aeb0081aba4",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "52d8c457ba2e631f683259af5325fef0aff3bf66",
"extension": "php",
"filename": "User.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 15392658,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 9729,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/src/Smartdiary/UserBundle/Entity/User.php",
"provenance": "stack-edu-0052.json.gz:44353",
"repo_name": "gianluca78/smartdiary",
"revision_date": "2014-02-25T09:00:37",
"revision_id": "6cd572a51a85638a2b34fce390cd2136feda957c",
"snapshot_id": "b55c52c78666721e43a4821ce4cc74682b9c6e23",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gianluca78/smartdiary/6cd572a51a85638a2b34fce390cd2136feda957c/src/Smartdiary/UserBundle/Entity/User.php",
"visit_date": "2021-01-21T09:17:21.081410",
"added": "2024-11-19T01:37:01.056005+00:00",
"created": "2014-02-25T09:00:37",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
package model
import (
"time"
"github.com/jinzhu/gorm"
//
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// DB 数据库链接单例
var DB *gorm.DB
// Database 在中间件中初始化mysql链接
func Database(connString string) {
db := newConn(connString)
//禁止表名复数形式
db.SingularTable(true)
// 启用Logger,显示详细日志
db.LogMode(true)
// 自定义的日志打印sql语句
db.SetLogger(&GormLogger{})
db.DB().SetMaxOpenConns(100) //设置数据库连接池最大连接数
db.DB().SetMaxIdleConns(20) //连接池最大允许的空闲连接数,如果没有sql任务需要执行的连接数大于20,超过的连接会被连接池关闭。
db.DB().SetConnMaxLifetime(time.Second * 30) //超时
DB = db
migration()
}
//newConn 创建新连接
func newConn(connString string) *gorm.DB {
// logger.Info(connString)
db, err := gorm.Open("mysql", connString)
if err != nil {
panic(err)
}
return db
}
//GetDB 获取gorm.DB对象
func GetDB() *gorm.DB {
return DB
}
|
b3059e2b5d937b98d6fe384b1eb38d4a172f1fc5
|
{
"blob_id": "b3059e2b5d937b98d6fe384b1eb38d4a172f1fc5",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-03T07:11:43",
"content_id": "7a8e68158f95e83fabaa7675b3a690c7dd34c791",
"detected_licenses": [
"MIT"
],
"directory_id": "1a42c7c502df097b059a56f47dd7d7d6c6355580",
"extension": "go",
"filename": "init.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 369769224,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1050,
"license": "MIT",
"license_type": "permissive",
"path": "/model/init.go",
"provenance": "stack-edu-0017.json.gz:385992",
"repo_name": "yizhixiaokong/bottest",
"revision_date": "2021-09-03T07:11:43",
"revision_id": "b26243e00cf02f61693c33a07672cf02bbb73669",
"snapshot_id": "834c7ba91f6eca4cffe01ad8f13fe9863de6d9b5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yizhixiaokong/bottest/b26243e00cf02f61693c33a07672cf02bbb73669/model/init.go",
"visit_date": "2023-07-22T02:14:57.309955",
"added": "2024-11-18T21:05:55.096114+00:00",
"created": "2021-09-03T07:11:43",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
import { IParamsRenderHtml } from "./decognition.ts";
export interface withCustomTab {
getTab(): Tab;
}
export interface ITab {
key: string;
text: string;
render: Function;
}
export class Tab {
private tabs: Array<ITab> = [];
/**
* createnew tab
* @param {string} key
* @param {string} text
* @param {Function} render
*/
public create(key: string, text: string, render: Function) {
this.tabs.push({ key, text, render } as ITab);
return this;
}
/**
* Get all tab
* @returns Array
*/
public get(): Array<ITab> {
return this.tabs;
}
public renderHeader(): string {
let result: string = "";
for (let i in this.tabs) {
let item: ITab = this.tabs[i];
result += `
<a href="#" data-tab="tab-${item.key}" class="flex py-2 px-4 mx-1 text-gray-300 hover:bg-indigo-600">
${item.text}
</a>`;
}
return result;
}
public async renderContent(params: IParamsRenderHtml): Promise<string> {
let result: string = "";
for (let i in this.tabs) {
let item: ITab = this.tabs[i];
let content = await (item.render(params));
result += `
<div class="tab-item h-full" id="tab-${item.key}">
${content}
</div>`;
}
return result;
}
}
|
6a08f4c057314afa919ea50e4f1ebc932883ce6f
|
{
"blob_id": "6a08f4c057314afa919ea50e4f1ebc932883ce6f",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-07T11:15:39",
"content_id": "956650fcaa7c7cbc5eadb8372014c8590a2d591a",
"detected_licenses": [
"MIT"
],
"directory_id": "033a7517470da30978f06d237b3d4a154f7d99fd",
"extension": "ts",
"filename": "tab.ts",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 277053980,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1443,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tab.ts",
"provenance": "stack-edu-0073.json.gz:817996",
"repo_name": "viandwi24/decognition",
"revision_date": "2020-07-07T11:15:39",
"revision_id": "2e5ca86478b65c272be97dea76d04e0b05220b4c",
"snapshot_id": "5d5f3dc631c4c373e6dc18e02460f9effb9ddc41",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/viandwi24/decognition/2e5ca86478b65c272be97dea76d04e0b05220b4c/src/tab.ts",
"visit_date": "2022-12-17T15:58:05.988349",
"added": "2024-11-19T00:35:07.819379+00:00",
"created": "2020-07-07T11:15:39",
"int_score": 3,
"score": 2.859375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
import { theme } from "@socialgouv/cdtn-ui";
import styled from "styled-components";
const { breakpoints, fonts, colors, spacings } = theme;
export const Label = styled.label`
display: flex;
align-items: center;
margin-right: 2em;
padding: 0;
`;
export const RadioContainer = styled.div`
display: flex;
flex-direction: ${(props) => (props.direction === "row" ? "row" : "column")};
align-items: flex-start;
justify-content: flex-start;
margin-bottom: ${spacings.base};
`;
export const SectionTitle = styled.h2`
margin-top: ${(props) =>
props.hasSmallMarginTop ? spacings.small : spacings.large};
margin-bottom: ${spacings.small};
color: ${({ theme }) => theme.altText};
font-weight: 600;
font-size: ${fonts.sizes.headings.small};
font-family: "Open Sans", sans-serif;
`;
export const Highlight = styled.strong`
color: ${({ theme }) => theme.primary};
font-weight: 700;
font-size: ${fonts.sizes.headings.small};
white-space: pre-line;
@media (max-width: ${breakpoints.mobile}) {
font-size: ${fonts.sizes.default};
}
`;
export const HighlightResult = styled(Highlight)`
font-size: 1.5em;
`;
export const SmallText = styled.p`
color: ${colors.paragraph};
font-size: ${fonts.sizes.small};
margin-top: ${spacings.xsmall};
`;
|
053cd2efbd07771d82f872d5403979cb4dc8e669
|
{
"blob_id": "053cd2efbd07771d82f872d5403979cb4dc8e669",
"branch_name": "refs/heads/dev",
"committer_date": "2023-09-04T13:07:42",
"content_id": "0618512bc6890b68020071007733732d14ce1cb4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "805490c2dc63f7befa5527a8493717a282c0dbfe",
"extension": "ts",
"filename": "stepStyles.ts",
"fork_events_count": 23,
"gha_created_at": "2018-04-26T08:37:10",
"gha_event_created_at": "2023-09-14T15:01:30",
"gha_language": "TypeScript",
"gha_license_id": "Apache-2.0",
"github_id": 131125682,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1284,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/packages/code-du-travail-frontend/src/outils/common/stepStyles.ts",
"provenance": "stack-edu-0075.json.gz:771",
"repo_name": "SocialGouv/code-du-travail-numerique",
"revision_date": "2023-09-04T13:07:42",
"revision_id": "6b9129a5170b21f6b16a9d4b364c925f369470e1",
"snapshot_id": "56ec420c13aa0e934eca4fd381ea08c9c3a25277",
"src_encoding": "UTF-8",
"star_events_count": 100,
"url": "https://raw.githubusercontent.com/SocialGouv/code-du-travail-numerique/6b9129a5170b21f6b16a9d4b364c925f369470e1/packages/code-du-travail-frontend/src/outils/common/stepStyles.ts",
"visit_date": "2023-09-05T18:08:33.825682",
"added": "2024-11-18T20:01:22.916022+00:00",
"created": "2023-09-04T13:07:42",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
#include "header/WebViewInNewThread.h"
void WebViewInNewThread::loadPageByUrl(QUrl url)
{
m_webView->load(url);
}
WebViewInNewThread::~WebViewInNewThread()
{
this->quit();
this->wait();
delete m_webView;
}
void WebViewInNewThread::do_exec()
{
this->exec();
//this may move the main event loop to this new thread.
QApplication::processEvents();
}
void WebViewInNewThread::run()
{
do_exec();
}
void WebViewInNewThread::download(QWebEngineDownloadItem* download)
{
Q_ASSERT(download && download->state() == QWebEngineDownloadItem::DownloadRequested);
QString path = QFileDialog::getSaveFileName(m_webView, tr("Save as"), download->path());
if (path.isEmpty())
return;
download->setPath(path);
download->accept();
}
|
90be64807c9f18dcc17b4c6214034d3a60a87d5e
|
{
"blob_id": "90be64807c9f18dcc17b4c6214034d3a60a87d5e",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-11T10:57:42",
"content_id": "80f1b6413c21ea10873abf0c44a30557630b7fd3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ca1f144a67f0dcb8304792cb6a44626a87abab26",
"extension": "cpp",
"filename": "WebViewInNewThread.cpp",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 237989539,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 735,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/source/WebViewInNewThread.cpp",
"provenance": "stack-edu-0002.json.gz:385236",
"repo_name": "Leonezz/OpenChart",
"revision_date": "2023-06-11T10:57:42",
"revision_id": "e271c7c4761dfb6bcc5f3e3cb282364e2d2f96fb",
"snapshot_id": "605e1ca9476629d1df20ec18912a6a0a4bdc69f8",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/Leonezz/OpenChart/e271c7c4761dfb6bcc5f3e3cb282364e2d2f96fb/source/WebViewInNewThread.cpp",
"visit_date": "2023-06-22T03:08:56.342790",
"added": "2024-11-18T23:31:36.714788+00:00",
"created": "2023-06-11T10:57:42",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
/*
* Copyright 2019 Red Hat
*
* 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 io.apicurio.registry.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import io.apicurio.registry.common.proto.Serde;
import io.apicurio.registry.content.ContentHandle;
import io.apicurio.registry.rules.compatibility.ProtobufFile;
import io.apicurio.registry.types.ArtifactType;
/**
* @author eric.wittmann@gmail.com
*/
public final class ArtifactTypeUtil {
private static final ObjectMapper mapper = new ObjectMapper();
/**
* Constructor.
*/
private ArtifactTypeUtil() {
}
/**
* Method that discovers the artifact type from the raw content of an artifact. This will
* attempt to parse the content (with the optional provided Content Type as a hint) and figure
* out what type of artifact it is. Examples include Avro, Protobuf, OpenAPI, etc. Most
* of the supported artifact types are JSON formatted. So in these cases we will need to
* look for some sort of type-specific marker in the content of the artifact. The method
* does its best to figure out the type, but will default to Avro if all else fails.
*
* @param content
* @param contentType
*/
public static ArtifactType discoverType(ContentHandle content, String contentType) {
boolean triedProto = false;
// If the content-type suggests it's protobuf, try that first.
if (contentType == null || contentType.toLowerCase().contains("proto")) {
triedProto = true;
ArtifactType type = tryProto(content);
if (type != null) {
return type;
}
}
// Try the various JSON formatted types
try {
JsonNode tree = mapper.readTree(content.content());
// OpenAPI
if (tree.has("openapi") || tree.has("swagger")) {
return ArtifactType.OPENAPI;
}
// AsyncAPI
if (tree.has("asyncapi")) {
return ArtifactType.ASYNCAPI;
}
// JSON Schema
if (tree.has("$schema") && tree.get("$schema").asText().contains("json-schema.org")) {
return ArtifactType.JSON;
}
// Kafka Connect??
// TODO detect Kafka Connect schemas
// Avro
return ArtifactType.AVRO;
} catch (Exception e) {
// Apparently it's not JSON.
}
// Try protobuf (only if we haven't already)
if (!triedProto) {
ArtifactType type = tryProto(content);
if (type != null) {
return type;
}
}
// Try GraphQL (SDL)
if (tryGraphQL(content)) {
return ArtifactType.GRAPHQL;
}
// Default to Avro
return ArtifactType.AVRO;
}
private static ArtifactType tryProto(ContentHandle content) {
try {
ProtobufFile.toProtoFileElement(content.content());
return ArtifactType.PROTOBUF;
} catch (Exception e) {
// Doesn't seem to be protobuf
}
try {
Serde.Schema.parseFrom(content.bytes());
return ArtifactType.PROTOBUF_FD;
} catch (Exception e) {
// Doesn't seem to be protobuf_fd
}
return null;
}
private static boolean tryGraphQL(ContentHandle content) {
try {
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(content.content());
if (typeRegistry != null) {
return true;
}
} catch (Exception e) {
// Must not be a GraphQL file
}
return false;
}
}
|
4ca7d95970645145dba6efd164d22e8b41644209
|
{
"blob_id": "4ca7d95970645145dba6efd164d22e8b41644209",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-15T19:01:16",
"content_id": "ecc75dd7be00af5d736710c22016d7f7266810a4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "39e1a4a17e1fdc1c45efd02f0a4f79f952d36777",
"extension": "java",
"filename": "ArtifactTypeUtil.java",
"fork_events_count": 0,
"gha_created_at": "2020-02-24T09:26:25",
"gha_event_created_at": "2020-02-24T09:26:26",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 242694597,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4478,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/io/apicurio/registry/util/ArtifactTypeUtil.java",
"provenance": "stack-edu-0029.json.gz:9157",
"repo_name": "cfoskin/apicurio-registry",
"revision_date": "2020-04-15T19:01:16",
"revision_id": "293e58bf1b54d1030fa5a9d902add2184087d89a",
"snapshot_id": "745afcdcb25879505be3b2467de770d72c282d82",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cfoskin/apicurio-registry/293e58bf1b54d1030fa5a9d902add2184087d89a/app/src/main/java/io/apicurio/registry/util/ArtifactTypeUtil.java",
"visit_date": "2021-01-14T17:23:13.955670",
"added": "2024-11-18T21:36:48.746380+00:00",
"created": "2020-04-15T19:01:16",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
package com.kwery.dao;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import com.kwery.models.EmailConfiguration;
import com.kwery.services.EmptyFromEmailException;
import com.kwery.services.mail.EmailValidator;
import com.kwery.services.mail.InvalidEmailException;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.LinkedList;
import java.util.List;
@Singleton
public class EmailConfigurationDao {
protected final Provider<EntityManager> entityManagerProvider;
protected final EmailValidator emailValidator;
@Inject
public EmailConfigurationDao(Provider<EntityManager> entityManagerProvider, EmailValidator emailValidator) {
this.entityManagerProvider = entityManagerProvider;
this.emailValidator = emailValidator;
}
/**
* @throws InvalidEmailException if any of the emails are found to be invalid.
* @throws com.kwery.services.EmptyFromEmailException if from email is empty.
*/
@Transactional
public synchronized void save(EmailConfiguration emailConfiguration) throws InvalidEmailException {
EntityManager e = entityManagerProvider.get();
sanitiseEmails(emailConfiguration);
if ("".equals(emailConfiguration.getFrom())) {
throw new EmptyFromEmailException();
}
List<String> invalids = validateEmails(emailConfiguration);
if (!invalids.isEmpty()) {
throw new InvalidEmailException(invalids);
}
if (emailConfiguration.getId() != null && emailConfiguration.getId() > 0) {
e.merge(emailConfiguration);
} else {
e.persist(emailConfiguration);
}
e.flush();
}
protected void sanitiseEmails(EmailConfiguration config) {
config.setBcc(emailValidator.emailCsvManipulation(config.getBcc()));
//These cannot be CSV, but we still use this method as it serves the purpose of cleaning up spaces etc
config.setFrom(emailValidator.emailCsvManipulation(config.getFrom()));
config.setReplyTo(emailValidator.emailCsvManipulation(config.getReplyTo()));
}
protected List<String> validateEmails(EmailConfiguration config) {
List<String> invalids = new LinkedList<>();
if (!"".equals(config.getBcc())) {
invalids.addAll(emailValidator.filterInvalidEmails(Splitter.on(',').splitToList(config.getBcc())));
}
if (!"".equals(config.getFrom())) {
invalids.addAll(emailValidator.filterInvalidEmails(ImmutableList.of(config.getFrom())));
}
if (!"".equals(config.getReplyTo())) {
invalids.addAll(emailValidator.filterInvalidEmails(ImmutableList.of(config.getReplyTo())));
}
return invalids;
}
@Transactional
public EmailConfiguration get() {
EntityManager e = entityManagerProvider.get();
CriteriaBuilder cb = e.getCriteriaBuilder();
CriteriaQuery<EmailConfiguration> cq = cb.createQuery(EmailConfiguration.class);
Root<EmailConfiguration> root = cq.from(EmailConfiguration.class);
CriteriaQuery<EmailConfiguration> all = cq.select(root);
return e.createQuery(all).getSingleResult();
}
@Transactional
public EmailConfiguration get(int id) {
return entityManagerProvider.get().find(EmailConfiguration.class, id);
}
}
|
487012cbabf0429c21dd58b5df037945f0232413
|
{
"blob_id": "487012cbabf0429c21dd58b5df037945f0232413",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-15T02:46:28",
"content_id": "27dfdd2dfff057ed97ef965465176ffb0095c89b",
"detected_licenses": [
"MIT"
],
"directory_id": "8c6d09f0f9f2561fe6192c84901d2619f7032373",
"extension": "java",
"filename": "EmailConfigurationDao.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3676,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/com/kwery/dao/EmailConfigurationDao.java",
"provenance": "stack-edu-0025.json.gz:634393",
"repo_name": "arulk/kwery",
"revision_date": "2018-08-15T02:46:28",
"revision_id": "a4a9586b2a065706ce80fc40019bd6bef8869f92",
"snapshot_id": "f40396fe34f258bad206c7d28e181de271f9a524",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/arulk/kwery/a4a9586b2a065706ce80fc40019bd6bef8869f92/src/main/java/com/kwery/dao/EmailConfigurationDao.java",
"visit_date": "2020-05-27T09:52:42.580872",
"added": "2024-11-18T23:24:43.833160+00:00",
"created": "2018-08-15T02:46:28",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz"
}
|
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\Sphere.h:12
namespace UnrealEngine
{
public partial class FSphere : NativeStructWrapper
{
public FSphere(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef)
{
}
/// <summary>
/// Default constructor (no initialization).
/// </summary>
public FSphere() :
base(E_CreateStruct_FSphere(), false)
{
}
/// <summary>
/// Creates and initializes a new sphere.
/// </summary>
/// <param name="int32">Passing int32 sets up zeroed sphere.</param>
public FSphere(int _p0) :
base(E_CreateStruct_FSphere_int32(_p0), false)
{
}
/// <summary>
/// Creates and initializes a new sphere with the specified parameters.
/// </summary>
/// <param name="inV">Center of sphere.</param>
/// <param name="inW">Radius of sphere.</param>
public FSphere(FVector inV, float inW) :
base(E_CreateStruct_FSphere_FVector_float(inV, inW), false)
{
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="pts">Pointer to list of points this sphere must contain.</param>
/// <param name="count">How many points are in the list.</param>
public FSphere(FVector pts, int count) :
base(E_CreateStruct_FSphere_FVector_int32(pts, count), false)
{
}
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_PROP_FSphere_Center_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FSphere_Center_SET(IntPtr Ptr, IntPtr Value);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_PROP_FSphere_W_GET(IntPtr Ptr);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E_PROP_FSphere_W_SET(IntPtr Ptr, float Value);
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FSphere();
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FSphere_int32(int _p0);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FSphere_FVector_float(IntPtr inV, float inW);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_CreateStruct_FSphere_FVector_int32(IntPtr pts, int count);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FSphere_Equals(IntPtr self, IntPtr sphere, float tolerance);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern float E_FSphere_GetVolume(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FSphere_Intersects(IntPtr self, IntPtr other, float tolerance);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FSphere_IsInside(IntPtr self, IntPtr other, float tolerance);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern bool E_FSphere_IsInside_o1(IntPtr self, IntPtr @in, float tolerance);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_FSphere_TransformBy(IntPtr self, IntPtr m);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr E_FSphere_TransformBy_o1(IntPtr self, IntPtr m);
#endregion
#region Property
/// <summary>
/// The sphere's center point.
/// </summary>
public FVector Center
{
get => E_PROP_FSphere_Center_GET(NativePointer);
set => E_PROP_FSphere_Center_SET(NativePointer, value);
}
/// <summary>
/// The sphere's radius.
/// </summary>
public float W
{
get => E_PROP_FSphere_W_GET(NativePointer);
set => E_PROP_FSphere_W_SET(NativePointer, value);
}
#endregion
#region ExternMethods
/// <summary>
/// Check whether two spheres are the same within specified tolerance.
/// </summary>
/// <param name="sphere">The other sphere.</param>
/// <param name="tolerance">Error Tolerance.</param>
/// <return>true</return>
public bool Equals(FSphere sphere, float tolerance)
=> E_FSphere_Equals(this, sphere, tolerance);
/// <summary>
/// Get volume of the current sphere
/// </summary>
/// <return>Volume</return>
public float GetVolume()
=> E_FSphere_GetVolume(this);
/// <summary>
/// Test whether this sphere intersects another.
/// </summary>
/// <param name="other">The other sphere.</param>
/// <param name="tolerance">Error tolerance.</param>
/// <return>true</return>
public bool Intersects(FSphere other, float tolerance)
=> E_FSphere_Intersects(this, other, tolerance);
/// <summary>
/// Check whether sphere is inside of another.
/// </summary>
/// <param name="other">The other sphere.</param>
/// <param name="tolerance">Error Tolerance.</param>
/// <return>true</return>
public bool IsInside(FSphere other, float tolerance)
=> E_FSphere_IsInside(this, other, tolerance);
/// <summary>
/// Checks whether the given location is inside this sphere.
/// </summary>
/// <param name="@in">The location to test for inside the bounding volume.</param>
/// <return>true</return>
public bool IsInside(FVector @in, float tolerance)
=> E_FSphere_IsInside_o1(this, @in, tolerance);
/// <summary>
/// Get result of Transforming sphere by Matrix.
/// </summary>
/// <param name="m">Matrix to transform by.</param>
/// <return>Result</return>
public FSphere TransformBy(FMatrix m)
=> E_FSphere_TransformBy(this, m);
/// <summary>
/// Get result of Transforming sphere with Transform.
/// </summary>
/// <param name="m">Transform information.</param>
/// <return>Result</return>
public FSphere TransformBy(FTransform m)
=> E_FSphere_TransformBy_o1(this, m);
#endregion
public static implicit operator IntPtr(FSphere self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator FSphere(IntPtr adress)
{
return adress == IntPtr.Zero ? null : new FSphere(adress, false);
}
}
}
|
73cc1a77c67a3775787785f24a5f3e543c8b2494
|
{
"blob_id": "73cc1a77c67a3775787785f24a5f3e543c8b2494",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-28T22:28:26",
"content_id": "0c37b85403e3d2d336e3e922dd52b9e22928b7e5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "01cf19848e6c3d505b757b0e714a05909e59e3ba",
"extension": "cs",
"filename": "FSphere.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 7192,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Plugins/UnrealDotNet/Source/UnrealEngineSharp/Generate/Struct/FSphere.cs",
"provenance": "stack-edu-0009.json.gz:824046",
"repo_name": "hefujie1988/UnrealDotNet",
"revision_date": "2019-06-28T22:28:26",
"revision_id": "55f6982727d8f24ba08bfaca73109bd8140428ab",
"snapshot_id": "3056a376e0f4fb82d3d55d74413727ed46c8c82c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hefujie1988/UnrealDotNet/55f6982727d8f24ba08bfaca73109bd8140428ab/Plugins/UnrealDotNet/Source/UnrealEngineSharp/Generate/Struct/FSphere.cs",
"visit_date": "2022-01-13T12:06:56.457734",
"added": "2024-11-19T01:00:47.018339+00:00",
"created": "2019-06-28T22:28:26",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
import fs from "fs-extra";
import path from "path";
import { BuilderState } from "..";
import { TEMPLATE_DIR } from "../../Shared/constants/paths";
import { InitMode } from "../impl/enums";
import { BuildOptions } from "../types/options";
async function buildTSProject(state: BuilderState, _: BuildOptions) {
state.logger.write("Building... (happens only on typescript projects)");
await state.shellStrict("tsc");
}
export async function copyTemplateFiles(
state: BuilderState,
options: BuildOptions,
) {
state.logger.writeIfVerbose("Copying template files");
/* Copy neccessary files */
await fs.copy(path.join(TEMPLATE_DIR, options.language), state.cwd);
/* Building project (if it is a typescript project) */
if (options.language === InitMode.TS) {
await buildTSProject(state, options);
}
}
|
6e2f003b96385461ccd49cb2cb3aef4ce65566ad
|
{
"blob_id": "6e2f003b96385461ccd49cb2cb3aef4ce65566ad",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-14T12:33:55",
"content_id": "642b3582c81bf1f82435502b31a276c1ba0ce81c",
"detected_licenses": [
"MIT"
],
"directory_id": "756db37b1c38ea9960e1bf18243a93495599176b",
"extension": "ts",
"filename": "copyTemplateFiles.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 384470920,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 811,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Builder/functions/copyTemplateFiles.ts",
"provenance": "stack-edu-0072.json.gz:334611",
"repo_name": "memothelemo/wumpbot",
"revision_date": "2021-07-14T12:33:55",
"revision_id": "5e660e774c23d3f8b0359d1cdf99955faa828a04",
"snapshot_id": "58f19e9fd2084ee1e906b2ca6cfdc226eba42f4c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/memothelemo/wumpbot/5e660e774c23d3f8b0359d1cdf99955faa828a04/src/Builder/functions/copyTemplateFiles.ts",
"visit_date": "2023-06-14T10:14:59.797948",
"added": "2024-11-19T01:20:16.060171+00:00",
"created": "2021-07-14T12:33:55",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
#include "event_mess_handle.h"
#include "test_config.h"
using namespace std;
void client_recive_cb(EventMessageHandle * mess_handle,EventMessage * mess,void * arg)
{
cout << "success get reply from Group "<<mess->group_name<<"["<<mess->mess_type<<"] ---- Message : " << mess->message << endl;
}
int main(void)
{
EventMessageHandle handler;
string host_config_path = std::string(TEST_SOURCE_DIR) + "host_config1.json";
string mess_config_path = std::string(TEST_SOURCE_DIR) + "mess_config.json";
cout << "host config file path = " << host_config_path << endl << "message config file path = " << mess_config_path << endl;
handler.init_handle(host_config_path.c_str(),mess_config_path.c_str());
handler.register_recive_handler("admin","reply",client_recive_cb,NULL);
cout << "Message Client Test" << endl;
/// cout << "---------- Message Callback Recive Test ------------" << endl;
int count = 0;
int return_code =0;
cout << "---------- Large Message Send Test ------------" << endl;
EventMessage mess;
string mess_str = "";
for(int i=0; i<1024*1024;i++)
{
mess_str += "w";
}
mess.prepare_send("admin","heart","host2",mess_str.c_str(),mess_str.size());
handler.sendMessage(&mess);
int c = 0;
while(c<10){
cout << "---------- Message Constantly Send Test ------------" << endl;
EventMessage while_mess;
EventMessage reply_mess;
string while_str = "send count : " + std::to_string(count);
string reply_str = "try to get reply --- count : " + std::to_string(count);
while_mess.prepare_send("admin","heart","host2",while_str.c_str(),while_str.size());
reply_mess.prepare_send("admin","reply","host2",reply_str.c_str(),reply_str.size());
return_code = handler.sendMessage(&while_mess);
handler.sendMessage(&reply_mess);
cout << "sendMessage return_code : " << return_code << endl;
if(return_code < 0)
{
cout << "send error" << std::endl;
cout << MessageError::getEventErrorStr(while_mess.error_no) << endl;
}
else
{
cout << while_mess.message << std::endl;
count++;
}
c++;
cout << "client Test [ "<< c << "]"<< std::endl;
//sleep(5);
}
while(1);
//handler.free_handle();
cout << " END client Test" << std::endl;
return 0;
}
|
9181ecddfa8cf61694801f804133c49b2a65da73
|
{
"blob_id": "9181ecddfa8cf61694801f804133c49b2a65da73",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-10T02:22:47",
"content_id": "7303b42abd7fd455d15370e038a1f03b31493cbb",
"detected_licenses": [
"MIT"
],
"directory_id": "1b0d2fc32d32bfd5d5c47d5ca5b78665117ce5a6",
"extension": "cc",
"filename": "event_mess_client_test.cc",
"fork_events_count": 0,
"gha_created_at": "2019-11-18T01:44:25",
"gha_event_created_at": "2020-07-10T02:22:48",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 222340924,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2428,
"license": "MIT",
"license_type": "permissive",
"path": "/multi_net_io/test/event_mess_client_test.cc",
"provenance": "stack-edu-0005.json.gz:164543",
"repo_name": "lwxwx/multi-master-tool",
"revision_date": "2020-07-10T02:22:47",
"revision_id": "7ad20d95786e10e16f6e65d47cfba60a0a96e186",
"snapshot_id": "87314210430064a350a6ccd713708eabaed89025",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lwxwx/multi-master-tool/7ad20d95786e10e16f6e65d47cfba60a0a96e186/multi_net_io/test/event_mess_client_test.cc",
"visit_date": "2021-07-16T16:28:33.813622",
"added": "2024-11-18T23:17:59.572082+00:00",
"created": "2020-07-10T02:22:47",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0023.json.gz"
}
|
package com.vishnus1224.teamworkapidemo.ui.presenter;
import com.vishnus1224.rxjavateamworkclient.model.Account;
import com.vishnus1224.rxjavateamworkclient.model.AccountResponse;
import com.vishnus1224.teamworkapidemo.di.scope.PerActivity;
import com.vishnus1224.teamworkapidemo.manager.PreferencesManager;
import com.vishnus1224.teamworkapidemo.manager.TokenManager;
import com.vishnus1224.teamworkapidemo.model.UserConfig;
import com.vishnus1224.teamworkapidemo.ui.view.LoginView;
import com.vishnus1224.teamworkapidemo.usecase.UseCase;
import com.vishnus1224.teamworkapidemo.util.Constants;
import java.net.UnknownHostException;
import javax.inject.Inject;
import javax.inject.Named;
import dagger.Lazy;
import rx.Subscriber;
/**
* Created by Vishnu on 8/14/2016.
*/
@PerActivity
public class LoginPresenter implements BasePresenter<LoginView> {
@Inject @Named("authentication")
Lazy<UseCase> useCase;
private LoginView loginView;
private PreferencesManager preferencesManager;
private TokenManager tokenManager;
@Inject
public LoginPresenter(PreferencesManager preferencesManager, TokenManager tokenManager) {
this.preferencesManager = preferencesManager;
this.tokenManager = tokenManager;
}
@Override
public void onViewAttached(LoginView loginView) {
this.loginView = loginView;
}
@Override
public void onViewDetached(LoginView loginView) {
useCase.get().unSubscribe();
this.loginView = null;
}
/**
* Attempt to authenticate the user.
* @param apiToken api token entered by the user.
*/
public void loginUser(String apiToken) {
loginView.showProgressDialog();
setToken(apiToken);
useCase.get().execute(new Subscriber<AccountResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
hideProgressDialog();
if (e instanceof UnknownHostException) {
loginView.showError("No Internet Connection");
} else {
loginView.showError("Authorization Failed");
}
}
@Override
public void onNext(AccountResponse accountResponse) {
saveTokenToPrefs();
saveUrlToPrefs(accountResponse.getAccount());
hideProgressDialog();
loginView.goToMainScreen();
}
});
}
/**
* Cancel the authentication flow.
*/
public void cancelLogin() {
useCase.get().unSubscribe();
}
public UserConfig obtainUserConfig(){
return new UserConfig(preferencesManager.get(Constants.PREFS_KEY_API_TOKEN),
preferencesManager.get(Constants.PREFS_KEY_SITE_URL));
}
private void setToken(String apiToken) {
tokenManager.setApiToken(apiToken);
}
private void saveUrlToPrefs(Account account) {
preferencesManager.save(Constants.PREFS_KEY_SITE_URL, account.getURL());
}
private void saveTokenToPrefs() {
preferencesManager.save(Constants.PREFS_KEY_API_TOKEN, tokenManager.getApiToken());
}
private void hideProgressDialog() {
loginView.hideProgressDialog();
}
}
|
eda702d9eb45fddfd9d5079f50e586f50f2268c5
|
{
"blob_id": "eda702d9eb45fddfd9d5079f50e586f50f2268c5",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-09T17:02:23",
"content_id": "064ac5a302fdadf91b30019eb99e2164b8ee1c1a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a1c8c01cd9cd6e8e694c69c3ffa33f1c77c29ab7",
"extension": "java",
"filename": "LoginPresenter.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 65601299,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3370,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/LoginPresenter.java",
"provenance": "stack-edu-0019.json.gz:276340",
"repo_name": "vishnus1224/RxJavaTeamworkClient",
"revision_date": "2016-09-09T17:02:23",
"revision_id": "114d1f0ab2fb2b34d83c29357cc84d9b21ca9a17",
"snapshot_id": "12aac521c80d4e031ba9a220a15b8425fd2aff1d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vishnus1224/RxJavaTeamworkClient/114d1f0ab2fb2b34d83c29357cc84d9b21ca9a17/TeamworkApiDemo/app/src/main/java/com/vishnus1224/teamworkapidemo/ui/presenter/LoginPresenter.java",
"visit_date": "2020-04-06T07:59:49.939403",
"added": "2024-11-19T01:30:06.289117+00:00",
"created": "2016-09-09T17:02:23",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
package ImagePreview;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePreview extends JPanel{
int longEdge, imgX, imgY;
float percent;
private BufferedImage bufImage;
/**
* Display image preview at correct aspect ratio by passing an int
* with the longest desired edge for the preview.
*
* @param inFile File variable to image to display in preview (jpg, png, gif)
* @param edge Length of the longest edge to display preview with
* @author Jon Pugh
*
*/
public ImagePreview(File inFile, int edge) {
try {
longEdge = edge;
bufImage = ImageIO.read(new File(inFile.getAbsolutePath()));
imgX = bufImage.getWidth();
imgY = bufImage.getHeight();
if (imgX > imgY)
{
percent = (float) imgY / imgX;
imgX = longEdge;
imgY = (int) Math.round(longEdge * percent);
}
else if (imgY > imgX)
{
percent = (float) imgX / imgY;
imgY = longEdge;
imgX = (int) Math.round(longEdge * percent);
}
else
{
imgX = imgY = longEdge;
}
}
catch (IOException ex) {
// handle exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bufImage, 0, 0, imgX, imgY, null); // see javadoc for more info on the parameters
}
}
|
1fb96ded232822d2a8a0b0ea4a46583fd81ef9d4
|
{
"blob_id": "1fb96ded232822d2a8a0b0ea4a46583fd81ef9d4",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-26T03:35:37",
"content_id": "7b5ed185faed374737416ccf091411b1e148513c",
"detected_licenses": [
"MIT"
],
"directory_id": "9b4a534e47a461b4f38992f2d40c4c59ee05903d",
"extension": "java",
"filename": "ImagePreview.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1700,
"license": "MIT",
"license_type": "permissive",
"path": "/src/ImagePreview/ImagePreview.java",
"provenance": "stack-edu-0020.json.gz:192884",
"repo_name": "AyishaSowkathali/CS3398-Rio-Bobcats-S2018",
"revision_date": "2018-04-26T03:35:37",
"revision_id": "de50c560050394c5d8e89e01173c49ea1cbe4006",
"snapshot_id": "33a7c4d208e2ff04084740f3a0fdb37cea1bdce9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AyishaSowkathali/CS3398-Rio-Bobcats-S2018/de50c560050394c5d8e89e01173c49ea1cbe4006/src/ImagePreview/ImagePreview.java",
"visit_date": "2020-03-13T23:39:56.467295",
"added": "2024-11-18T23:09:16.588506+00:00",
"created": "2018-04-26T03:35:37",
"int_score": 3,
"score": 3.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
## Merge
One of Git's most powerful features is the ability to easily create and merge branches. Git distributed nature encourages users to create new branches often and to merge them regularly as a part of the development process. This fundamentally improves the development workflow for most projects by encouraging smaller, more focused, granular commits.
A commonly used branching workflow in Git is to create a new code branch for each new feature, bug fix, or enhancement. These are called Feature Branches. Each branch compartmentalizes the commits related to a particular feature. Once the new feature is complete – i.e. a set of changes has been committed on the feature branch – it is ready to be merged back into the master branch (or other main code line branch depending on the workflow in use).
By default, git merge command refuses to merge histories that do not share a common ancestor. This option can be used to override this safety when merging histories of two projects that started their lives independently. As that is a very rare occasion, no configuration variable to enable this by default exists and will not be added.
## How to Merge
1. Fork a repository on GitHub(If not a Collaborator)

2. Clone it onto your computer

3. Make a branch and move to it

4. Make a Commit

5. Checkout to Master branch

6. Git Merge the new branch with master

|
9ace7372931ac5d4151725f1338e5465f8feeb9b
|
{
"blob_id": "9ace7372931ac5d4151725f1338e5465f8feeb9b",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-22T09:18:51",
"content_id": "8d5d41d7f5fd78b2a02abddd50ce5eea2bf2ce60",
"detected_licenses": [
"MIT"
],
"directory_id": "678903ac5ed500226daa1a23acd30f0097c1b063",
"extension": "md",
"filename": "Merge.md",
"fork_events_count": 0,
"gha_created_at": "2020-09-19T13:34:16",
"gha_event_created_at": "2020-09-22T07:39:46",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 296876536,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1946,
"license": "MIT",
"license_type": "permissive",
"path": "/Merge.md",
"provenance": "stack-edu-markdown-0004.json.gz:188574",
"repo_name": "Sakthi0722/TeamProject1",
"revision_date": "2020-09-22T09:18:51",
"revision_id": "a25acc6a3b3308eba75e1385b6437533c37523b2",
"snapshot_id": "92a833f063d4d5c53247bc4f78a2b879e1bf0352",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Sakthi0722/TeamProject1/a25acc6a3b3308eba75e1385b6437533c37523b2/Merge.md",
"visit_date": "2022-12-10T21:15:53.643112",
"added": "2024-11-18T23:51:20.316736+00:00",
"created": "2020-09-22T09:18:51",
"int_score": 4,
"score": 3.671875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz"
}
|
import React, {Component} from 'react';
class Login extends Component {
render() {
if (this.props.user == true) {
return(
<div className="login-button">
<button type="button" name="Logout">logout</button>
</div>
)
} else {
return(
<div className="login-cont">
<button className="login-button" name="Login/register" onClick={this.props.navigateTo}>dashboard</button>
</div>
)
}
}
}
export default Login;
|
68d77486b5347894548acb28cc50f009830c5a7c
|
{
"blob_id": "68d77486b5347894548acb28cc50f009830c5a7c",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-10T04:01:27",
"content_id": "2d91273b761920f52e980986461d87d3fe1011ed",
"detected_licenses": [
"MIT"
],
"directory_id": "39184e501385888557818d7270b497d25ebdbe2e",
"extension": "jsx",
"filename": "Login.jsx",
"fork_events_count": 1,
"gha_created_at": "2017-04-24T01:28:32",
"gha_event_created_at": "2017-05-03T21:00:00",
"gha_language": "JavaScript",
"gha_license_id": null,
"github_id": 89185194,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 495,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Landing/Navbar/Login.jsx",
"provenance": "stack-edu-0034.json.gz:332376",
"repo_name": "MichaelMansourati/colourscape-react",
"revision_date": "2017-05-10T04:01:27",
"revision_id": "ae32c6764d59755dcd26063b34391a6d0f92acf4",
"snapshot_id": "cdf011cb608fc56abf7935ff93f60fa12f7ec5d8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/MichaelMansourati/colourscape-react/ae32c6764d59755dcd26063b34391a6d0f92acf4/src/Landing/Navbar/Login.jsx",
"visit_date": "2021-01-20T00:46:09.367426",
"added": "2024-11-19T01:10:24.981280+00:00",
"created": "2017-05-10T04:01:27",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz"
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2013 UVC Ingenieure http://uvc-ingenieure.de/
* Author: Max Holtzberg <mholtzberg@uvc-ingenieure.de>
*
* 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.
*/
#include <stdio.h>
#include <eatft.h>
#include "test.h"
#define LABEL_FONT 3
#define BUTTON_FONT 1
#define BACKGROUND_COLOR EATFT_BLUE
#define FOREGROUND_COLOR EATFT_BLACK
#define LABEL_HEIGHT 120
#define WIDGETS_WIDTH (500)
#define BUTTONS_HEIGHT (CONFIG_EATFT_HEIGHT - LABEL_HEIGHT)
#define WIDGETS_X ((CONFIG_EATFT_WIDTH - WIDGETS_WIDTH) / 2)
static const struct eatft_rect label_rect PROGMEM = {
.x = WIDGETS_X,
.y = 0,
.width = WIDGETS_WIDTH,
.height = LABEL_HEIGHT
};
static const struct eatft_rect buttons_rect PROGMEM = {
.x = WIDGETS_X,
.y = LABEL_HEIGHT,
.width = WIDGETS_WIDTH,
.height = CONFIG_EATFT_HEIGHT - LABEL_HEIGHT
};
static void render_label(struct eatft *tft, const char *text)
{
eatft_setfont(tft, LABEL_FONT);
eatft_setfontcolor(tft,
FOREGROUND_COLOR,
BACKGROUND_COLOR);
eatft_text_drawr(tft, &label_rect, EATFT_MID_CENTER, text);
eatft_flush(tft);
}
static void button_clicked(struct eatft *tft, struct eatft_widget *widget,
bool down)
{
int button = (int)widget->priv;
char str[32];
if (!down)
return;
sprintf(str, "Pushed %d", button);
puts(str);
render_label(tft, str);
}
static void render_buttons(struct eatft *tft)
{
int i;
char str[32];
eatft_button_setframe(tft, 6, 0);
eatft_button_setframecolor(tft,
EATFT_BLACK, EATFT_BLACK, EATFT_WHITE,
EATFT_BLACK, EATFT_BLACK, EATFT_GRAY);
eatft_button_setfontcolor(
tft,
FOREGROUND_COLOR,
FOREGROUND_COLOR);
eatft_button_setfont(tft, BUTTON_FONT);
eatft_button_setoffset(tft, 1, 2);
eatft_flush(tft);
eatft_wdt_window_set(tft, &buttons_rect);
for (i = 0; i < 5; i++) {
sprintf(str, "Button %d", i);
eatft_wdt_button_createw(
tft,
button_clicked, /* callback */
(void*)i, /* priv */
EATFT_ALIGN_LEFT, str);
}
eatft_wdt_window_clear(tft);
}
void test_render(struct eatft *tft)
{
/* initialize tft */
eatft_terminal_enable(tft, false);
eatft_color_set(tft, EATFT_WHITE, EATFT_WHITE);
eatft_clear(tft);
eatft_flush(tft);
eatft_setfontcolor(tft, FOREGROUND_COLOR, BACKGROUND_COLOR);
eatft_flush(tft);
render_label(tft, "Push a button!");
render_buttons(tft);
}
|
176f65a0ceaf6024b7b62c16b64bf5a2f915d63b
|
{
"blob_id": "176f65a0ceaf6024b7b62c16b64bf5a2f915d63b",
"branch_name": "refs/heads/master",
"committer_date": "2014-02-18T10:03:27",
"content_id": "bdbbd2e777021e50b45b123c59b4c2febb83d1d7",
"detected_licenses": [
"MIT"
],
"directory_id": "be5a4b83b4137a83f6975524a4799f33f556448f",
"extension": "c",
"filename": "test.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3694,
"license": "MIT",
"license_type": "permissive",
"path": "/test/test.c",
"provenance": "stack-edu-0001.json.gz:535292",
"repo_name": "uvc-ingenieure/ediptft",
"revision_date": "2014-02-18T10:03:27",
"revision_id": "25b6e4d4b01172221f008e2e244e1949860ba6e9",
"snapshot_id": "02a430c80b2844daa8e110ca085fcc41f1deda63",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/uvc-ingenieure/ediptft/25b6e4d4b01172221f008e2e244e1949860ba6e9/test/test.c",
"visit_date": "2016-09-11T13:19:46.268530",
"added": "2024-11-18T21:52:52.554541+00:00",
"created": "2014-02-18T10:03:27",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz"
}
|
package goclone
import (
"github.com/spf13/cobra"
"log"
)
var (
// Flags
// Login bool // remove login flag for now
Serve bool
Open bool
// Root cmd
rootCmd = &cobra.Command{
Use: "goclone <url>",
Short: "Clone a website with ease!",
Long: `Copy websites to your computer! goclone is a utility that allows you to download a website from the Internet to a local directory. Get html, css, js, images, and other files from the server to your computer. goclone arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online.`, // TODO Update link once we change repo name
Args: cobra.ArbitraryArgs,
Run: func(cmd *cobra.Command, args []string) {
// Print the usage if no args are passed in :)
if len(args) < 1 {
if err := cmd.Usage(); err != nil {
log.Fatal(err)
}
return
}
// Otherwise.. clone ahead!
cloneSite(args)
},
}
)
// Execute the clone command
func Execute() {
// Persistent Flags
rootCmd.PersistentFlags().BoolVarP(&Open, "open", "o", false, "Automatically open project in deafult browser")
// rootCmd.PersistentFlags().BoolVarP(&Login, "login", "l", false, "Wether to use a username or password")
rootCmd.PersistentFlags().BoolVarP(&Serve, "serve", "s", false, "Serve the generated files using Echo.")
// Execute the command :)
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
|
596eb1053369e613f0b7c8486bc51a22a4af2668
|
{
"blob_id": "596eb1053369e613f0b7c8486bc51a22a4af2668",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-25T10:05:28",
"content_id": "ce5d1913c3816c2dfd58df144ac5a8edd3662dd1",
"detected_licenses": [
"MIT"
],
"directory_id": "9ce35c7c26bb924b681bd2a48371f6e35249fbed",
"extension": "go",
"filename": "root.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1504,
"license": "MIT",
"license_type": "permissive",
"path": "/cmd/goclone/root.go",
"provenance": "stack-edu-0016.json.gz:724529",
"repo_name": "mojocrash8/goclone",
"revision_date": "2021-02-25T10:05:28",
"revision_id": "a3163b8593b386e4f78ad0afb294f12569c60489",
"snapshot_id": "5e8cfd34f9d57f0d7e70cec6f3460fd28430d8c6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mojocrash8/goclone/a3163b8593b386e4f78ad0afb294f12569c60489/cmd/goclone/root.go",
"visit_date": "2023-03-19T22:26:30.349688",
"added": "2024-11-18T19:36:49.763789+00:00",
"created": "2021-02-25T10:05:28",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
"""This is the entry point of the program."""
def _is_prime(x):
for i in range(2,x):
if x%i==0:
return False
else:
return True
def list_of_prime_numbers(x):
a=[]
for i in range(2,x+1):
if _is_prime(i):
a.append(i)
return a
if __name__ == '__main__':
print(_is_prime(19))
|
41df54fcccc79f23b843c0cd4c46b1ab5b56a42d
|
{
"blob_id": "41df54fcccc79f23b843c0cd4c46b1ab5b56a42d",
"branch_name": "refs/heads/master",
"committer_date": "2016-10-27T23:00:55",
"content_id": "95fa845730331c449dc6a72878cd07a11e629465",
"detected_licenses": [
"MIT"
],
"directory_id": "070d54ec78cb82fea1aa2e2e3dacafa95ecb299e",
"extension": "py",
"filename": "main.py",
"fork_events_count": 1,
"gha_created_at": "2016-10-27T22:10:14",
"gha_event_created_at": "2016-10-27T22:10:15",
"gha_language": null,
"gha_license_id": null,
"github_id": 72152233,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 348,
"license": "MIT",
"license_type": "permissive",
"path": "/list_of_prime_numbers/main.py",
"provenance": "stack-edu-0059.json.gz:524806",
"repo_name": "amerca/itp-w1-list-of-prime-numbers",
"revision_date": "2016-10-27T23:00:55",
"revision_id": "4873912e141e2327998ffdaa30460dc7dc9eb864",
"snapshot_id": "e119446b01ad33b9b80c9c1a53b079f0212dac5a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/amerca/itp-w1-list-of-prime-numbers/4873912e141e2327998ffdaa30460dc7dc9eb864/list_of_prime_numbers/main.py",
"visit_date": "2021-01-12T13:12:49.360181",
"added": "2024-11-19T02:18:13.636268+00:00",
"created": "2016-10-27T23:00:55",
"int_score": 4,
"score": 3.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
<?php
include './config/Database.php';
include './models/Order.php';
$database = new Database();
$code = $_GET['code'];
$address='';
if (!empty($code)) {
$db = $database->connect();
$stmt = $db->prepare("SELECT COUNT(*) as total FROM `order` WHERE code=:userCode");
$stmt->bindParam(':userCode', $code, PDO::PARAM_STR);
$stmt->execute();
// Check if any categories
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if($row['total'] == '1'){
$stmt = $db->prepare("SELECT `address`.`address` FROM `order` INNER JOIN `address` ON `order`.idAddress = `address`.idAddress WHERE code = :user_Code");
$stmt->bindParam(':user_Code', $code, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$address = $row['address'];
}
} else {
header('Location: invalidDeliveryCode.php');
}
}
}
?>
<!DOCTYPE html>
<html>
<head lang="it" dir="ltr">
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta http-equiv="content-language" content="it">
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="revisit-after" content="1 Day">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="TODO">
<meta name="keywords" content="TODO">
<meta name="robots" content="index, follow">
<meta name="title" content="TODO">
<meta property="og:type" content="website">
<meta property="og:url" content="TODO">
<meta property="og:title" content="TODO">
<meta property="og:description" content="TODO">
<meta property="og:image" content="TODO">
<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="TODO">
<meta property="twitter:title" content="TODO">
<meta property="twitter:description" content="TODO">
<meta property="twitter:image" content="TODO">
<title>Magazzino - Verify Delivery Address</title>
<link rel="shortcut icon" href="TODO" />
<link rel="icon" href="assets/img/logo-salotto.png">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body id="verifyDeliveryAddress">
<div class="container">
<div class="card principalCard col-xl-8 col-lg-8 col-md-12 col-sm-12 col-xs-12 col-12 mx-auto pl-0 pr-0">
<div class="card-body-header">
<p class="d-inline"><b>Verifica indirizzo di consegna</b></p>
</div>
<p class="mb-1 mt-1 title">Il tuo ordine risulta essere <b>ancora in consegna</b>, nonostante siano passati più di 14 giorni. Ti preghiamo di <b>confermare</b> o <b>modificare</b> l’indirizzo di spedizione.</p>
<p class="mb-1 mt-3 title2"><b>L'attuale indirizzo di consegna è:</b></p>
<div class="card-body-header d-flex justify-content-center">
<p class="d-inline mt-2"><b><?php echo $address ?></b></p>
</div>
<div class="row">
<div class="col-12">
<p class="mt-3 title">Se è sbagliato inserisci il nuovo indirizzo qua sotto e poi premi <span style="color:var(--first-color);">"<b>Conferma</b>"</span> </p>
<p class="mt-3 title">In caso tontrario premi <span style="color:var(--first-color);"> "<b>Torna alla Home<b>"</span> </p>
</div>
</div>
<div class="row">
<div class="col-12">
<input id="delivery-address" class="input mt-1 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-xs-12 col-12" placeholder="Nuovo indirizzo" type="text">
</div>
</div>
<div class="row">
<div class="col-12">
<button id="submit-delivery-address" class="button btn-light btn-secondary btn mt-4 col-xl-3 col-lg-3 col-md-3 col-sm-3 col-xs-3 col-12 float-right" onclick="window.location.href='newAddress.php'"
><b>Conferma</b></button>
<button class="button btn btn-light btn-secondary mt-4 col-xl-3 col-lg-3 col-md-3 col-sm-3 col-xs-3 col-12" onclick="window.location.href='deliveryCode.php'">
<span><b>Torna alla home</b></span>
</button>
</div>
</div>
</div>
</div>
<!-- JS -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.min.js"></script>
<script src="https://kit.fontawesome.com/667eeb8441.js" crossorigin="anonymous"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
|
242af9fe02df47e2114beff9e93d9218cc6255f3
|
{
"blob_id": "242af9fe02df47e2114beff9e93d9218cc6255f3",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-08T14:00:29",
"content_id": "adaac071836164cb27f0de5e21c04b6f00294ea7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1efeec3f439d7a6ad66e4b9025a72ce8f78ee78b",
"extension": "php",
"filename": "verifyDeliveryAddress.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 334674647,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 5221,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/warehouse/verifyDeliveryAddress.php",
"provenance": "stack-edu-0049.json.gz:125366",
"repo_name": "Salotto-SGS/warehouse-management",
"revision_date": "2021-02-08T14:00:29",
"revision_id": "0942e88cf673756c7da69c8cf0982fe0b0ee5aa2",
"snapshot_id": "e88a65ddeffe022cfda36e06c3de0c03952cd76d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Salotto-SGS/warehouse-management/0942e88cf673756c7da69c8cf0982fe0b0ee5aa2/warehouse/verifyDeliveryAddress.php",
"visit_date": "2023-02-28T00:38:00.594297",
"added": "2024-11-19T02:07:40.441895+00:00",
"created": "2021-02-08T14:00:29",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
/* Copyright (c) 2013, Linaro Limited
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <odp_queue.h>
#include <odp_queue_internal.h>
#include <odp_std_types.h>
#include <odp_align.h>
#include <odp_buffer.h>
#include <odp_buffer_internal.h>
#include <odp_buffer_pool_internal.h>
#include <odp_internal.h>
#include <odp_shared_memory.h>
#include <odp_schedule_internal.h>
#include <odp_config.h>
#include <configs/odp_config_platform.h>
#include <odp_packet_io_internal.h>
#include <odp_packet_io_queue.h>
#include <odp_debug.h>
#include <odp_hints.h>
#ifdef USE_TICKETLOCK
#include <odp_ticketlock.h>
#define LOCK(a) odp_ticketlock_lock(a)
#define UNLOCK(a) odp_ticketlock_unlock(a)
#define LOCK_INIT(a) odp_ticketlock_init(a)
#else
#include <odp_spinlock.h>
#define LOCK(a) odp_spinlock_lock(a)
#define UNLOCK(a) odp_spinlock_unlock(a)
#define LOCK_INIT(a) odp_spinlock_init(a)
#endif
#include <string.h>
typedef struct queue_table_t {
queue_entry_t queue[ODP_CONFIG_QUEUES];
} queue_table_t;
static queue_table_t *queue_tbl;
queue_entry_t *get_qentry(uint32_t queue_id)
{
return &queue_tbl->queue[queue_id];
}
static void queue_init(queue_entry_t *queue, const char *name,
odp_queue_type_t type, odp_queue_param_t *param)
{
strncpy(queue->s.name, name, ODP_QUEUE_NAME_LEN - 1);
queue->s.type = type;
if (param) {
memcpy(&queue->s.param, param, sizeof(odp_queue_param_t));
} else {
/* Defaults */
memset(&queue->s.param, 0, sizeof(odp_queue_param_t));
queue->s.param.sched.prio = ODP_SCHED_PRIO_DEFAULT;
queue->s.param.sched.sync = ODP_SCHED_SYNC_DEFAULT;
queue->s.param.sched.group = ODP_SCHED_GROUP_DEFAULT;
}
switch (type) {
case ODP_QUEUE_TYPE_PKTIN:
queue->s.enqueue = queue_enq;
queue->s.dequeue = pktin_dequeue;
queue->s.enqueue_multi = queue_enq_multi;
queue->s.dequeue_multi = pktin_deq_multi;
break;
case ODP_QUEUE_TYPE_PKTOUT:
queue->s.enqueue = pktout_enqueue;
queue->s.dequeue = queue_deq;
queue->s.enqueue_multi = pktout_enq_multi;
queue->s.dequeue_multi = queue_deq_multi;
break;
default:
queue->s.enqueue = queue_enq;
queue->s.dequeue = queue_deq;
queue->s.enqueue_multi = queue_enq_multi;
queue->s.dequeue_multi = queue_deq_multi;
break;
}
queue->s.head = NULL;
queue->s.tail = NULL;
queue->s.sched_buf = ODP_BUFFER_INVALID;
}
int odp_queue_init_global(void)
{
uint32_t i;
ODP_DBG("Queue init ... ");
queue_tbl = odp_shm_reserve("odp_queues",
sizeof(queue_table_t),
sizeof(queue_entry_t));
if (queue_tbl == NULL)
return -1;
memset(queue_tbl, 0, sizeof(queue_table_t));
for (i = 0; i < ODP_CONFIG_QUEUES; i++) {
/* init locks */
queue_entry_t *queue = get_qentry(i);
LOCK_INIT(&queue->s.lock);
queue->s.handle = queue_from_id(i);
queue->s.status = QUEUE_STATUS_FREE;
/*
* TODO: HW queue is mapped dirrectly to queue_entry_t
* instance. It may worth to allocate HW queue on open.
*/
queue->s.hw_queue = TI_ODP_PUBLIC_QUEUE_BASE_IDX + i;
}
ODP_DBG("done\n");
ODP_DBG("Queue init global\n");
ODP_DBG(" struct queue_entry_s size %zu\n",
sizeof(struct queue_entry_s));
ODP_DBG(" queue_entry_t size %zu\n",
sizeof(queue_entry_t));
ODP_DBG("\n");
return 0;
}
odp_queue_type_t odp_queue_type(odp_queue_t handle)
{
queue_entry_t *queue;
queue = queue_to_qentry(handle);
return queue->s.type;
}
odp_schedule_sync_t odp_queue_sched_type(odp_queue_t handle)
{
queue_entry_t *queue;
queue = queue_to_qentry(handle);
return queue->s.param.sched.sync;
}
odp_queue_t _odp_queue_create(const char *name, odp_queue_type_t type,
odp_queue_param_t *param, uint32_t hw_queue)
{
uint32_t i;
queue_entry_t *queue;
odp_queue_t handle = ODP_QUEUE_INVALID;
for (i = 0; i < ODP_CONFIG_QUEUES; i++) {
queue = &queue_tbl->queue[i];
if (queue->s.status != QUEUE_STATUS_FREE)
continue;
LOCK(&queue->s.lock);
if (queue->s.status == QUEUE_STATUS_FREE) {
if (hw_queue)
queue->s.hw_queue = hw_queue;
/*
* Don't open hw queue if its number is specified
* as it is most probably opened by Linux kernel
*/
else if (ti_em_osal_hw_queue_open(queue->s.hw_queue)
!= EM_OK) {
UNLOCK(&queue->s.lock);
continue;
}
queue_init(queue, name, type, param);
if (type == ODP_QUEUE_TYPE_SCHED ||
type == ODP_QUEUE_TYPE_PKTIN)
queue->s.status = QUEUE_STATUS_NOTSCHED;
else
queue->s.status = QUEUE_STATUS_READY;
handle = queue->s.handle;
UNLOCK(&queue->s.lock);
break;
}
UNLOCK(&queue->s.lock);
}
if (handle != ODP_QUEUE_INVALID &&
(type == ODP_QUEUE_TYPE_SCHED || type == ODP_QUEUE_TYPE_PKTIN)) {
odp_buffer_t buf;
buf = odp_schedule_buffer_alloc(handle);
if (buf == ODP_BUFFER_INVALID) {
ODP_ERR("queue_init: sched buf alloc failed\n");
return ODP_QUEUE_INVALID;
}
queue->s.sched_buf = buf;
odp_schedule_mask_set(handle, queue->s.param.sched.prio);
}
return handle;
}
odp_queue_t odp_queue_create(const char *name, odp_queue_type_t type,
odp_queue_param_t *param)
{
return _odp_queue_create(name, type, param, 0);
}
odp_buffer_t queue_sched_buf(odp_queue_t handle)
{
queue_entry_t *queue;
queue = queue_to_qentry(handle);
return queue->s.sched_buf;
}
int queue_sched_atomic(odp_queue_t handle)
{
queue_entry_t *queue;
queue = queue_to_qentry(handle);
return queue->s.param.sched.sync == ODP_SCHED_SYNC_ATOMIC;
}
odp_queue_t odp_queue_lookup(const char *name)
{
uint32_t i;
for (i = 0; i < ODP_CONFIG_QUEUES; i++) {
queue_entry_t *queue = &queue_tbl->queue[i];
if (queue->s.status == QUEUE_STATUS_FREE)
continue;
LOCK(&queue->s.lock);
if (strcmp(name, queue->s.name) == 0) {
/* found it */
UNLOCK(&queue->s.lock);
return queue->s.handle;
}
UNLOCK(&queue->s.lock);
}
return ODP_QUEUE_INVALID;
}
int queue_enq(queue_entry_t *queue, odp_buffer_hdr_t *buf_hdr)
{
_ti_hw_queue_push_desc(queue->s.hw_queue, buf_hdr);
if (queue->s.type == ODP_QUEUE_TYPE_SCHED) {
int sched = 0;
LOCK(&queue->s.lock);
if (queue->s.status == QUEUE_STATUS_NOTSCHED) {
queue->s.status = QUEUE_STATUS_SCHED;
sched = 1;
}
UNLOCK(&queue->s.lock);
/* Add queue to scheduling */
if (sched)
odp_schedule_queue(queue->s.handle,
queue->s.param.sched.prio);
}
return 0;
}
int queue_enq_multi(queue_entry_t *queue, odp_buffer_hdr_t *buf_hdr[], int num)
{
int i;
/*
* TODO: Should this series of buffers be enqueued atomically?
* Can another buffer be pushed in this queue in the middle?
*/
for (i = 0; i < num; i++) {
/* TODO: Implement multi dequeue a lower level */
_ti_hw_queue_push_desc(queue->s.hw_queue, buf_hdr[i]);
}
if (queue->s.type == ODP_QUEUE_TYPE_SCHED) {
int sched = 0;
LOCK(&queue->s.lock);
if (queue->s.status == QUEUE_STATUS_NOTSCHED) {
queue->s.status = QUEUE_STATUS_SCHED;
sched = 1;
}
UNLOCK(&queue->s.lock);
/* Add queue to scheduling */
if (sched)
odp_schedule_queue(queue->s.handle,
queue->s.param.sched.prio);
}
return 0;
}
int odp_queue_enq_multi(odp_queue_t handle, odp_buffer_t buf[], int num)
{
odp_buffer_hdr_t *buf_hdr[QUEUE_MULTI_MAX];
queue_entry_t *queue;
int i;
if (num > QUEUE_MULTI_MAX)
num = QUEUE_MULTI_MAX;
queue = queue_to_qentry(handle);
for (i = 0; i < num; i++)
buf_hdr[i] = odp_buf_to_hdr(buf[i]);
return queue->s.enqueue_multi(queue, buf_hdr, num);
}
int odp_queue_enq(odp_queue_t handle, odp_buffer_t buf)
{
odp_buffer_hdr_t *buf_hdr;
queue_entry_t *queue;
queue = queue_to_qentry(handle);
buf_hdr = odp_buf_to_hdr(buf);
return queue->s.enqueue(queue, buf_hdr);
}
odp_buffer_hdr_t *queue_deq(queue_entry_t *queue)
{
odp_buffer_hdr_t *buf_hdr;
buf_hdr = (odp_buffer_hdr_t *)ti_em_osal_hw_queue_pop(queue->s.hw_queue,
TI_EM_MEM_PUBLIC_DESC);
if (!buf_hdr && queue->s.type == ODP_QUEUE_TYPE_SCHED) {
LOCK(&queue->s.lock);
if (!buf_hdr && queue->s.status == QUEUE_STATUS_SCHED)
queue->s.status = QUEUE_STATUS_NOTSCHED;
UNLOCK(&queue->s.lock);
}
return buf_hdr;
}
int queue_deq_multi(queue_entry_t *queue, odp_buffer_hdr_t *buf_hdr[], int num)
{
int i;
for (i = 0; i < num; i++) {
/* TODO: Implement multi dequeue a lower level */
buf_hdr[i] = (odp_buffer_hdr_t *)ti_em_osal_hw_queue_pop(
queue->s.hw_queue,
TI_EM_MEM_PUBLIC_DESC);
if (!buf_hdr[i]) {
if (queue->s.type != ODP_QUEUE_TYPE_SCHED)
break;
LOCK(&queue->s.lock);
if (queue->s.status == QUEUE_STATUS_SCHED)
queue->s.status = QUEUE_STATUS_NOTSCHED;
UNLOCK(&queue->s.lock);
break;
}
}
return i;
}
int odp_queue_deq_multi(odp_queue_t handle, odp_buffer_t buf[], int num)
{
queue_entry_t *queue;
odp_buffer_hdr_t *buf_hdr[QUEUE_MULTI_MAX];
int i, ret;
if (num > QUEUE_MULTI_MAX)
num = QUEUE_MULTI_MAX;
queue = queue_to_qentry(handle);
ret = queue->s.dequeue_multi(queue, buf_hdr, num);
for (i = 0; i < ret; i++)
buf[i] = hdr_to_odp_buf(buf_hdr[i]);
return ret;
}
odp_buffer_t odp_queue_deq(odp_queue_t handle)
{
queue_entry_t *queue;
odp_buffer_hdr_t *buf_hdr;
queue = queue_to_qentry(handle);
buf_hdr = queue->s.dequeue(queue);
if (buf_hdr)
return hdr_to_odp_buf(buf_hdr);
return ODP_BUFFER_INVALID;
}
void queue_lock(queue_entry_t *queue)
{
LOCK(&queue->s.lock);
}
void queue_unlock(queue_entry_t *queue)
{
UNLOCK(&queue->s.lock);
}
|
900daee6c852a7f6d62204e3c1babbbbbc71e8a6
|
{
"blob_id": "900daee6c852a7f6d62204e3c1babbbbbc71e8a6",
"branch_name": "refs/heads/master",
"committer_date": "2014-06-26T18:30:17",
"content_id": "031eeffdbf14792e1d5ec17d29f26d42de9db518",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "45174048966842f751b22e9ee1355be9cb90e224",
"extension": "c",
"filename": "odp_queue.c",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 23260564,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9409,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/platform/linux-keystone2/source/odp_queue.c",
"provenance": "stack-edu-0001.json.gz:203417",
"repo_name": "gonzopancho/odp-crypto",
"revision_date": "2014-06-26T18:29:02",
"revision_id": "c412fb0f79e578e00decc3624bfea6986c4bcb5f",
"snapshot_id": "907042ccaec7edc52f91ebfc88fac298d654d63f",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/gonzopancho/odp-crypto/c412fb0f79e578e00decc3624bfea6986c4bcb5f/platform/linux-keystone2/source/odp_queue.c",
"visit_date": "2021-01-18T10:08:53.613103",
"added": "2024-11-18T21:52:47.869637+00:00",
"created": "2014-06-26T18:29:02",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz"
}
|
import React from 'react';
import {compose, withMemo, withState, withCallback} from '@truefit/bach';
import {withSelector} from '@truefit/bach-redux';
import {withStyles} from '@truefit/bach-material-ui';
import {renderIf} from '@truefit/bach-recompose';
import Button from '@material-ui/core/Button';
import Loading from './loading';
import Speakers from './sessionModalSpeakers';
import Detail from './sessionModalDetail';
import Empty from './empty';
import {
loadingSessionDetailSelector,
speakersForSessionSelector,
} from '../selectors';
import {DATA_STATE} from 'constants';
const MODE = {
DETAIL: 0,
SPEAKERS: 1,
};
// selection
const SelectionButtonContent = ({color, children, handleClick}) => (
<Button color={color} onClick={handleClick}>
{children}
</Button>
);
const SelectionButton = compose(
withMemo('color', ({mode, value}) =>
mode === value ? 'primary' : 'default',
),
withCallback('handleClick', ({setMode, value}) => () => {
setMode(value);
}),
)(SelectionButtonContent);
const SelectionContent = ({classes, mode, setMode, speakers}) => (
<div className={classes.modeSelection}>
<SelectionButton value={MODE.DETAIL} mode={mode} setMode={setMode}>
Detail
</SelectionButton>
<SelectionButton value={MODE.SPEAKERS} mode={mode} setMode={setMode}>
Speaker{speakers.length <= 1 ? '' : 's'}
</SelectionButton>
</div>
);
const Selection = compose(
withSelector('speakers', speakersForSessionSelector),
withStyles({
modeSelection: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 10,
},
}),
)(SelectionContent);
// content
const Content = compose(
withSelector('loading', loadingSessionDetailSelector),
renderIf(
({loading}) => loading === DATA_STATE.LOADING_DATA_NONE_CACHED,
Loading,
),
renderIf(
({mode}) => mode === MODE.SPEAKERS,
({session}) => <Speakers session={session} />,
),
renderIf(
({mode}) => mode === MODE.DETAIL,
({session}) => <Detail session={session} />,
),
)(Empty);
// combine
const ModalContent = props => (
<>
<Selection {...props} />
<Content {...props} />
</>
);
export default compose(withState('mode', 'setMode', MODE.DETAIL))(ModalContent);
|
a6fb755616addcb358c39361c0bbb6e7a4689f78
|
{
"blob_id": "a6fb755616addcb358c39361c0bbb6e7a4689f78",
"branch_name": "refs/heads/main",
"committer_date": "2019-12-12T20:05:09",
"content_id": "ec254150d70ee39f7222dfe1974885bc744c585c",
"detected_licenses": [
"MIT"
],
"directory_id": "6599f46e464eec209f70806aea5c5e3c2f8ed948",
"extension": "js",
"filename": "sessionModalContent.js",
"fork_events_count": 1,
"gha_created_at": "2019-02-06T17:09:26",
"gha_event_created_at": "2020-07-16T19:30:14",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 169443421,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2277,
"license": "MIT",
"license_type": "permissive",
"path": "/site/app/features/schedule/components/sessionModalContent.js",
"provenance": "stack-edu-0043.json.gz:377616",
"repo_name": "jgretz/conference-schedule",
"revision_date": "2019-12-12T20:05:09",
"revision_id": "6b874539c60959e365d9f14c6322404e0c1371a9",
"snapshot_id": "c21cf07d659a23365084c10ed218411298761be1",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/jgretz/conference-schedule/6b874539c60959e365d9f14c6322404e0c1371a9/site/app/features/schedule/components/sessionModalContent.js",
"visit_date": "2021-07-09T16:06:49.106221",
"added": "2024-11-19T00:59:57.727813+00:00",
"created": "2019-12-12T20:05:09",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
package io.committed.krill.extraction.pdfbox;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/** A {@link ContentHandlerDecorator} which emits elements in the the XHTML namespace. */
public class SimpleXhtmlContentHandler extends ContentHandlerDecorator {
/** The Constant XHTML. */
public static final String XHTML = "http://www.w3.org/1999/xhtml";
/**
* Instantiates a new simple xhtml content handler.
*
* @param delegate the delegate
*/
public SimpleXhtmlContentHandler(ContentHandler delegate) {
super(delegate);
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
startPrefixMapping("", XHTML);
}
@Override
public void endDocument() throws SAXException {
endPrefixMapping("");
super.endDocument();
}
/**
* Start element.
*
* @param name the name
* @param strings the strings
* @throws SAXException the SAX exception
*/
public void startElement(String name, String... strings) throws SAXException {
startElement(XHTML, name, name, attributes(strings));
}
/**
* Characters.
*
* @param string the string
* @throws SAXException the SAX exception
*/
public void characters(String string) throws SAXException {
characters(string.toCharArray(), 0, string.length());
}
/**
* End element.
*
* @param name the name
* @throws SAXException the SAX exception
*/
public void endElement(String name) throws SAXException {
endElement(XHTML, name, name);
}
/**
* Generates an Attributes object from a list of key-value pairs provided in a flat array /
* varargs.
*
* @param attributePairs the attribute pairs
* @return the attributes
*/
private static Attributes attributes(String... attributePairs) {
if (attributePairs.length % 2 != 0) {
throw new IllegalArgumentException("Odd number of attribute pair components!");
}
AttributesImpl attributes = new AttributesImpl();
for (int i = 0; i < attributePairs.length; i += 2) {
attributes.addAttribute(
"", attributePairs[i], attributePairs[i], "CDATA", attributePairs[i + 1]);
}
return attributes;
}
}
|
6bf1cadc33f391d246ca03b63a776e68d4a916b6
|
{
"blob_id": "6bf1cadc33f391d246ca03b63a776e68d4a916b6",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-28T16:00:54",
"content_id": "7cd94bbcd8f2d5c25f74b68ff96951571f3818f5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e68e68337a7cf027da7c6d14ec2442716a8a6e77",
"extension": "java",
"filename": "SimpleXhtmlContentHandler.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2279,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/io/committed/krill/extraction/pdfbox/SimpleXhtmlContentHandler.java",
"provenance": "stack-edu-0030.json.gz:464266",
"repo_name": "zhongguogu/krill",
"revision_date": "2020-10-28T16:00:54",
"revision_id": "59f9cfeb5960411dc88e0305faf7d66eef217fde",
"snapshot_id": "4d47a4e21d72a708ae92663d2c2116365b217b8d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zhongguogu/krill/59f9cfeb5960411dc88e0305faf7d66eef217fde/src/main/java/io/committed/krill/extraction/pdfbox/SimpleXhtmlContentHandler.java",
"visit_date": "2023-07-04T23:01:38.189202",
"added": "2024-11-18T23:23:33.776680+00:00",
"created": "2020-10-28T16:00:54",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz"
}
|
/**
* Attached to a record field to define how the parent record field is handled for
* URI resolution and JSON-LD context generation.
*
*/
export interface JsonldPredicate {
/**
* The predicate URI that this field corresponds to.
* Corresponds to JSON-LD `@id` directive.
*
*/
_id?: string;
/**
* The context type hint, corresponds to JSON-LD `@type` directive.
*
* * If the value of this field is `@id` and `identity` is false or
* unspecified, the parent field must be resolved using the link
* resolution rules. If `identity` is true, the parent field must be
* resolved using the identifier expansion rules.
*
* * If the value of this field is `@vocab`, the parent field must be
* resolved using the vocabulary resolution rules.
*
*/
_type?: string;
/**
* Structure hint, corresponds to JSON-LD `@container` directive.
*
*/
_container?: string;
/**
* If true and `_type` is `@id` this indicates that the parent field must
* be resolved according to identity resolution rules instead of link
* resolution rules. In addition, the field value is considered an
* assertion that the linked value exists; absence of an object in the loaded document
* with the URI is not an error.
*
*/
identity?: boolean;
/**
* If true, this indicates that link validation traversal must stop at
* this field. This field (it is is a URI) or any fields under it (if it
* is an object or array) are not subject to link checking.
*
*/
noLinkCheck?: boolean;
}
|
1a7c6d1cec49c1405fbd8240ab184531d5e74f60
|
{
"blob_id": "1a7c6d1cec49c1405fbd8240ab184531d5e74f60",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-17T09:52:37",
"content_id": "9cd5b6ab590a298376f17f3cc76a8c8a6ddd2551",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e22909e21cadba56e1778eefcb62e99938f2c64b",
"extension": "ts",
"filename": "JsonldPredicate.ts",
"fork_events_count": 19,
"gha_created_at": "2016-05-18T14:42:37",
"gha_event_created_at": "2023-03-03T19:18:17",
"gha_language": "TypeScript",
"gha_license_id": "Apache-2.0",
"github_id": 59124271,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1650,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/mappings/draft-3/JsonldPredicate.ts",
"provenance": "stack-edu-0072.json.gz:542666",
"repo_name": "rabix/cwl-ts",
"revision_date": "2023-01-17T09:52:37",
"revision_id": "7f6fc5e4a35643a39f5c322bb7d9739e9a94393d",
"snapshot_id": "22e040effe9c1cb5f119ac25e516c403ca7155bb",
"src_encoding": "UTF-8",
"star_events_count": 57,
"url": "https://raw.githubusercontent.com/rabix/cwl-ts/7f6fc5e4a35643a39f5c322bb7d9739e9a94393d/src/mappings/draft-3/JsonldPredicate.ts",
"visit_date": "2023-03-16T14:22:37.049509",
"added": "2024-11-18T18:59:12.356140+00:00",
"created": "2023-01-17T09:52:37",
"int_score": 3,
"score": 3.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
import { takeEvery, put, call } from 'redux-saga/effects';
import { addStructure, addHistory, addResult, editStructure } from './actions';
import * as Request from '../../base/requests';
import history from '../../base/history';
import { URLS } from '../../config';
import { getUrlParams, stringifyUrl } from '../../base/parseUrl';
import { repeatedRequests, requestSaga, catchErrSaga, requestSagaContinius } from '../../base/sagas';
import { convertCmlToBase64, clearEditor, exportCml, importCml, convertCmlToBase64Arr } from '../../base/marvinAPI';
import {
modal,
addModels,
addMagic,
} from '../../base/actions';
import {
SAGA_CREATE_RESULT_TASK,
SAGA_CREATE_TASK,
SAGA_CREATE_TASK_SEARCH,
SAGA_DRAW_STRUCTURE,
SAGA_EDIT_STRUCTURE_1,
SAGA_EDIT_TASK_SEARCH,
SAGA_INIT_RESULT_PAGE,
SAGA_INIT_VALIDATE_PAGE,
SAGA_REVALIDATE_TASK,
SAGA_DRAW_STRUCTURE_CALLBACK,
SAGA_EDIT_STRUCTURE_CALLBACK,
} from './constants';
// Index Page
function* createTask({ data }) {
const response = yield call(Request.createSearchTask, { data });
yield call(history.push, stringifyUrl(URLS.VALIDATE, { task: response.data.task }));
}
function* drawStructure() {
yield call(clearEditor);
yield put(modal(true, SAGA_DRAW_STRUCTURE_CALLBACK));
}
function* drawStructureCallback() {
const data = yield call(exportCml);
yield put(modal(false));
yield put({ type: SAGA_CREATE_TASK, data });
}
// Validate Page
function* validateTask() {
const urlParams = yield getUrlParams();
const models = yield call(Request.getModels);
const magic = yield call(Request.getMagic);
const task = yield call(repeatedRequests, Request.getSearchTask, urlParams.task);
const structureAndBase64 = yield call(convertCmlToBase64Arr, task.data.structures);
yield put(addStructure({ data: structureAndBase64, type: task.data.type }));
yield put(addModels(models.data));
yield put(addMagic(magic.data));
}
function* editStructureR({ data }) {
yield call(importCml, data);
yield put(modal(true, SAGA_EDIT_STRUCTURE_CALLBACK));
}
function* editStructureCallback() {
const data = yield call(exportCml);
const base64 = yield call(convertCmlToBase64, data);
yield put(modal(false));
yield put(editStructure({ data, base64 }));
}
function* revalidateTask(action) {
yield call(createTask, action);
yield call(validateTask);
}
function* createResultTask({ structure, selectModel }) {
const urlParams = getUrlParams();
const { data } = structure;
const response = yield call(Request.createResultTask, { models: [{ model: selectModel.model, data }], structure: 1 }, urlParams.task);
const resultTaskId = response.data.task;
yield put(addHistory({ resultTaskId, selectModel, validateTaskId: urlParams.task, ...structure }));
yield call(history.push, stringifyUrl(URLS.RESULT, { task: resultTaskId }));
}
// Result page
function* resultPage() {
const urlParams = yield getUrlParams();
const responce = yield call(repeatedRequests, Request.getResultTask, urlParams.task);
const results = yield call(convertCmlToBase64Arr, responce.data.structures, { width: 700, height: 450, typeImg: 'image/png' });
yield put(addResult(results));
}
function* createStructure() {
const cml = yield call(exportCml);
yield put(modal(false));
yield put({ type: SAGA_CREATE_TASK, cml });
}
function* editTaskStructure() {
const cml = yield call(exportCml);
const base64 = yield call(convertCmlToBase64, cml);
yield put(modal(false));
yield put(editStructure(cml, base64));
}
export function* sagas() {
// Index Page
yield takeEvery(SAGA_CREATE_TASK, requestSagaContinius, createTask);
yield takeEvery(SAGA_DRAW_STRUCTURE, catchErrSaga, drawStructure);
yield takeEvery(SAGA_DRAW_STRUCTURE_CALLBACK, catchErrSaga, drawStructureCallback);
// Validate Page
yield takeEvery(SAGA_INIT_VALIDATE_PAGE, requestSaga, validateTask);
yield takeEvery(SAGA_EDIT_STRUCTURE_1, catchErrSaga, editStructureR);
yield takeEvery(SAGA_REVALIDATE_TASK, revalidateTask);
yield takeEvery(SAGA_CREATE_RESULT_TASK, requestSagaContinius, createResultTask);
yield takeEvery(SAGA_EDIT_STRUCTURE_CALLBACK, catchErrSaga, editStructureCallback);
// Result Page
yield takeEvery(SAGA_INIT_RESULT_PAGE, requestSaga, resultPage);
yield takeEvery(SAGA_CREATE_TASK_SEARCH, catchErrSaga, createStructure);
yield takeEvery(SAGA_EDIT_TASK_SEARCH, catchErrSaga, editTaskStructure);
}
|
758924bc74bb377d8315ccf12a6bc51793e77a9a
|
{
"blob_id": "758924bc74bb377d8315ccf12a6bc51793e77a9a",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-17T10:19:10",
"content_id": "20abc8768fe5bf64591fcaf954457786b3935a72",
"detected_licenses": [
"MIT"
],
"directory_id": "1ede57885bfa5a62883f7a0c199d2677ccf0b198",
"extension": "js",
"filename": "sagas.js",
"fork_events_count": 1,
"gha_created_at": "2018-01-17T18:21:37",
"gha_event_created_at": "2018-05-17T10:19:11",
"gha_language": "JavaScript",
"gha_license_id": null,
"github_id": 117875147,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4406,
"license": "MIT",
"license_type": "permissive",
"path": "/src/search/core/sagas.js",
"provenance": "stack-edu-0040.json.gz:289461",
"repo_name": "deljus/alter-ui",
"revision_date": "2018-05-17T10:19:10",
"revision_id": "33e9b01c8f6af5058a2f30cfa5bc761feb4ed8f0",
"snapshot_id": "e20eb52d61680e887c928093117ef213809a3ebf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deljus/alter-ui/33e9b01c8f6af5058a2f30cfa5bc761feb4ed8f0/src/search/core/sagas.js",
"visit_date": "2021-09-14T23:15:46.451830",
"added": "2024-11-19T00:50:38.489184+00:00",
"created": "2018-05-17T10:19:10",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz"
}
|
# Gaussian Process
- Need to give length scale to all the directions.
- Giving length scale [1.5 1.5], what if we have a wall in between. So signal strength will change drastically.
- what grid do we need? 0.1 grid takes a lot of time. 33000 points?
- We saw that at the boundaries, there was increase in the RSSI prediction. For example in the below figure, at y=5, which is actually a wall, the RSSI value bumps.

- GP optimization of parameters the, noise variance in the likelihood is going negative. H
|
8a94d9beb54fd3c5fabdf446a674776119d871c6
|
{
"blob_id": "8a94d9beb54fd3c5fabdf446a674776119d871c6",
"branch_name": "refs/heads/master",
"committer_date": "2018-01-15T11:41:12",
"content_id": "67dfe9c8b3bb2b4b0036ca33390e909600c43acc",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "143bf6ef321ec970f80edef4ffd02ed09fbb510c",
"extension": "md",
"filename": "implementation.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 78523964,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 570,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/implementation.md",
"provenance": "stack-edu-markdown-0004.json.gz:153328",
"repo_name": "imsrgadich/indoor_position_fingerprint",
"revision_date": "2018-01-15T11:41:12",
"revision_id": "523d43ecdeef908c4dd7a2224f4e1a6b3c6e963b",
"snapshot_id": "6fbb66539821c32b5ec7e1dde2753073ea570da1",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/imsrgadich/indoor_position_fingerprint/523d43ecdeef908c4dd7a2224f4e1a6b3c6e963b/implementation.md",
"visit_date": "2021-03-16T07:39:28.851366",
"added": "2024-11-18T21:32:43.731252+00:00",
"created": "2018-01-15T11:41:12",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz"
}
|
# -*-mode:sh-*- vim:ft=sh
{{ if eq .chezmoi.os "darwin" }}
{{ if eq .chezmoi.arch "arm64" }}
[ -f /opt/homebrew/bin/brew ] && eval "$(/opt/homebrew/bin/brew shellenv)"
{{ else }}
[ -f /usr/local/bin/brew ] && eval "$(/usr/local/bin/brew shellenv)"
{{ end }}
{{ else if eq .chezmoi.os "linux" }}
[ -f /home/linuxbrew/.linuxbrew/bin/brew ] && eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
{{ end }}
|
23853ae3470752df0a76f31d5ed49a2c9dbdf458
|
{
"blob_id": "23853ae3470752df0a76f31d5ed49a2c9dbdf458",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-26T09:36:18",
"content_id": "01550cea8163c2d8aebf24bb151a65500ff9a0d1",
"detected_licenses": [
"MIT"
],
"directory_id": "141820488748fc3aca8b9755fff6bbbe481b2f6b",
"extension": "",
"filename": "script_eval_brew",
"fork_events_count": 0,
"gha_created_at": "2021-12-02T15:16:50",
"gha_event_created_at": "2021-12-20T09:45:22",
"gha_language": "Shell",
"gha_license_id": "MIT",
"github_id": 434270642,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 407,
"license": "MIT",
"license_type": "permissive",
"path": "/home/.chezmoitemplates/common/script_eval_brew",
"provenance": "stack-edu-0069.json.gz:337080",
"repo_name": "MasahiroSakoda/dotfiles",
"revision_date": "2023-07-26T09:36:18",
"revision_id": "86ec9b2572ab4ab6014e1cfbc278a915887011da",
"snapshot_id": "b8e26f7eace822d2204d7cb3c9d1ce6edb85d07a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/MasahiroSakoda/dotfiles/86ec9b2572ab4ab6014e1cfbc278a915887011da/home/.chezmoitemplates/common/script_eval_brew",
"visit_date": "2023-08-03T04:30:50.630000",
"added": "2024-11-19T02:15:43.934710+00:00",
"created": "2023-07-26T09:36:18",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
function sumLine(line) {
const calcRegex = /[+-]?(\d+(\.\d+)?)/g
const calc = line.match(calcRegex) || [];
let total = 0
while (calc.length) {
total += parseFloat(calc.shift());
}
return `${total}`;
}
function getRoll(max, min = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
async function parse({ text }) {
const cmd = /\(roll\s([^)]+)\)/gi
const dice = /(?:([+\-])?(?:(\d*)?([><]))?(\d*)?d(\d*)?)/gi
const results = []
if (!text) return results
let match
while ((match = cmd.exec(text)) !== null) {
const queries = match[1].trim()
queries.split(' ').forEach(query => {
let rollLog = '';
const line = query.replace(dice, (...matches) => {
let [match, groupOp, limit, filterOp, nDice = 1, diceN] = matches
let rolls = []
let log = ''
let rolling = nDice
while (rolling--) {
const roll = diceN ? getRoll(diceN) : getRoll(1, -1)
rolls.push(roll)
}
rolls.sort((a, b) => a - b)
if (filterOp) {
const actualLimit = limit ? (limit > nDice ? nDice : limit) : 1
if (filterOp == '>') {
const divise = nDice - actualLimit
let discarded = rolls.slice(0, divise)
let kept = rolls.slice(divise, rolls.length)
log = `${discarded.join(' ')}${discarded.length && kept.length ? ' ' : ''}**${kept.join(' ')}**`
rolls = kept
} else {
let kept = rolls.slice(0, actualLimit)
let discarded = rolls.slice(actualLimit, rolls.length)
log = `**${kept.join(' ')}**${kept.length && discarded.length ? ' ' : ''}${discarded.join(' ')}`
rolls = kept
}
} else {
log = rolls.join(' ')
}
if (groupOp == '-' || nDice > 1) {
let result = 0
if (groupOp == '-') {
result = rolls.reduce((a, b) => a - b, 0)
} else {
result = rolls.reduce((a, b) => a + b, 0)
}
log += ` ↝ ${result}`
rolls = result
} else {
[rolls] = rolls
}
rollLog += `${rollLog ? '\n' : ''}[${match} ↝ ${log}]`
return rolls >= 0 ? `+${rolls}` : rolls
})
results.push([rollLog, sumLine(line)])
});
}
return results
}
module.exports = parse
|
64d73b227db2d9f52ed469316927121b2d8056b6
|
{
"blob_id": "64d73b227db2d9f52ed469316927121b2d8056b6",
"branch_name": "refs/heads/master",
"committer_date": "2022-09-08T17:01:52",
"content_id": "9049f1a397c2ae1633990c864eb8461fe7716c10",
"detected_licenses": [
"MIT"
],
"directory_id": "337d22cf803beb95033eeec9dc29eca52288e07a",
"extension": "js",
"filename": "diceroller.js",
"fork_events_count": 1,
"gha_created_at": "2019-02-22T00:53:56",
"gha_event_created_at": "2023-03-05T01:35:44",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 171969098,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2374,
"license": "MIT",
"license_type": "permissive",
"path": "/src/diceroller.js",
"provenance": "stack-edu-0044.json.gz:385046",
"repo_name": "vihainen/simassan",
"revision_date": "2022-09-08T17:01:52",
"revision_id": "064aedddefdb18292a72427c4365dfe395526d27",
"snapshot_id": "f97f3b7dfd755e5e38fd245653febaa22d30a3f6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vihainen/simassan/064aedddefdb18292a72427c4365dfe395526d27/src/diceroller.js",
"visit_date": "2023-03-10T09:07:16.511626",
"added": "2024-11-19T01:13:03.144563+00:00",
"created": "2022-09-08T17:01:52",
"int_score": 3,
"score": 2.96875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
import { Component, Input } from '@angular/core';
import { ShowcaseMetaEntry } from '../../meta';
@Component({
selector: 'sbb-variant-limitation',
templateUrl: './variant-limitation.component.html',
styleUrls: ['./variant-limitation.component.scss'],
})
export class VariantLimitationComponent {
@Input()
showcaseMetaEntry: ShowcaseMetaEntry;
get variantOnly(): 'standard' | 'lean' {
return this.showcaseMetaEntry?.variantOnly;
}
get oppositeVariant(): 'standard' | 'lean' {
if (this.variantOnly === 'standard') {
return 'lean';
}
return 'standard';
}
}
|
b233b2cb1bad545469ddf7789c5ea38848a51f87
|
{
"blob_id": "b233b2cb1bad545469ddf7789c5ea38848a51f87",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-02T20:17:41",
"content_id": "87a1c177d1f5b62f1ea061c15e3744f39c210963",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "42ae436ee882de8b59234a16b7457d04e86ec234",
"extension": "ts",
"filename": "variant-limitation.component.ts",
"fork_events_count": 20,
"gha_created_at": "2019-04-15T18:50:19",
"gha_event_created_at": "2023-09-14T15:04:56",
"gha_language": "TypeScript",
"gha_license_id": "NOASSERTION",
"github_id": 181547091,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 598,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/src/showcase/app/shared/component-viewer/variant-limitation-component/variant-limitation.component.ts",
"provenance": "stack-edu-0075.json.gz:479439",
"repo_name": "sbb-design-systems/sbb-angular",
"revision_date": "2023-09-02T20:17:41",
"revision_id": "4eb6c2fafc1e33bda23024e5b4e0aedaadd9b4b0",
"snapshot_id": "28172305d7eefa41a5f0c0b758c61ca10182693f",
"src_encoding": "UTF-8",
"star_events_count": 77,
"url": "https://raw.githubusercontent.com/sbb-design-systems/sbb-angular/4eb6c2fafc1e33bda23024e5b4e0aedaadd9b4b0/src/showcase/app/shared/component-viewer/variant-limitation-component/variant-limitation.component.ts",
"visit_date": "2023-09-04T04:15:52.898963",
"added": "2024-11-18T22:23:58.038360+00:00",
"created": "2023-09-02T20:17:41",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.